Bug 1608150 [wpt PR 21112] - Add missing space in `./wpt lint` command line docs...
[gecko.git] / image / IDecodingTask.cpp
blobaba407d59263e4035270ea87c0d721f9ad0acbd7
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 "IDecodingTask.h"
8 #include "nsThreadUtils.h"
10 #include "Decoder.h"
11 #include "DecodePool.h"
12 #include "RasterImage.h"
13 #include "SurfaceCache.h"
15 #include "mozilla/SystemGroup.h"
17 namespace mozilla {
19 using gfx::IntRect;
21 namespace image {
23 ///////////////////////////////////////////////////////////////////////////////
24 // Helpers for sending notifications to the image associated with a decoder.
25 ///////////////////////////////////////////////////////////////////////////////
27 void IDecodingTask::EnsureHasEventTarget(NotNull<RasterImage*> aImage) {
28 if (!mEventTarget) {
29 // We determine the event target as late as possible, at the first dispatch
30 // time, because the observers bound to an imgRequest will affect it.
31 // We cache it rather than query for the event target each time because the
32 // event target can change. We don't want to risk events being executed in
33 // a different order than they are dispatched, which can happen if we
34 // selected scheduler groups which have no ordering guarantees relative to
35 // each other (e.g. it moves from scheduler group A for doc group DA to
36 // scheduler group B for doc group DB due to changing observers -- if we
37 // dispatched the first event on A, and the second on B, we don't know which
38 // will execute first.)
39 RefPtr<ProgressTracker> tracker = aImage->GetProgressTracker();
40 if (tracker) {
41 mEventTarget = tracker->GetEventTarget();
42 } else {
43 mEventTarget = SystemGroup::EventTargetFor(TaskCategory::Other);
48 bool IDecodingTask::IsOnEventTarget() const {
49 // This is essentially equivalent to NS_IsOnMainThread() because all of the
50 // event targets are for the main thread (although perhaps with a different
51 // label / scheduler group). The observers in ProgressTracker may have
52 // different event targets from this, so this is just a best effort guess.
53 bool current = false;
54 mEventTarget->IsOnCurrentThread(&current);
55 return current;
58 void IDecodingTask::NotifyProgress(NotNull<RasterImage*> aImage,
59 NotNull<Decoder*> aDecoder) {
60 MOZ_ASSERT(aDecoder->HasProgress() && !aDecoder->IsMetadataDecode());
61 EnsureHasEventTarget(aImage);
63 // Capture the decoder's state. If we need to notify asynchronously, it's
64 // important that we don't wait until the lambda actually runs to capture the
65 // state that we're going to notify. That would both introduce data races on
66 // the decoder's state and cause inconsistencies between the NotifyProgress()
67 // calls we make off-main-thread and the notifications that RasterImage
68 // actually receives, which would cause bugs.
69 Progress progress = aDecoder->TakeProgress();
70 IntRect invalidRect = aDecoder->TakeInvalidRect();
71 Maybe<uint32_t> frameCount = aDecoder->TakeCompleteFrameCount();
72 DecoderFlags decoderFlags = aDecoder->GetDecoderFlags();
73 SurfaceFlags surfaceFlags = aDecoder->GetSurfaceFlags();
75 // Synchronously notify if we can.
76 if (IsOnEventTarget() && !(decoderFlags & DecoderFlags::ASYNC_NOTIFY)) {
77 aImage->NotifyProgress(progress, invalidRect, frameCount, decoderFlags,
78 surfaceFlags);
79 return;
82 // We're forced to notify asynchronously.
83 NotNull<RefPtr<RasterImage>> image = aImage;
84 mEventTarget->Dispatch(CreateMediumHighRunnable(NS_NewRunnableFunction(
85 "IDecodingTask::NotifyProgress",
86 [=]() -> void {
87 image->NotifyProgress(progress, invalidRect,
88 frameCount, decoderFlags,
89 surfaceFlags);
90 })),
91 NS_DISPATCH_NORMAL);
94 void IDecodingTask::NotifyDecodeComplete(NotNull<RasterImage*> aImage,
95 NotNull<Decoder*> aDecoder) {
96 MOZ_ASSERT(aDecoder->HasError() || !aDecoder->InFrame(),
97 "Decode complete in the middle of a frame?");
98 EnsureHasEventTarget(aImage);
100 // Capture the decoder's state.
101 DecoderFinalStatus finalStatus = aDecoder->FinalStatus();
102 ImageMetadata metadata = aDecoder->GetImageMetadata();
103 DecoderTelemetry telemetry = aDecoder->Telemetry();
104 Progress progress = aDecoder->TakeProgress();
105 IntRect invalidRect = aDecoder->TakeInvalidRect();
106 Maybe<uint32_t> frameCount = aDecoder->TakeCompleteFrameCount();
107 DecoderFlags decoderFlags = aDecoder->GetDecoderFlags();
108 SurfaceFlags surfaceFlags = aDecoder->GetSurfaceFlags();
110 // Synchronously notify if we can.
111 if (IsOnEventTarget() && !(decoderFlags & DecoderFlags::ASYNC_NOTIFY)) {
112 aImage->NotifyDecodeComplete(finalStatus, metadata, telemetry, progress,
113 invalidRect, frameCount, decoderFlags,
114 surfaceFlags);
115 return;
118 // We're forced to notify asynchronously.
119 NotNull<RefPtr<RasterImage>> image = aImage;
120 mEventTarget->Dispatch(CreateMediumHighRunnable(NS_NewRunnableFunction(
121 "IDecodingTask::NotifyDecodeComplete",
122 [=]() -> void {
123 image->NotifyDecodeComplete(
124 finalStatus, metadata, telemetry, progress,
125 invalidRect, frameCount, decoderFlags,
126 surfaceFlags);
127 })),
128 NS_DISPATCH_NORMAL);
131 ///////////////////////////////////////////////////////////////////////////////
132 // IDecodingTask implementation.
133 ///////////////////////////////////////////////////////////////////////////////
135 void IDecodingTask::Resume() { DecodePool::Singleton()->AsyncRun(this); }
137 ///////////////////////////////////////////////////////////////////////////////
138 // MetadataDecodingTask implementation.
139 ///////////////////////////////////////////////////////////////////////////////
141 MetadataDecodingTask::MetadataDecodingTask(NotNull<Decoder*> aDecoder)
142 : mMutex("mozilla::image::MetadataDecodingTask"), mDecoder(aDecoder) {
143 MOZ_ASSERT(mDecoder->IsMetadataDecode(),
144 "Use DecodingTask for non-metadata decodes");
147 void MetadataDecodingTask::Run() {
148 MutexAutoLock lock(mMutex);
150 LexerResult result = mDecoder->Decode(WrapNotNull(this));
152 if (result.is<TerminalState>()) {
153 NotifyDecodeComplete(mDecoder->GetImage(), mDecoder);
154 return; // We're done.
157 if (result == LexerResult(Yield::NEED_MORE_DATA)) {
158 // We can't make any more progress right now. We also don't want to report
159 // any progress, because it's important that metadata decode results are
160 // delivered atomically. The decoder itself will ensure that we get
161 // reenqueued when more data is available; just return for now.
162 return;
165 MOZ_ASSERT_UNREACHABLE("Metadata decode yielded for an unexpected reason");
168 ///////////////////////////////////////////////////////////////////////////////
169 // AnonymousDecodingTask implementation.
170 ///////////////////////////////////////////////////////////////////////////////
172 AnonymousDecodingTask::AnonymousDecodingTask(NotNull<Decoder*> aDecoder,
173 bool aResumable)
174 : mDecoder(aDecoder), mResumable(aResumable) {}
176 void AnonymousDecodingTask::Run() {
177 while (true) {
178 LexerResult result = mDecoder->Decode(WrapNotNull(this));
180 if (result.is<TerminalState>()) {
181 return; // We're done.
184 if (result == LexerResult(Yield::NEED_MORE_DATA)) {
185 // We can't make any more progress right now. Let the caller decide how to
186 // handle it.
187 return;
190 // Right now we don't do anything special for other kinds of yields, so just
191 // keep working.
192 MOZ_ASSERT(result.is<Yield>());
196 void AnonymousDecodingTask::Resume() {
197 // Anonymous decoders normally get all their data at once. We have tests
198 // where they don't; typically in these situations, the test re-runs them
199 // manually. However some tests want to verify Resume works, so they will
200 // explicitly request this behaviour.
201 if (mResumable) {
202 RefPtr<AnonymousDecodingTask> self(this);
203 NS_DispatchToMainThread(
204 NS_NewRunnableFunction("image::AnonymousDecodingTask::Resume",
205 [self]() -> void { self->Run(); }));
209 } // namespace image
210 } // namespace mozilla