1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * This file declares the RasterImage class, which
9 * handles static and animated rasterized images.
11 * @author Stuart Parmenter <pavlov@netscape.com>
12 * @author Chris Saari <saari@netscape.com>
13 * @author Arron Mogge <paper@animecity.nu>
14 * @author Andrew Smith <asmith15@learn.senecac.on.ca>
17 #ifndef mozilla_image_RasterImage_h
18 #define mozilla_image_RasterImage_h
22 #include "imgIContainer.h"
23 #include "nsIProperties.h"
25 #include "LookupResult.h"
26 #include "nsThreadUtils.h"
27 #include "DecoderFactory.h"
28 #include "FrameAnimator.h"
29 #include "ImageMetadata.h"
30 #include "ISurfaceProvider.h"
31 #include "Orientation.h"
32 #include "mozilla/Attributes.h"
33 #include "mozilla/Maybe.h"
34 #include "mozilla/MemoryReporting.h"
35 #include "mozilla/NotNull.h"
36 #include "mozilla/TimeStamp.h"
37 #include "mozilla/WeakPtr.h"
38 #include "mozilla/UniquePtr.h"
39 #include "ImageContainer.h"
40 #include "PlaybackType.h"
42 # include "imgIContainerDebug.h"
48 #define NS_RASTERIMAGE_CID \
49 { /* 376ff2c1-9bf6-418a-b143-3340c00112f7 */ \
50 0x376ff2c1, 0x9bf6, 0x418a, { \
51 0xb1, 0x43, 0x33, 0x40, 0xc0, 0x01, 0x12, 0xf7 \
56 * Handles static and animated image containers.
59 * @par A Quick Walk Through
60 * The decoder initializes this class and calls AppendFrame() to add a frame.
61 * Once RasterImage detects more than one frame, it starts the animation
62 * with StartAnimation(). Note that the invalidation events for RasterImage are
63 * generated automatically using nsRefreshDriver.
66 * StartAnimation() initializes the animation helper object and sets the time
67 * the first frame was displayed to the current clock time.
70 * When the refresh driver corresponding to the imgIContainer that this image is
71 * a part of notifies the RasterImage that it's time to invalidate,
72 * RequestRefresh() is called with a given TimeStamp to advance to. As long as
73 * the timeout of the given frame (the frame's "delay") plus the time that frame
74 * was first displayed is less than or equal to the TimeStamp given,
75 * RequestRefresh() calls AdvanceFrame().
78 * AdvanceFrame() is responsible for advancing a single frame of the animation.
79 * It can return true, meaning that the frame advanced, or false, meaning that
80 * the frame failed to advance (usually because the next frame hasn't been
81 * decoded yet). It is also responsible for performing the final animation stop
82 * procedure if the final frame of a non-looping animation is reached.
85 * Each frame can have a different method of removing itself. These are
86 * listed as imgIContainer::cDispose... constants. Notify() calls
87 * DoComposite() to handle any special frame destruction.
90 * The basic path through DoComposite() is:
91 * 1) Calculate Area that needs updating, which is at least the area of
93 * 2) Dispose of previous frame.
94 * 3) Draw new image onto compositingFrame.
95 * See comments in DoComposite() for more information and optimizations.
98 * The rest of the RasterImage specific functions are used by DoComposite to
99 * destroy the old frame and build the new one.
102 * <li> "Mask", "Alpha", and "Alpha Level" are interchangeable phrases in
103 * respects to RasterImage.
106 * <li> GIFs never have more than a 1 bit alpha.
107 * <li> APNGs may have a full alpha channel.
110 * <li> Background color specified in GIF is ignored by web browsers.
113 * <li> If Frame 3 wants to dispose by restoring previous, what it wants is to
114 * restore the composition up to and including Frame 2, as well as Frame 2s
115 * disposal. So, in the middle of DoComposite when composing Frame 3, right
116 * after destroying Frame 2's area, we copy compositingFrame to
117 * prevCompositingFrame. When DoComposite gets called to do Frame 4, we
118 * copy prevCompositingFrame back, and then draw Frame 4 on top.
121 * The mAnim structure has members only needed for animated images, so
122 * it's not allocated until the second frame is added.
128 class ImageContainer
;
131 } // namespace layers
136 struct DecoderFinalStatus
;
137 struct DecoderTelemetry
;
141 class RasterImage final
: public ImageResource
,
142 public nsIProperties
,
143 public SupportsWeakPtr
<RasterImage
>
146 public imgIContainerDebug
149 // (no public constructor - use ImageFactory)
150 virtual ~RasterImage();
153 MOZ_DECLARE_WEAKREFERENCE_TYPENAME(RasterImage
)
154 NS_DECL_THREADSAFE_ISUPPORTS
155 NS_DECL_NSIPROPERTIES
156 NS_DECL_IMGICONTAINER
158 NS_DECL_IMGICONTAINERDEBUG
161 nsresult
GetNativeSizes(nsTArray
<gfx::IntSize
>& aNativeSizes
) const override
;
162 size_t GetNativeSizesLength() const override
;
163 virtual nsresult
StartAnimation() override
;
164 virtual nsresult
StopAnimation() override
;
166 // Methods inherited from Image
167 virtual void OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) override
;
169 virtual size_t SizeOfSourceWithComputedFallback(
170 SizeOfState
& aState
) const override
;
171 virtual void CollectSizeOfSurfaces(nsTArray
<SurfaceMemoryCounter
>& aCounters
,
172 MallocSizeOf aMallocSizeOf
) const override
;
174 /* Triggers discarding. */
177 //////////////////////////////////////////////////////////////////////////////
178 // Decoder callbacks.
179 //////////////////////////////////////////////////////////////////////////////
182 * Sends the provided progress notifications to ProgressTracker.
186 * @param aProgress The progress notifications to send.
187 * @param aInvalidRect An invalidation rect to send.
188 * @param aFrameCount If Some(), an updated count of the number of frames of
189 * animation the decoder has finished decoding so far.
190 * This is a lower bound for the total number of
191 * animation frames this image has.
192 * @param aDecoderFlags The decoder flags used by the decoder that generated
193 * these notifications, or DefaultDecoderFlags() if the
194 * notifications don't come from a decoder.
195 * @param aSurfaceFlags The surface flags used by the decoder that generated
196 * these notifications, or DefaultSurfaceFlags() if the
197 * notifications don't come from a decoder.
199 void NotifyProgress(Progress aProgress
,
200 const gfx::IntRect
& aInvalidRect
= nsIntRect(),
201 const Maybe
<uint32_t>& aFrameCount
= Nothing(),
202 DecoderFlags aDecoderFlags
= DefaultDecoderFlags(),
203 SurfaceFlags aSurfaceFlags
= DefaultSurfaceFlags());
206 * Records decoding results, sends out any final notifications, updates the
207 * state of this image, and records telemetry.
211 * @param aStatus Final status information about the decoder. (Whether
212 * it encountered an error, etc.)
213 * @param aMetadata Metadata about this image that the decoder gathered.
214 * @param aTelemetry Telemetry data about the decoder.
215 * @param aProgress Any final progress notifications to send.
216 * @param aInvalidRect Any final invalidation rect to send.
217 * @param aFrameCount If Some(), a final updated count of the number of
218 * frames of animation the decoder has finished decoding so far. This is a
219 * lower bound for the total number of animation frames this image has.
220 * @param aDecoderFlags The decoder flags used by the decoder.
221 * @param aSurfaceFlags The surface flags used by the decoder.
223 void NotifyDecodeComplete(
224 const DecoderFinalStatus
& aStatus
, const ImageMetadata
& aMetadata
,
225 const DecoderTelemetry
& aTelemetry
, Progress aProgress
,
226 const gfx::IntRect
& aInvalidRect
, const Maybe
<uint32_t>& aFrameCount
,
227 DecoderFlags aDecoderFlags
, SurfaceFlags aSurfaceFlags
);
229 // Helper method for NotifyDecodeComplete.
230 void ReportDecoderError();
232 //////////////////////////////////////////////////////////////////////////////
233 // Network callbacks.
234 //////////////////////////////////////////////////////////////////////////////
236 virtual nsresult
OnImageDataAvailable(nsIRequest
* aRequest
,
237 nsISupports
* aContext
,
238 nsIInputStream
* aInStr
,
239 uint64_t aSourceOffset
,
240 uint32_t aCount
) override
;
241 virtual nsresult
OnImageDataComplete(nsIRequest
* aRequest
,
242 nsISupports
* aContext
, nsresult aStatus
,
243 bool aLastPart
) override
;
245 void NotifyForLoadEvent(Progress aProgress
);
248 * A hint of the number of bytes of source data that the image contains. If
249 * called early on, this can help reduce copying and reallocations by
250 * appropriately preallocating the source data buffer.
252 * We take this approach rather than having the source data management code do
253 * something more complicated (like chunklisting) because HTTP is by far the
254 * dominant source of images, and the Content-Length header is quite reliable.
255 * Thus, pre-allocation simplifies code and reduces the total number of
258 nsresult
SetSourceSizeHint(uint32_t aSizeHint
);
260 nsCString
GetURIString() {
263 GetURI()->GetSpec(spec
);
269 nsresult
Init(const char* aMimeType
, uint32_t aFlags
);
272 * Tries to retrieve a surface for this image with size @aSize, surface flags
273 * matching @aFlags, and a playback type of @aPlaybackType.
275 * If @aFlags specifies FLAG_SYNC_DECODE and we already have all the image
276 * data, we'll attempt a sync decode if no matching surface is found. If
277 * FLAG_SYNC_DECODE was not specified and no matching surface was found, we'll
278 * kick off an async decode so that the surface is (hopefully) available next
279 * time it's requested. aMarkUsed determines if we mark the surface used in
280 * the surface cache or not.
282 * @return a drawable surface, which may be empty if the requested surface
283 * could not be found.
285 LookupResult
LookupFrame(const gfx::IntSize
& aSize
, uint32_t aFlags
,
286 PlaybackType aPlaybackType
, bool aMarkUsed
);
288 /// Helper method for LookupFrame().
289 LookupResult
LookupFrameInternal(const gfx::IntSize
& aSize
, uint32_t aFlags
,
290 PlaybackType aPlaybackType
, bool aMarkUsed
);
292 ImgDrawResult
DrawInternal(DrawableSurface
&& aFrameRef
, gfxContext
* aContext
,
293 const nsIntSize
& aSize
, const ImageRegion
& aRegion
,
294 gfx::SamplingFilter aSamplingFilter
,
295 uint32_t aFlags
, float aOpacity
);
297 Tuple
<ImgDrawResult
, gfx::IntSize
, RefPtr
<gfx::SourceSurface
>>
298 GetFrameInternal(const gfx::IntSize
& aSize
,
299 const Maybe
<SVGImageContext
>& aSVGContext
,
300 uint32_t aWhichFrame
, uint32_t aFlags
) override
;
302 Tuple
<ImgDrawResult
, gfx::IntSize
> GetImageContainerSize(
303 layers::LayerManager
* aManager
, const gfx::IntSize
& aSize
,
304 uint32_t aFlags
) override
;
306 //////////////////////////////////////////////////////////////////////////////
308 //////////////////////////////////////////////////////////////////////////////
311 * Creates and runs a decoder, either synchronously or asynchronously
312 * according to @aFlags. Decodes at the provided target size @aSize, using
313 * decode flags @aFlags. Performs a single-frame decode of this image unless
314 * we know the image is animated *and* @aPlaybackType is
315 * PlaybackType::eAnimated.
317 * It's an error to call Decode() before this image's intrinsic size is
318 * available. A metadata decode must successfully complete first.
320 * Returns true of the decode was run synchronously.
322 bool Decode(const gfx::IntSize
& aSize
, uint32_t aFlags
,
323 PlaybackType aPlaybackType
);
326 * Creates and runs a metadata decoder, either synchronously or
327 * asynchronously according to @aFlags.
329 NS_IMETHOD
DecodeMetadata(uint32_t aFlags
);
332 * Sets the size, inherent orientation, animation metadata, and other
333 * information about the image gathered during decoding.
335 * This function may be called multiple times, but will throw an error if
336 * subsequent calls do not match the first.
338 * @param aMetadata The metadata to set on this image.
339 * @param aFromMetadataDecode True if this metadata came from a metadata
340 * decode; false if it came from a full decode.
341 * @return |true| unless a catastrophic failure was discovered. If |false| is
342 * returned, it indicates that the image is corrupt in a way that requires all
343 * surfaces to be discarded to recover.
345 bool SetMetadata(const ImageMetadata
& aMetadata
, bool aFromMetadataDecode
);
348 * In catastrophic circumstances like a GPU driver crash, the contents of our
349 * frames may become invalid. If the information we gathered during the
350 * metadata decode proves to be wrong due to image corruption, the frames we
351 * have may violate this class's invariants. Either way, we need to
352 * immediately discard the invalid frames and redecode so that callers don't
353 * perceive that we've entered an invalid state.
355 * RecoverFromInvalidFrames discards all existing frames and redecodes using
356 * the provided @aSize and @aFlags.
358 void RecoverFromInvalidFrames(const nsIntSize
& aSize
, uint32_t aFlags
);
360 void OnSurfaceDiscardedInternal(bool aAnimatedFramesDiscarded
);
364 nsTArray
<nsIntSize
> mNativeSizes
;
365 Orientation mOrientation
;
367 /// If this has a value, we're waiting for SetSize() to send the load event.
368 Maybe
<Progress
> mLoadProgress
;
370 nsCOMPtr
<nsIProperties
> mProperties
;
372 /// If this image is animated, a FrameAnimator which manages its animation.
373 UniquePtr
<FrameAnimator
> mFrameAnimator
;
375 /// Animation timeline and other state for animation images.
376 Maybe
<AnimationState
> mAnimationState
;
381 // The type of decoder this image needs. Computed from the MIME type in
383 DecoderType mDecoderType
;
385 // How many times we've decoded this image.
386 // This is currently only used for statistics
387 int32_t mDecodeCount
;
390 uint32_t mFramesNotified
;
393 // The source data for this image.
394 NotNull
<RefPtr
<SourceBuffer
>> mSourceBuffer
;
396 // Boolean flags (clustered together to conserve space):
397 bool mHasSize
: 1; // Has SetSize() been called?
398 bool mTransient
: 1; // Is the image short-lived?
399 bool mSyncLoad
: 1; // Are we loading synchronously?
400 bool mDiscardable
: 1; // Is container discardable?
401 bool mSomeSourceData
: 1; // Do we have some source data?
402 bool mAllSourceData
: 1; // Do we have all the source data?
403 bool mHasBeenDecoded
: 1; // Decoded at least once?
405 // Whether we're waiting to start animation. If we get a StartAnimation() call
406 // but we don't yet have more than one frame, mPendingAnimation is set so that
407 // we know to start animation later if/when we have more frames.
408 bool mPendingAnimation
: 1;
410 // Whether the animation can stop, due to running out
411 // of frames, or no more owning request
412 bool mAnimationFinished
: 1;
414 // Whether, once we are done doing a metadata decode, we should immediately
415 // kick off a full decode.
416 bool mWantFullDecode
: 1;
418 TimeStamp mDrawStartTime
;
420 //////////////////////////////////////////////////////////////////////////////
422 //////////////////////////////////////////////////////////////////////////////
424 // Determines whether we can downscale during decode with the given
426 bool CanDownscaleDuringDecode(const nsIntSize
& aSize
, uint32_t aFlags
);
431 class HandleErrorWorker
: public Runnable
{
434 * Called from decoder threads when DoError() is called, since errors can't
435 * be handled safely off-main-thread. Dispatches an event which reinvokes
436 * DoError on the main thread if there isn't one already pending.
438 static void DispatchIfNeeded(RasterImage
* aImage
);
440 NS_IMETHOD
Run() override
;
443 explicit HandleErrorWorker(RasterImage
* aImage
);
445 RefPtr
<RasterImage
> mImage
;
453 DrawableSurface
RequestDecodeForSizeInternal(const gfx::IntSize
& aSize
,
455 uint32_t aWhichFrame
);
458 explicit RasterImage(nsIURI
* aURI
= nullptr);
460 bool ShouldAnimate() override
;
462 friend class ImageFactory
;
465 inline NS_IMETHODIMP
RasterImage::GetAnimationMode(uint16_t* aAnimationMode
) {
466 return GetAnimationModeInternal(aAnimationMode
);
470 } // namespace mozilla
473 * Casting RasterImage to nsISupports is ambiguous. This method handles that.
475 inline nsISupports
* ToSupports(mozilla::image::RasterImage
* p
) {
476 return NS_ISUPPORTS_CAST(mozilla::image::ImageResource
*, p
);
479 #endif /* mozilla_image_RasterImage_h */