Bug 1728524 [wpt PR 30282] - Add CONNECT response WPTs for WebTransport, a=testonly
[gecko.git] / image / IDecodingTask.cpp
blobd165cc0cadd57d58531300d39dd3dd1ef2183f53
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 namespace mozilla {
17 using gfx::IntRect;
19 namespace image {
21 ///////////////////////////////////////////////////////////////////////////////
22 // Helpers for sending notifications to the image associated with a decoder.
23 ///////////////////////////////////////////////////////////////////////////////
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();
46 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(&current);
53 return current;
56 void IDecodingTask::NotifyProgress(NotNull<RasterImage*> aImage,
57 NotNull<Decoder*> aDecoder) {
58 MOZ_ASSERT(aDecoder->HasProgress() && !aDecoder->IsMetadataDecode());
59 EnsureHasEventTarget(aImage);
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();
74 // Synchronously notify if we can.
75 if (IsOnEventTarget() && !(decoderFlags & DecoderFlags::ASYNC_NOTIFY)) {
76 aImage->NotifyProgress(progress, invalidRect, frameCount, decoderFlags,
77 surfaceFlags);
78 return;
81 // Don't try to dispatch after shutdown, we'll just leak the runnable.
82 if (gXPCOMThreadsShutDown) {
83 return;
86 // We're forced to notify asynchronously.
87 NotNull<RefPtr<RasterImage>> image = aImage;
88 mEventTarget->Dispatch(CreateMediumHighRunnable(NS_NewRunnableFunction(
89 "IDecodingTask::NotifyProgress",
90 [=]() -> void {
91 image->NotifyProgress(progress, invalidRect,
92 frameCount, decoderFlags,
93 surfaceFlags);
94 })),
95 NS_DISPATCH_NORMAL);
98 void IDecodingTask::NotifyDecodeComplete(NotNull<RasterImage*> aImage,
99 NotNull<Decoder*> aDecoder) {
100 MOZ_ASSERT(aDecoder->HasError() || !aDecoder->InFrame(),
101 "Decode complete in the middle of a frame?");
102 EnsureHasEventTarget(aImage);
104 // Capture the decoder's state.
105 DecoderFinalStatus finalStatus = aDecoder->FinalStatus();
106 ImageMetadata metadata = aDecoder->GetImageMetadata();
107 DecoderTelemetry telemetry = aDecoder->Telemetry();
108 Progress progress = aDecoder->TakeProgress();
109 UnorientedIntRect invalidRect =
110 UnorientedIntRect::FromUnknownRect(aDecoder->TakeInvalidRect());
111 Maybe<uint32_t> frameCount = aDecoder->TakeCompleteFrameCount();
112 DecoderFlags decoderFlags = aDecoder->GetDecoderFlags();
113 SurfaceFlags surfaceFlags = aDecoder->GetSurfaceFlags();
115 // Synchronously notify if we can.
116 if (IsOnEventTarget() && !(decoderFlags & DecoderFlags::ASYNC_NOTIFY)) {
117 aImage->NotifyDecodeComplete(finalStatus, metadata, telemetry, progress,
118 invalidRect, frameCount, decoderFlags,
119 surfaceFlags);
120 return;
123 // Don't try to dispatch after shutdown, we'll just leak the runnable.
124 if (gXPCOMThreadsShutDown) {
125 return;
128 // We're forced to notify asynchronously.
129 NotNull<RefPtr<RasterImage>> image = aImage;
130 mEventTarget->Dispatch(CreateMediumHighRunnable(NS_NewRunnableFunction(
131 "IDecodingTask::NotifyDecodeComplete",
132 [=]() -> void {
133 image->NotifyDecodeComplete(
134 finalStatus, metadata, telemetry, progress,
135 invalidRect, frameCount, decoderFlags,
136 surfaceFlags);
137 })),
138 NS_DISPATCH_NORMAL);
141 ///////////////////////////////////////////////////////////////////////////////
142 // IDecodingTask implementation.
143 ///////////////////////////////////////////////////////////////////////////////
145 void IDecodingTask::Resume() { DecodePool::Singleton()->AsyncRun(this); }
147 ///////////////////////////////////////////////////////////////////////////////
148 // MetadataDecodingTask implementation.
149 ///////////////////////////////////////////////////////////////////////////////
151 MetadataDecodingTask::MetadataDecodingTask(NotNull<Decoder*> aDecoder)
152 : mMutex("mozilla::image::MetadataDecodingTask"), mDecoder(aDecoder) {
153 MOZ_ASSERT(mDecoder->IsMetadataDecode(),
154 "Use DecodingTask for non-metadata decodes");
157 void MetadataDecodingTask::Run() {
158 MutexAutoLock lock(mMutex);
160 LexerResult result = mDecoder->Decode(WrapNotNull(this));
162 if (result.is<TerminalState>()) {
163 NotifyDecodeComplete(mDecoder->GetImage(), mDecoder);
164 return; // We're done.
167 if (result == LexerResult(Yield::NEED_MORE_DATA)) {
168 // We can't make any more progress right now. We also don't want to report
169 // any progress, because it's important that metadata decode results are
170 // delivered atomically. The decoder itself will ensure that we get
171 // reenqueued when more data is available; just return for now.
172 return;
175 MOZ_ASSERT_UNREACHABLE("Metadata decode yielded for an unexpected reason");
178 ///////////////////////////////////////////////////////////////////////////////
179 // AnonymousDecodingTask implementation.
180 ///////////////////////////////////////////////////////////////////////////////
182 AnonymousDecodingTask::AnonymousDecodingTask(NotNull<Decoder*> aDecoder,
183 bool aResumable)
184 : mDecoder(aDecoder), mResumable(aResumable) {}
186 void AnonymousDecodingTask::Run() {
187 while (true) {
188 LexerResult result = mDecoder->Decode(WrapNotNull(this));
190 if (result.is<TerminalState>()) {
191 return; // We're done.
194 if (result == LexerResult(Yield::NEED_MORE_DATA)) {
195 // We can't make any more progress right now. Let the caller decide how to
196 // handle it.
197 return;
200 // Right now we don't do anything special for other kinds of yields, so just
201 // keep working.
202 MOZ_ASSERT(result.is<Yield>());
206 void AnonymousDecodingTask::Resume() {
207 // Anonymous decoders normally get all their data at once. We have tests
208 // where they don't; typically in these situations, the test re-runs them
209 // manually. However some tests want to verify Resume works, so they will
210 // explicitly request this behaviour.
211 if (mResumable) {
212 RefPtr<AnonymousDecodingTask> self(this);
213 NS_DispatchToMainThread(
214 NS_NewRunnableFunction("image::AnonymousDecodingTask::Resume",
215 [self]() -> void { self->Run(); }));
219 } // namespace image
220 } // namespace mozilla