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"
24 #include "LookupResult.h"
25 #include "nsThreadUtils.h"
26 #include "DecoderFactory.h"
27 #include "FrameAnimator.h"
28 #include "ImageMetadata.h"
29 #include "ISurfaceProvider.h"
30 #include "Orientation.h"
31 #include "mozilla/AtomicBitfields.h"
32 #include "mozilla/Attributes.h"
33 #include "mozilla/Maybe.h"
34 #include "mozilla/MemoryReporting.h"
35 #include "mozilla/NotNull.h"
36 #include "mozilla/StaticPrefs_image.h"
37 #include "mozilla/TimeStamp.h"
38 #include "mozilla/WeakPtr.h"
39 #include "mozilla/UniquePtr.h"
40 #include "ImageContainer.h"
41 #include "PlaybackType.h"
43 # include "imgIContainerDebug.h"
49 #define NS_RASTERIMAGE_CID \
50 { /* 376ff2c1-9bf6-418a-b143-3340c00112f7 */ \
51 0x376ff2c1, 0x9bf6, 0x418a, { \
52 0xb1, 0x43, 0x33, 0x40, 0xc0, 0x01, 0x12, 0xf7 \
57 * Handles static and animated image containers.
60 * @par A Quick Walk Through
61 * The decoder initializes this class and calls AppendFrame() to add a frame.
62 * Once RasterImage detects more than one frame, it starts the animation
63 * with StartAnimation(). Note that the invalidation events for RasterImage are
64 * generated automatically using nsRefreshDriver.
67 * StartAnimation() initializes the animation helper object and sets the time
68 * the first frame was displayed to the current clock time.
71 * When the refresh driver corresponding to the imgIContainer that this image is
72 * a part of notifies the RasterImage that it's time to invalidate,
73 * RequestRefresh() is called with a given TimeStamp to advance to. As long as
74 * the timeout of the given frame (the frame's "delay") plus the time that frame
75 * was first displayed is less than or equal to the TimeStamp given,
76 * RequestRefresh() calls AdvanceFrame().
79 * AdvanceFrame() is responsible for advancing a single frame of the animation.
80 * It can return true, meaning that the frame advanced, or false, meaning that
81 * the frame failed to advance (usually because the next frame hasn't been
82 * decoded yet). It is also responsible for performing the final animation stop
83 * procedure if the final frame of a non-looping animation is reached.
86 * Each frame can have a different method of removing itself. These are
87 * listed as imgIContainer::cDispose... constants. Notify() calls
88 * DoComposite() to handle any special frame destruction.
91 * The basic path through DoComposite() is:
92 * 1) Calculate Area that needs updating, which is at least the area of
94 * 2) Dispose of previous frame.
95 * 3) Draw new image onto compositingFrame.
96 * See comments in DoComposite() for more information and optimizations.
99 * The rest of the RasterImage specific functions are used by DoComposite to
100 * destroy the old frame and build the new one.
103 * <li> "Mask", "Alpha", and "Alpha Level" are interchangeable phrases in
104 * respects to RasterImage.
107 * <li> GIFs never have more than a 1 bit alpha.
108 * <li> APNGs may have a full alpha channel.
111 * <li> Background color specified in GIF is ignored by web browsers.
114 * <li> If Frame 3 wants to dispose by restoring previous, what it wants is to
115 * restore the composition up to and including Frame 2, as well as Frame 2s
116 * disposal. So, in the middle of DoComposite when composing Frame 3, right
117 * after destroying Frame 2's area, we copy compositingFrame to
118 * prevCompositingFrame. When DoComposite gets called to do Frame 4, we
119 * copy prevCompositingFrame back, and then draw Frame 4 on top.
122 * The mAnim structure has members only needed for animated images, so
123 * it's not allocated until the second frame is added.
128 // Pixel values in an image considering orientation metadata, such as the size
129 // of an image as seen by consumers of the image.
131 // Any public methods on RasterImage that use untyped units are interpreted as
133 struct OrientedPixel
{};
135 struct IsPixel
<OrientedPixel
> : std::true_type
{};
136 typedef gfx::IntSizeTyped
<OrientedPixel
> OrientedIntSize
;
137 typedef gfx::IntRectTyped
<OrientedPixel
> OrientedIntRect
;
139 // Pixel values in an image ignoring orientation metadata, such as are stored
140 // in surfaces and the raw pixel data in the image.
141 struct UnorientedPixel
{};
143 struct IsPixel
<UnorientedPixel
> : std::true_type
{};
144 typedef gfx::IntSizeTyped
<UnorientedPixel
> UnorientedIntSize
;
145 typedef gfx::IntRectTyped
<UnorientedPixel
> UnorientedIntRect
;
148 class ImageContainer
;
151 } // namespace layers
156 struct DecoderFinalStatus
;
157 struct DecoderTelemetry
;
161 class RasterImage final
: public ImageResource
,
162 public SupportsWeakPtr
165 public imgIContainerDebug
168 // (no public constructor - use ImageFactory)
169 virtual ~RasterImage();
172 NS_DECL_THREADSAFE_ISUPPORTS
173 NS_DECL_IMGICONTAINER
175 NS_DECL_IMGICONTAINERDEBUG
178 nsresult
GetNativeSizes(nsTArray
<gfx::IntSize
>& aNativeSizes
) const override
;
179 size_t GetNativeSizesLength() const override
;
180 virtual nsresult
StartAnimation() override
;
181 virtual nsresult
StopAnimation() override
;
183 // Methods inherited from Image
184 virtual void OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) override
;
186 virtual size_t SizeOfSourceWithComputedFallback(
187 SizeOfState
& aState
) const override
;
188 virtual void CollectSizeOfSurfaces(nsTArray
<SurfaceMemoryCounter
>& aCounters
,
189 MallocSizeOf aMallocSizeOf
) const override
;
191 /* Triggers discarding. */
194 //////////////////////////////////////////////////////////////////////////////
195 // Decoder callbacks.
196 //////////////////////////////////////////////////////////////////////////////
199 * Sends the provided progress notifications to ProgressTracker.
203 * @param aProgress The progress notifications to send.
204 * @param aInvalidRect An invalidation rect to send.
205 * @param aFrameCount If Some(), an updated count of the number of frames of
206 * animation the decoder has finished decoding so far.
207 * This is a lower bound for the total number of
208 * animation frames this image has.
209 * @param aDecoderFlags The decoder flags used by the decoder that generated
210 * these notifications, or DefaultDecoderFlags() if the
211 * notifications don't come from a decoder.
212 * @param aSurfaceFlags The surface flags used by the decoder that generated
213 * these notifications, or DefaultSurfaceFlags() if the
214 * notifications don't come from a decoder.
218 const UnorientedIntRect
& aInvalidRect
= UnorientedIntRect(),
219 const Maybe
<uint32_t>& aFrameCount
= Nothing(),
220 DecoderFlags aDecoderFlags
= DefaultDecoderFlags(),
221 SurfaceFlags aSurfaceFlags
= DefaultSurfaceFlags());
224 * Records decoding results, sends out any final notifications, updates the
225 * state of this image, and records telemetry.
229 * @param aStatus Final status information about the decoder. (Whether
230 * it encountered an error, etc.)
231 * @param aMetadata Metadata about this image that the decoder gathered.
232 * @param aTelemetry Telemetry data about the decoder.
233 * @param aProgress Any final progress notifications to send.
234 * @param aInvalidRect Any final invalidation rect to send.
235 * @param aFrameCount If Some(), a final updated count of the number of
236 * frames of animation the decoder has finished decoding so far. This is a
237 * lower bound for the total number of animation frames this image has.
238 * @param aDecoderFlags The decoder flags used by the decoder.
239 * @param aSurfaceFlags The surface flags used by the decoder.
241 void NotifyDecodeComplete(
242 const DecoderFinalStatus
& aStatus
, const ImageMetadata
& aMetadata
,
243 const DecoderTelemetry
& aTelemetry
, Progress aProgress
,
244 const UnorientedIntRect
& aInvalidRect
, const Maybe
<uint32_t>& aFrameCount
,
245 DecoderFlags aDecoderFlags
, SurfaceFlags aSurfaceFlags
);
247 // Helper method for NotifyDecodeComplete.
248 void ReportDecoderError();
250 //////////////////////////////////////////////////////////////////////////////
251 // Network callbacks.
252 //////////////////////////////////////////////////////////////////////////////
254 virtual nsresult
OnImageDataAvailable(nsIRequest
* aRequest
,
255 nsISupports
* aContext
,
256 nsIInputStream
* aInStr
,
257 uint64_t aSourceOffset
,
258 uint32_t aCount
) override
;
259 virtual nsresult
OnImageDataComplete(nsIRequest
* aRequest
,
260 nsISupports
* aContext
, nsresult aStatus
,
261 bool aLastPart
) override
;
263 void NotifyForLoadEvent(Progress aProgress
);
266 * A hint of the number of bytes of source data that the image contains. If
267 * called early on, this can help reduce copying and reallocations by
268 * appropriately preallocating the source data buffer.
270 * We take this approach rather than having the source data management code do
271 * something more complicated (like chunklisting) because HTTP is by far the
272 * dominant source of images, and the Content-Length header is quite reliable.
273 * Thus, pre-allocation simplifies code and reduces the total number of
276 nsresult
SetSourceSizeHint(uint32_t aSizeHint
);
278 nsCString
GetURIString() {
281 GetURI()->GetSpec(spec
);
287 nsresult
Init(const char* aMimeType
, uint32_t aFlags
);
290 * Tries to retrieve a surface for this image with size @aSize, surface flags
291 * matching @aFlags, and a playback type of @aPlaybackType.
293 * If @aFlags specifies FLAG_SYNC_DECODE and we already have all the image
294 * data, we'll attempt a sync decode if no matching surface is found. If
295 * FLAG_SYNC_DECODE was not specified and no matching surface was found, we'll
296 * kick off an async decode so that the surface is (hopefully) available next
297 * time it's requested. aMarkUsed determines if we mark the surface used in
298 * the surface cache or not.
300 * @return a drawable surface, which may be empty if the requested surface
301 * could not be found.
303 LookupResult
LookupFrame(const UnorientedIntSize
& aSize
, uint32_t aFlags
,
304 PlaybackType aPlaybackType
, bool aMarkUsed
);
306 /// Helper method for LookupFrame().
307 LookupResult
LookupFrameInternal(const UnorientedIntSize
& aSize
,
308 uint32_t aFlags
, PlaybackType aPlaybackType
,
311 ImgDrawResult
DrawInternal(DrawableSurface
&& aFrameRef
, gfxContext
* aContext
,
312 const UnorientedIntSize
& aSize
,
313 const ImageRegion
& aRegion
,
314 gfx::SamplingFilter aSamplingFilter
,
315 uint32_t aFlags
, float aOpacity
);
317 Tuple
<ImgDrawResult
, gfx::IntSize
, RefPtr
<gfx::SourceSurface
>>
318 GetFrameInternal(const gfx::IntSize
& aSize
,
319 const Maybe
<SVGImageContext
>& aSVGContext
,
320 uint32_t aWhichFrame
, uint32_t aFlags
) override
;
322 Tuple
<ImgDrawResult
, gfx::IntSize
> GetImageContainerSize(
323 layers::LayerManager
* aManager
, const gfx::IntSize
& aSize
,
324 uint32_t aFlags
) override
;
326 //////////////////////////////////////////////////////////////////////////////
328 //////////////////////////////////////////////////////////////////////////////
331 * Creates and runs a decoder, either synchronously or asynchronously
332 * according to @aFlags. Decodes at the provided target size @aSize, using
333 * decode flags @aFlags. Performs a single-frame decode of this image unless
334 * we know the image is animated *and* @aPlaybackType is
335 * PlaybackType::eAnimated.
337 * It's an error to call Decode() before this image's intrinsic size is
338 * available. A metadata decode must successfully complete first.
340 * aOutRanSync is set to true if the decode was run synchronously.
341 * aOutFailed is set to true if failed to start a decode.
343 void Decode(const UnorientedIntSize
& aSize
, uint32_t aFlags
,
344 PlaybackType aPlaybackType
, bool& aOutRanSync
, bool& aOutFailed
);
347 * Creates and runs a metadata decoder, either synchronously or
348 * asynchronously according to @aFlags.
350 NS_IMETHOD
DecodeMetadata(uint32_t aFlags
);
353 * Sets the size, inherent orientation, animation metadata, and other
354 * information about the image gathered during decoding.
356 * This function may be called multiple times, but will throw an error if
357 * subsequent calls do not match the first.
359 * @param aMetadata The metadata to set on this image.
360 * @param aFromMetadataDecode True if this metadata came from a metadata
361 * decode; false if it came from a full decode.
362 * @return |true| unless a catastrophic failure was discovered. If |false| is
363 * returned, it indicates that the image is corrupt in a way that requires all
364 * surfaces to be discarded to recover.
366 bool SetMetadata(const ImageMetadata
& aMetadata
, bool aFromMetadataDecode
);
369 * In catastrophic circumstances like a GPU driver crash, the contents of our
370 * frames may become invalid. If the information we gathered during the
371 * metadata decode proves to be wrong due to image corruption, the frames we
372 * have may violate this class's invariants. Either way, we need to
373 * immediately discard the invalid frames and redecode so that callers don't
374 * perceive that we've entered an invalid state.
376 * RecoverFromInvalidFrames discards all existing frames and redecodes using
377 * the provided @aSize and @aFlags.
379 void RecoverFromInvalidFrames(const UnorientedIntSize
& aSize
,
382 void OnSurfaceDiscardedInternal(bool aAnimatedFramesDiscarded
);
385 * Computes a matrix that applies the rotation and reflection specified by
386 * UsedOrientation(), or that matrix's inverse if aInvert is true.
388 * See OrientedImage::OrientationMatrix.
390 gfxMatrix
OrientationMatrix(const UnorientedIntSize
& aSize
,
391 bool aInvert
= false) const;
394 * The orientation value to honor for this image.
396 * If the image.honor-orientation-metadata pref is true, then this returns
397 * the orientation from the image's metadata. Otherwise, it returns an
398 * Orientation that indicates no transformation is needed.
400 Orientation
UsedOrientation() const {
401 return LoadHandledOrientation() ? mOrientation
: Orientation();
404 // Functions to convert between oriented and unoriented pixels.
405 UnorientedIntSize
ToUnoriented(OrientedIntSize aSize
) const {
406 return UsedOrientation().SwapsWidthAndHeight()
407 ? UnorientedIntSize(aSize
.height
, aSize
.width
)
408 : UnorientedIntSize(aSize
.width
, aSize
.height
);
410 OrientedIntSize
ToOriented(UnorientedIntSize aSize
) const {
411 return UsedOrientation().SwapsWidthAndHeight()
412 ? OrientedIntSize(aSize
.height
, aSize
.width
)
413 : OrientedIntSize(aSize
.width
, aSize
.height
);
415 OrientedIntRect
ToOriented(UnorientedIntRect aRect
) const;
416 UnorientedIntRect
ToUnoriented(OrientedIntRect aRect
) const;
419 OrientedIntSize mSize
;
420 nsTArray
<OrientedIntSize
> mNativeSizes
;
422 // The orientation required to correctly orient the image, from the image's
425 // When the image.honor-orientation-metadata pref is enabled, the RasterImage
426 // will handle and apply this orientation itself.
428 // When the pref is disabled, it is the responsibility of users of the
429 // RasterImage to wrap it in an OrientedImage if desired.
430 Orientation mOrientation
;
432 /// If this has a value, we're waiting for SetSize() to send the load event.
433 Maybe
<Progress
> mLoadProgress
;
435 // Hotspot of this image, or (0, 0) if there is no hotspot data.
437 // We assume (and assert) that no image has both orientation metadata and a
438 // hotspot, so we store this as an untyped point.
439 gfx::IntPoint mHotspot
;
441 /// If this image is animated, a FrameAnimator which manages its animation.
442 UniquePtr
<FrameAnimator
> mFrameAnimator
;
444 /// Animation timeline and other state for animation images.
445 Maybe
<AnimationState
> mAnimationState
;
450 // The type of decoder this image needs. Computed from the MIME type in
452 DecoderType mDecoderType
;
454 // How many times we've decoded this image.
455 // This is currently only used for statistics
456 int32_t mDecodeCount
;
459 uint32_t mFramesNotified
;
462 // The source data for this image.
463 NotNull
<RefPtr
<SourceBuffer
>> mSourceBuffer
;
465 // Boolean flags (clustered together to conserve space):
466 MOZ_ATOMIC_BITFIELDS(
467 mAtomicBitfields
, 16,
468 ((bool, HasSize
, 1), // Has SetSize() been called?
469 (bool, Transient
, 1), // Is the image short-lived?
470 (bool, SyncLoad
, 1), // Are we loading synchronously?
471 (bool, Discardable
, 1), // Is container discardable?
472 (bool, SomeSourceData
, 1), // Do we have some source data?
473 (bool, AllSourceData
, 1), // Do we have all the source data?
474 (bool, HasBeenDecoded
, 1), // Decoded at least once?
476 // Whether we're waiting to start animation. If we get a StartAnimation()
477 // call but we don't yet have more than one frame, mPendingAnimation is
478 // set so that we know to start animation later if/when we have more
480 (bool, PendingAnimation
, 1),
482 // Whether the animation can stop, due to running out
483 // of frames, or no more owning request
484 (bool, AnimationFinished
, 1),
486 // Whether, once we are done doing a metadata decode, we should
487 // immediately kick off a full decode.
488 (bool, WantFullDecode
, 1),
490 // Whether this RasterImage handled orientation of the image.
492 // This will be set based on the value of the
493 // image.honor-orientation-metadata pref at the time the RasterImage is
496 // NOTE(heycam): Once the image.honor-orientation-metadata pref is
497 // removed, this member (and the UsedOrientation() function) can also be
499 (bool, HandledOrientation
, 1)))
501 TimeStamp mDrawStartTime
;
503 //////////////////////////////////////////////////////////////////////////////
505 //////////////////////////////////////////////////////////////////////////////
507 // Determines whether we can downscale during decode with the given
509 bool CanDownscaleDuringDecode(const UnorientedIntSize
& aSize
,
515 class HandleErrorWorker
: public Runnable
{
518 * Called from decoder threads when DoError() is called, since errors can't
519 * be handled safely off-main-thread. Dispatches an event which reinvokes
520 * DoError on the main thread if there isn't one already pending.
522 static void DispatchIfNeeded(RasterImage
* aImage
);
524 NS_IMETHOD
Run() override
;
527 explicit HandleErrorWorker(RasterImage
* aImage
);
529 RefPtr
<RasterImage
> mImage
;
537 LookupResult
RequestDecodeForSizeInternal(const UnorientedIntSize
& aSize
,
539 uint32_t aWhichFrame
);
542 explicit RasterImage(nsIURI
* aURI
= nullptr);
544 bool ShouldAnimate() override
;
546 friend class ImageFactory
;
549 inline NS_IMETHODIMP
RasterImage::GetAnimationMode(uint16_t* aAnimationMode
) {
550 return GetAnimationModeInternal(aAnimationMode
);
554 } // namespace mozilla
557 * Casting RasterImage to nsISupports is ambiguous. This method handles that.
559 inline nsISupports
* ToSupports(mozilla::image::RasterImage
* p
) {
560 return NS_ISUPPORTS_CAST(mozilla::image::ImageResource
*, p
);
563 #endif /* mozilla_image_RasterImage_h */