1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "DecodePool.h"
9 #include "GeckoProfiler.h"
10 #include "IDecodingTask.h"
11 #include "ISurfaceProvider.h"
12 #include "gfxPlatform.h"
13 #include "mozilla/gfx/2D.h"
14 #include "mozilla/gfx/Point.h"
15 #include "mozilla/Telemetry.h"
16 #include "nsComponentManagerUtils.h"
17 #include "nsProxyRelease.h"
18 #include "nsServiceManagerUtils.h"
20 using mozilla::gfx::IntPoint
;
21 using mozilla::gfx::IntRect
;
22 using mozilla::gfx::IntSize
;
23 using mozilla::gfx::SurfaceFormat
;
28 class MOZ_STACK_CLASS AutoRecordDecoderTelemetry final
{
30 explicit AutoRecordDecoderTelemetry(Decoder
* aDecoder
) : mDecoder(aDecoder
) {
33 // Begin recording telemetry data.
34 mStartTime
= TimeStamp::Now();
37 ~AutoRecordDecoderTelemetry() {
39 mDecoder
->mDecodeTime
+= (TimeStamp::Now() - mStartTime
);
47 Decoder::Decoder(RasterImage
* aImage
)
48 : mInProfile(nullptr),
52 mCMSMode(gfxPlatform::GetCMSMode()),
54 mFrameRecycler(nullptr),
55 mProgress(NoProgress
),
57 mLoopLength(FrameTimeout::Zero()),
58 mDecoderFlags(DefaultDecoderFlags()),
59 mSurfaceFlags(DefaultSurfaceFlags()),
61 mMetadataDecode(false),
62 mHaveExplicitOutputSize(false),
64 mFinishedNewFrame(false),
65 mHasFrameToTake(false),
66 mReachedTerminalState(false),
69 mShouldReportError(false),
70 mFinalizeFrames(true) {}
73 MOZ_ASSERT(mProgress
== NoProgress
|| !mImage
,
74 "Destroying Decoder without taking all its progress changes");
75 MOZ_ASSERT(mInvalidRect
.IsEmpty() || !mImage
,
76 "Destroying Decoder without taking all its invalidations");
80 // mTransform belongs to us only if mInProfile is non-null
82 qcms_transform_release(mTransform
);
84 qcms_profile_release(mInProfile
);
87 if (mImage
&& !NS_IsMainThread()) {
88 // Dispatch mImage to main thread to prevent it from being destructed by the
90 SurfaceCache::ReleaseImageOnMainThread(mImage
.forget());
94 void Decoder::SetSurfaceFlags(SurfaceFlags aSurfaceFlags
) {
95 MOZ_ASSERT(!mInitialized
);
96 mSurfaceFlags
= aSurfaceFlags
;
97 if (mSurfaceFlags
& SurfaceFlags::NO_COLORSPACE_CONVERSION
) {
98 mCMSMode
= eCMSMode_Off
;
102 qcms_profile
* Decoder::GetCMSOutputProfile() const {
103 if (mSurfaceFlags
& SurfaceFlags::TO_SRGB_COLORSPACE
) {
104 return gfxPlatform::GetCMSsRGBProfile();
106 return gfxPlatform::GetCMSOutputProfile();
109 qcms_transform
* Decoder::GetCMSsRGBTransform(SurfaceFormat aFormat
) const {
110 if (mSurfaceFlags
& SurfaceFlags::TO_SRGB_COLORSPACE
) {
111 // We want a transform to convert from sRGB to device space, but we are
112 // already using sRGB as our device space. That means we can skip
113 // color management entirely.
118 case SurfaceFormat::B8G8R8A8
:
119 case SurfaceFormat::B8G8R8X8
:
120 return gfxPlatform::GetCMSBGRATransform();
121 case SurfaceFormat::R8G8B8A8
:
122 case SurfaceFormat::R8G8B8X8
:
123 return gfxPlatform::GetCMSRGBATransform();
124 case SurfaceFormat::R8G8B8
:
125 return gfxPlatform::GetCMSRGBTransform();
127 MOZ_ASSERT_UNREACHABLE("Unsupported surface format!");
133 * Common implementation of the decoder interface.
136 nsresult
Decoder::Init() {
137 // No re-initializing
138 MOZ_ASSERT(!mInitialized
, "Can't re-initialize a decoder!");
140 // All decoders must have a SourceBufferIterator.
141 MOZ_ASSERT(mIterator
);
143 // Metadata decoders must not set an output size.
144 MOZ_ASSERT_IF(mMetadataDecode
, !mHaveExplicitOutputSize
);
146 // All decoders must be anonymous except for metadata decoders.
147 // XXX(seth): Soon that exception will be removed.
148 MOZ_ASSERT_IF(mImage
, IsMetadataDecode());
150 // Implementation-specific initialization.
151 nsresult rv
= InitInternal();
158 LexerResult
Decoder::Decode(IResumable
* aOnResume
/* = nullptr */) {
159 MOZ_ASSERT(mInitialized
, "Should be initialized here");
160 MOZ_ASSERT(mIterator
, "Should have a SourceBufferIterator");
162 // If we're already done, don't attempt to keep decoding.
163 if (GetDecodeDone()) {
164 return LexerResult(HasError() ? TerminalState::FAILURE
165 : TerminalState::SUCCESS
);
168 LexerResult
lexerResult(TerminalState::FAILURE
);
170 AUTO_PROFILER_LABEL_CATEGORY_PAIR(GRAPHICS_ImageDecoding
);
171 AutoRecordDecoderTelemetry
telemetry(this);
173 lexerResult
= DoDecode(*mIterator
, aOnResume
);
176 if (lexerResult
.is
<Yield
>()) {
177 // We either need more data to continue (in which case either @aOnResume or
178 // the caller will reschedule us to run again later), or the decoder is
179 // yielding to allow the caller access to some intermediate output.
183 // We reached a terminal state; we're now done decoding.
184 MOZ_ASSERT(lexerResult
.is
<TerminalState
>());
185 mReachedTerminalState
= true;
187 // If decoding failed, record that fact.
188 if (lexerResult
.as
<TerminalState
>() == TerminalState::FAILURE
) {
192 // Perform final cleanup.
195 return LexerResult(HasError() ? TerminalState::FAILURE
196 : TerminalState::SUCCESS
);
199 LexerResult
Decoder::TerminateFailure() {
202 // Perform final cleanup if need be.
203 if (!mReachedTerminalState
) {
204 mReachedTerminalState
= true;
208 return LexerResult(TerminalState::FAILURE
);
211 bool Decoder::ShouldSyncDecode(size_t aByteLimit
) {
212 MOZ_ASSERT(aByteLimit
> 0);
213 MOZ_ASSERT(mIterator
, "Should have a SourceBufferIterator");
215 return mIterator
->RemainingBytesIsNoMoreThan(aByteLimit
);
218 void Decoder::CompleteDecode() {
219 // Implementation-specific finalization.
220 nsresult rv
= BeforeFinishInternal();
225 rv
= HasError() ? FinishWithErrorInternal() : FinishInternal();
230 if (IsMetadataDecode()) {
231 // If this was a metadata decode and we never got a size, the decode failed.
238 // If the implementation left us mid-frame, finish that up. Note that it may
239 // have left us transparent.
241 PostHasTransparency();
245 // If PostDecodeDone() has not been called, we may need to send teardown
246 // notifications if it is unrecoverable.
248 // We should always report an error to the console in this case.
249 mShouldReportError
= true;
251 if (GetCompleteFrameCount() > 0) {
252 // We're usable if we have at least one complete frame, so do exactly
253 // what we should have when the decoder completed.
254 PostHasTransparency();
257 // We're not usable. Record some final progress indicating the error.
258 mProgress
|= FLAG_DECODE_COMPLETE
| FLAG_HAS_ERROR
;
263 MOZ_ASSERT(HasError() || mCurrentFrame
, "Should have an error or a frame");
265 // If this image wasn't animated and isn't a transient image, mark its frame
266 // as optimizable. We don't support optimizing animated images and
267 // optimizing transient images isn't worth it.
268 if (!HasAnimation() &&
269 !(mDecoderFlags
& DecoderFlags::IMAGE_IS_TRANSIENT
) && mCurrentFrame
) {
270 mCurrentFrame
->SetOptimizable();
275 void Decoder::SetOutputSize(const gfx::IntSize
& aSize
) {
276 mOutputSize
= Some(aSize
);
277 mHaveExplicitOutputSize
= true;
280 Maybe
<gfx::IntSize
> Decoder::ExplicitOutputSize() const {
281 MOZ_ASSERT_IF(mHaveExplicitOutputSize
, mOutputSize
);
282 return mHaveExplicitOutputSize
? mOutputSize
: Nothing();
285 Maybe
<uint32_t> Decoder::TakeCompleteFrameCount() {
286 const bool finishedNewFrame
= mFinishedNewFrame
;
287 mFinishedNewFrame
= false;
288 return finishedNewFrame
? Some(GetCompleteFrameCount()) : Nothing();
291 DecoderFinalStatus
Decoder::FinalStatus() const {
292 return DecoderFinalStatus(IsMetadataDecode(), GetDecodeDone(), HasError(),
293 ShouldReportError());
296 DecoderTelemetry
Decoder::Telemetry() const {
297 MOZ_ASSERT(mIterator
);
298 return DecoderTelemetry(SpeedHistogram(),
299 mIterator
? mIterator
->ByteCount() : 0,
300 mIterator
? mIterator
->ChunkCount() : 0, mDecodeTime
);
303 nsresult
Decoder::AllocateFrame(const gfx::IntSize
& aOutputSize
,
304 gfx::SurfaceFormat aFormat
,
305 const Maybe
<AnimationParams
>& aAnimParams
) {
306 mCurrentFrame
= AllocateFrameInternal(aOutputSize
, aFormat
, aAnimParams
,
307 std::move(mCurrentFrame
));
310 mHasFrameToTake
= true;
312 // Gather the raw pointers the decoders will use.
313 mCurrentFrame
->GetImageData(&mImageData
, &mImageDataLength
);
315 // We should now be on |aFrameNum|. (Note that we're comparing the frame
316 // number, which is zero-based, with the frame count, which is one-based.)
317 MOZ_ASSERT_IF(aAnimParams
, aAnimParams
->mFrameNum
+ 1 == mFrameCount
);
319 // If we're past the first frame, PostIsAnimated() should've been called.
320 MOZ_ASSERT_IF(mFrameCount
> 1, HasAnimation());
322 // Update our state to reflect the new frame.
323 MOZ_ASSERT(!mInFrame
, "Starting new frame but not done with old one!");
327 return mCurrentFrame
? NS_OK
: NS_ERROR_FAILURE
;
330 RawAccessFrameRef
Decoder::AllocateFrameInternal(
331 const gfx::IntSize
& aOutputSize
, SurfaceFormat aFormat
,
332 const Maybe
<AnimationParams
>& aAnimParams
,
333 RawAccessFrameRef
&& aPreviousFrame
) {
335 return RawAccessFrameRef();
338 uint32_t frameNum
= aAnimParams
? aAnimParams
->mFrameNum
: 0;
339 if (frameNum
!= mFrameCount
) {
340 MOZ_ASSERT_UNREACHABLE("Allocating frames out of order");
341 return RawAccessFrameRef();
344 if (aOutputSize
.width
<= 0 || aOutputSize
.height
<= 0) {
345 NS_WARNING("Trying to add frame with zero or negative size");
346 return RawAccessFrameRef();
350 MOZ_ASSERT(aPreviousFrame
, "Must provide a previous frame when animated");
351 aPreviousFrame
->SetRawAccessOnly();
355 if (aPreviousFrame
->GetDisposalMethod() !=
356 DisposalMethod::RESTORE_PREVIOUS
) {
357 // If the new restore frame is the direct previous frame, then we know
358 // the dirty rect is composed only of the current frame's blend rect and
359 // the restore frame's clear rect (if applicable) which are handled in
361 mRestoreFrame
= std::move(aPreviousFrame
);
362 mRestoreDirtyRect
.SetBox(0, 0, 0, 0);
364 // We only need the previous frame's dirty rect, because while there may
365 // have been several frames between us and mRestoreFrame, the only areas
366 // that changed are the restore frame's clear rect, the current frame
367 // blending rect, and the previous frame's blending rect. All else is
368 // forgotten due to us restoring the same frame again.
369 mRestoreDirtyRect
= aPreviousFrame
->GetBoundedBlendRect();
373 RawAccessFrameRef ref
;
375 // If we have a frame recycler, it must be for an animated image producing
376 // full frames. If the higher layers are discarding frames because of the
377 // memory footprint, then the recycler will allow us to reuse the buffers.
378 // Each frame should be the same size and have mostly the same properties.
379 if (mFrameRecycler
) {
380 MOZ_ASSERT(aAnimParams
);
382 ref
= mFrameRecycler
->RecycleFrame(mRecycleRect
);
384 // If the recycled frame is actually the current restore frame, we cannot
385 // use it. If the next restore frame is the new frame we are creating, in
386 // theory we could reuse it, but we would need to store the restore frame
387 // animation parameters elsewhere. For now we just drop it.
388 bool blocked
= ref
.get() == mRestoreFrame
.get();
390 blocked
= NS_FAILED(ref
->InitForDecoderRecycle(aAnimParams
.ref()));
399 // Either the recycler had nothing to give us, or we don't have a recycler.
400 // Produce a new frame to store the data.
402 // There is no underlying data to reuse, so reset the recycle rect to be
403 // the full frame, to ensure the restore frame is fully copied.
404 mRecycleRect
= IntRect(IntPoint(0, 0), aOutputSize
);
406 bool nonPremult
= bool(mSurfaceFlags
& SurfaceFlags::NO_PREMULTIPLY_ALPHA
);
407 auto frame
= MakeNotNull
<RefPtr
<imgFrame
>>();
408 if (NS_FAILED(frame
->InitForDecoder(aOutputSize
, aFormat
, nonPremult
,
409 aAnimParams
, bool(mFrameRecycler
)))) {
410 NS_WARNING("imgFrame::Init should succeed");
411 return RawAccessFrameRef();
414 ref
= frame
->RawAccessRef();
417 return RawAccessFrameRef();
421 frame
->SetRawAccessOnly();
431 * Hook stubs. Override these as necessary in decoder implementations.
434 nsresult
Decoder::InitInternal() { return NS_OK
; }
435 nsresult
Decoder::BeforeFinishInternal() { return NS_OK
; }
436 nsresult
Decoder::FinishInternal() { return NS_OK
; }
438 nsresult
Decoder::FinishWithErrorInternal() {
439 MOZ_ASSERT(!mInFrame
);
444 * Progress Notifications
447 void Decoder::PostSize(int32_t aWidth
, int32_t aHeight
,
448 Orientation aOrientation
/* = Orientation()*/) {
450 MOZ_ASSERT(aWidth
>= 0, "Width can't be negative!");
451 MOZ_ASSERT(aHeight
>= 0, "Height can't be negative!");
453 // Set our intrinsic size.
454 mImageMetadata
.SetSize(aWidth
, aHeight
, aOrientation
);
456 // Verify it is the expected size, if given. Note that this is only used by
457 // the ICO decoder for embedded image types, so only its subdecoders are
458 // required to handle failures in PostSize.
459 if (!IsExpectedSize()) {
464 // Set our output size if it's not already set.
466 mOutputSize
= Some(IntSize(aWidth
, aHeight
));
469 MOZ_ASSERT(mOutputSize
->width
<= aWidth
&& mOutputSize
->height
<= aHeight
,
470 "Output size will result in upscaling");
472 // Record this notification.
473 mProgress
|= FLAG_SIZE_AVAILABLE
;
476 void Decoder::PostHasTransparency() { mProgress
|= FLAG_HAS_TRANSPARENCY
; }
478 void Decoder::PostIsAnimated(FrameTimeout aFirstFrameTimeout
) {
479 mProgress
|= FLAG_IS_ANIMATED
;
480 mImageMetadata
.SetHasAnimation();
481 mImageMetadata
.SetFirstFrameTimeout(aFirstFrameTimeout
);
484 void Decoder::PostFrameStop(Opacity aFrameOpacity
) {
485 // We should be mid-frame
486 MOZ_ASSERT(!IsMetadataDecode(), "Stopping frame during metadata decode");
487 MOZ_ASSERT(mInFrame
, "Stopping frame when we didn't start one");
488 MOZ_ASSERT(mCurrentFrame
, "Stopping frame when we don't have one");
492 mFinishedNewFrame
= true;
494 mCurrentFrame
->Finish(aFrameOpacity
, mFinalizeFrames
);
496 mProgress
|= FLAG_FRAME_COMPLETE
;
498 mLoopLength
+= mCurrentFrame
->GetTimeout();
500 if (mFrameCount
== 1) {
501 // If we're not sending partial invalidations, then we send an invalidation
502 // here when the first frame is complete.
503 if (!ShouldSendPartialInvalidations()) {
504 mInvalidRect
.UnionRect(mInvalidRect
, IntRect(IntPoint(), Size()));
507 // If we dispose of the first frame by clearing it, then the first frame's
508 // refresh area is all of itself. RESTORE_PREVIOUS is invalid (assumed to
509 // be DISPOSE_CLEAR).
510 switch (mCurrentFrame
->GetDisposalMethod()) {
512 MOZ_FALLTHROUGH_ASSERT("Unexpected DisposalMethod");
513 case DisposalMethod::CLEAR
:
514 case DisposalMethod::CLEAR_ALL
:
515 case DisposalMethod::RESTORE_PREVIOUS
:
516 mFirstFrameRefreshArea
= IntRect(IntPoint(), Size());
518 case DisposalMethod::KEEP
:
519 case DisposalMethod::NOT_SPECIFIED
:
523 // Some GIFs are huge but only have a small area that they animate. We only
524 // need to refresh that small area when frame 0 comes around again.
525 mFirstFrameRefreshArea
.UnionRect(mFirstFrameRefreshArea
,
526 mCurrentFrame
->GetBoundedBlendRect());
530 void Decoder::PostInvalidation(const gfx::IntRect
& aRect
,
531 const Maybe
<gfx::IntRect
>& aRectAtOutputSize
533 // We should be mid-frame
534 MOZ_ASSERT(mInFrame
, "Can't invalidate when not mid-frame!");
535 MOZ_ASSERT(mCurrentFrame
, "Can't invalidate when not mid-frame!");
537 // Record this invalidation, unless we're not sending partial invalidations
538 // or we're past the first frame.
539 if (ShouldSendPartialInvalidations() && mFrameCount
== 1) {
540 mInvalidRect
.UnionRect(mInvalidRect
, aRect
);
541 mCurrentFrame
->ImageUpdated(aRectAtOutputSize
.valueOr(aRect
));
545 void Decoder::PostDecodeDone(int32_t aLoopCount
/* = 0 */) {
546 MOZ_ASSERT(!IsMetadataDecode(), "Done with decoding in metadata decode");
547 MOZ_ASSERT(!mInFrame
, "Can't be done decoding if we're mid-frame!");
548 MOZ_ASSERT(!mDecodeDone
, "Decode already done!");
551 mImageMetadata
.SetLoopCount(aLoopCount
);
553 // Some metadata that we track should take into account every frame in the
554 // image. If this is a first-frame-only decode, our accumulated loop length
555 // and first frame refresh area only includes the first frame, so it's not
556 // correct and we don't record it.
557 if (!IsFirstFrameDecode()) {
558 mImageMetadata
.SetLoopLength(mLoopLength
);
559 mImageMetadata
.SetFirstFrameRefreshArea(mFirstFrameRefreshArea
);
562 mProgress
|= FLAG_DECODE_COMPLETE
;
565 void Decoder::PostError() {
569 MOZ_ASSERT(mCurrentFrame
);
570 MOZ_ASSERT(mFrameCount
> 0);
571 mCurrentFrame
->Abort();
574 mHasFrameToTake
= false;
579 } // namespace mozilla