File: BitmapImageSource.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (716 lines) | stat: -rw-r--r-- 25,341 bytes parent folder | download | duplicates (6)
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/*
 * Copyright (C) 2024 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 "BitmapImageSource.h"

#include "BitmapImage.h"
#include "BitmapImageDescriptor.h"
#include "GraphicsContext.h"
#include "ImageBuffer.h"
#include "ImageDecoder.h"
#include "ImageFrameAnimator.h"
#include "ImageObserver.h"
#include "Logging.h"

namespace WebCore {

Ref<BitmapImageSource> BitmapImageSource::create(BitmapImage& bitmapImage, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
{
    return adoptRef(*new BitmapImageSource(bitmapImage, alphaOption, gammaAndColorProfileOption));
}

BitmapImageSource::BitmapImageSource(BitmapImage& bitmapImage, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
    : m_bitmapImage(&bitmapImage)
    , m_alphaOption(alphaOption)
    , m_gammaAndColorProfileOption(gammaAndColorProfileOption)
    , m_descriptor(*this)
{
}

BitmapImageSource::~BitmapImageSource() = default;

ImageDecoder* BitmapImageSource::decoder(FragmentedSharedBuffer* data) const
{
    if (m_decoder)
        return m_decoder.get();

    if (!data)
        return nullptr;

    m_decoder = ImageDecoder::create(*data, mimeType(), m_alphaOption, m_gammaAndColorProfileOption);
    if (!m_decoder)
        return nullptr;

    m_decoder->setEncodedDataStatusChangeCallback([weakThis = ThreadSafeWeakPtr { *this }] (auto status) {
        if (RefPtr protectedThis = weakThis.get())
            protectedThis->encodedDataStatusChanged(status);
    });

    if (auto expectedContentLength = this->expectedContentLength())
        m_decoder->setExpectedContentSize(expectedContentLength);

    return m_decoder.get();
}

ImageFrameAnimator* BitmapImageSource::frameAnimator() const
{
    if (m_frameAnimator)
        return m_frameAnimator.get();

    // Number of frames can only be known for sure when loadimg the image is complete.
    if (encodedDataStatus() != EncodedDataStatus::Complete)
        return nullptr;

    if (!isAnimated())
        return nullptr;

    m_frameAnimator = makeUniqueWithoutRefCountedCheck<ImageFrameAnimator>(const_cast<BitmapImageSource&>(*this));
    return m_frameAnimator.get();
}

ImageFrameWorkQueue& BitmapImageSource::workQueue() const
{
    if (!m_workQueue)
        m_workQueue = ImageFrameWorkQueue::create(const_cast<BitmapImageSource&>(*this));
    return *m_workQueue;
}

void BitmapImageSource::encodedDataStatusChanged(EncodedDataStatus status)
{
    ASSERT(m_decoder);

    if (status >= EncodedDataStatus::SizeAvailable)
        m_frames.resizeToFit(m_decoder->frameCount());

    if (auto imageObserver = this->imageObserver())
        imageObserver->encodedDataStatusChanged(*m_bitmapImage, status);
}

EncodedDataStatus BitmapImageSource::dataChanged(FragmentedSharedBuffer* data, bool allDataReceived)
{
    m_descriptor.clear();

    auto status = setData(data, allDataReceived);
    if (status < EncodedDataStatus::TypeAvailable)
        return status;

    encodedDataStatusChanged(status);
    return status;
}

void BitmapImageSource::destroyDecodedData(bool destroyAll)
{
    LOG(Images, "BitmapImageSource::%s - %p - url: %s. Decoded data with destroyAll = %d will be destroyed.", __FUNCTION__, this, sourceUTF8().data(), destroyAll);

    bool canDestroyDecodedData = destroyAll && this->canDestroyDecodedData();

    unsigned primaryFrameIndex = this->primaryFrameIndex();
    unsigned currentFrameIndex = this->currentFrameIndex();
    unsigned decodedSize = 0;

    for (unsigned index = 0, framesSize = m_frames.size(); index < framesSize; ++index) {
        if (!canDestroyDecodedData && (index == primaryFrameIndex || index == currentFrameIndex))
            continue;

        if (!destroyAll && index > currentFrameIndex)
            break;

        decodedSize += m_frames[index].clearImage();
    }

    decodedSizeReset(decodedSize);

    // There's no need to throw away the decoder unless we're explicitly asked
    // to destroy all of the frames.
    if (destroyAll && isDecodingWorkQueueIdle())
        resetData();
    else
        clearFrameBufferCache();
}

void BitmapImageSource::decodedSizeChanged(long long decodedSize)
{
    if (!decodedSize)
        return;

    if (auto imageObserver = this->imageObserver())
        imageObserver->decodedSizeChanged(*m_bitmapImage, decodedSize);
}

void BitmapImageSource::decodedSizeIncreased(unsigned decodedSize)
{
    if (!decodedSize)
        return;

    m_decodedSize += decodedSize;

    // The fully-decoded frame will subsume the partially decoded data used
    // to determine image properties.
    long long changeSize = static_cast<long long>(decodedSize) - m_decodedPropertiesSize;
    m_decodedPropertiesSize = 0;
    decodedSizeChanged(changeSize);
}

void BitmapImageSource::decodedSizeDecreased(unsigned decodedSize)
{
    if (!decodedSize)
        return;

    ASSERT(m_decodedSize >= decodedSize);
    m_decodedSize -= decodedSize;
    decodedSizeChanged(-static_cast<long long>(decodedSize));
}

void BitmapImageSource::decodedSizeReset(unsigned decodedSize)
{
    ASSERT(m_decodedSize >= decodedSize);
    m_decodedSize -= decodedSize;

    // Clearing the ImageSource destroys the extra decoded data used for
    // determining image properties.
    decodedSize += m_decodedPropertiesSize;
    m_decodedPropertiesSize = 0;
    decodedSizeChanged(-static_cast<long long>(decodedSize));
}

void BitmapImageSource::destroyNativeImageAtIndex(unsigned index)
{
    if (index >= m_frames.size())
        return;

    decodedSizeDecreased(m_frames[index].clearImage());
}

bool BitmapImageSource::canDestroyDecodedData() const
{
    // Animated images should preserve the current frame till the next one finishes decoding.
    if (!isDecodingWorkQueueIdle())
        return false;

    // Small image should be decoded synchronously. Deleting its decoded frame is fine.
    if (!isLargeForDecoding())
        return true;

    if (auto imageObserver = this->imageObserver())
        return imageObserver->canDestroyDecodedData(*m_bitmapImage);

    return true;
}

void BitmapImageSource::didDecodeProperties(unsigned decodedPropertiesSize)
{
    if (m_decodedSize)
        return;

    long long decodedSize = static_cast<long long>(decodedPropertiesSize) - m_decodedPropertiesSize;
    m_decodedPropertiesSize = decodedPropertiesSize;
    decodedSizeChanged(decodedSize);
}

void BitmapImageSource::clearFrameBufferCache()
{
    if (!m_decoder)
        return;

    m_decoder->clearFrameBufferCache(currentFrameIndex());
}

EncodedDataStatus BitmapImageSource::setData(FragmentedSharedBuffer* data, bool allDataReceived)
{
    if (!data)
        return EncodedDataStatus::Unknown;

    RefPtr decoder = this->decoder(data);
    if (!decoder)
        return EncodedDataStatus::Unknown;

    decoder->setData(*data, allDataReceived);
    m_allDataReceived = allDataReceived;
    return encodedDataStatus();
}

void BitmapImageSource::resetData()
{
    m_decoder = nullptr;

    if (m_bitmapImage)
        setData(m_bitmapImage->data(), m_allDataReceived);
}

void BitmapImageSource::startAnimation()
{
    startAnimation(SubsamplingLevel::Default, DecodingMode::Synchronous);
}

bool BitmapImageSource::startAnimation(SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    RefPtr frameAnimator = this->frameAnimator();
    if (!frameAnimator)
        return false;

    return frameAnimator->startAnimation(subsamplingLevel, options);
}

void BitmapImageSource::stopAnimation()
{
    if (!m_frameAnimator || !m_frameAnimator->isAnimating())
        return;

    m_frameAnimator->stopAnimation();
    stopDecodingWorkQueue();
}

void BitmapImageSource::resetAnimation()
{
    if (!m_frameAnimator)
        return;

    m_frameAnimator->resetAnimation();
}

bool BitmapImageSource::isAnimated() const
{
    return frameCount() > 1 && repetitionCount() != RepetitionCountNone;
}

bool BitmapImageSource::isAnimating() const
{
    return m_frameAnimator && m_frameAnimator->isAnimating();
}

bool BitmapImageSource::isAnimationAllowed() const
{
    if (m_frameAnimator && !m_frameAnimator->isAnimationAllowed())
        return false;

    // ImageObserver may disallow animation.
    if (auto imageObserver = this->imageObserver())
        return imageObserver->allowsAnimation(*m_bitmapImage);

    return true;
}

bool BitmapImageSource::hasEverAnimated() const
{
    return m_frameAnimator && m_frameAnimator->hasEverAnimated();
}

bool BitmapImageSource::isLargeForDecoding() const
{
    auto sizeInBytes = size(ImageOrientation::Orientation::None).unclampedArea() * sizeof(uint32_t);
    return sizeInBytes > (isAnimated() ? 100 * KB : 500 * KB);
}

bool BitmapImageSource::isDecodingWorkQueueIdle() const
{
    return !m_workQueue || m_workQueue->isIdle();
}

void BitmapImageSource::stopDecodingWorkQueue()
{
    LOG(Images, "BitmapImageSource::%s - %p - url: %s. Decoding work queue will be stopped.", __FUNCTION__, this, sourceUTF8().data());

    if (!m_workQueue || !m_workQueue->isIdle())
        return;

    m_workQueue->stop();
}

bool BitmapImageSource::isPendingDecodingAtIndex(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options) const
{
    if (!m_workQueue)
        return false;

    return m_workQueue->isPendingDecodingAtIndex(index, subsamplingLevel, options);
}

bool BitmapImageSource::isCompatibleWithOptionsAtIndex(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options) const
{
    return frameAtIndex(index).hasDecodedNativeImageCompatibleWithOptions(subsamplingLevel, options);
}

void BitmapImageSource::decode(Function<void(DecodingStatus)>&& decodeCallback)
{
    m_decodeCallbacks.append(WTFMove(decodeCallback));
    unsigned index = currentFrameIndex();

    if (isPendingDecodingAtIndex(index, SubsamplingLevel::Default, DecodingMode::Asynchronous)) {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d is being decoded.", __FUNCTION__, this, sourceUTF8().data(), index);
        return;
    }

    bool isCompatibleNativeImage = isCompatibleWithOptionsAtIndex(index, SubsamplingLevel::Default, DecodingMode::Asynchronous);
    RefPtr frameAnimator = this->frameAnimator();

    if (frameAnimator && (frameAnimator->hasEverAnimated() || isCompatibleNativeImage)) {
        // startAnimation() always decodes the nextFrame which is currentFrameIndex + 1.
        // If primaryFrameIndex = 0, then the sequence of decoding is { 1, 2, .., n, 0, 1, ...}.
        if (startAnimation(SubsamplingLevel::Default, DecodingMode::Asynchronous)) {
            LOG(Images, "BitmapImageSource::%s - %p - url: %s. Animator has requested decoding next frame at index = %d.", __FUNCTION__, this, sourceUTF8().data(), index);
            return;
        }
    }

    if (!isCompatibleNativeImage) {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Decoding for frame at index = %d will be requested.", __FUNCTION__, this, sourceUTF8().data(), index);
        requestNativeImageAtIndex(index, SubsamplingLevel::Default, ImageAnimatingState::No, { DecodingMode::Asynchronous });
        return;
    }

    LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d was decoded for natural size.", __FUNCTION__, this, sourceUTF8().data(), index);
    callDecodeCallbacks(DecodingStatus::Complete);
}

void BitmapImageSource::callDecodeCallbacks(DecodingStatus status)
{
    if (m_decodeCallbacks.isEmpty())
        return;
    for (auto& decodeCallback : m_decodeCallbacks)
        decodeCallback(status);
    m_decodeCallbacks.clear();
}

void BitmapImageSource::imageFrameAtIndexAvailable(unsigned index, ImageAnimatingState animatingState, DecodingStatus decodingStatus)
{
    ASSERT_UNUSED(index, index < frameCount());

    // Decode callbacks have to called regardless of the decoding status.
    // Decoding promises have to resolved or rejected.
    callDecodeCallbacks(decodingStatus);

    if (decodingStatus == DecodingStatus::Invalid)
        return;

    if (auto imageObserver = this->imageObserver())
        imageObserver->imageFrameAvailable(*m_bitmapImage, animatingState, nullptr, decodingStatus);
}

void BitmapImageSource::imageFrameDecodeAtIndexHasFinished(unsigned index, ImageAnimatingState animatingState, DecodingStatus decodingStatus)
{
    // Depending on its timer, the animator may call or postpone calling imageFrameAvailable().
    if (m_frameAnimator && m_frameAnimator->imageFrameDecodeAtIndexHasFinished(index, animatingState, decodingStatus))
        return;

    imageFrameAtIndexAvailable(index, animatingState, decodingStatus);
}

void BitmapImageSource::imageFrameDecodeAtIndexHasFinished(unsigned index, SubsamplingLevel subsamplingLevel, ImageAnimatingState animatingState, const DecodingOptions& options, RefPtr<NativeImage>&& nativeImage)
{
    ASSERT(index < m_frames.size());

    if (!nativeImage || !m_decoder) {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d has failed.", __FUNCTION__, this, sourceUTF8().data(), index);

        destroyNativeImageAtIndex(index);
        imageFrameDecodeAtIndexHasFinished(index, animatingState, DecodingStatus::Invalid);
    } else {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d has been decoded.", __FUNCTION__, this, sourceUTF8().data(), index);

        cacheNativeImageAtIndex(index, subsamplingLevel, options, nativeImage.releaseNonNull());

        if (frameAtIndex(index).isComplete())
            ++m_decodeCountForTesting;

        imageFrameDecodeAtIndexHasFinished(index, animatingState, frameDecodingStatusAtIndex(index));
    }

    // Do not leave any decoding work queue idle for static images.
    if (animatingState == ImageAnimatingState::No)
        stopDecodingWorkQueue();
}

unsigned BitmapImageSource::currentFrameIndex() const
{
    return m_frameAnimator ? m_frameAnimator->currentFrameIndex() : primaryFrameIndex();
}

void BitmapImageSource::cacheMetadataAtIndex(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    ASSERT(m_decoder);

    if (index >= m_frames.size())
        return;

    auto& frame = m_frames[index];

    m_decoder->fetchFrameMetaDataAtIndex(index, subsamplingLevel, options, frame);

    if (repetitionCount())
        frame.m_duration = m_decoder->frameDurationAtIndex(index);
}

void BitmapImageSource::cacheNativeImageAtIndex(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options, Ref<NativeImage>&& nativeImage)
{
    ASSERT(m_decoder);

    if (index >= m_frames.size())
        return;

    destroyNativeImageAtIndex(index);

    // Do not cache NativeImage if adding its frameByes to MemoryCache will cause numerical overflow.
    auto frameBytes = nativeImage->size().unclampedArea() * sizeof(uint32_t);
    if (!isInBounds<unsigned>(frameBytes + m_decodedSize))
        return;

    auto& frame = m_frames[index];
    frame.m_nativeImage = WTFMove(nativeImage);

    cacheMetadataAtIndex(index, subsamplingLevel, options);
    decodedSizeIncreased(frame.frameBytes());
}

const ImageFrame& BitmapImageSource::frameAtIndex(unsigned index) const
{
    if (index >= m_frames.size())
        return ImageFrame::defaultFrame();

    return m_frames[index];
}

const ImageFrame& BitmapImageSource::frameAtIndexCacheIfNeeded(unsigned index, const std::optional<SubsamplingLevel>& subsamplingLevel)
{
    if (!m_decoder)
        return ImageFrame::defaultFrame();

    if (index >= m_frames.size())
        return ImageFrame::defaultFrame();

    auto& frame = m_frames[index];
    auto subsamplingLevelValue = subsamplingLevel.value_or(frame.subsamplingLevel());

    if (frame.isComplete() && subsamplingLevelValue == frame.subsamplingLevel())
        return frame;

    destroyNativeImageAtIndex(index);

    // Retrieve the metadata from ImageDecoder if the ImageFrame isn't complete.
    cacheMetadataAtIndex(index, subsamplingLevelValue, { });
    return frame;
}

DecodingStatus BitmapImageSource::requestNativeImageAtIndex(unsigned index, SubsamplingLevel subsamplingLevel, ImageAnimatingState animatingState, const DecodingOptions& options)
{
    if (index >= m_frames.size())
        return DecodingStatus::Invalid;

    LOG(Images, "BitmapImageSource::%s - %p - url: %s. Decoding for frame at index = %d will be requested.", __FUNCTION__, this, sourceUTF8().data(), index);

    workQueue().dispatch({ index, subsamplingLevel, animatingState, options });

    if (m_clearDecoderAfterAsyncFrameRequestForTesting)
        resetData();

    return DecodingStatus::Decoding;
}

DecodingStatus BitmapImageSource::requestNativeImageAtIndexIfNeeded(unsigned index, SubsamplingLevel subsamplingLevel, ImageAnimatingState animatingState, const DecodingOptions& options)
{
    if (index >= m_frames.size())
        return DecodingStatus::Invalid;

    // Never decode the same frame from two different threads.
    if (isPendingDecodingAtIndex(index, subsamplingLevel, options)) {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d is being decoded.", __FUNCTION__, this, sourceUTF8().data(), index);
        ++m_blankDrawCountForTesting;
        return DecodingStatus::Decoding;
    }

    // isCompatibleWithOptionsAtIndex() returns true only if the frame is complete.
    if (isCompatibleWithOptionsAtIndex(index, subsamplingLevel, options))
        return DecodingStatus::Complete;

    return requestNativeImageAtIndex(index, subsamplingLevel, animatingState, options);
}

Expected<Ref<NativeImage>, DecodingStatus> BitmapImageSource::nativeImageAtIndexCacheIfNeeded(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    if (!m_decoder)
        return makeUnexpected(DecodingStatus::Invalid);

    if (index >= m_frames.size())
        return makeUnexpected(DecodingStatus::Invalid);

    // FIXME: Remove this for CG; ImageIO should be thread safe when decoding the same frame from multiple threads.
    // Never decode the same frame from two different threads.
    if (isPendingDecodingAtIndex(index, subsamplingLevel, options)) {
        LOG(Images, "BitmapImageSource::%s - %p - url: %s. Frame at index = %d is being decoded.", __FUNCTION__, this, sourceUTF8().data(), index);
        ++m_blankDrawCountForTesting;
        return makeUnexpected(DecodingStatus::Decoding);
    }

    if (!isCompatibleWithOptionsAtIndex(index, subsamplingLevel, options)) {
        PlatformImagePtr platformImage = m_decoder->createFrameImageAtIndex(index, subsamplingLevel, DecodingMode::Synchronous);

        RefPtr nativeImage = NativeImage::create(WTFMove(platformImage));
        if (!nativeImage)
            return makeUnexpected(DecodingStatus::Invalid);

        cacheNativeImageAtIndex(index, subsamplingLevel, DecodingMode::Synchronous, nativeImage.releaseNonNull());
    }

    if (RefPtr nativeImage = frameAtIndex(index).nativeImage())
        return nativeImage.releaseNonNull();

    return makeUnexpected(DecodingStatus::Invalid);
}

Expected<Ref<NativeImage>, DecodingStatus> BitmapImageSource::nativeImageAtIndexRequestIfNeeded(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    if (!m_decoder)
        return makeUnexpected(DecodingStatus::Invalid);

    ASSERT(!isAnimated());

    auto status = requestNativeImageAtIndexIfNeeded(index, subsamplingLevel, ImageAnimatingState::No, options);
    if (status == DecodingStatus::Invalid || status == DecodingStatus::Decoding)
        return makeUnexpected(status);

    if (RefPtr nativeImage = frameAtIndex(index).nativeImage())
        return nativeImage.releaseNonNull();

    return makeUnexpected(DecodingStatus::Invalid);
}

Expected<Ref<NativeImage>, DecodingStatus> BitmapImageSource::nativeImageAtIndexForDrawing(unsigned index, SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    // If this is an animated image and the frame is not available, we have no
    // choice but to decode it synchronously. Otherwise, a flicker will happen.
    if (options.decodingMode() == DecodingMode::Asynchronous && !isAnimated())
        return nativeImageAtIndexRequestIfNeeded(index, subsamplingLevel, options);
    return nativeImageAtIndexCacheIfNeeded(index, subsamplingLevel, options);
}

Expected<Ref<NativeImage>, DecodingStatus> BitmapImageSource::currentNativeImageForDrawing(SubsamplingLevel subsamplingLevel, const DecodingOptions& options)
{
    startAnimation(subsamplingLevel, options);

    auto effectiveOptions = options;

    // If frame0 is displayed for the first time, startAnimation() has to request decoding frame1
    // asynchronously. A flicker will occur if we request decoding frame0 also asynchronously.
    if (options.decodingMode() == DecodingMode::Asynchronous && isAnimated() && !hasEverAnimated())
        effectiveOptions = { DecodingMode::Synchronous, options.sizeForDrawing() };

    return nativeImageAtIndexForDrawing(currentFrameIndex(), subsamplingLevel, effectiveOptions);
}

RefPtr<NativeImage> BitmapImageSource::nativeImageAtIndex(unsigned index)
{
    auto nativeImage = nativeImageAtIndexCacheIfNeeded(index);
    if (!nativeImage)
        return nullptr;
    return RefPtr { nativeImage->ptr() };
}

RefPtr<NativeImage> BitmapImageSource::preTransformedNativeImageAtIndex(unsigned index, ImageOrientation orientation)
{
    RefPtr nativeImage = nativeImageAtIndex(index);
    if (!nativeImage)
        return nullptr;

    auto size =  this->size();
    auto sourceSize = this->sourceSize();

    if (orientation == ImageOrientation::Orientation::FromImage)
        orientation = frameOrientationAtIndex(index);

    if (orientation == ImageOrientation::Orientation::None && size == sourceSize)
        return nativeImage;

    RefPtr buffer = ImageBuffer::create(size, RenderingMode::Unaccelerated, RenderingPurpose::Unspecified, 1, DestinationColorSpace::SRGB(), ImageBufferPixelFormat::BGRA8);
    if (!buffer)
        return nativeImage;

    auto destinationRect = FloatRect { FloatPoint(), size };
    auto sourceRect = FloatRect { FloatPoint(), sourceSize };

    buffer->context().drawNativeImage(*nativeImage, destinationRect, sourceRect, { orientation });
    return ImageBuffer::sinkIntoNativeImage(WTFMove(buffer));
}

IntSize BitmapImageSource::frameSizeAtIndex(unsigned index, SubsamplingLevel subsamplingLevel) const
{
    return const_cast<BitmapImageSource&>(*this).frameAtIndexCacheIfNeeded(index, subsamplingLevel).size();
}

Seconds BitmapImageSource::frameDurationAtIndex(unsigned index) const
{
    return const_cast<BitmapImageSource&>(*this).frameAtIndexCacheIfNeeded(index).duration();
}

ImageOrientation BitmapImageSource::frameOrientationAtIndex(unsigned index) const
{
    return const_cast<BitmapImageSource&>(*this).frameAtIndexCacheIfNeeded(index).orientation();
}

DecodingStatus BitmapImageSource::frameDecodingStatusAtIndex(unsigned index) const
{
    return const_cast<BitmapImageSource&>(*this).frameAtIndexCacheIfNeeded(index).decodingStatus();
}

RefPtr<ImageObserver> BitmapImageSource::imageObserver() const
{
    return m_bitmapImage ? m_bitmapImage->imageObserver() : nullptr;
}

String BitmapImageSource::mimeType() const
{
    return m_bitmapImage ? m_bitmapImage->mimeType() : emptyString();
}

long long BitmapImageSource::expectedContentLength() const
{
    return m_bitmapImage ? m_bitmapImage->expectedContentLength() : 0;
}

CString BitmapImageSource::sourceUTF8() const
{
    return m_bitmapImage ? m_bitmapImage->sourceUTF8() : ""_s;
}

void BitmapImageSource::setMinimumDecodingDurationForTesting(Seconds duration)
{
    workQueue().setMinimumDecodingDurationForTesting(duration);
}

void BitmapImageSource::dump(TextStream& ts) const
{
    ts.dumpProperty("source-utf8", sourceUTF8());

    if (m_workQueue)
        m_workQueue->dump(ts);

    if (m_frameAnimator)
        m_frameAnimator->dump(ts);

    m_descriptor.dump(ts);

    ts.dumpProperty("decoded-size", m_decodedSize);
    ts.dumpProperty("decode-count-for-testing", m_decodeCountForTesting);
}

} // namespace WebCore