Debian Codegraph @

vcl/skia/SkiaHelper.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
10 #include <sal/config.h>
11
12 #include <config_features.h>
13
14 #include <string_view>
15
16 #include <vcl/skia/SkiaHelper.hxx>
17 #include <rtl/ustrbuf.hxx>
18
19 #if !HAVE_FEATURE_SKIA
20
21 namespace SkiaHelper
22 {
23 bool isVCLSkiaEnabled() { return false; }
24 bool isAlphaMaskBlendingEnabled() { return false; }
25
26 } // namespace
27
28 #else
29
30 #include <rtl/bootstrap.hxx>
31 #include <vcl/svapp.hxx>
32 #include <desktop/crashreport.hxx>
33 #include <officecfg/Office/Common.hxx>
34 #include <watchdog.hxx>
35 #include <skia/zone.hxx>
36 #include <sal/log.hxx>
37 #include <driverblocklist.hxx>
38 #include <skia/utils.hxx>
39 #include <config_folders.h>
40 #include <config_skia.h>
41 #include <osl/file.hxx>
42 #include <tools/stream.hxx>
43 #include <atomic>
44 #include <list>
45 #include <o3tl/lru_map.hxx>
46
47 #include <com/sun/star/configuration/theDefaultProvider.hpp>
48 #include <com/sun/star/util/XFlushable.hpp>
49
50 #include <SkBitmap.h>
51 #include <SkCanvas.h>
52 #include <include/codec/SkEncodedImageFormat.h>
53 #include <SkPaint.h>
54 #include <SkSurface.h>
55 #include <SkGraphics.h>
56 #include <ganesh/GrDirectContext.h>
57 #include <SkRuntimeEffect.h>
58 #include <SkStream.h>
59 #include <SkTileMode.h>
60 #include <skia_compiler.hxx>
61 #include <skia_opts.hxx>
62 #if defined(MACOSX)
63 #include <premac.h>
64 #endif
65 #ifdef SK_VULKAN
66 #include <tools/window/VulkanWindowContext.h>
67 #endif
68 #ifdef SK_METAL
69 #include <tools/window/MetalWindowContext.h>
70 #endif
71 #if defined(MACOSX)
72 #include <postmac.h>
73 #endif
74 #include <src/core/SkOpts.h>
75 #include <src/core/SkChecksum.h>
76 #include <include/encode/SkPngEncoder.h>
77 #include <ganesh/SkSurfaceGanesh.h>
78 #if defined _MSC_VER
79 #pragma warning(disable : 4100) // "unreferenced formal parameter"
80 #pragma warning(disable : 4324) // "structure was padded due to alignment specifier"
81 #endif
82 #if defined __clang__
83 #pragma clang diagnostic push
84 #pragma clang diagnostic ignored "-Wunused-parameter"
85 #endif
86 #if defined __GNUC__ && !defined __clang__
87 #pragma GCC diagnostic push
88 #pragma GCC diagnostic ignored "-Wunused-parameter"
89 #endif
90 #include <src/image/SkImage_Base.h>
91 #if defined __GNUC__ && !defined __clang__
92 #pragma GCC diagnostic pop
93 #endif
94 #if defined __clang__
95 #pragma clang diagnostic pop
96 #endif
97
98 #include <fstream>
99
100 #ifdef SK_METAL
101 #ifdef MACOSX
102 #include <quartz/cgutils.h>
103 #endif
104 #endif
105
106 namespace SkiaHelper
107 {
108 static OUString getCacheFolder()
109 {
110 OUString url(u"${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER
111 "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/cache/"_ustr);
112 rtl::Bootstrap::expandMacros(url);
113 osl::Directory::create(url);
114 return url;
115 }
116
117 static void writeToLog(SvStream& stream, const char* key, const char* value)
118 {
119 stream.WriteOString(key);
120 stream.WriteOString(": ");
121 stream.WriteOString(value);
122 stream.WriteChar('\n');
123 }
124
125 OUString readLog()
126 {
127 SvFileStream logFile(getCacheFolder() + "/skia.log", StreamMode::READ);
128
129 OUStringBuffer sResult;
130 OStringBuffer sLine;
131 while (logFile.ReadLine(sLine))
132 sResult.append(OStringToOUString(sLine, RTL_TEXTENCODING_UTF8) + "\n");
133
134 return sResult.toString();
135 }
136
137 uint32_t vendorId = 0;
138
139 #ifdef SK_VULKAN
140 static void writeToLog(SvStream& stream, const char* key, std::u16string_view value)
141 {
142 writeToLog(stream, key, OUStringToOString(value, RTL_TEXTENCODING_UTF8).getStr());
143 }
144
145 static OUString getDenylistFile()
146 {
147 OUString url(u"$BRAND_BASE_DIR/" LIBO_SHARE_FOLDER ""_ustr);
148 rtl::Bootstrap::expandMacros(url);
149
150 return url + "/skia/skia_denylist_vulkan.xml";
151 }
152
153 static OUString versionAsString(uint32_t version)
154 {
155 return OUString::number(version >> 22) + "." + OUString::number((version >> 12) & 0x3ff) + "."
156 + OUString::number(version & 0xfff);
157 }
158
159 static std::string_view vendorAsString(uint32_t vendor)
160 {
161 return DriverBlocklist::GetVendorNameFromId(vendor);
162 }
163
164 // returns old value
165 static bool setForceSkiaRaster(bool val)
166 {
167 const bool oldValue = officecfg::Office::Common::VCL::ForceSkiaRaster::get();
168 if (oldValue != val && !officecfg::Office::Common::VCL::ForceSkiaRaster::isReadOnly())
169 {
170 auto batch(comphelper::ConfigurationChanges::create());
171 officecfg::Office::Common::VCL::ForceSkiaRaster::set(val, batch);
172 batch->commit();
173
174 // make sure the change is written to the configuration
175 if (auto xFlushable{ css::configuration::theDefaultProvider::get(
176 comphelper::getProcessComponentContext())
177 .query<css::util::XFlushable>() })
178 xFlushable->flush();
179 }
180 return oldValue;
181 }
182
183 // Note that this function also logs system information about Vulkan.
184 static bool isVulkanDenylisted(const VkPhysicalDeviceProperties& props)
185 {
186 static const char* const types[]
187 = { "other", "integrated", "discrete", "virtual", "cpu", "??" }; // VkPhysicalDeviceType
188 vendorId = props.vendorID;
189 OUString vendorIdStr = "0x" + OUString::number(props.vendorID, 16);
190 OUString deviceIdStr = "0x" + OUString::number(props.deviceID, 16);
191 OUString driverVersionString = versionAsString(props.driverVersion);
192 OUString apiVersion = versionAsString(props.apiVersion);
193 const char* deviceType = types[std::min<unsigned>(props.deviceType, SAL_N_ELEMENTS(types) - 1)];
194
195 CrashReporter::addKeyValue(u"VulkanVendor"_ustr, vendorIdStr, CrashReporter::AddItem);
196 CrashReporter::addKeyValue(u"VulkanDevice"_ustr, deviceIdStr, CrashReporter::AddItem);
197 CrashReporter::addKeyValue(u"VulkanAPI"_ustr, apiVersion, CrashReporter::AddItem);
198 CrashReporter::addKeyValue(u"VulkanDriver"_ustr, driverVersionString, CrashReporter::AddItem);
199 CrashReporter::addKeyValue(u"VulkanDeviceType"_ustr, OUString::createFromAscii(deviceType),
200 CrashReporter::AddItem);
201 CrashReporter::addKeyValue(u"VulkanDeviceName"_ustr,
202 OUString::createFromAscii(props.deviceName), CrashReporter::Write);
203
204 SvFileStream logFile(getCacheFolder() + "/skia.log", StreamMode::WRITE | StreamMode::TRUNC);
205 writeToLog(logFile, "RenderMethod", "vulkan");
206 writeToLog(logFile, "Vendor", vendorIdStr);
207 writeToLog(logFile, "Device", deviceIdStr);
208 writeToLog(logFile, "API", apiVersion);
209 writeToLog(logFile, "Driver", driverVersionString);
210 writeToLog(logFile, "DeviceType", deviceType);
211 writeToLog(logFile, "DeviceName", props.deviceName);
212
213 SAL_INFO("vcl.skia",
214 "Vulkan API version: " << apiVersion << ", driver version: " << driverVersionString
215 << ", vendor: " << vendorIdStr << " ("
216 << vendorAsString(vendorId) << "), device: " << deviceIdStr
217 << ", type: " << deviceType << ", name: " << props.deviceName);
218 bool denylisted
219 = DriverBlocklist::IsDeviceBlocked(getDenylistFile(), DriverBlocklist::VersionType::Vulkan,
220 driverVersionString, vendorIdStr, deviceIdStr);
221 writeToLog(logFile, "Denylisted", denylisted ? "yes" : "no");
222 return denylisted;
223 }
224 #endif
225
226 #ifdef SK_METAL
227 static void writeSkiaMetalInfo()
228 {
229 SvFileStream logFile(getCacheFolder() + "/skia.log", StreamMode::WRITE | StreamMode::TRUNC);
230 writeToLog(logFile, "RenderMethod", "metal");
231 }
232 #endif
233
234 static void writeSkiaRasterInfo()
235 {
236 SvFileStream logFile(getCacheFolder() + "/skia.log", StreamMode::WRITE | StreamMode::TRUNC);
237 writeToLog(logFile, "RenderMethod", "raster");
238 // Log compiler, Skia works best when compiled with Clang.
239 writeToLog(logFile, "Compiler", skia_compiler_name());
240 }
241
242 #if defined(SK_VULKAN) || defined(SK_METAL)
243 static std::unique_ptr<skwindow::WindowContext> getTemporaryWindowContext();
244 #endif
245
246 static RenderMethod initRenderMethodToUse()
247 {
248 if (Application::IsBitmapRendering())
249 return RenderRaster;
250 #if defined(MACOSX) || defined(_WIN32)
251 // macOS/win can __only__ render via skia - there, we can only disable HW acceleration
252 if (Application::IsSafeModeEnabled())
253 return RenderRaster;
254 #endif
255
256 if (const char* env = getenv("SAL_SKIA"))
257 {
258 if (strcmp(env, "raster") == 0)
259 return RenderRaster;
260 #if defined SK_METAL
261 if (strcmp(env, "metal") == 0)
262 return RenderMetal;
263 #elif defined SK_VULKAN
264 if (strcmp(env, "vulkan") == 0)
265 return RenderVulkan;
266 #endif
267 SAL_WARN("vcl.skia", "Unrecognized value of SAL_SKIA");
268 abort();
269 }
270 if (officecfg::Office::Common::VCL::ForceSkiaRaster::get())
271 return RenderRaster;
272 #if defined SK_METAL
273 return RenderMetal;
274 #elif defined SK_VULKAN
275 return RenderVulkan;
276 #else
277 return RenderRaster;
278 #endif
279 }
280
281 static std::atomic<RenderMethod>& accessRenderMethodToUse()
282 {
283 static std::atomic<RenderMethod> methodToUse = initRenderMethodToUse();
284 return methodToUse;
285 }
286
287 RenderMethod renderMethodToUse() { return accessRenderMethodToUse(); }
288
289 static void forceRasterRenderMethod() { accessRenderMethodToUse() = RenderRaster; }
290
291 static void checkDeviceDenylisted(bool blockDisable)
292 {
293 static bool done = false;
294 if (done)
295 return;
296
297 SkiaZone zone;
298
299 bool useRaster = false;
300 switch (renderMethodToUse())
301 {
302 case RenderVulkan:
303 {
304 #ifdef SK_VULKAN
305 // Temporarily change config to force software rendering. If the following HW check
306 // crashes, this config change will stay active, and will make sure to avoid use of
307 // faulty HW/driver on the nest start
308 const bool oldForceSkiaRasterValue = setForceSkiaRaster(true);
309
310 // First try if a GrDirectContext already exists.
311 std::unique_ptr<skwindow::WindowContext> temporaryWindowContext;
312 GrDirectContext* grDirectContext
313 = skwindow::internal::VulkanWindowContext::getSharedGrDirectContext();
314 if (!grDirectContext)
315 {
316 // This function is called from isVclSkiaEnabled(), which
317 // may be called when deciding which X11 visual to use,
318 // and that visual is normally needed when creating
319 // Skia's VulkanWindowContext, which is needed for the GrDirectContext.
320 // Avoid the loop by creating a temporary WindowContext
321 // that will use the default X11 visual (that shouldn't matter
322 // for just finding out information about Vulkan) and destroying
323 // the temporary context will clean up again.
324 temporaryWindowContext = getTemporaryWindowContext();
325 grDirectContext
326 = skwindow::internal::VulkanWindowContext::getSharedGrDirectContext();
327 }
328 bool denylisted = true; // assume the worst
329 if (grDirectContext) // Vulkan was initialized properly
330 {
331 denylisted = isVulkanDenylisted(
332 skwindow::internal::VulkanWindowContext::getPhysDeviceProperties());
333 SAL_INFO("vcl.skia", "Vulkan denylisted: " << denylisted);
334 }
335 else
336 SAL_INFO("vcl.skia", "Vulkan could not be initialized");
337 if (denylisted && !blockDisable)
338 {
339 forceRasterRenderMethod();
340 useRaster = true;
341 }
342
343 // The check succeeded; restore the original value
344 setForceSkiaRaster(oldForceSkiaRasterValue);
345 #else
346 SAL_WARN("vcl.skia", "Vulkan support not built in");
347 (void)blockDisable;
348 useRaster = true;
349 #endif
350 break;
351 }
352 case RenderMetal:
353 {
354 #ifdef SK_METAL
355 // First try if a GrDirectContext already exists.
356 std::unique_ptr<skwindow::WindowContext> temporaryWindowContext;
357 GrDirectContext* grDirectContext = skwindow::internal::getMetalSharedGrDirectContext();
358 if (!grDirectContext)
359 {
360 // Create a temporary window context just to get the GrDirectContext,
361 // as an initial test of Metal functionality.
362 temporaryWindowContext = getTemporaryWindowContext();
363 grDirectContext = skwindow::internal::getMetalSharedGrDirectContext();
364 }
365 if (grDirectContext) // Metal was initialized properly
366 {
367 #ifdef MACOSX
368 if (!blockDisable && !DefaultMTLDeviceIsSupported())
369 {
370 SAL_INFO("vcl.skia", "Metal default device not supported");
371 forceRasterRenderMethod();
372 useRaster = true;
373 }
374 else
375 #endif
376 {
377 SAL_INFO("vcl.skia", "Using Skia Metal mode");
378 writeSkiaMetalInfo();
379 }
380 }
381 else
382 {
383 SAL_INFO("vcl.skia", "Metal could not be initialized");
384 forceRasterRenderMethod();
385 useRaster = true;
386 }
387 #else
388 SAL_WARN("vcl.skia", "Metal support not built in");
389 useRaster = true;
390 #endif
391 break;
392 }
393 case RenderRaster:
394 useRaster = true;
395 break;
396 }
397 if (useRaster)
398 {
399 SAL_INFO("vcl.skia", "Using Skia raster mode");
400 // software, never denylisted
401 writeSkiaRasterInfo();
402 }
403 done = true;
404 }
405
406 static std::atomic<bool> skiaSupportedByBackend = false;
407 static bool supportsVCLSkia()
408 {
409 if (skiaSupportedByBackend)
410 return true;
411 SAL_INFO("vcl.skia", "Skia not supported by VCL backend, disabling");
412 return false;
413 }
414
415 static bool initVCLSkiaEnabled()
416 {
417 /**
418 * Should only be called once! Changing the results in the same
419 * run will mix Skia and normal rendering.
420 */
421
422 // allow global disable when testing SystemPrimitiveRenderer since current Skia on Win does not
423 // harmonize with using Direct2D and D2DPixelProcessor2D
424 if (std::getenv("TEST_SYSTEM_PRIMITIVE_RENDERER") != nullptr)
425 return false;
426
427 /*
428 * There are a number of cases that these environment variables cover:
429 * * SAL_FORCESKIA forces Skia if disabled by UI options or denylisted
430 * * SAL_DISABLESKIA avoids the use of Skia regardless of any option
431 */
432
433 bool bSalDisableSkia = getenv("SAL_DISABLESKIA") != nullptr;
434 #if defined(MACOSX) || defined(_WIN32)
435 if (bSalDisableSkia)
436 {
437 SAL_WARN("vcl", "macOS/win requires Skia, so ignoring SAL_DISABLESKIA");
438 bSalDisableSkia = false;
439 }
440 #endif
441
442 bool bRet = false;
443 if (supportsVCLSkia() && !bSalDisableSkia)
444 {
445 const bool bForceSkia = getenv("SAL_FORCESKIA") != nullptr
446 || officecfg::Office::Common::VCL::ForceSkia::get();
447 #if defined(MACOSX) || defined(_WIN32)
448 bRet = true; // macOS/win can __only__ render via skia
449 #else
450 bRet = bForceSkia;
451 // If not forced, don't enable in safe mode
452 if (!bRet && !Application::IsSafeModeEnabled())
453 {
454 bRet = getenv("SAL_ENABLESKIA") != nullptr
455 || officecfg::Office::Common::VCL::UseSkia::get();
456 }
457 #endif
458
459 if (bRet)
460 {
461 // Set up all things needed for using Skia.
462 SkGraphics::Init();
463 SkLoOpts::Init();
464 // if bForceSkia, don't actually block if denylisted, but log it if enabled,
465 // and also get the vendor id; otherwise, switch to raster if driver is denylisted
466 checkDeviceDenylisted(bForceSkia);
467 WatchdogThread::start();
468 }
469 }
470
471 CrashReporter::addKeyValue(u"UseSkia"_ustr, OUString::boolean(bRet), CrashReporter::Write);
472
473 return bRet;
474 }
475
476 bool isVCLSkiaEnabled()
477 {
478 static const bool val = initVCLSkiaEnabled();
479 return val;
480 }
481
482 bool isAlphaMaskBlendingEnabled() { return false; }
483
484 // If needed, we'll allocate one extra window context so that we have a valid GrDirectContext
485 // from Vulkan/MetalWindowContext.
486 static std::unique_ptr<skwindow::WindowContext> sharedWindowContext;
487
488 static std::unique_ptr<skwindow::WindowContext> (*createGpuWindowContextFunction)(bool) = nullptr;
489 static void setCreateGpuWindowContext(std::unique_ptr<skwindow::WindowContext> (*function)(bool))
490 {
491 createGpuWindowContextFunction = function;
492 }
493
494 GrDirectContext* getSharedGrDirectContext()
495 {
496 SkiaZone zone;
497 assert(renderMethodToUse() != RenderRaster);
498 if (sharedWindowContext)
499 return sharedWindowContext->directContext();
500 // TODO mutex?
501 // Set up the shared GrDirectContext from Skia's (patched) Vulkan/MetalWindowContext, if it's been
502 // already set up.
503 switch (renderMethodToUse())
504 {
505 case RenderVulkan:
506 #ifdef SK_VULKAN
507 if (GrDirectContext* context
508 = skwindow::internal::VulkanWindowContext::getSharedGrDirectContext())
509 return context;
510 #endif
511 break;
512 case RenderMetal:
513 #ifdef SK_METAL
514 if (GrDirectContext* context = skwindow::internal::getMetalSharedGrDirectContext())
515 return context;
516 #endif
517 break;
518 case RenderRaster:
519 abort();
520 }
521 static bool done = false;
522 if (done)
523 return nullptr;
524 done = true;
525 if (createGpuWindowContextFunction == nullptr)
526 return nullptr; // not initialized properly (e.g. used from a VCL backend with no Skia support)
527 sharedWindowContext = createGpuWindowContextFunction(false);
528 GrDirectContext* grDirectContext
529 = sharedWindowContext ? sharedWindowContext->directContext() : nullptr;
530 if (grDirectContext)
531 return grDirectContext;
532 SAL_WARN_IF(renderMethodToUse() == RenderVulkan, "vcl.skia",
533 "Cannot create Vulkan GPU context, falling back to Raster");
534 SAL_WARN_IF(renderMethodToUse() == RenderMetal, "vcl.skia",
535 "Cannot create Metal GPU context, falling back to Raster");
536 forceRasterRenderMethod();
537 return nullptr;
538 }
539
540 #if defined(SK_VULKAN) || defined(SK_METAL)
541 static std::unique_ptr<skwindow::WindowContext> getTemporaryWindowContext()
542 {
543 if (createGpuWindowContextFunction == nullptr)
544 return nullptr;
545 return createGpuWindowContextFunction(true);
546 }
547 #endif
548
549 static RenderMethod renderMethodToUseForSize(const SkISize& size)
550 {
551 // Do not use GPU for small surfaces. The problem is that due to the separate alpha hack
552 // we quite often may call GetBitmap() on VirtualDevice, which is relatively slow
553 // when the pixels need to be fetched from the GPU. And there are documents that use
554 // many tiny surfaces (bsc#1183308 for example), where this slowness adds up too much.
555 // This should be re-evaluated once the separate alpha hack is removed (SKIA_USE_BITMAP32)
556 // and we no longer (hopefully) fetch pixels that often.
557 if (size.width() <= 32 && size.height() <= 32)
558 return RenderRaster;
559 return renderMethodToUse();
560 }
561
562 sk_sp<SkSurface> createSkSurface(int width, int height, SkColorType type, SkAlphaType alpha)
563 {
564 SkiaZone zone;
565 assert(type == kN32_SkColorType || type == kAlpha_8_SkColorType);
566 sk_sp<SkSurface> surface;
567 switch (renderMethodToUseForSize({ width, height }))
568 {
569 case RenderVulkan:
570 case RenderMetal:
571 {
572 if (GrDirectContext* grDirectContext = getSharedGrDirectContext())
573 {
574 surface = SkSurfaces::RenderTarget(grDirectContext, skgpu::Budgeted::kNo,
575 SkImageInfo::Make(width, height, type, alpha), 0,
576 surfaceProps());
577 if (surface)
578 {
579 #ifdef DBG_UTIL
580 prefillSurface(surface);
581 #endif
582 return surface;
583 }
584 SAL_WARN_IF(renderMethodToUse() == RenderVulkan, "vcl.skia",
585 "Cannot create Vulkan GPU offscreen surface, falling back to Raster");
586 SAL_WARN_IF(renderMethodToUse() == RenderMetal, "vcl.skia",
587 "Cannot create Metal GPU offscreen surface, falling back to Raster");
588 }
589 break;
590 }
591 default:
592 break;
593 }
594 // Create raster surface as a fallback.
595 surface = SkSurfaces::Raster(SkImageInfo::Make(width, height, type, alpha), surfaceProps());
596 assert(surface);
597 if (surface)
598 {
599 #ifdef DBG_UTIL
600 prefillSurface(surface);
601 #endif
602 return surface;
603 }
604 // In non-debug builds we could return SkSurface::MakeNull() and try to cope with the situation,
605 // but that can lead to unnoticed data loss, so better fail clearly.
606 abort();
607 }
608
609 sk_sp<SkImage> createSkImage(const SkBitmap& bitmap)
610 {
611 SkiaZone zone;
612 assert(bitmap.colorType() == kN32_SkColorType || bitmap.colorType() == kAlpha_8_SkColorType);
613 switch (renderMethodToUseForSize(bitmap.dimensions()))
614 {
615 case RenderVulkan:
616 case RenderMetal:
617 {
618 if (GrDirectContext* grDirectContext = getSharedGrDirectContext())
619 {
620 sk_sp<SkSurface> surface = SkSurfaces::RenderTarget(
621 grDirectContext, skgpu::Budgeted::kNo,
622 bitmap.info().makeAlphaType(kPremul_SkAlphaType), 0, surfaceProps());
623 if (surface)
624 {
625 SkPaint paint;
626 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
627 surface->getCanvas()->drawImage(bitmap.asImage(), 0, 0, SkSamplingOptions(),
628 &paint);
629 return makeCheckedImageSnapshot(surface);
630 }
631 // Try to fall back in non-debug builds.
632 SAL_WARN_IF(renderMethodToUse() == RenderVulkan, "vcl.skia",
633 "Cannot create Vulkan GPU offscreen surface, falling back to Raster");
634 SAL_WARN_IF(renderMethodToUse() == RenderMetal, "vcl.skia",
635 "Cannot create Metal GPU offscreen surface, falling back to Raster");
636 }
637 break;
638 }
639 default:
640 break;
641 }
642 // Create raster image as a fallback.
643 sk_sp<SkImage> image = SkImages::RasterFromBitmap(bitmap);
644 assert(image);
645 return image;
646 }
647
648 sk_sp<SkImage> makeCheckedImageSnapshot(sk_sp<SkSurface> surface)
649 {
650 sk_sp<SkImage> ret = surface->makeImageSnapshot();
651 assert(ret);
652 if (ret)
653 return ret;
654 abort();
655 }
656
657 sk_sp<SkImage> makeCheckedImageSnapshot(sk_sp<SkSurface> surface, const SkIRect& bounds)
658 {
659 sk_sp<SkImage> ret = surface->makeImageSnapshot(bounds);
660 assert(ret);
661 if (ret)
662 return ret;
663 abort();
664 }
665
666 namespace
667 {
668 // Image cache, for saving results of complex operations such as drawTransformedBitmap().
669 struct ImageCacheItem
670 {
671 OString key;
672 sk_sp<SkImage> image;
673 tools::Long size; // cost of the item
674 long long keepInCacheUntilMilliseconds; // don't remove from cache before this timestamp
675 };
676 } //namespace
677
678 // LRU cache, last item is the least recently used. Hopefully there won't be that many items
679 // to require a hash/map. Using o3tl::lru_map would be simpler, but it doesn't support
680 // calculating cost of each item.
681 static std::list<ImageCacheItem> imageCache;
682 static tools::Long imageCacheSize = 0; // sum of all ImageCacheItem.size
683
684 // Related: tdf#166994 set the minimum amount of time that an image must
685 // remain in the image cache to 5 seconds. 2 seconds appears to be enough
686 // on macOS but set it to 5 seconds just to be safe.
687 const long long imageMinKeepInCacheMilliseconds = 5000;
688
689 void addCachedImage(const OString& key, sk_sp<SkImage> image)
690 {
691 static bool disabled = getenv("SAL_DISABLE_SKIA_CACHE") != nullptr;
692 if (disabled)
693 return;
694 tools::Long size = static_cast<tools::Long>(image->width()) * image->height()
695 * SkColorTypeBytesPerPixel(image->imageInfo().colorType());
696 auto time = std::chrono::steady_clock::now().time_since_epoch();
697 auto now = std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
698 imageCache.push_front({ key, image, size, now + imageMinKeepInCacheMilliseconds });
699 imageCacheSize += size;
700 SAL_INFO("vcl.skia.trace", "addcachedimage " << image << " :" << size << "/" << imageCacheSize);
701 const tools::Long maxSize = maxImageCacheSize();
702 while (imageCacheSize > maxSize)
703 {
704 assert(!imageCache.empty());
705
706 // tdf#166994 Don't remove image from cache too quickly
707 // While an animation is running, the same images are drawn in a
708 // repeating cycle but each frame is removed from the cache before
709 // it is drawn again.
710 // Blending a bitmap with an alpha channel can be very slow so
711 // it is much faster to keep all of the frames in the image cache.
712 // So, allow the image cache to temporarily increase in size by
713 // deferring removal of an image if it was cached within the last
714 // few seconds.
715 if (now < imageCache.back().keepInCacheUntilMilliseconds)
716 break;
717
718 imageCacheSize -= imageCache.back().size;
719 SAL_INFO("vcl.skia.trace",
720 "least used removal " << imageCache.back().image << ":" << imageCache.back().size);
721 imageCache.pop_back();
722 }
723 }
724
725 sk_sp<SkImage> findCachedImage(const OString& key)
726 {
727 for (auto it = imageCache.begin(); it != imageCache.end(); ++it)
728 {
729 if (it->key == key)
730 {
731 auto time = std::chrono::steady_clock::now().time_since_epoch();
732 auto now = std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
733 it->keepInCacheUntilMilliseconds = now + imageMinKeepInCacheMilliseconds;
734 sk_sp<SkImage> ret = it->image;
735 SAL_INFO("vcl.skia.trace", "findcachedimage " << key << " : " << it->image << " found");
736 imageCache.splice(imageCache.begin(), imageCache, it);
737 return ret;
738 }
739 }
740 SAL_INFO("vcl.skia.trace", "findcachedimage " << key << " not found");
741 return nullptr;
742 }
743
744 void removeCachedImage(sk_sp<SkImage> image)
745 {
746 for (auto it = imageCache.begin(); it != imageCache.end();)
747 {
748 if (it->image == image)
749 {
750 imageCacheSize -= it->size;
751 assert(imageCacheSize >= 0);
752 it = imageCache.erase(it);
753 }
754 else
755 ++it;
756 }
757 }
758
759 tools::Long maxImageCacheSize()
760 {
761 // Defaults to 4x 2000px 32bpp images, 64MiB.
762 return officecfg::Office::Common::Cache::Skia::ImageCacheSize::get();
763 }
764
765 static o3tl::lru_map<uint32_t, uint32_t> checksumCache(256);
766
767 static uint32_t computeSkPixmapChecksum(const SkPixmap& pixmap)
768 {
769 // Use uint32_t because that's what SkChecksum::Hash32() returns.
770 static_assert(std::is_same_v<uint32_t, decltype(SkChecksum::Hash32(nullptr, 0, 0))>);
771 const size_t dataRowBytes = pixmap.width() << pixmap.shiftPerPixel();
772 if (dataRowBytes == pixmap.rowBytes())
773 return SkChecksum::Hash32(pixmap.addr(), pixmap.height() * dataRowBytes, 0);
774 uint32_t sum = 0;
775 for (int row = 0; row < pixmap.height(); ++row)
776 sum = SkChecksum::Hash32(pixmap.addr(0, row), dataRowBytes, sum);
777 return sum;
778 }
779
780 uint32_t getSkImageChecksum(sk_sp<SkImage> image)
781 {
782 // Cache the checksums based on the uniqueID() (which should stay the same
783 // for the same image), because it may be still somewhat expensive.
784 uint32_t id = image->uniqueID();
785 auto it = checksumCache.find(id);
786 if (it != checksumCache.end())
787 return it->second;
788 SkPixmap pixmap;
789 if (!image->peekPixels(&pixmap))
790 abort(); // Fetching of GPU-based pixels is expensive, and shouldn't(?) be needed anyway.
791 uint32_t checksum = computeSkPixmapChecksum(pixmap);
792 checksumCache.insert({ id, checksum });
793 return checksum;
794 }
795
796 static sk_sp<SkBlender> invertBlender;
797 static sk_sp<SkBlender> xorBlender;
798
799 // This does the invert operation, i.e. result = color(255-R,255-G,255-B,A).
800 void setBlenderInvert(SkPaint* paint)
801 {
802 if (!invertBlender)
803 {
804 // Note that the colors are premultiplied, so '1 - dst.r' must be
805 // written as 'dst.a - dst.r', since premultiplied R is in the range (0-A).
806 const char* const diff = R"(
807 vec4 main( vec4 src, vec4 dst )
808 {
809 return vec4( dst.a - dst.r, dst.a - dst.g, dst.a - dst.b, dst.a );
810 }
811 )";
812 auto effect = SkRuntimeEffect::MakeForBlender(SkString(diff));
813 if (!effect.effect)
814 {
815 SAL_WARN("vcl.skia",
816 "SKRuntimeEffect::MakeForBlender failed: " << effect.errorText.c_str());
817 abort();
818 }
819 invertBlender = effect.effect->makeBlender(nullptr);
820 }
821 paint->setBlender(invertBlender);
822 }
823
824 // This does the xor operation, i.e. bitwise xor of RGB values of both colors.
825 void setBlenderXor(SkPaint* paint)
826 {
827 if (!xorBlender)
828 {
829 // Note that the colors are premultiplied, converting to 0-255 range
830 // must also unpremultiply.
831 const char* const diff = R"(
832 vec4 main( vec4 src, vec4 dst )
833 {
834 return vec4(
835 float(int(src.r * src.a * 255.0) ^ int(dst.r * dst.a * 255.0)) / 255.0 / dst.a,
836 float(int(src.g * src.a * 255.0) ^ int(dst.g * dst.a * 255.0)) / 255.0 / dst.a,
837 float(int(src.b * src.a * 255.0) ^ int(dst.b * dst.a * 255.0)) / 255.0 / dst.a,
838 dst.a );
839 }
840 )";
841 SkRuntimeEffect::Options opts;
842 // Skia does not allow binary operators in the default ES2Strict mode, but that's only
843 // because of OpenGL support. We don't use OpenGL, and it's safe for all modes that we do use.
844 // https://groups.google.com/g/skia-discuss/c/EPLuQbg64Kc/m/2uDXFIGhAwAJ
845 opts.maxVersionAllowed = SkSL::Version::k300;
846 auto effect = SkRuntimeEffect::MakeForBlender(SkString(diff), opts);
847 if (!effect.effect)
848 {
849 SAL_WARN("vcl.skia",
850 "SKRuntimeEffect::MakeForBlender failed: " << effect.errorText.c_str());
851 abort();
852 }
853 xorBlender = effect.effect->makeBlender(nullptr);
854 }
855 paint->setBlender(xorBlender);
856 }
857
858 void cleanup()
859 {
860 sharedWindowContext.reset();
861 imageCache.clear();
862 imageCacheSize = 0;
863 invertBlender.reset();
864 xorBlender.reset();
865 }
866
867 static SkSurfaceProps commonSurfaceProps;
868 const SkSurfaceProps* surfaceProps() { return &commonSurfaceProps; }
869
870 void setPixelGeometry(SkPixelGeometry pixelGeometry)
871 {
872 commonSurfaceProps = SkSurfaceProps(commonSurfaceProps.flags(), pixelGeometry);
873 }
874
875 // Skia should not be used from VCL backends that do not actually support it, as there will be setup missing.
876 // The code here (that is in the vcl lib) needs a function for creating Vulkan/Metal context that is
877 // usually available only in the backend libs.
878 void prepareSkia(std::unique_ptr<skwindow::WindowContext> (*createGpuWindowContext)(bool))
879 {
880 setCreateGpuWindowContext(createGpuWindowContext);
881 skiaSupportedByBackend = true;
882 }
883
884 void dump(const SkBitmap& bitmap, const char* file)
885 {
886 dump(SkImages::RasterFromBitmap(bitmap), file);
887 }
888
889 void dump(const sk_sp<SkSurface>& surface, const char* file)
890 {
891 if (auto dContext = GrAsDirectContext(surface->getCanvas()->recordingContext()))
892 dContext->flushAndSubmit();
893 dump(makeCheckedImageSnapshot(surface), file);
894 }
895
896 void dump(const sk_sp<SkImage>& image, const char* file)
897 {
898 SkBitmap bm;
899 if (!as_IB(image)->getROPixels(getSharedGrDirectContext(), &bm))
900 return;
901 SkPixmap pixmap;
902 if (!bm.peekPixels(&pixmap))
903 return;
904 SkPngEncoder::Options opts;
905 opts.fFilterFlags = SkPngEncoder::FilterFlag::kNone;
906 opts.fZLibLevel = 1;
907 SkDynamicMemoryWStream stream;
908 if (!SkPngEncoder::Encode(&stream, pixmap, opts))
909 return;
910 sk_sp<SkData> data = stream.detachAsData();
911 std::ofstream ostream(file, std::ios::binary);
912 ostream.write(static_cast<const char*>(data->data()), data->size());
913 }
914
915 #ifdef DBG_UTIL
916 void prefillSurface(const sk_sp<SkSurface>& surface)
917 {
918 // Pre-fill the surface with deterministic garbage.
919 SkBitmap bitmap;
920 bitmap.allocN32Pixels(2, 2);
921 SkPMColor* scanline;
922 scanline = bitmap.getAddr32(0, 0);
923 *scanline++ = SkPreMultiplyARGB(0xFF, 0xBF, 0x80, 0x40);
924 *scanline++ = SkPreMultiplyARGB(0xFF, 0x40, 0x80, 0xBF);
925 scanline = bitmap.getAddr32(0, 1);
926 *scanline++ = SkPreMultiplyARGB(0xFF, 0xE3, 0x5C, 0x13);
927 *scanline++ = SkPreMultiplyARGB(0xFF, 0x13, 0x5C, 0xE3);
928 bitmap.setImmutable();
929 SkPaint paint;
930 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
931 paint.setShader(
932 bitmap.makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, SkSamplingOptions()));
933 surface->getCanvas()->drawPaint(paint);
934 }
935 #endif
936
937 } // namespace
938
939 #endif // HAVE_FEATURE_SKIA
940
941 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */