File: WebCodecsVideoFrame.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 (578 lines) | stat: -rw-r--r-- 25,442 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/*
 * 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 "WebCodecsVideoFrame.h"

#if ENABLE(WEB_CODECS)

#include "CSSStyleImageValue.h"
#include "CachedImage.h"
#include "DOMRectReadOnly.h"
#include "ExceptionOr.h"
#include "HTMLCanvasElement.h"
#include "HTMLImageElement.h"
#include "HTMLVideoElement.h"
#include "ImageBitmap.h"
#include "ImageBuffer.h"
#include "JSDOMPromiseDeferred.h"
#include "JSPlaneLayout.h"
#include "OffscreenCanvas.h"
#include "PixelBuffer.h"
#include "SVGImageElement.h"
#include "VideoColorSpace.h"
#include "WebCodecsVideoFrameAlgorithms.h"

#if PLATFORM(COCOA)
#include "VideoFrameCV.h"
#endif

#if USE(GSTREAMER)
#include "VideoFrameGStreamer.h"
#endif

namespace WebCore {

WebCodecsVideoFrame::WebCodecsVideoFrame(ScriptExecutionContext& context)
    : ContextDestructionObserver(&context)
{
}

WebCodecsVideoFrame::WebCodecsVideoFrame(ScriptExecutionContext& context, WebCodecsVideoFrameData&& data)
    : ContextDestructionObserver(&context)
    , m_data(WTFMove(data))
{
}

WebCodecsVideoFrame::~WebCodecsVideoFrame()
{
    if (m_isDetached)
        return;
    if (auto* context = scriptExecutionContext()) {
        context->postTask([](auto& context) {
            context.addConsoleMessage(MessageSource::JS, MessageLevel::Warning, "A VideoFrame was destroyed without having been closed explicitly"_s);
        });
    }
}

// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
static std::optional<Exception> checkImageUsability(ScriptExecutionContext& context, const WebCodecsVideoFrame::CanvasImageSource& source)
{
    return switchOn(source,
    [&] (const RefPtr<HTMLImageElement>& imageElement) -> std::optional<Exception> {
        if (!imageElement->originClean(*context.securityOrigin()))
            return Exception { SecurityError, "Image element is tainted"_s };

        auto* image = imageElement->cachedImage() ? imageElement->cachedImage()->image() : nullptr;
        if (!image)
            return Exception { InvalidStateError,  "Image element has no data"_s };
        if (!image->width() || !image->height())
            return Exception { InvalidStateError,  "Image element has a bad size"_s };
        return { };
    },
    [] (const RefPtr<SVGImageElement>& imageElement) -> std::optional<Exception> {
        if (imageElement->renderingTaintsOrigin())
            return Exception { SecurityError, "Image element is tainted"_s };

        auto* image = imageElement->cachedImage() ? imageElement->cachedImage()->image() : nullptr;
        if (!image)
            return Exception { InvalidStateError,  "Image element has no data"_s };
        if (!image->width() || !image->height())
            return Exception { InvalidStateError,  "Image element has a bad size"_s };
        return { };
    },
    [&] (const RefPtr<CSSStyleImageValue>& cssImage) -> std::optional<Exception> {
        UNUSED_PARAM(cssImage);
        ASSERT(!cssImage->isLoadedFromOpaqueSource());
        return Exception { SecurityError, "Image element is tainted"_s };
    },
#if ENABLE(VIDEO)
    [&] (const RefPtr<HTMLVideoElement>& video) -> std::optional<Exception> {
        auto* origin = context.securityOrigin();
        if (video->taintsOrigin(*origin))
            return Exception { SecurityError, "Video element is tainted"_s };

        auto readyState = video->readyState();
        if (readyState < HTMLMediaElement::HAVE_CURRENT_DATA)
            return Exception { InvalidStateError,  "Video element has no data"_s };
        return { };
    },
#endif
    [] (const RefPtr<HTMLCanvasElement>& canvas) -> std::optional<Exception> {
        if (!canvas->originClean())
            return Exception { SecurityError, "Image element is tainted"_s };

        auto size = canvas->size();
        if (!size.width() || !size.height())
            return Exception { InvalidStateError,  "Input canvas has a bad size"_s };
        return { };
    },
#if ENABLE(OFFSCREEN_CANVAS)
    [] (const RefPtr<OffscreenCanvas>& canvas) -> std::optional<Exception> {
        if (!canvas->originClean())
            return Exception { SecurityError, "Image element is tainted"_s };

        if (!canvas->width() || !canvas->height())
            return Exception { InvalidStateError,  "Input canvas has a bad size"_s };
        return { };
    },
#endif
    [] (const RefPtr<ImageBitmap>& image) -> std::optional<Exception> {
        if (image->isDetached())
            return Exception { InvalidStateError,  "Input ImageBitmap is detached"_s };

        if (!image->originClean())
            return Exception { SecurityError,  "Input ImageBitmap is tainted"_s };
        return { };
    });
}

ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::create(ScriptExecutionContext& context, CanvasImageSource&& source, Init&& init)
{
    if (auto exception = checkImageUsability(context, source))
        return WTFMove(*exception);

    return switchOn(source,
    [&] (RefPtr<HTMLImageElement>& imageElement) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        auto image = imageElement->cachedImage()->image()->nativeImageForCurrentFrame();
        if (!image)
            return Exception { InvalidStateError,  "Image element has no video frame"_s };

        return initializeFrameWithResourceAndSize(context, image.releaseNonNull(), WTFMove(init));
    },
    [&] (RefPtr<SVGImageElement>& imageElement) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        auto image = imageElement->cachedImage()->image()->nativeImageForCurrentFrame();
        if (!image)
            return Exception { InvalidStateError,  "Image element has no video frame"_s };

        return initializeFrameWithResourceAndSize(context, image.releaseNonNull(), WTFMove(init));
    },
    [&] (RefPtr<CSSStyleImageValue>& cssImage) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        auto image = cssImage->image()->image()->nativeImageForCurrentFrame();
        if (!image)
            return Exception { InvalidStateError,  "CSS Image has no video frame"_s };

        return initializeFrameWithResourceAndSize(context, image.releaseNonNull(), WTFMove(init));
    },
#if ENABLE(VIDEO)
    [&] (RefPtr<HTMLVideoElement>& video) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        RefPtr<VideoFrame> videoFrame = video->player() ? video->player()->videoFrameForCurrentTime() : nullptr;
        if (!videoFrame)
            return Exception { InvalidStateError,  "Video element has no video frame"_s };
        return initializeFrameFromOtherFrame(context, videoFrame.releaseNonNull(), WTFMove(init));
    },
#endif
    [&] (RefPtr<HTMLCanvasElement>& canvas) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        if (!canvas->width() || !canvas->height())
            return Exception { InvalidStateError,  "Input canvas has a bad size"_s };

        auto videoFrame = canvas->toVideoFrame();
        if (!videoFrame)
            return Exception { InvalidStateError,  "Canvas has no frame"_s };
        return initializeFrameFromOtherFrame(context, videoFrame.releaseNonNull(), WTFMove(init));
    },
#if ENABLE(OFFSCREEN_CANVAS)
    [&] (RefPtr<OffscreenCanvas>& canvas) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        if (!canvas->width() || !canvas->height())
            return Exception { InvalidStateError,  "Input canvas has a bad size"_s };

        auto* imageBuffer = canvas->buffer();
        if (!imageBuffer)
            return Exception { InvalidStateError,  "Input canvas has no image buffer"_s };

        return create(context, *imageBuffer, { static_cast<int>(canvas->width()), static_cast<int>(canvas->height()) }, WTFMove(init));
    },
#endif // ENABLE(OFFSCREEN_CANVAS)
    [&] (RefPtr<ImageBitmap>& image) -> ExceptionOr<Ref<WebCodecsVideoFrame>> {
        if (!init.timestamp)
            return Exception { TypeError,  "timestamp is not provided"_s };

        if (!image->width() || !image->height())
            return Exception { InvalidStateError,  "Input image has a bad size"_s };

        auto* imageBuffer = image->buffer();
        if (!imageBuffer)
            return Exception { InvalidStateError,  "Input image has no image buffer"_s };

        return create(context, *imageBuffer, { static_cast<int>(image->width()), static_cast<int>(image->height()) }, WTFMove(init));
    });
}

ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::create(ScriptExecutionContext& context, ImageBuffer& buffer, IntSize size, WebCodecsVideoFrame::Init&& init)
{
    PixelBufferFormat format { AlphaPremultiplication::Unpremultiplied, PixelFormat::BGRA8, DestinationColorSpace::SRGB() };
    IntRect region { IntPoint::zero(), size };

    auto pixelBuffer = buffer.getPixelBuffer(format, region);
    if (!pixelBuffer)
        return Exception { InvalidStateError,  "Buffer has no frame"_s };

    auto videoFrame = VideoFrame::createFromPixelBuffer(pixelBuffer.releaseNonNull(), { PlatformVideoColorPrimaries::Bt709, PlatformVideoTransferCharacteristics::Iec6196621, PlatformVideoMatrixCoefficients::Rgb, true });

    if (!videoFrame)
        return Exception { InvalidStateError,  "Unable to create frame from buffer"_s };

    return WebCodecsVideoFrame::initializeFrameFromOtherFrame(context, videoFrame.releaseNonNull(), WTFMove(init));
}

ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::create(ScriptExecutionContext& context, Ref<WebCodecsVideoFrame>&& initFrame, Init&& init)
{
    if (initFrame->isDetached())
        return Exception { InvalidStateError,  "VideoFrame is detached"_s };
    return initializeFrameFromOtherFrame(context, WTFMove(initFrame), WTFMove(init));
}

static std::optional<Exception> validateI420Sizes(const WebCodecsVideoFrame::BufferInit& init)
{
    if (init.codedWidth % 2 || init.codedHeight % 2)
        return Exception { TypeError, "coded width or height is odd"_s };
    if (init.visibleRect && (static_cast<size_t>(init.visibleRect->x) % 2 || static_cast<size_t>(init.visibleRect->x) % 2))
        return Exception { TypeError, "visible x or y is odd"_s };
    return { };
}

// https://w3c.github.io/webcodecs/#dom-videoframe-videoframe-data-init
ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::create(ScriptExecutionContext& context, BufferSource&& data, BufferInit&& init)
{
    if (!isValidVideoFrameBufferInit(init))
        return Exception { TypeError, "buffer init is not valid"_s };

    DOMRectInit defaultRect { 0, 0, static_cast<double>(init.codedWidth), static_cast<double>(init.codedHeight) };
    auto parsedRectOrExtension = parseVisibleRect(defaultRect, init.visibleRect, init.codedWidth, init.codedHeight, init.format);
    if (parsedRectOrExtension.hasException())
        return parsedRectOrExtension.releaseException();

    auto parsedRect = parsedRectOrExtension.releaseReturnValue();
    auto layoutOrException = computeLayoutAndAllocationSize(defaultRect, init.layout, init.format);
    if (layoutOrException.hasException())
        return layoutOrException.releaseException();
    
    auto layout = layoutOrException.releaseReturnValue();
    if (data.length() < layout.allocationSize)
        return Exception { TypeError, makeString("Data is too small ", data.length(), " / ", layout.allocationSize) };

    auto colorSpace = videoFramePickColorSpace(init.colorSpace, init.format);
    RefPtr<VideoFrame> videoFrame;
    if (init.format == VideoPixelFormat::NV12) {
        if (init.codedWidth % 2 || init.codedHeight % 2)
            return Exception { TypeError, "coded width or height is odd"_s };
        if (init.visibleRect && (static_cast<size_t>(init.visibleRect->x) % 2 || static_cast<size_t>(init.visibleRect->x) % 2))
            return Exception { TypeError, "visible x or y is odd"_s };
        videoFrame = VideoFrame::createNV12({ data.data(), data.length() }, parsedRect.width, parsedRect.height, layout.computedLayouts[0], layout.computedLayouts[1], WTFMove(colorSpace));
    } else if (init.format == VideoPixelFormat::RGBA || init.format == VideoPixelFormat::RGBX)
        videoFrame = VideoFrame::createRGBA({ data.data(), data.length() }, parsedRect.width, parsedRect.height, layout.computedLayouts[0], WTFMove(colorSpace));
    else if (init.format == VideoPixelFormat::BGRA || init.format == VideoPixelFormat::BGRX)
        videoFrame = VideoFrame::createBGRA({ data.data(), data.length() }, parsedRect.width, parsedRect.height, layout.computedLayouts[0], WTFMove(colorSpace));
    else if (init.format == VideoPixelFormat::I420) {
        if (auto exception = validateI420Sizes(init))
            return WTFMove(*exception);
        videoFrame = VideoFrame::createI420({ data.data(), data.length() }, parsedRect.width, parsedRect.height, layout.computedLayouts[0], layout.computedLayouts[1], layout.computedLayouts[2], WTFMove(colorSpace));
    } else if (init.format == VideoPixelFormat::I420A) {
        if (auto exception = validateI420Sizes(init))
            return WTFMove(*exception);
        videoFrame = VideoFrame::createI420A({ data.data(), data.length() }, parsedRect.width, parsedRect.height, layout.computedLayouts[0], layout.computedLayouts[1], layout.computedLayouts[2], layout.computedLayouts[3], WTFMove(colorSpace));
    } else
        return Exception { NotSupportedError, "VideoPixelFormat is not supported"_s };

    if (!videoFrame)
        return Exception { TypeError, "Unable to create internal resource from data"_s };
    
    return WebCodecsVideoFrame::create(context, videoFrame.releaseNonNull(), WTFMove(init));
}

Ref<WebCodecsVideoFrame> WebCodecsVideoFrame::create(ScriptExecutionContext& context, Ref<VideoFrame>&& videoFrame, BufferInit&& init)
{
    ASSERT(isValidVideoFrameBufferInit(init));

    auto result = adoptRef(*new WebCodecsVideoFrame(context));
    result->m_data.internalFrame = WTFMove(videoFrame);
    result->m_data.format = init.format;

    result->m_data.codedWidth = result->m_data.internalFrame->presentationSize().width();
    result->m_data.codedHeight = result->m_data.internalFrame->presentationSize().height();

    result->m_data.visibleLeft = 0;
    result->m_data.visibleTop = 0;

    if (init.visibleRect) {
        result->m_data.visibleWidth = init.visibleRect->width;
        result->m_data.visibleHeight = init.visibleRect->height;
    } else {
        result->m_data.visibleWidth = result->m_data.codedWidth;
        result->m_data.visibleHeight = result->m_data.codedHeight;
    }

    result->m_data.displayWidth = init.displayWidth.value_or(result->m_data.visibleWidth);
    result->m_data.displayHeight = init.displayHeight.value_or(result->m_data.visibleHeight);

    result->m_data.duration = init.duration;
    result->m_data.timestamp = init.timestamp;

    return result;
}

static VideoPixelFormat computeVideoPixelFormat(VideoPixelFormat baseFormat, bool shouldDiscardAlpha)
{
    if (!shouldDiscardAlpha)
        return baseFormat;
    switch (baseFormat) {
    case VideoPixelFormat::I420:
    case VideoPixelFormat::I422:
    case VideoPixelFormat::NV12:
    case VideoPixelFormat::I444:
    case VideoPixelFormat::RGBX:
    case VideoPixelFormat::BGRX:
        return baseFormat;
    case VideoPixelFormat::I420A:
        return VideoPixelFormat::I420;
    case VideoPixelFormat::RGBA:
        return VideoPixelFormat::RGBX;
    case VideoPixelFormat::BGRA:
        return VideoPixelFormat::BGRX;
    }
    return baseFormat;
}

// https://w3c.github.io/webcodecs/#videoframe-initialize-frame-from-other-frame
ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::initializeFrameFromOtherFrame(ScriptExecutionContext& context, Ref<WebCodecsVideoFrame>&& videoFrame, Init&& init)
{
    auto codedWidth = videoFrame->m_data.codedWidth;
    auto codedHeight = videoFrame->m_data.codedHeight;
    auto format = computeVideoPixelFormat(videoFrame->m_data.format.value_or(VideoPixelFormat::I420), init.alpha == WebCodecsAlphaOption::Discard);
    if (!validateVideoFrameInit(init, codedWidth, codedHeight, format))
        return Exception { TypeError,  "VideoFrameInit is not valid"_s };

    auto result = adoptRef(*new WebCodecsVideoFrame(context));
    result->m_data.internalFrame = videoFrame->m_data.internalFrame;
    if (videoFrame->m_data.format)
        result->m_data.format = format;

    result->m_data.codedWidth = videoFrame->m_data.codedWidth;
    result->m_data.codedHeight = videoFrame->m_data.codedHeight;

    initializeVisibleRectAndDisplaySize(result.get(), init, DOMRectInit { static_cast<double>(videoFrame->m_data.visibleLeft), static_cast<double>(videoFrame->m_data.visibleTop), static_cast<double>(videoFrame->m_data.visibleWidth), static_cast<double>(videoFrame->m_data.visibleHeight) }, videoFrame->m_data.displayWidth, videoFrame->m_data.displayHeight);

    result->m_data.duration = init.duration ? init.duration : videoFrame->m_data.duration;
    result->m_data.timestamp = init.timestamp.value_or(videoFrame->m_data.timestamp);

    return result;
}

ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::initializeFrameFromOtherFrame(ScriptExecutionContext& context, Ref<VideoFrame>&& internalVideoFrame, Init&& init)
{
    auto codedWidth = internalVideoFrame->presentationSize().width();
    auto codedHeight = internalVideoFrame->presentationSize().height();
    auto format = convertVideoFramePixelFormat(internalVideoFrame->pixelFormat(), init.alpha == WebCodecsAlphaOption::Discard);
    if (!validateVideoFrameInit(init, codedWidth, codedHeight, format))
        return Exception { TypeError,  "VideoFrameInit is not valid"_s };

    auto result = adoptRef(*new WebCodecsVideoFrame(context));
    result->m_data.internalFrame = WTFMove(internalVideoFrame);
    result->m_data.format = format;
    result->m_data.codedWidth = codedWidth;
    result->m_data.codedHeight = codedHeight;

    initializeVisibleRectAndDisplaySize(result.get(), init, DOMRectInit { 0, 0 , static_cast<double>(result->m_data.codedWidth), static_cast<double>(result->m_data.codedHeight) }, result->m_data.codedWidth, result->m_data.codedHeight);

    result->m_data.duration = init.duration;
    // FIXME: Use internalVideoFrame timestamp if available and init has no timestamp.
    result->m_data.timestamp = init.timestamp.value_or(0);

    return result;
}

// https://w3c.github.io/webcodecs/#videoframe-initialize-frame-with-resource-and-size
ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::initializeFrameWithResourceAndSize(ScriptExecutionContext& context, Ref<NativeImage>&& image, Init&& init)
{
    auto internalVideoFrame = VideoFrame::fromNativeImage(image.get());
    if (!internalVideoFrame)
        return Exception { TypeError,  "image has no resource"_s };

    auto codedWidth = image->size().width();
    auto codedHeight = image->size().height();
    auto format = convertVideoFramePixelFormat(internalVideoFrame->pixelFormat(), init.alpha == WebCodecsAlphaOption::Discard);
    if (!validateVideoFrameInit(init, codedWidth, codedHeight, format))
        return Exception { TypeError,  "VideoFrameInit is not valid"_s };

    auto result = adoptRef(*new WebCodecsVideoFrame(context));
    result->m_data.internalFrame = WTFMove(internalVideoFrame);
    result->m_data.format = format;
    result->m_data.codedWidth = codedWidth;
    result->m_data.codedHeight = codedHeight;

    initializeVisibleRectAndDisplaySize(result.get(), init, DOMRectInit { 0, 0 , static_cast<double>(result->m_data.codedWidth), static_cast<double>(result->m_data.codedHeight) }, result->m_data.codedWidth, result->m_data.codedHeight);

    result->m_data.duration = init.duration;
    result->m_data.timestamp = init.timestamp.value_or(0);

    return result;
}


ExceptionOr<size_t> WebCodecsVideoFrame::allocationSize(const CopyToOptions& options)
{
    if (isDetached())
        return Exception { InvalidStateError,  "VideoFrame is detached"_s };

    if (!m_data.format)
        return Exception { NotSupportedError,  "VideoFrame has no format"_s };

    auto layoutOrException = parseVideoFrameCopyToOptions(*this, options);
    if (layoutOrException.hasException())
        return layoutOrException.releaseException();

    return layoutOrException.returnValue().allocationSize;
}

void WebCodecsVideoFrame::copyTo(BufferSource&& source, CopyToOptions&& options, CopyToPromise&& promise)
{
    if (isDetached()) {
        promise.reject(Exception { InvalidStateError,  "VideoFrame is detached"_s });
        return;
    }
    if (!m_data.format) {
        promise.reject(Exception { NotSupportedError,  "VideoFrame has no format"_s });
        return;
    }

    auto combinedLayoutOrException = parseVideoFrameCopyToOptions(*this, options);
    if (combinedLayoutOrException.hasException()) {
        promise.reject(combinedLayoutOrException.releaseException());
        return;
    }

    auto combinedLayout = combinedLayoutOrException.releaseReturnValue();
    if (source.length() < combinedLayout.allocationSize) {
        promise.reject(Exception { TypeError,  "Buffer is too small"_s });
        return;
    }

    std::span<uint8_t> buffer { static_cast<uint8_t*>(source.mutableData()), source.length() };
    m_data.internalFrame->copyTo(buffer, *m_data.format, WTFMove(combinedLayout.computedLayouts), [source = WTFMove(source), promise = WTFMove(promise)](auto planeLayouts) mutable {
        if (!planeLayouts) {
            promise.reject(Exception { TypeError,  "Unable to copy data"_s });
            return;
        }
        promise.resolve(WTFMove(*planeLayouts));
    });
}

ExceptionOr<Ref<WebCodecsVideoFrame>> WebCodecsVideoFrame::clone(ScriptExecutionContext& context)
{
    if (isDetached())
        return Exception { InvalidStateError,  "VideoFrame is detached"_s };

    auto clone = adoptRef(*new WebCodecsVideoFrame(context, WebCodecsVideoFrameData { m_data }));

    clone->m_colorSpace = &colorSpace();
    clone->m_codedRect = codedRect();
    clone->m_visibleRect = visibleRect();
    clone->m_isDetached = m_isDetached;

    return clone;
}

// https://w3c.github.io/webcodecs/#close-videoframe
void WebCodecsVideoFrame::close()
{
    m_data.internalFrame = nullptr;

    m_isDetached = true;

    m_data.format = { };

    m_data.codedWidth = 0;
    m_data.codedHeight = 0;
    m_data.displayWidth = 0;
    m_data.displayHeight = 0;
    m_data.visibleWidth = 0;
    m_data.visibleHeight = 0;
    m_data.visibleLeft = 0;
    m_data.visibleTop = 0;

    m_codedRect = nullptr;
    m_visibleRect = nullptr;
}

DOMRectReadOnly* WebCodecsVideoFrame::codedRect() const
{
    if (m_isDetached)
        return nullptr;
    if (!m_codedRect)
        m_codedRect = DOMRectReadOnly::create(0, 0, m_data.codedWidth, m_data.codedHeight);

    return m_codedRect.get();
}

DOMRectReadOnly* WebCodecsVideoFrame::visibleRect() const
{
    if (m_isDetached)
        return nullptr;
    if (!m_visibleRect)
        m_visibleRect = DOMRectReadOnly::create(m_data.visibleLeft, m_data.visibleTop, m_data.visibleWidth, m_data.visibleHeight);

    return m_visibleRect.get();
}

void WebCodecsVideoFrame::setDisplaySize(size_t width, size_t height)
{
    m_data.displayWidth = width;
    m_data.displayHeight = height;
}

void WebCodecsVideoFrame::setVisibleRect(const DOMRectInit& rect)
{
    m_data.visibleLeft = rect.x;
    m_data.visibleTop = rect.y;
    m_data.visibleWidth = rect.width;
    m_data.visibleHeight = rect.height;
}

VideoColorSpace& WebCodecsVideoFrame::colorSpace() const
{
    if (!m_colorSpace)
        m_colorSpace = m_data.internalFrame ? VideoColorSpace::create(m_data.internalFrame->colorSpace()) : VideoColorSpace::create();

    return *m_colorSpace.get();
}

} // namespace WebCore

#endif // ENABLE(WEB_CODECS)