File: ImageBuffer.cpp

package info (click to toggle)
wpewebkit 2.38.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 311,508 kB
  • sloc: cpp: 2,653,313; javascript: 289,013; ansic: 121,268; xml: 64,149; python: 35,534; ruby: 17,287; perl: 15,877; asm: 11,072; yacc: 2,326; sh: 1,863; lex: 1,319; java: 937; makefile: 146; pascal: 60
file content (494 lines) | stat: -rw-r--r-- 17,976 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
 * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2016-2022 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ImageBuffer.h"

#include "BitmapImage.h"
#include "Filter.h"
#include "FilterImage.h"
#include "FilterResults.h"
#include "GraphicsContext.h"
#include "HostWindow.h"
#include "MIMETypeRegistry.h"
#include "PlatformImageBuffer.h"
#include "ProcessCapabilities.h"
#include <wtf/text/Base64.h>

#if USE(CG)
#include "ImageBufferUtilitiesCG.h"
#endif
#if USE(CAIRO)
#include "ImageBufferUtilitiesCairo.h"
#endif

namespace WebCore {

static const float MaxClampedLength = 4096;
static const float MaxClampedArea = MaxClampedLength * MaxClampedLength;

RefPtr<ImageBuffer> ImageBuffer::create(const FloatSize& size, RenderingPurpose purpose, float resolutionScale, const DestinationColorSpace& colorSpace, PixelFormat pixelFormat, OptionSet<ImageBufferOptions> options, const CreationContext& creationContext)
{
    RefPtr<ImageBuffer> imageBuffer;

    // Give UseDisplayList a higher precedence since it is a debug option.
    if (options.contains(ImageBufferOptions::UseDisplayList)) {
        if (options.contains(ImageBufferOptions::Accelerated))
            imageBuffer = DisplayList::ImageBuffer::create<AcceleratedImageBufferBackend>(size, resolutionScale, colorSpace, pixelFormat, purpose, creationContext);

        if (!imageBuffer)
            imageBuffer = DisplayList::ImageBuffer::create<UnacceleratedImageBufferBackend>(size, resolutionScale, colorSpace, pixelFormat, purpose, creationContext);
    }

    if (creationContext.hostWindow && !imageBuffer) {
        auto renderingMode = options.contains(ImageBufferOptions::Accelerated) ? RenderingMode::Accelerated : RenderingMode::Unaccelerated;
        imageBuffer = creationContext.hostWindow->createImageBuffer(size, renderingMode, purpose, resolutionScale, colorSpace, pixelFormat, creationContext.avoidIOSurfaceSizeCheckInWebProcessForTesting);
    }

    if (imageBuffer)
        return imageBuffer;

    if (options.contains(ImageBufferOptions::Accelerated) && ProcessCapabilities::canUseAcceleratedBuffers()) {
#if HAVE(IOSURFACE)
        imageBuffer = IOSurfaceImageBuffer::create(size, resolutionScale, colorSpace, pixelFormat, purpose, creationContext);
#endif
    }

    if (!imageBuffer)
        imageBuffer = create<UnacceleratedImageBufferBackend>(size, resolutionScale, colorSpace, pixelFormat, purpose, creationContext);

    return imageBuffer;
}

ImageBuffer::ImageBuffer(const ImageBufferBackend::Parameters& parameters, const ImageBufferBackend::Info& backendInfo, std::unique_ptr<ImageBufferBackend>&& backend, RenderingResourceIdentifier renderingResourceIdentifier)
    : m_parameters(parameters)
    , m_backendInfo(backendInfo)
    , m_backend(WTFMove(backend))
    , m_renderingResourceIdentifier(renderingResourceIdentifier)
{
}

ImageBuffer::~ImageBuffer() = default;

bool ImageBuffer::sizeNeedsClamping(const FloatSize& size)
{
    if (size.isEmpty())
        return false;

    return floorf(size.height()) * floorf(size.width()) > MaxClampedArea;
}

bool ImageBuffer::sizeNeedsClamping(const FloatSize& size, FloatSize& scale)
{
    FloatSize scaledSize(size);
    scaledSize.scale(scale.width(), scale.height());

    if (!sizeNeedsClamping(scaledSize))
        return false;

    // The area of scaled size is bigger than the upper limit, adjust the scale to fit.
    scale.scale(sqrtf(MaxClampedArea / (scaledSize.width() * scaledSize.height())));
    ASSERT(!sizeNeedsClamping(size, scale));
    return true;
}

FloatSize ImageBuffer::clampedSize(const FloatSize& size)
{
    return size.shrunkTo(FloatSize(MaxClampedLength, MaxClampedLength));
}

FloatSize ImageBuffer::clampedSize(const FloatSize& size, FloatSize& scale)
{
    if (size.isEmpty())
        return size;

    FloatSize clampedSize = ImageBuffer::clampedSize(size);
    scale = clampedSize / size;
    ASSERT(!sizeNeedsClamping(clampedSize));
    ASSERT(!sizeNeedsClamping(size, scale));
    return clampedSize;
}

FloatRect ImageBuffer::clampedRect(const FloatRect& rect)
{
    return FloatRect(rect.location(), clampedSize(rect.size()));
}

static RefPtr<ImageBuffer> copyImageBuffer(Ref<ImageBuffer> source, PreserveResolution preserveResolution)
{
    if (source->resolutionScale() == 1 || preserveResolution == PreserveResolution::Yes) {
        if (source->hasOneRef())
            return source;
    }
    auto copySize = source->logicalSize();
    auto copyScale = preserveResolution == PreserveResolution::Yes ? source->resolutionScale() : 1.f;
    auto copyBuffer = source->context().createImageBuffer(copySize, copyScale, source->colorSpace());
    if (!copyBuffer)
        return nullptr;
    if (source->hasOneRef())
        ImageBuffer::drawConsuming(WTFMove(source), copyBuffer->context(), FloatRect { { }, copySize }, FloatRect { 0, 0, -1, -1 }, CompositeOperator::Copy);
    else
        copyBuffer->context().drawImageBuffer(source, FloatPoint { }, CompositeOperator::Copy);
    return copyBuffer;
}

static RefPtr<NativeImage> copyImageBufferToNativeImage(Ref<ImageBuffer> source, BackingStoreCopy copyBehavior, PreserveResolution preserveResolution)
{
    if (source->resolutionScale() == 1 || preserveResolution == PreserveResolution::Yes) {
        if (source->hasOneRef())
            return ImageBuffer::sinkIntoNativeImage(WTFMove(source));
        return source->copyNativeImage(copyBehavior);
    }
    auto copyBuffer = copyImageBuffer(WTFMove(source), preserveResolution);
    if (!copyBuffer)
        return nullptr;
    return ImageBuffer::sinkIntoNativeImage(WTFMove(copyBuffer));
}

static RefPtr<NativeImage> copyImageBufferToOpaqueNativeImage(Ref<ImageBuffer> source, PreserveResolution preserveResolution)
{
    // Composite this ImageBuffer on top of opaque black, because JPEG does not have an alpha channel.
    auto copyBuffer = copyImageBuffer(WTFMove(source), preserveResolution);
    if (!copyBuffer)
        return { };
    // We composite the copy on top of black by drawing black under the copy.
    copyBuffer->context().fillRect({ { }, copyBuffer->logicalSize() }, Color::black, CompositeOperator::DestinationOver);
    return ImageBuffer::sinkIntoNativeImage(WTFMove(copyBuffer));
}

RefPtr<ImageBuffer> ImageBuffer::clone() const
{
    return copyImageBuffer(const_cast<ImageBuffer&>(*this), PreserveResolution::Yes);
}

GraphicsContext& ImageBuffer::context() const
{
    ASSERT(m_backend);
    ASSERT(volatilityState() == VolatilityState::NonVolatile);
    return m_backend->context();
}

void ImageBuffer::flushContext()
{
    if (auto* backend = ensureBackendCreated()) {
        flushDrawingContext();
        backend->flushContext();
    }
}

void ImageBuffer::setBackend(std::unique_ptr<ImageBufferBackend>&& backend)
{
    ASSERT(!m_backend);
    m_backend = WTFMove(backend);
}

IntSize ImageBuffer::backendSize() const
{
    if (auto* backend = ensureBackendCreated())
        return backend->backendSize();
    return { };
}

RefPtr<NativeImage> ImageBuffer::copyNativeImage(BackingStoreCopy copyBehavior) const
{
    if (auto* backend = ensureBackendCreated()) {
        const_cast<ImageBuffer&>(*this).flushDrawingContext();
        return backend->copyNativeImage(copyBehavior);
    }
    return nullptr;
}

RefPtr<NativeImage> ImageBuffer::copyNativeImageForDrawing(BackingStoreCopy copyBehavior) const
{
    if (auto* backend = ensureBackendCreated()) {
        const_cast<ImageBuffer&>(*this).flushDrawingContext();
        return backend->copyNativeImageForDrawing(copyBehavior);
    }
    return nullptr;
}

RefPtr<NativeImage> ImageBuffer::sinkIntoNativeImage()
{
    if (auto* backend = ensureBackendCreated()) {
        flushDrawingContext();
        return backend->sinkIntoNativeImage();
    }
    return nullptr;
}

RefPtr<Image> ImageBuffer::filteredImage(Filter& filter)
{
    auto* backend = ensureBackendCreated();
    if (!backend)
        return nullptr;

    const_cast<ImageBuffer&>(*this).flushDrawingContext();

    FilterResults results;
    auto result = filter.apply(this, { { }, logicalSize() }, results);
    if (!result)
        return nullptr;

    auto imageBuffer = result->imageBuffer();
    if (!imageBuffer)
        return nullptr;

    return imageBuffer->copyImage();
}

#if USE(CAIRO)
RefPtr<cairo_surface_t> ImageBuffer::createCairoSurface()
{
    auto* backend = ensureBackendCreated();
    if (!backend)
        return nullptr;

    auto surface = backend->createCairoSurface();

    ref(); // Balanced by deref below.

    static cairo_user_data_key_t dataKey;
    cairo_surface_set_user_data(surface.get(), &dataKey, this, [](void *buffer) {
        static_cast<ImageBuffer*>(buffer)->deref();
    });

    return surface;
}
#endif

RefPtr<NativeImage> ImageBuffer::sinkIntoNativeImage(RefPtr<ImageBuffer> source)
{
    if (!source)
        return nullptr;
    return source->sinkIntoNativeImage();
}

RefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, PreserveResolution preserveResolution) const
{
    auto image = copyImageBufferToNativeImage(const_cast<ImageBuffer&>(*this), copyBehavior, preserveResolution);
    if (!image)
        return nullptr;
    return BitmapImage::create(image.releaseNonNull());
}

