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/. */
5
6 #include "IDecodingTask.h"
7
8 #include "nsThreadUtils.h"
9
10 #include "Decoder.h"
11 #include "DecodePool.h"
12 #include "RasterImage.h"
13 #include "SurfaceCache.h"
14
15 namespace mozilla {
16
17 using gfx::IntRect;
18
19 namespace image {
20
21 ///////////////////////////////////////////////////////////////////////////////
22 // Helpers for sending notifications to the image associated with a decoder.
23 ///////////////////////////////////////////////////////////////////////////////
24
EnsureHasEventTarget(NotNull<RasterImage * > aImage)25 void IDecodingTask::EnsureHasEventTarget(NotNull<RasterImage*> aImage) {
26 if (!mEventTarget) {
27 // We determine the event target as late as possible, at the first dispatch
28 // time, because the observers bound to an imgRequest will affect it.
29 // We cache it rather than query for the event target each time because the
30 // event target can change. We don't want to risk events being executed in
31 // a different order than they are dispatched, which can happen if we
32 // selected scheduler groups which have no ordering guarantees relative to
33 // each other (e.g. it moves from scheduler group A for doc group DA to
34 // scheduler group B for doc group DB due to changing observers -- if we
35 // dispatched the first event on A, and the second on B, we don't know which
36 // will execute first.)
37 RefPtr<ProgressTracker> tracker = aImage->GetProgressTracker();
38 if (tracker) {
39 mEventTarget = tracker->GetEventTarget();
40 } else {
41 mEventTarget = GetMainThreadSerialEventTarget();
42 }
43 }
44 }
45
IsOnEventTarget() const46 bool IDecodingTask::IsOnEventTarget() const {
47 // This is essentially equivalent to NS_IsOnMainThread() because all of the
48 // event targets are for the main thread (although perhaps with a different
49 // label / scheduler group). The observers in ProgressTracker may have
50 // different event targets from this, so this is just a best effort guess.
51 bool current = false;
52 mEventTarget->IsOnCurrentThread(¤t);
53 return current;
54 }
55
NotifyProgress(NotNull<RasterImage * > aImage,NotNull<Decoder * > aDecoder)56 void IDecodingTask::NotifyProgress(NotNull<RasterImage*> aImage,
57 NotNull<Decoder*> aDecoder) {
58 MOZ_ASSERT(aDecoder->HasProgress() && !aDecoder->IsMetadataDecode());
59 EnsureHasEventTarget(aImage);
60
61 // Capture the decoder's state. If we need to notify asynchronously, it's
62 // important that we don't wait until the lambda actually runs to capture the
63 // state that we're going to notify. That would both introduce data races on
64 // the decoder's state and cause inconsistencies between the NotifyProgress()
65 // calls we make off-main-thread and the notifications that RasterImage
66 // actually receives, which would cause bugs.
67 Progress progress = aDecoder->TakeProgress();
68 UnorientedIntRect invalidRect =
69 UnorientedIntRect::FromUnknownRect(aDecoder->TakeInvalidRect());
70 Maybe<uint32_t> frameCount = aDecoder->TakeCompleteFrameCount();
71 DecoderFlags decoderFlags = aDecoder->GetDecoderFlags();
72 SurfaceFlags surfaceFlags = aDecoder->GetSurfaceFlags();
73
74 // Synchronously notify if we can.
75 if (IsOnEventTarget() && !(decoderFlags & DecoderFlags::ASYNC_NOTIFY)) {
76 aImage->NotifyProgress(progress, invalidRect, frameCount, decoderFlags,
77 surfaceFlags);
78 return;
79 }
80
81 // We're forced to notify asynchronously.
82 NotNull<RefPtr<RasterImage>> image = aImage;
83 mEventTarget->Dispatch(CreateMediumHighRunnable(NS_NewRunnableFunction(
84 "IDecodingTask::NotifyProgress",
85 [=]() -> void {
86 image->NotifyProgress(progress, invalidRect,
87 frameCount, decoderFlags,
88 surfaceFlags);
89 })),
90 NS_DISPATCH_NORMAL);
91 }
92
NotifyDecodeComplete(NotNull<RasterImage * > aImage,NotNull<Decoder * > aDecoder)93 void IDecodingTask::NotifyDecodeComplete(NotNull<RasterImage*> aImage,
94 NotNull<Decoder*> aDecoder) {
95 MOZ_ASSERT(aDecoder->HasError() || !aDecoder->InFrame(),
96 "Decode complete in the middle of a frame?");
97 EnsureHasEventTarget(aImage);
98
99 // Capture the decoder's state.
100 DecoderFinalStatus finalStatus = aDecoder->FinalStatus();
101 ImageMetadata metadata = aDecoder->GetImageMetadata();
102 DecoderTelemetry telemetry = aDecoder->Telemetry();
103 Progress progress = aDecoder->TakeProgress();
104 UnorientedIntRect invalidRect =
105 UnorientedIntRect::FromUnknownRect(aDecoder->TakeInvalidRect());
106 Maybe<uint32_t> frameCount = aDecoder->TakeCompleteFrameCount();
107 DecoderFlags decoderFlags = aDecoder->GetDecoderFlags();
108 SurfaceFlags surfaceFlags = aDecoder->GetSurfaceFlags();
109
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;
116 }
117
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);
129 }
130
131 ///////////////////////////////////////////////////////////////////////////////
132 // IDecodingTask implementation.
133 ///////////////////////////////////////////////////////////////////////////////
134
Resume()135 void IDecodingTask::Resume() { DecodePool::Singleton()->AsyncRun(this); }
136
137 ///////////////////////////////////////////////////////////////////////////////
138 // MetadataDecodingTask implementation.
139 ///////////////////////////////////////////////////////////////////////////////
140
MetadataDecodingTask(NotNull<Decoder * > aDecoder)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");
145 }
146
Run()147 void MetadataDecodingTask::Run() {
148 MutexAutoLock lock(mMutex);
149
150 LexerResult result = mDecoder->Decode(WrapNotNull(this));
151
152 if (result.is<TerminalState>()) {
153 NotifyDecodeComplete(mDecoder->GetImage(), mDecoder);
154 return; // We're done.
155 }
156
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;
163 }
164
165 MOZ_ASSERT_UNREACHABLE("Metadata decode yielded for an unexpected reason");
166 }
167
168 ///////////////////////////////////////////////////////////////////////////////
169 // AnonymousDecodingTask implementation.
170 ///////////////////////////////////////////////////////////////////////////////
171
AnonymousDecodingTask(NotNull<Decoder * > aDecoder,bool aResumable)172 AnonymousDecodingTask::AnonymousDecodingTask(NotNull<Decoder*> aDecoder,
173 bool aResumable)
174 : mDecoder(aDecoder), mResumable(aResumable) {}
175
Run()176 void AnonymousDecodingTask::Run() {
177 while (true) {
178 LexerResult result = mDecoder->Decode(WrapNotNull(this));
179
180 if (result.is<TerminalState>()) {
181 return; // We're done.
182 }
183
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;
188 }
189
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>());
193 }
194 }
195
Resume()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(); }));
206 }
207 }
208
209 } // namespace image
210 } // namespace mozilla
211