#include "config.h"
#include "BitmapImage.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "ImageBuffer.h"
#include "ImageObserver.h"
#include "IntRect.h"
#include "Logging.h"
#include "MIMETypeRegistry.h"
#include "TextStream.h"
#include "Timer.h"
#include <wtf/CurrentTime.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>
#if PLATFORM(IOS)
#include <limits>
#endif
namespace WebCore {
BitmapImage::BitmapImage(ImageObserver* observer)
: Image(observer)
, m_source(this)
{
}
BitmapImage::BitmapImage(NativeImagePtr&& image, ImageObserver* observer)
: Image(observer)
, m_source(WTFMove(image))
{
}
BitmapImage::~BitmapImage()
{
invalidatePlatformData();
stopAnimation();
}
void BitmapImage::destroyDecodedData(bool destroyAll)
{
if (!destroyAll)
m_source.destroyDecodedDataBeforeFrame(m_currentFrame);
else if (m_source.hasDecodingQueue())
m_source.destroyAllDecodedDataExcludeFrame(m_currentFrame);
else
m_source.destroyAllDecodedData();
if (!destroyAll || m_source.hasDecodingQueue())
m_source.clearFrameBufferCache(m_currentFrame);
else
m_source.clear(data());
invalidatePlatformData();
}
void BitmapImage::destroyDecodedDataIfNecessary(bool destroyAll)
{
if (!data() && frameCount())
return;
if (m_source.decodedSize() < LargeAnimationCutoff)
return;
destroyDecodedData(destroyAll);
}
bool BitmapImage::dataChanged(bool allDataReceived)
{
return m_source.dataChanged(data(), allDataReceived);
}
NativeImagePtr BitmapImage::frameImageAtIndex(size_t index, SubsamplingLevel subsamplingLevel, const GraphicsContext* targetContext)
{
if (!frameHasValidNativeImageAtIndex(index, subsamplingLevel)) {
LOG(Images, "BitmapImage %p %s - subsamplingLevel was %d, resampling", this, __FUNCTION__, static_cast<int>(frameSubsamplingLevelAtIndex(index)));
invalidatePlatformData();
}
return m_source.frameImageAtIndex(index, subsamplingLevel, targetContext);
}
NativeImagePtr BitmapImage::nativeImage(const GraphicsContext* targetContext)
{
return frameImageAtIndex(0, SubsamplingLevel::Default, targetContext);
}
NativeImagePtr BitmapImage::nativeImageForCurrentFrame(const GraphicsContext* targetContext)
{
return frameImageAtIndex(m_currentFrame, SubsamplingLevel::Default, targetContext);
}
#if USE(CG)
NativeImagePtr BitmapImage::nativeImageOfSize(const IntSize& size, const GraphicsContext* targetContext)
{
size_t count = frameCount();
for (size_t i = 0; i < count; ++i) {
auto image = frameImageAtIndex(i, SubsamplingLevel::Default, targetContext);
if (image && nativeImageSize(image) == size)
return image;
}
return frameImageAtIndex(0, SubsamplingLevel::Default, targetContext);
}
Vector<NativeImagePtr> BitmapImage::framesNativeImages()
{
Vector<NativeImagePtr> images;
size_t count = frameCount();
for (size_t i = 0; i < count; ++i) {
if (auto image = frameImageAtIndex(i))
images.append(image);
}
return images;
}
#endif
#if !ASSERT_DISABLED
bool BitmapImage::notSolidColor()
{
return size().width() != 1 || size().height() != 1 || frameCount() > 1;
}
#endif
void BitmapImage::draw(GraphicsContext& context, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, BlendMode mode, ImageOrientationDescription description)
{
if (destRect.isEmpty() || srcRect.isEmpty())
return;
StartAnimationResult result = internalStartAnimation();
Color color;
if (result == StartAnimationResult::DecodingActive && showDebugBackground())
color = Color::yellow;
else
color = singlePixelSolidColor();
if (color.isValid()) {
fillWithSolidColor(context, destRect, color, op);
return;
}
float scale = subsamplingScale(context, destRect, srcRect);
m_currentSubsamplingLevel = allowSubsampling() ? m_source.subsamplingLevelForScale(scale) : SubsamplingLevel::Default;
LOG(Images, "BitmapImage %p draw - subsamplingLevel %d at scale %.4f", this, static_cast<int>(m_currentSubsamplingLevel), scale);
ASSERT_IMPLIES(result == StartAnimationResult::DecodingActive, m_source.frameHasValidNativeImageAtIndex(m_currentFrame, m_currentSubsamplingLevel));
auto image = frameImageAtIndex(m_currentFrame, m_currentSubsamplingLevel, &context);
if (!image) return;
ImageOrientation orientation(description.imageOrientation());
if (description.respectImageOrientation() == RespectImageOrientation)
orientation = frameOrientationAtIndex(m_currentFrame);
drawNativeImage(image, context, destRect, srcRect, IntSize(size()), op, mode, orientation);
if (imageObserver())
imageObserver()->didDraw(this);
}
void BitmapImage::drawPattern(GraphicsContext& ctxt, const FloatRect& destRect, const FloatRect& tileRect, const AffineTransform& transform, const FloatPoint& phase, const FloatSize& spacing, CompositeOperator op, BlendMode blendMode)
{
if (tileRect.isEmpty())
return;
if (!ctxt.drawLuminanceMask()) {
Image::drawPattern(ctxt, destRect, tileRect, transform, phase, spacing, op, blendMode);
return;
}
if (!m_cachedImage) {
auto buffer = ImageBuffer::createCompatibleBuffer(expandedIntSize(tileRect.size()), ColorSpaceSRGB, ctxt);
if (!buffer)
return;
ImageObserver* observer = imageObserver();
setImageObserver(nullptr);
draw(buffer->context(), tileRect, tileRect, op, blendMode, ImageOrientationDescription());
setImageObserver(observer);
buffer->convertToLuminanceMask();
m_cachedImage = buffer->copyImage(DontCopyBackingStore, Unscaled);
if (!m_cachedImage)
return;
}
ctxt.setDrawLuminanceMask(false);
m_cachedImage->drawPattern(ctxt, destRect, tileRect, transform, phase, spacing, op, blendMode);
}
bool BitmapImage::shouldAnimate()
{
return repetitionCount() && !m_animationFinished && imageObserver();
}
bool BitmapImage::canAnimate()
{
return shouldAnimate() && frameCount() > 1;
}
void BitmapImage::clearTimer()
{
m_frameTimer = nullptr;
}
void BitmapImage::startTimer(double delay)
{
ASSERT(!m_frameTimer);
m_frameTimer = std::make_unique<Timer>(*this, &BitmapImage::advanceAnimation);
m_frameTimer->startOneShot(delay);
}
BitmapImage::StartAnimationResult BitmapImage::internalStartAnimation()
{
if (!canAnimate())
return StartAnimationResult::CannotStart;
if (m_frameTimer)
return StartAnimationResult::TimerActive;
size_t nextFrame = (m_currentFrame + 1) % frameCount();
if (frameIsBeingDecodedAtIndex(nextFrame))
return StartAnimationResult::DecodingActive;
if (m_currentFrame >= frameCount() - 1) {
if (!m_source.isAllDataReceived() && repetitionCount() == RepetitionCountOnce)
return StartAnimationResult::IncompleteData;
++m_repetitionsComplete;
if (repetitionCount() != RepetitionCountInfinite && m_repetitionsComplete >= repetitionCount()) {
m_animationFinished = true;
destroyDecodedDataIfNecessary(false);
return StartAnimationResult::CannotStart;
}
destroyDecodedDataIfNecessary(true);
}
if (!m_source.isAllDataReceived() && !frameIsCompleteAtIndex(nextFrame))
return StartAnimationResult::IncompleteData;
double time = monotonicallyIncreasingTime();
if (!m_desiredFrameStartTime)
m_desiredFrameStartTime = time;
m_desiredFrameStartTime = std::max(time, m_desiredFrameStartTime + frameDurationAtIndex(m_currentFrame));
if ((allowAnimatedImageAsyncDecoding() && m_source.isAsyncDecodingRequired()) || isAsyncDecodingForcedForTesting()) {
if (!m_source.requestFrameAsyncDecodingAtIndex(nextFrame, m_currentSubsamplingLevel))
LOG(Images, "BitmapImage %p %s - cachedFrameCount %ld nextFrame %ld", this, __FUNCTION__, ++m_cachedFrameCount, nextFrame);
m_desiredFrameDecodeTimeForTesting = time + std::max(m_frameDecodingDurationForTesting, 0.0f);
}
ASSERT(!m_frameTimer);
startTimer(m_desiredFrameStartTime - time);
return StartAnimationResult::Started;
}
void BitmapImage::advanceAnimation()
{
clearTimer();
if (isAsyncDecodingForcedForTesting()) {
double time = monotonicallyIncreasingTime();
if (m_desiredFrameDecodeTimeForTesting > std::max(time, m_desiredFrameStartTime)) {
startTimer(m_desiredFrameDecodeTimeForTesting - time);
return;
}
}
size_t nextFrame = (m_currentFrame + 1) % frameCount();
if (!frameIsBeingDecodedAtIndex(nextFrame))
internalAdvanceAnimation();
else {
if (showDebugBackground())
imageObserver()->changedInRect(this);
LOG(Images, "BitmapImage %p %s - lateFrameCount %ld nextFrame %ld", this, __FUNCTION__, ++m_lateFrameCount, nextFrame);
}
}
void BitmapImage::internalAdvanceAnimation()
{
m_currentFrame = (m_currentFrame + 1) % frameCount();
ASSERT(!frameIsBeingDecodedAtIndex(m_currentFrame));
destroyDecodedDataIfNecessary(false);
if (imageObserver())
imageObserver()->animationAdvanced(this);
}
void BitmapImage::stopAnimation()
{
clearTimer();
m_source.stopAsyncDecodingQueue();
}
void BitmapImage::resetAnimation()
{
stopAnimation();
m_currentFrame = 0;
m_repetitionsComplete = RepetitionCountNone;
m_desiredFrameStartTime = 0;
m_animationFinished = false;
destroyDecodedDataIfNecessary(true);
}
void BitmapImage::newFrameNativeImageAvailableAtIndex(size_t index)
{
UNUSED_PARAM(index);
ASSERT(index == (m_currentFrame + 1) % frameCount());
if (canAnimate() && !m_frameTimer)
internalAdvanceAnimation();
else
LOG(Images, "BitmapImage %p %s - earlyFrameCount %ld nextFrame %ld", this, __FUNCTION__, ++m_earlyFrameCount, index);
}
void BitmapImage::dump(TextStream& ts) const
{
Image::dump(ts);
if (isAnimated())
ts.dumpProperty("current-frame", m_currentFrame);
m_source.dump(ts);
}
}