RefPtr<Image> ImageBuffer::sinkIntoImage(RefPtr<ImageBuffer> source, PreserveResolution preserveResolution)
{
    if (!source)
        return nullptr;
    RefPtr<NativeImage> image;
    if (source->resolutionScale() == 1 || preserveResolution == PreserveResolution::Yes)
        image = sinkIntoNativeImage(WTFMove(source));
    else {
        auto copyBuffer = source->context().createImageBuffer(source->logicalSize(), 1.f, source->colorSpace());
        if (!copyBuffer)
            return nullptr;
        copyBuffer->context().drawConsumingImageBuffer(WTFMove(source), FloatRect { { }, copyBuffer->logicalSize() }, CompositeOperator::Copy);
        image = ImageBuffer::sinkIntoNativeImage(WTFMove(copyBuffer));
    }
    if (!image)
        return nullptr;
    return BitmapImage::create(image.releaseNonNull());
}

void ImageBuffer::draw(GraphicsContext& destContext, const FloatRect& destRect, const FloatRect& srcRect, const ImagePaintingOptions& options)
{
    FloatRect srcRectScaled = srcRect;
    srcRectScaled.scale(resolutionScale());

    if (auto* backend = ensureBackendCreated()) {
        if (auto image = copyNativeImageForDrawing(&destContext == &context() ? CopyBackingStore : DontCopyBackingStore))
            destContext.drawNativeImage(*image, backendSize(), destRect, srcRectScaled, options);
        backend->finalizeDrawIntoContext(destContext);
    }
}

