File: WebCodecsVideoFrameAlgorithms.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (329 lines) | stat: -rw-r--r-- 12,967 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
/*
 * Copyright (C) 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. 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 "WebCodecsVideoFrameAlgorithms.h"

#if ENABLE(WEB_CODECS)

#include "DOMRectReadOnly.h"
#include "ExceptionOr.h"
#include "VideoColorSpace.h"

namespace WebCore {

// https://w3c.github.io/webcodecs/#valid-videoframebufferinit
bool isValidVideoFrameBufferInit(const WebCodecsVideoFrame::BufferInit& init)
{
    if (!init.codedWidth || !init.codedHeight)
        return false;

    if (init.visibleRect) {
        if (init.visibleRect->x < 0 || init.visibleRect->y < 0 || init.visibleRect->width < 0 || init.visibleRect->height < 0)
            return false;
        if (!std::isfinite(init.visibleRect->x) || !std::isfinite(init.visibleRect->y) || !std::isfinite(init.visibleRect->width) || !std::isfinite(init.visibleRect->height))
            return false;

        if (init.visibleRect->y + init.visibleRect->height > init.codedHeight)
            return false;

        if (init.visibleRect->x + init.visibleRect->width > init.codedWidth)
            return false;
    }

    if (init.displayWidth && !init.displayWidth)
        return false;
    if (init.displayHeight && !init.displayHeight)
        return false;
    return true;
}

static bool isMultiple(double value, unsigned factor)
{
     return !(static_cast<unsigned>(value) % factor);
}

// https://w3c.github.io/webcodecs/#videoframe-verify-rect-offset-alignment
bool verifyRectOffsetAlignment(VideoPixelFormat format, const DOMRectInit& rect)
{
    switch (format) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I420A:
    case VideoPixelFormat::I422:
    case VideoPixelFormat::NV12:
        return isMultiple(rect.x, 2) && isMultiple(rect.y, 2);
    case VideoPixelFormat::I444:
    case VideoPixelFormat::RGBA:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRA:
    case VideoPixelFormat::BGRX:
        return true;
    }
    return false;
}

// https://w3c.github.io/webcodecs/#videoframe-verify-rect-size-alignment
bool verifyRectSizeAlignment(VideoPixelFormat format, const DOMRectInit& rect)
{
    switch (format) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I420A:
        return !(static_cast<unsigned>(rect.width) % 2) && !(static_cast<unsigned>(rect.height) % 2);
    case VideoPixelFormat::I422:
        return !(static_cast<unsigned>(rect.width) % 2) && !(static_cast<unsigned>(rect.height) % 2);
    case VideoPixelFormat::I444:
        return true;
    case VideoPixelFormat::NV12:
        return !(static_cast<unsigned>(rect.width) % 2) && !(static_cast<unsigned>(rect.height) % 2);
    case VideoPixelFormat::RGBA:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRA:
    case VideoPixelFormat::BGRX:
        return true;
    }
    return false;
}

// https://w3c.github.io/webcodecs/#videoframe-parse-visible-rect
ExceptionOr<DOMRectInit> parseVisibleRect(const DOMRectInit& defaultRect, const std::optional<DOMRectInit>& overrideRect, size_t codedWidth, size_t codedHeight, VideoPixelFormat format)
{
    auto sourceRect = defaultRect;
    if (overrideRect) {
        if (!overrideRect->width || !overrideRect->height)
            return Exception { TypeError, "overrideRect is not valid"_s };
        if (overrideRect->x + overrideRect->width > codedWidth)
            return Exception { TypeError, "overrideRect is not valid"_s };
        if (overrideRect->y + overrideRect->height > codedHeight)
            return Exception { TypeError, "overrideRect is not valid"_s };
        sourceRect = *overrideRect;
    }
    if (!verifyRectOffsetAlignment(format, sourceRect))
        return Exception { TypeError, "offset alignment is invalid"_s };
    return sourceRect;
}

size_t videoPixelFormatToPlaneCount(VideoPixelFormat format)
{
    switch (format) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I444:
    case VideoPixelFormat::I422:
        return 3;
    case VideoPixelFormat::I420A:
        return 4;
    case VideoPixelFormat::NV12:
        return 2;
    case VideoPixelFormat::RGBA:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRA:
    case VideoPixelFormat::BGRX:
        return 1;
    }
    return 1;
}

size_t videoPixelFormatToSampleByteSizePerPlane()
{
    return 1;
}

static inline size_t sampleCountPerPixel(VideoPixelFormat format, size_t planeNumber)
{
    switch (format) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I420A:
    case VideoPixelFormat::I444:
    case VideoPixelFormat::I422:
        return 1;
    case VideoPixelFormat::NV12:
        return planeNumber ? 2 : 1;
    case VideoPixelFormat::RGBA:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRA:
    case VideoPixelFormat::BGRX:
        return 4;
    }
    return 1;
}

size_t videoPixelFormatToSubSampling(VideoPixelFormat format, size_t planeNumber)
{
    switch (format) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I444:
    case VideoPixelFormat::I422:
    case VideoPixelFormat::NV12:
        return planeNumber ? 2 : 1;
    case VideoPixelFormat::I420A:
        return (planeNumber == 1 || planeNumber == 2) ? 2 : 1;
    case VideoPixelFormat::RGBA:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRA:
    case VideoPixelFormat::BGRX:
        return 1;
    }
    return 1;
}

// https://w3c.github.io/webcodecs/#videoframe-compute-layout-and-allocation-size
ExceptionOr<CombinedPlaneLayout> computeLayoutAndAllocationSize(const DOMRectInit& parsedRect, const std::optional<Vector<PlaneLayout>>& layout, VideoPixelFormat format)
{
    auto planeCount = videoPixelFormatToPlaneCount(format);
    if (layout && layout->size() != planeCount)
        return Exception { TypeError, "layout size is invalid"_s };

    size_t minAllocationSize = 0;
    Vector<ComputedPlaneLayout> computedLayouts;
    computedLayouts.reserveInitialCapacity(planeCount);
    Vector<size_t> endOffsets;
    endOffsets.reserveInitialCapacity(planeCount);
    for (size_t i = 0; i < planeCount; ++i) {
        size_t pixelSampleCount = sampleCountPerPixel(format, i);

        auto sampleBytes = videoPixelFormatToSampleByteSizePerPlane();
        auto sampleWidth = videoPixelFormatToSubSampling(format, i);
        auto sampleHeight = videoPixelFormatToSubSampling(format, i);
        auto sampleWidthBytes = sampleWidth * sampleBytes;

        ComputedPlaneLayout computedLayout;
        computedLayout.sourceTop = parsedRect.y / sampleHeight;
        computedLayout.sourceHeight = parsedRect.height / sampleHeight;
        computedLayout.sourceLeftBytes = pixelSampleCount * parsedRect.x / sampleWidthBytes;
        computedLayout.sourceWidthBytes = pixelSampleCount * parsedRect.width / sampleWidthBytes;

        if (layout) {
            if (layout.value()[i].stride < computedLayout.sourceWidthBytes)
                return Exception { TypeError, "layout stride is invalid"_s };

            computedLayout.destinationOffset = layout.value()[i].offset;
            computedLayout.destinationStride = layout.value()[i].stride;
        } else {
            computedLayout.destinationOffset = minAllocationSize;
            computedLayout.destinationStride = computedLayout.sourceWidthBytes;
        }

        size_t planeSize, planeEnd;
        if (!WTF::safeMultiply(computedLayout.destinationStride, computedLayout.sourceHeight, planeSize) || planeSize > std::numeric_limits<uint32_t>::max())
            return Exception { TypeError, "planeSize is too big"_s };

        if (!WTF::safeAdd(planeSize, computedLayout.destinationOffset, planeEnd) || planeEnd > std::numeric_limits<uint32_t>::max())
            return Exception { TypeError, "planeEnd is too big"_s };

        endOffsets.uncheckedAppend(planeEnd);
        minAllocationSize = std::max(minAllocationSize, planeEnd);

        for (size_t j = 1; j < i; ++j) {
            if (planeEnd > computedLayouts[j].destinationOffset && endOffsets[j] > computedLayout.destinationOffset)
                return Exception { TypeError, "planes are overlapping"_s };
        }

        computedLayouts.uncheckedAppend(computedLayout);
    }

    return CombinedPlaneLayout { minAllocationSize, WTFMove(computedLayouts) };
}

// https://w3c.github.io/webcodecs/#videoframe-parse-videoframecopytooptions
ExceptionOr<CombinedPlaneLayout> parseVideoFrameCopyToOptions(const WebCodecsVideoFrame& frame, const WebCodecsVideoFrame::CopyToOptions& options)
{
    ASSERT(!frame.isDetached());
    ASSERT(frame.format());

    if (options.rect && !verifyRectSizeAlignment(*frame.format(), *options.rect))
        return Exception { TypeError, "rect size alignment is invalid"_s };

    auto& visibleRect = *frame.visibleRect();
    auto parsedRect = parseVisibleRect({ visibleRect.x(), visibleRect.y(), visibleRect.width(), visibleRect.height() }, options.rect, frame.codedWidth(), frame.codedHeight(), *frame.format());

    if (parsedRect.hasException())
        return parsedRect.releaseException();

    return computeLayoutAndAllocationSize(parsedRect.returnValue(), options.layout, *frame.format());
}

// https://w3c.github.io/webcodecs/#videoframe-initialize-visible-rect-and-display-size
void initializeVisibleRectAndDisplaySize(WebCodecsVideoFrame& frame, const WebCodecsVideoFrame::Init& init, const DOMRectInit& defaultVisibleRect, size_t defaultDisplayWidth, size_t defaultDisplayHeight)
{
    auto visibleRect = init.visibleRect.value_or(defaultVisibleRect);
    frame.setVisibleRect(visibleRect);
    if (init.displayWidth && init.displayHeight)
        frame.setDisplaySize(*init.displayWidth, *init.displayHeight);
    else {
        auto widthScale = defaultDisplayWidth / defaultVisibleRect.width;
        auto heightScale = defaultDisplayHeight / defaultVisibleRect.height;
        frame.setDisplaySize(visibleRect.width * widthScale, visibleRect.height * heightScale);
    }
}

// https://w3c.github.io/webcodecs/#videoframe-pick-color-space
VideoColorSpaceInit videoFramePickColorSpace(const std::optional<VideoColorSpaceInit>& overrideColorSpace, VideoPixelFormat format)
{
    if (overrideColorSpace)
        return *overrideColorSpace;

    if (isRGBVideoPixelFormat(format))
        return { PlatformVideoColorPrimaries::Bt709, PlatformVideoTransferCharacteristics::Iec6196621, PlatformVideoMatrixCoefficients::Rgb, true };

    return { PlatformVideoColorPrimaries::Bt709, PlatformVideoTransferCharacteristics::Bt709, PlatformVideoMatrixCoefficients::Bt709, false };
}

// https://w3c.github.io/webcodecs/#validate-videoframeinit
static bool isNegativeOrNonFinite(double value)
{
    return value < 0 || !std::isfinite(value);
}

bool validateVideoFrameInit(const WebCodecsVideoFrame::Init& init, size_t codedWidth, size_t codedHeight, VideoPixelFormat format)
{
    if (init.visibleRect) {
        auto& visibleRect = *init.visibleRect;
        if (!verifyRectOffsetAlignment(format, visibleRect))
            return false;

        if (isNegativeOrNonFinite(visibleRect.x) || isNegativeOrNonFinite(visibleRect.y) || isNegativeOrNonFinite(visibleRect.width) || isNegativeOrNonFinite(visibleRect.height))
            return false;
        if (!visibleRect.width || !visibleRect.height)
            return false;

        if (visibleRect.y + visibleRect.height > codedHeight)
            return false;
        if (visibleRect.x + visibleRect.width > codedWidth)
            return false;
    }

    if (!codedWidth || !codedHeight)
        return false;

    if (!!init.displayWidth != !!init.displayHeight)
        return false;
    if (init.displayWidth && (!*init.displayWidth || !*init.displayHeight))
        return false;

    return true;
}

} // namespace WebCore

#endif // ENABLE(WEB_CODECS)