Bug 1698786: part 1) Add some logging to `mozInlineSpellChecker`. r=masayuki
[gecko.git] / image / Decoder.cpp
blob41816114412211ec99c8d3fc14abd98d03566a56
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/. */
6 #include "Decoder.h"
8 #include "DecodePool.h"
9 #include "IDecodingTask.h"
10 #include "ISurfaceProvider.h"
11 #include "gfxPlatform.h"
12 #include "mozilla/gfx/2D.h"
13 #include "mozilla/gfx/Point.h"
14 #include "mozilla/ProfilerLabels.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;
25 namespace mozilla {
26 namespace image {
28 class MOZ_STACK_CLASS AutoRecordDecoderTelemetry final {
29 public:
30 explicit AutoRecordDecoderTelemetry(Decoder* aDecoder) : mDecoder(aDecoder) {
31 MOZ_ASSERT(mDecoder);
33 // Begin recording telemetry data.
34 mStartTime = TimeStamp::Now();
37 ~AutoRecordDecoderTelemetry() {
38 // Finish telemetry.
39 mDecoder->mDecodeTime += (TimeStamp::Now() - mStartTime);
42 private:
43 Decoder* mDecoder;
44 TimeStamp mStartTime;
47 Decoder::Decoder(RasterImage* aImage)
48 : mInProfile(nullptr),
49 mTransform(nullptr),
50 mImageData(nullptr),
51 mImageDataLength(0),
52 mCMSMode(gfxPlatform::GetCMSMode()),
53 mImage(aImage),
54 mFrameRecycler(nullptr),
55 mProgress(NoProgress),
56 mFrameCount(0),
57 mLoopLength(FrameTimeout::Zero()),
58 mDecoderFlags(DefaultDecoderFlags()),
59 mSurfaceFlags(DefaultSurfaceFlags()),
60 mInitialized(false),
61 mMetadataDecode(false),
62 mHaveExplicitOutputSize(false),
63 mInFrame(false),
64 mFinishedNewFrame(false),
65 mHasFrameToTake(false),
66 mReachedTerminalState(false),
67 mDecodeDone(false),
68 mError(false),
69 mShouldReportError(false),
70 mFinalizeFrames(true) {}
72 Decoder::~Decoder() {
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");
77 mInitialized = false;
79 if (mInProfile) {
80 // mTransform belongs to us only if mInProfile is non-null
81 if (mTransform) {
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
89 // decode thread.
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 = CMSMode::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.
114 return nullptr;
117 switch (aFormat) {
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();
126 default:
127 MOZ_ASSERT_UNREACHABLE("Unsupported surface format!");
128 return nullptr;
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();
153 mInitialized = true;
155 return rv;
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.
180 return lexerResult;
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) {
189 PostError();
192 // Perform final cleanup.
193 CompleteDecode();
195 return LexerResult(HasError() ? TerminalState::FAILURE
196 : TerminalState::SUCCESS);
199 LexerResult Decoder::TerminateFailure() {
200 PostError();
202 // Perform final cleanup if need be.
203 if (!mReachedTerminalState) {
204 mReachedTerminalState = true;
205 CompleteDecode();
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();
221 if (NS_FAILED(rv)) {
222 PostError();
225 rv = HasError() ? FinishWithErrorInternal() : FinishInternal();
226 if (NS_FAILED(rv)) {
227 PostError();
230 if (IsMetadataDecode()) {
231 // If this was a metadata decode and we never got a size, the decode failed.
232 if (!HasSize()) {
233 PostError();
235 return;
238 // If the implementation left us mid-frame, finish that up. Note that it may
239 // have left us transparent.
240 if (mInFrame) {
241 PostHasTransparency();
242 PostFrameStop();
245 // If PostDecodeDone() has not been called, we may need to send teardown
246 // notifications if it is unrecoverable.
247 if (!mDecodeDone) {
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();
255 PostDecodeDone();
256 } else {
257 // We're not usable. Record some final progress indicating the error.
258 mProgress |= FLAG_DECODE_COMPLETE | FLAG_HAS_ERROR;
262 if (mDecodeDone) {
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));
309 if (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!");
324 mInFrame = true;
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) {
334 if (HasError()) {
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();
349 if (frameNum == 1) {
350 MOZ_ASSERT(aPreviousFrame, "Must provide a previous frame when animated");
351 aPreviousFrame->SetRawAccessOnly();
354 if (frameNum > 0) {
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
360 // filters.
361 mRestoreFrame = std::move(aPreviousFrame);
362 mRestoreDirtyRect.SetBox(0, 0, 0, 0);
363 } else {
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);
383 if (ref) {
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();
389 if (!blocked) {
390 blocked = NS_FAILED(ref->InitForDecoderRecycle(aAnimParams.ref()));
393 if (blocked) {
394 ref.reset();
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.
401 if (!ref) {
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();
415 if (!ref) {
416 frame->Abort();
417 return RawAccessFrameRef();
420 if (frameNum > 0) {
421 frame->SetRawAccessOnly();
425 mFrameCount++;
427 return ref;
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);
440 return NS_OK;
444 * Progress Notifications
447 void Decoder::PostSize(int32_t aWidth, int32_t aHeight,
448 Orientation aOrientation /* = Orientation()*/) {
449 // Validate.
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()) {
460 PostError();
461 return;
464 // Set our output size if it's not already set.
465 if (!mOutputSize) {
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");
490 // Update our state.
491 mInFrame = false;
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()) {
511 default:
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());
517 break;
518 case DisposalMethod::KEEP:
519 case DisposalMethod::NOT_SPECIFIED:
520 break;
522 } else {
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
532 /* = Nothing() */) {
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!");
549 mDecodeDone = true;
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() {
566 mError = true;
568 if (mInFrame) {
569 MOZ_ASSERT(mCurrentFrame);
570 MOZ_ASSERT(mFrameCount > 0);
571 mCurrentFrame->Abort();
572 mInFrame = false;
573 --mFrameCount;
574 mHasFrameToTake = false;
578 } // namespace image
579 } // namespace mozilla