void ImageBuffer::drawPattern(GraphicsContext& destContext, const FloatRect& destRect, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize& spacing, const ImagePaintingOptions& options)
{
    FloatRect adjustedSrcRect = srcRect;
    adjustedSrcRect.scale(resolutionScale());

    if (ensureBackendCreated()) {
        if (auto image = copyImage(&destContext == &context() ? CopyBackingStore : DontCopyBackingStore))
            image->drawPattern(destContext, destRect, adjustedSrcRect, patternTransform, phase, spacing, options);
    }
}

void ImageBuffer::drawConsuming(GraphicsContext& destContext, const FloatRect& destRect, const FloatRect& srcRect, const ImagePaintingOptions& options)
{
    FloatRect adjustedSrcRect = srcRect;
    adjustedSrcRect.scale(resolutionScale());

    ASSERT(&destContext != &context());
    if (auto* backend = ensureBackendCreated()) {
        auto backendSize = backend->backendSize();
        if (auto image = sinkIntoNativeImage())
            destContext.drawNativeImage(*image, backendSize, destRect, adjustedSrcRect, options);
    }
}

void ImageBuffer::drawConsuming(RefPtr<ImageBuffer> imageBuffer, GraphicsContext& context, const FloatRect& destRect, const FloatRect& srcRect, const ImagePaintingOptions& options)
{
    imageBuffer->drawConsuming(context, destRect, srcRect, options);
}

void ImageBuffer::clipToMask(GraphicsContext& destContext, const FloatRect& destRect)
{
    if (auto* backend = ensureBackendCreated()) {
        flushContext();
        backend->clipToMask(destContext, destRect);
    }
}

