File: RemoteResourceCacheProxy.cpp

package info (click to toggle)
webkit2gtk 2.51.4-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 481,584 kB
  • sloc: cpp: 3,903,132; javascript: 198,251; ansic: 165,758; python: 51,432; asm: 21,819; ruby: 18,095; perl: 16,963; xml: 4,623; sh: 2,408; yacc: 2,356; java: 2,019; lex: 1,358; pascal: 372; makefile: 203
file content (361 lines) | stat: -rw-r--r-- 14,343 bytes parent folder | download
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
/*
 * Copyright (C) 2020-2023 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. AND ITS CONTRIBUTORS ``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 ITS 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 "RemoteResourceCacheProxy.h"

#if ENABLE(GPU_PROCESS)

#include "ArgumentCoders.h"
#include "Logging.h"
#include "RemoteImageBufferProxy.h"
#include "RemoteNativeImageProxy.h"
#include "RemoteRenderingBackendProxy.h"
#include "WebProcess.h"
#include <WebCore/FontCustomPlatformData.h>
#include <wtf/TZoneMallocInlines.h>

namespace WebKit {
using namespace WebCore;

namespace {
struct CreateShareableBitmapResult {
    Ref<ShareableBitmap> bitmap;
    PlatformImagePtr platformImage;
};
}

static std::optional<CreateShareableBitmapResult> createShareableBitmapForNativeImage(NativeImage& image, const DestinationColorSpace& fallbackColorSpace)
{
    RefPtr<ShareableBitmap> bitmap;
    PlatformImagePtr platformImage;
#if USE(CG)
    bitmap = ShareableBitmap::createFromImagePixels(image);
    if (bitmap)
        platformImage = bitmap->createPlatformImage(DontCopyBackingStore, ShouldInterpolate::Yes);
#endif

    // If we failed to create ShareableBitmap or PlatformImage, fall back to image-draw method.
    if (!platformImage) {
        bitmap = ShareableBitmap::createFromImageDraw(image, fallbackColorSpace);
        if (bitmap)
            platformImage = bitmap->createPlatformImage(DontCopyBackingStore, ShouldInterpolate::Yes);

        // If createGraphicsContext() failed because the image fallbackColorSpace is not
        // supported for output, fallback to SRGB.
        if (!platformImage) {
            bitmap = ShareableBitmap::createFromImageDraw(image, DestinationColorSpace::SRGB());
            if (bitmap)
                platformImage = bitmap->createPlatformImage(DontCopyBackingStore, ShouldInterpolate::Yes);
        }
    }
    if (!platformImage)
        return std::nullopt;
    return CreateShareableBitmapResult { bitmap.releaseNonNull(), WTFMove(platformImage) };
}

WTF_MAKE_TZONE_ALLOCATED_IMPL(RemoteResourceCacheProxy);

UniqueRef<RemoteResourceCacheProxy> RemoteResourceCacheProxy::create(RemoteRenderingBackendProxy& remoteRenderingBackendProxy)
{
    return UniqueRef<RemoteResourceCacheProxy> { *new RemoteResourceCacheProxy(remoteRenderingBackendProxy) };
}

RemoteResourceCacheProxy::RemoteResourceCacheProxy(RemoteRenderingBackendProxy& remoteRenderingBackendProxy)
    : m_remoteRenderingBackendProxy(remoteRenderingBackendProxy)
{
}

RemoteResourceCacheProxy::~RemoteResourceCacheProxy() = default;

Ref<RemoteNativeImageProxy> RemoteResourceCacheProxy::createNativeImage(const IntSize& size, PlatformColorSpace&& colorSpace, bool hasAlpha)
{
    WeakRef weakThis = m_remoteNativeImageProxyWeakFactory.createWeakPtr(*this).releaseNonNull();
    Ref nativeImage = RemoteNativeImageProxy::create(size, WTFMove(colorSpace), hasAlpha, WTFMove(weakThis));
    m_nativeImages.add(nativeImage.ptr(), NativeImageEntry { nullptr, true });
    return nativeImage;
}

RemoteGradientIdentifier RemoteResourceCacheProxy::recordGradientUse(Gradient& gradient)
{
    auto result = m_gradients.ensure(&gradient, [] {
        return RemoteGradientIdentifier::generate();
    });
    auto identifier = result.iterator->value;
    if (result.isNewEntry) {
        gradient.addObserver(m_resourceObserverWeakFactory.createWeakPtr(static_cast<RenderingResourceObserver&>(*this)).releaseNonNull());
        m_remoteRenderingBackendProxy->cacheGradient(gradient, identifier);
    }
    return identifier;
}

void RemoteResourceCacheProxy::recordFilterUse(Filter& filter)
{
    if (m_filters.add(filter.renderingResourceIdentifier()).isNewEntry) {
        filter.addObserver(m_resourceObserverWeakFactory.createWeakPtr(static_cast<RenderingResourceObserver&>(*this)).releaseNonNull());
        m_remoteRenderingBackendProxy->cacheFilter(filter);
    }
}

bool RemoteResourceCacheProxy::recordNativeImageUse(NativeImage& image, const DestinationColorSpace& fallbackColorSpace)
{
    if (isMainRunLoop())
        WebProcess::singleton().deferNonVisibleProcessEarlyMemoryCleanupTimer();
    std::optional<ShareableBitmap::Handle> handle;
    auto entry = m_nativeImages.find(&image);
    if (entry != m_nativeImages.end()) {
        if (entry->value.existsInRemote)
            return true;
        if (!entry->value.bitmap)
            return false;
        handle = RefPtr { entry->value.bitmap }->createHandle();
        if (handle)
            entry->value.existsInRemote = true;
    } else {
        auto result = createShareableBitmapForNativeImage(image, fallbackColorSpace);
        if (result) {
            Ref bitmap = WTFMove(result->bitmap);
            PlatformImagePtr platformImage = WTFMove(result->platformImage);
            handle = bitmap->createHandle();
            if (handle) {
                handle->takeOwnershipOfMemory(MemoryLedger::Graphics);
                m_nativeImages.add(&image, NativeImageEntry { WTFMove(bitmap), true });
                // Set itself as an observer to NativeImage, so releaseNativeImage()
                // gets called when NativeImage is being deleted.
                image.addObserver(m_nativeImageResourceObserverWeakFactory.createWeakPtr(static_cast<RenderingResourceObserver&>(*this)).releaseNonNull());
                // Replace the contents of the original NativeImage to save memory.
                image.replacePlatformImage(WTFMove(platformImage));
            }
        }
    }
    if (!handle) {
        LOG_WITH_STREAM(Images, stream
            << "RemoteResourceCacheProxy::recordNativeImageUse() " << this
            << " image.size(): " << image.size()
            << " image.colorSpace(): " << image.colorSpace()
            << " ShareableBitmap could not be created; bailing.");
        return false;
    }
    m_remoteRenderingBackendProxy->cacheNativeImage(WTFMove(*handle), image.renderingResourceIdentifier());
    return true;
}

void RemoteResourceCacheProxy::recordFontUse(Font& font)
{
    if (RefPtr platformData = font.platformData().customPlatformData())
        recordFontCustomPlatformDataUse(*platformData);

    auto result = m_fonts.add(font.renderingResourceIdentifier(), m_renderingUpdateID);

    if (result.isNewEntry) {
        auto renderingResourceIdentifier = font.platformData().customPlatformData() ? std::optional(font.platformData().customPlatformData()->m_renderingResourceIdentifier) : std::nullopt;
        m_remoteRenderingBackendProxy->cacheFont(font.attributes(), font.platformData().attributes(), renderingResourceIdentifier);
        ++m_numberOfFontsUsedInCurrentRenderingUpdate;
        return;
    }

    auto& currentState = result.iterator->value;
    if (currentState != m_renderingUpdateID) {
        currentState = m_renderingUpdateID;
        ++m_numberOfFontsUsedInCurrentRenderingUpdate;
    }
}

void RemoteResourceCacheProxy::recordFontCustomPlatformDataUse(const FontCustomPlatformData& customPlatformData)
{
    auto result = m_fontCustomPlatformDatas.add(customPlatformData.m_renderingResourceIdentifier, m_renderingUpdateID);

    if (result.isNewEntry) {
        m_remoteRenderingBackendProxy->cacheFontCustomPlatformData(customPlatformData);
        ++m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate;
        return;
    }

    auto& currentState = result.iterator->value;
    if (currentState != m_renderingUpdateID) {
        currentState = m_renderingUpdateID;
        ++m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate;
    }
}

RemoteDisplayListIdentifier RemoteResourceCacheProxy::recordDisplayListUse(const DisplayList::DisplayList& displayList)
{
    auto result = m_displayLists.ensure(&displayList, [] {
        return RemoteDisplayListIdentifier::generate();
    });
    auto identifier = result.iterator->value; // Stash the identifier since the next call will recurse.
    if (result.isNewEntry) {
        displayList.addObserver(m_resourceObserverWeakFactory.createWeakPtr(static_cast<RenderingResourceObserver&>(*this)).releaseNonNull());
        // Note: this might recurse back to RemoteResourceCacheProxy::recordDisplayListUse().
        // thus we must ensure that we are not in m_displayLists.ensure.. call stack.
        m_remoteRenderingBackendProxy->cacheDisplayList(identifier, displayList);
        // result.iterator is not valid anymore.
    }
    return identifier;
}

void RemoteResourceCacheProxy::willDestroyNativeImage(const NativeImage& image)
{
    auto entry = m_nativeImages.takeOptional(&image);
    RELEASE_ASSERT(entry);
    if (!entry->existsInRemote)
        return;
    m_remoteRenderingBackendProxy->releaseNativeImage(image.renderingResourceIdentifier());
}

void RemoteResourceCacheProxy::willDestroyRemoteNativeImageProxy(const RemoteNativeImageProxy& image)
{
    willDestroyNativeImage(image);
}

PlatformImagePtr RemoteResourceCacheProxy::platformImage(const RemoteNativeImageProxy& image)
{
    auto it = m_nativeImages.find(&image);
    RELEASE_ASSERT(it != m_nativeImages.end());
    auto& entry = it->value;
    if (!entry.existsInRemote)
        return nullptr;
    if (!entry.bitmap) {
        auto bitmap = m_remoteRenderingBackendProxy->nativeImageBitmap(image);
        if (!bitmap)
            return nullptr;
        entry.bitmap = WTFMove(bitmap);
    }
    return RefPtr { entry.bitmap }->createPlatformImage();
}

void RemoteResourceCacheProxy::willDestroyGradient(const Gradient& gradient)
{
    auto identifier = m_gradients.take(&gradient);
    RELEASE_ASSERT(identifier);
    m_remoteRenderingBackendProxy->releaseGradient(*identifier);
}

void RemoteResourceCacheProxy::willDestroyFilter(RenderingResourceIdentifier identifier)
{
    bool removed = m_filters.remove(identifier);
    RELEASE_ASSERT(removed);
    m_remoteRenderingBackendProxy->releaseFilter(identifier);
}

void RemoteResourceCacheProxy::willDestroyDisplayList(const DisplayList::DisplayList& displayList)
{
    auto identifier = m_displayLists.take(&displayList);
    RELEASE_ASSERT(identifier);
    m_remoteRenderingBackendProxy->releaseDisplayList(*identifier);
}

void RemoteResourceCacheProxy::prepareForNextRenderingUpdate()
{
    m_numberOfFontsUsedInCurrentRenderingUpdate = 0;
    m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate = 0;
}

void RemoteResourceCacheProxy::releaseFonts()
{
    m_fonts.clear();
    m_numberOfFontsUsedInCurrentRenderingUpdate = 0;
}

void RemoteResourceCacheProxy::releaseFontCustomPlatformDatas()
{
    m_fontCustomPlatformDatas.clear();
    m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate = 0;
}

void RemoteResourceCacheProxy::finalizeRenderingUpdateForFonts()
{
    static constexpr unsigned minimumRenderingUpdateCountToKeepFontAlive = 4;

    unsigned totalFontCount = m_fonts.size();
    RELEASE_ASSERT(m_numberOfFontsUsedInCurrentRenderingUpdate <= totalFontCount);
    if (totalFontCount != m_numberOfFontsUsedInCurrentRenderingUpdate) {
        HashSet<WebCore::RenderingResourceIdentifier> toRemove;
        auto renderingUpdateID = m_renderingUpdateID;
        for (auto& item : m_fonts) {
            if (renderingUpdateID - item.value >= minimumRenderingUpdateCountToKeepFontAlive) {
                toRemove.add(item.key);
                m_remoteRenderingBackendProxy->releaseFont(item.key);
            }
        }

        m_fonts.removeIf([&](const auto& bucket) {
            return toRemove.contains(bucket.key);
        });
    }

    totalFontCount = m_fontCustomPlatformDatas.size();
    RELEASE_ASSERT(m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate <= totalFontCount);
    if (totalFontCount != m_numberOfFontCustomPlatformDatasUsedInCurrentRenderingUpdate) {
        HashSet<WebCore::RenderingResourceIdentifier> toRemove;
        auto renderingUpdateID = m_renderingUpdateID;
        for (auto& item : m_fontCustomPlatformDatas) {
            if (renderingUpdateID - item.value >= minimumRenderingUpdateCountToKeepFontAlive) {
                toRemove.add(item.key);
                m_remoteRenderingBackendProxy->releaseFontCustomPlatformData(item.key);
            }
        }

        m_fontCustomPlatformDatas.removeIf([&](const auto& bucket) {
            return toRemove.contains(bucket.key);
        });
    }
}

void RemoteResourceCacheProxy::didPaintLayers()
{
    finalizeRenderingUpdateForFonts();
    prepareForNextRenderingUpdate();
    m_renderingUpdateID++;
}

void RemoteResourceCacheProxy::releaseMemory()
{
    // Release all resources that consume memory in GPUP.
    // Other resources should be released by releasing the resource object references.
    m_resourceObserverWeakFactory.revokeAll();
    m_filters.clear();
    m_gradients.clear();
    m_displayLists.clear();
    releaseFonts();
    releaseFontCustomPlatformDatas();
}

void RemoteResourceCacheProxy::disconnect()
{
    m_resourceObserverWeakFactory.revokeAll();
    m_filters.clear();
    m_gradients.clear();
    m_displayLists.clear();
    releaseFonts();
    releaseFontCustomPlatformDatas();

    for (auto& value : m_nativeImages.values())
        value.existsInRemote = false;
}

} // namespace WebKit

#endif // ENABLE(GPU_PROCESS)