void ImageBuffer::convertToLuminanceMask()
{
    if (auto* backend = ensureBackendCreated()) {
        flushContext();
        backend->convertToLuminanceMask();
    }
}

void ImageBuffer::transformToColorSpace(const DestinationColorSpace& newColorSpace)
{
    if (auto* backend = ensureBackendCreated()) {
        flushDrawingContext();
        backend->transformToColorSpace(newColorSpace);
        m_parameters.colorSpace = newColorSpace;
    }
}

String ImageBuffer::toDataURL(const String& mimeType, std::optional<double> quality, PreserveResolution preserveResolution) const
{
    return toDataURL(Ref { const_cast<ImageBuffer&>(*this) }, mimeType, quality, preserveResolution);
}

Vector<uint8_t> ImageBuffer::toData(const String& mimeType, std::optional<double> quality, PreserveResolution preserveResolution) const
{
    return toData(Ref { const_cast<ImageBuffer&>(*this) }, mimeType, quality, preserveResolution);
}

String ImageBuffer::toDataURL(Ref<ImageBuffer> source, const String& mimeType, std::optional<double> quality, PreserveResolution preserveResolution)
{
    auto encodedData = toData(WTFMove(source), mimeType, quality, preserveResolution);
    if (encodedData.isEmpty())
        return "data:,"_s;
    return makeString("data:", mimeType, ";base64,", base64Encoded(encodedData));
}

Vector<uint8_t> ImageBuffer::toData(Ref<ImageBuffer> source, const String& mimeType, std::optional<double> quality, PreserveResolution preserveResolution)
{
    RefPtr<NativeImage> image = MIMETypeRegistry::isJPEGMIMEType(mimeType) ? copyImageBufferToOpaqueNativeImage(WTFMove(source), preserveResolution) : copyImageBufferToNativeImage(WTFMove(source), DontCopyBackingStore, preserveResolution);
    if (!image)
        return { };
    return encodeData(image->platformImage().get(), mimeType, quality);
}

RefPtr<PixelBuffer> ImageBuffer::getPixelBuffer(const PixelBufferFormat& outputFormat, const IntRect& srcRect, const ImageBufferAllocator& allocator) const
{
    if (auto* backend = ensureBackendCreated()) {
        const_cast<ImageBuffer&>(*this).flushContext();
        return backend->getPixelBuffer(outputFormat, srcRect, allocator);
    }
    return nullptr;
}

void ImageBuffer::putPixelBuffer(const PixelBuffer& pixelBuffer, const IntRect& srcRect, const IntPoint& destPoint, AlphaPremultiplication destFormat)
{
    if (auto* backend = ensureBackendCreated()) {
        flushContext();
        backend->putPixelBuffer(pixelBuffer, srcRect, destPoint, destFormat);
    }
}

PlatformLayer* ImageBuffer::platformLayer() const
{
    if (auto* backend = ensureBackendCreated())
        return backend->platformLayer();
    return nullptr;
}

bool ImageBuffer::copyToPlatformTexture(GraphicsContextGL& context, GCGLenum target, PlatformGLObject destinationTexture, GCGLenum internalformat, bool premultiplyAlpha, bool flipY) const
{
    if (auto* backend = ensureBackendCreated())
        return backend->copyToPlatformTexture(context, target, destinationTexture, internalformat, premultiplyAlpha, flipY);
    return false;
}

bool ImageBuffer::isInUse() const
{
    if (auto* backend = ensureBackendCreated())
        return backend->isInUse();
    return false;
}

void ImageBuffer::releaseGraphicsContext()
{
    if (auto* backend = ensureBackendCreated())
        return backend->releaseGraphicsContext();
}

bool ImageBuffer::setVolatile()
{
    if (auto* backend = ensureBackendCreated())
        return backend->setVolatile();

    return true; // Just claim we succeedded.
}

SetNonVolatileResult ImageBuffer::setNonVolatile()
{
    if (auto* backend = ensureBackendCreated())
        return backend->setNonVolatile();
    return SetNonVolatileResult::Valid;
}

VolatilityState ImageBuffer::volatilityState() const
{
    if (auto* backend = ensureBackendCreated())
        return backend->volatilityState();
    return VolatilityState::NonVolatile;
}

void ImageBuffer::setVolatilityState(VolatilityState volatilityState)
{
    if (auto* backend = ensureBackendCreated())
        backend->setVolatilityState(volatilityState);
}

void ImageBuffer::clearContents()
{
    if (auto* backend = ensureBackendCreated())
        backend->clearContents();
}

std::unique_ptr<ThreadSafeImageBufferFlusher> ImageBuffer::createFlusher()
{
    if (auto* backend = ensureBackendCreated())
        return backend->createFlusher();
    return nullptr;
}

} // namespace WebCore