Bug 1728955: part 8) Refactor `DisplayErrCode` in Windows' `nsClipboard`. r=masayuki
[gecko.git] / image / RasterImage.h
blob2b58b58039cc80763ac4e763fd742ae0f7355a7f
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/. */
7 /** @file
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
20 #include "Image.h"
21 #include "nsCOMPtr.h"
22 #include "imgIContainer.h"
23 #include "nsTArray.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 "mozilla/image/Resolution.h"
41 #include "ImageContainer.h"
42 #include "PlaybackType.h"
43 #ifdef DEBUG
44 # include "imgIContainerDebug.h"
45 #endif
47 class nsIInputStream;
48 class nsIRequest;
50 #define NS_RASTERIMAGE_CID \
51 { /* 376ff2c1-9bf6-418a-b143-3340c00112f7 */ \
52 0x376ff2c1, 0x9bf6, 0x418a, { \
53 0xb1, 0x43, 0x33, 0x40, 0xc0, 0x01, 0x12, 0xf7 \
54 } \
57 /**
58 * Handles static and animated image containers.
61 * @par A Quick Walk Through
62 * The decoder initializes this class and calls AppendFrame() to add a frame.
63 * Once RasterImage detects more than one frame, it starts the animation
64 * with StartAnimation(). Note that the invalidation events for RasterImage are
65 * generated automatically using nsRefreshDriver.
67 * @par
68 * StartAnimation() initializes the animation helper object and sets the time
69 * the first frame was displayed to the current clock time.
71 * @par
72 * When the refresh driver corresponding to the imgIContainer that this image is
73 * a part of notifies the RasterImage that it's time to invalidate,
74 * RequestRefresh() is called with a given TimeStamp to advance to. As long as
75 * the timeout of the given frame (the frame's "delay") plus the time that frame
76 * was first displayed is less than or equal to the TimeStamp given,
77 * RequestRefresh() calls AdvanceFrame().
79 * @par
80 * AdvanceFrame() is responsible for advancing a single frame of the animation.
81 * It can return true, meaning that the frame advanced, or false, meaning that
82 * the frame failed to advance (usually because the next frame hasn't been
83 * decoded yet). It is also responsible for performing the final animation stop
84 * procedure if the final frame of a non-looping animation is reached.
86 * @par
87 * Each frame can have a different method of removing itself. These are
88 * listed as imgIContainer::cDispose... constants. Notify() calls
89 * DoComposite() to handle any special frame destruction.
91 * @par
92 * The basic path through DoComposite() is:
93 * 1) Calculate Area that needs updating, which is at least the area of
94 * aNextFrame.
95 * 2) Dispose of previous frame.
96 * 3) Draw new image onto compositingFrame.
97 * See comments in DoComposite() for more information and optimizations.
99 * @par
100 * The rest of the RasterImage specific functions are used by DoComposite to
101 * destroy the old frame and build the new one.
103 * @note
104 * <li> "Mask", "Alpha", and "Alpha Level" are interchangeable phrases in
105 * respects to RasterImage.
107 * @par
108 * <li> GIFs never have more than a 1 bit alpha.
109 * <li> APNGs may have a full alpha channel.
111 * @par
112 * <li> Background color specified in GIF is ignored by web browsers.
114 * @par
115 * <li> If Frame 3 wants to dispose by restoring previous, what it wants is to
116 * restore the composition up to and including Frame 2, as well as Frame 2s
117 * disposal. So, in the middle of DoComposite when composing Frame 3, right
118 * after destroying Frame 2's area, we copy compositingFrame to
119 * prevCompositingFrame. When DoComposite gets called to do Frame 4, we
120 * copy prevCompositingFrame back, and then draw Frame 4 on top.
122 * @par
123 * The mAnim structure has members only needed for animated images, so
124 * it's not allocated until the second frame is added.
127 namespace mozilla {
129 // Pixel values in an image considering orientation metadata, such as the size
130 // of an image as seen by consumers of the image.
132 // Any public methods on RasterImage that use untyped units are interpreted as
133 // oriented pixels.
134 struct OrientedPixel {};
135 template <>
136 struct IsPixel<OrientedPixel> : std::true_type {};
137 typedef gfx::IntSizeTyped<OrientedPixel> OrientedIntSize;
138 typedef gfx::IntRectTyped<OrientedPixel> OrientedIntRect;
140 // Pixel values in an image ignoring orientation metadata, such as are stored
141 // in surfaces and the raw pixel data in the image.
142 struct UnorientedPixel {};
143 template <>
144 struct IsPixel<UnorientedPixel> : std::true_type {};
145 typedef gfx::IntSizeTyped<UnorientedPixel> UnorientedIntSize;
146 typedef gfx::IntRectTyped<UnorientedPixel> UnorientedIntRect;
148 namespace layers {
149 class ImageContainer;
150 class Image;
151 class LayersManager;
152 } // namespace layers
154 namespace image {
156 class Decoder;
157 struct DecoderFinalStatus;
158 struct DecoderTelemetry;
159 class ImageMetadata;
160 class SourceBuffer;
162 class RasterImage final : public ImageResource,
163 public SupportsWeakPtr
164 #ifdef DEBUG
166 public imgIContainerDebug
167 #endif
169 // (no public constructor - use ImageFactory)
170 virtual ~RasterImage();
172 public:
173 NS_DECL_THREADSAFE_ISUPPORTS
174 NS_DECL_IMGICONTAINER
175 #ifdef DEBUG
176 NS_DECL_IMGICONTAINERDEBUG
177 #endif
179 nsresult GetNativeSizes(nsTArray<gfx::IntSize>& aNativeSizes) const override;
180 size_t GetNativeSizesLength() const override;
181 virtual nsresult StartAnimation() override;
182 virtual nsresult StopAnimation() override;
184 // Methods inherited from Image
185 virtual void OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) override;
187 virtual size_t SizeOfSourceWithComputedFallback(
188 SizeOfState& aState) const override;
189 virtual void CollectSizeOfSurfaces(nsTArray<SurfaceMemoryCounter>& aCounters,
190 MallocSizeOf aMallocSizeOf) const override;
192 /* Triggers discarding. */
193 void Discard();
195 //////////////////////////////////////////////////////////////////////////////
196 // Decoder callbacks.
197 //////////////////////////////////////////////////////////////////////////////
200 * Sends the provided progress notifications to ProgressTracker.
202 * Main-thread only.
204 * @param aProgress The progress notifications to send.
205 * @param aInvalidRect An invalidation rect to send.
206 * @param aFrameCount If Some(), an updated count of the number of frames of
207 * animation the decoder has finished decoding so far.
208 * This is a lower bound for the total number of
209 * animation frames this image has.
210 * @param aDecoderFlags The decoder flags used by the decoder that generated
211 * these notifications, or DefaultDecoderFlags() if the
212 * notifications don't come from a decoder.
213 * @param aSurfaceFlags The surface flags used by the decoder that generated
214 * these notifications, or DefaultSurfaceFlags() if the
215 * notifications don't come from a decoder.
217 void NotifyProgress(
218 Progress aProgress,
219 const UnorientedIntRect& aInvalidRect = UnorientedIntRect(),
220 const Maybe<uint32_t>& aFrameCount = Nothing(),
221 DecoderFlags aDecoderFlags = DefaultDecoderFlags(),
222 SurfaceFlags aSurfaceFlags = DefaultSurfaceFlags());
225 * Records decoding results, sends out any final notifications, updates the
226 * state of this image, and records telemetry.
228 * Main-thread only.
230 * @param aStatus Final status information about the decoder. (Whether
231 * it encountered an error, etc.)
232 * @param aMetadata Metadata about this image that the decoder gathered.
233 * @param aTelemetry Telemetry data about the decoder.
234 * @param aProgress Any final progress notifications to send.
235 * @param aInvalidRect Any final invalidation rect to send.
236 * @param aFrameCount If Some(), a final updated count of the number of
237 * frames of animation the decoder has finished decoding so far. This is a
238 * lower bound for the total number of animation frames this image has.
239 * @param aDecoderFlags The decoder flags used by the decoder.
240 * @param aSurfaceFlags The surface flags used by the decoder.
242 void NotifyDecodeComplete(
243 const DecoderFinalStatus& aStatus, const ImageMetadata& aMetadata,
244 const DecoderTelemetry& aTelemetry, Progress aProgress,
245 const UnorientedIntRect& aInvalidRect, const Maybe<uint32_t>& aFrameCount,
246 DecoderFlags aDecoderFlags, SurfaceFlags aSurfaceFlags);
248 // Helper method for NotifyDecodeComplete.
249 void ReportDecoderError();
251 //////////////////////////////////////////////////////////////////////////////
252 // Network callbacks.
253 //////////////////////////////////////////////////////////////////////////////
255 virtual nsresult OnImageDataAvailable(nsIRequest* aRequest,
256 nsISupports* aContext,
257 nsIInputStream* aInStr,
258 uint64_t aSourceOffset,
259 uint32_t aCount) override;
260 virtual nsresult OnImageDataComplete(nsIRequest* aRequest,
261 nsISupports* aContext, nsresult aStatus,
262 bool aLastPart) override;
264 void NotifyForLoadEvent(Progress aProgress);
267 * A hint of the number of bytes of source data that the image contains. If
268 * called early on, this can help reduce copying and reallocations by
269 * appropriately preallocating the source data buffer.
271 * We take this approach rather than having the source data management code do
272 * something more complicated (like chunklisting) because HTTP is by far the
273 * dominant source of images, and the Content-Length header is quite reliable.
274 * Thus, pre-allocation simplifies code and reduces the total number of
275 * allocations.
277 nsresult SetSourceSizeHint(uint32_t aSizeHint);
279 nsCString GetURIString() {
280 nsCString spec;
281 if (GetURI()) {
282 GetURI()->GetSpec(spec);
284 return spec;
287 private:
288 nsresult Init(const char* aMimeType, uint32_t aFlags);
291 * Tries to retrieve a surface for this image with size @aSize, surface flags
292 * matching @aFlags, and a playback type of @aPlaybackType.
294 * If @aFlags specifies FLAG_SYNC_DECODE and we already have all the image
295 * data, we'll attempt a sync decode if no matching surface is found. If
296 * FLAG_SYNC_DECODE was not specified and no matching surface was found, we'll
297 * kick off an async decode so that the surface is (hopefully) available next
298 * time it's requested. aMarkUsed determines if we mark the surface used in
299 * the surface cache or not.
301 * @return a drawable surface, which may be empty if the requested surface
302 * could not be found.
304 LookupResult LookupFrame(const UnorientedIntSize& aSize, uint32_t aFlags,
305 PlaybackType aPlaybackType, bool aMarkUsed);
307 /// Helper method for LookupFrame().
308 LookupResult LookupFrameInternal(const UnorientedIntSize& aSize,
309 uint32_t aFlags, PlaybackType aPlaybackType,
310 bool aMarkUsed);
312 ImgDrawResult DrawInternal(DrawableSurface&& aFrameRef, gfxContext* aContext,
313 const UnorientedIntSize& aSize,
314 const ImageRegion& aRegion,
315 gfx::SamplingFilter aSamplingFilter,
316 uint32_t aFlags, float aOpacity);
318 Tuple<ImgDrawResult, gfx::IntSize, RefPtr<gfx::SourceSurface>>
319 GetFrameInternal(const gfx::IntSize& aSize,
320 const Maybe<SVGImageContext>& aSVGContext,
321 const Maybe<ImageIntRegion>& aRegion, uint32_t aWhichFrame,
322 uint32_t aFlags) override;
324 Tuple<ImgDrawResult, gfx::IntSize> GetImageContainerSize(
325 WindowRenderer* aRenderer, const gfx::IntSize& aSize,
326 uint32_t aFlags) override;
328 //////////////////////////////////////////////////////////////////////////////
329 // Decoding.
330 //////////////////////////////////////////////////////////////////////////////
333 * Creates and runs a decoder, either synchronously or asynchronously
334 * according to @aFlags. Decodes at the provided target size @aSize, using
335 * decode flags @aFlags. Performs a single-frame decode of this image unless
336 * we know the image is animated *and* @aPlaybackType is
337 * PlaybackType::eAnimated.
339 * It's an error to call Decode() before this image's intrinsic size is
340 * available. A metadata decode must successfully complete first.
342 * aOutRanSync is set to true if the decode was run synchronously.
343 * aOutFailed is set to true if failed to start a decode.
345 void Decode(const UnorientedIntSize& aSize, uint32_t aFlags,
346 PlaybackType aPlaybackType, bool& aOutRanSync, bool& aOutFailed);
349 * Creates and runs a metadata decoder, either synchronously or
350 * asynchronously according to @aFlags.
352 NS_IMETHOD DecodeMetadata(uint32_t aFlags);
355 * Sets the size, inherent orientation, animation metadata, and other
356 * information about the image gathered during decoding.
358 * This function may be called multiple times, but will throw an error if
359 * subsequent calls do not match the first.
361 * @param aMetadata The metadata to set on this image.
362 * @param aFromMetadataDecode True if this metadata came from a metadata
363 * decode; false if it came from a full decode.
364 * @return |true| unless a catastrophic failure was discovered. If |false| is
365 * returned, it indicates that the image is corrupt in a way that requires all
366 * surfaces to be discarded to recover.
368 bool SetMetadata(const ImageMetadata& aMetadata, bool aFromMetadataDecode);
371 * In catastrophic circumstances like a GPU driver crash, the contents of our
372 * frames may become invalid. If the information we gathered during the
373 * metadata decode proves to be wrong due to image corruption, the frames we
374 * have may violate this class's invariants. Either way, we need to
375 * immediately discard the invalid frames and redecode so that callers don't
376 * perceive that we've entered an invalid state.
378 * RecoverFromInvalidFrames discards all existing frames and redecodes using
379 * the provided @aSize and @aFlags.
381 void RecoverFromInvalidFrames(const UnorientedIntSize& aSize,
382 uint32_t aFlags);
384 void OnSurfaceDiscardedInternal(bool aAnimatedFramesDiscarded);
387 * Computes a matrix that applies the rotation and reflection specified by
388 * mOrientation, or that matrix's inverse if aInvert is true.
390 * See OrientedImage::OrientationMatrix.
392 gfxMatrix OrientationMatrix(const UnorientedIntSize& aSize,
393 bool aInvert = false) const;
395 // Functions to convert between oriented and unoriented pixels.
396 UnorientedIntSize ToUnoriented(OrientedIntSize aSize) const {
397 return mOrientation.SwapsWidthAndHeight()
398 ? UnorientedIntSize(aSize.height, aSize.width)
399 : UnorientedIntSize(aSize.width, aSize.height);
401 OrientedIntSize ToOriented(UnorientedIntSize aSize) const {
402 return mOrientation.SwapsWidthAndHeight()
403 ? OrientedIntSize(aSize.height, aSize.width)
404 : OrientedIntSize(aSize.width, aSize.height);
406 OrientedIntRect ToOriented(UnorientedIntRect aRect) const;
407 UnorientedIntRect ToUnoriented(OrientedIntRect aRect) const;
409 private: // data
410 OrientedIntSize mSize;
411 nsTArray<OrientedIntSize> mNativeSizes;
413 // The orientation required to correctly orient the image, from the image's
414 // metadata. RasterImage will handle and apply this orientation itself.
415 Orientation mOrientation;
417 // The resolution as specified in the image metadata, in dppx.
418 Resolution mResolution;
420 /// If this has a value, we're waiting for SetSize() to send the load event.
421 Maybe<Progress> mLoadProgress;
423 // Hotspot of this image, or (0, 0) if there is no hotspot data.
425 // We assume (and assert) that no image has both orientation metadata and a
426 // hotspot, so we store this as an untyped point.
427 gfx::IntPoint mHotspot;
429 /// If this image is animated, a FrameAnimator which manages its animation.
430 UniquePtr<FrameAnimator> mFrameAnimator;
432 /// Animation timeline and other state for animation images.
433 Maybe<AnimationState> mAnimationState;
435 // Image locking.
436 uint32_t mLockCount;
438 // The type of decoder this image needs. Computed from the MIME type in
439 // Init().
440 DecoderType mDecoderType;
442 // How many times we've decoded this image.
443 // This is currently only used for statistics
444 int32_t mDecodeCount;
446 #ifdef DEBUG
447 uint32_t mFramesNotified;
448 #endif
450 // The source data for this image.
451 NotNull<RefPtr<SourceBuffer>> mSourceBuffer;
453 // Boolean flags (clustered together to conserve space):
454 MOZ_ATOMIC_BITFIELDS(
455 mAtomicBitfields, 16,
456 ((bool, HasSize, 1), // Has SetSize() been called?
457 (bool, Transient, 1), // Is the image short-lived?
458 (bool, SyncLoad, 1), // Are we loading synchronously?
459 (bool, Discardable, 1), // Is container discardable?
460 (bool, SomeSourceData, 1), // Do we have some source data?
461 (bool, AllSourceData, 1), // Do we have all the source data?
462 (bool, HasBeenDecoded, 1), // Decoded at least once?
464 // Whether we're waiting to start animation. If we get a StartAnimation()
465 // call but we don't yet have more than one frame, mPendingAnimation is
466 // set so that we know to start animation later if/when we have more
467 // frames.
468 (bool, PendingAnimation, 1),
470 // Whether the animation can stop, due to running out
471 // of frames, or no more owning request
472 (bool, AnimationFinished, 1),
474 // Whether, once we are done doing a metadata decode, we should
475 // immediately kick off a full decode.
476 (bool, WantFullDecode, 1)))
478 TimeStamp mDrawStartTime;
480 //////////////////////////////////////////////////////////////////////////////
481 // Scaling.
482 //////////////////////////////////////////////////////////////////////////////
484 // Determines whether we can downscale during decode with the given
485 // parameters.
486 bool CanDownscaleDuringDecode(const UnorientedIntSize& aSize,
487 uint32_t aFlags);
489 // Error handling.
490 void DoError();
492 class HandleErrorWorker : public Runnable {
493 public:
495 * Called from decoder threads when DoError() is called, since errors can't
496 * be handled safely off-main-thread. Dispatches an event which reinvokes
497 * DoError on the main thread if there isn't one already pending.
499 static void DispatchIfNeeded(RasterImage* aImage);
501 NS_IMETHOD Run() override;
503 private:
504 explicit HandleErrorWorker(RasterImage* aImage);
506 RefPtr<RasterImage> mImage;
509 // Helpers
510 bool CanDiscard();
512 bool IsOpaque();
514 LookupResult RequestDecodeForSizeInternal(const UnorientedIntSize& aSize,
515 uint32_t aFlags,
516 uint32_t aWhichFrame);
518 protected:
519 explicit RasterImage(nsIURI* aURI = nullptr);
521 bool ShouldAnimate() override;
523 friend class ImageFactory;
526 inline NS_IMETHODIMP RasterImage::GetAnimationMode(uint16_t* aAnimationMode) {
527 return GetAnimationModeInternal(aAnimationMode);
530 } // namespace image
531 } // namespace mozilla
534 * Casting RasterImage to nsISupports is ambiguous. This method handles that.
536 inline nsISupports* ToSupports(mozilla::image::RasterImage* p) {
537 return NS_ISUPPORTS_CAST(mozilla::image::ImageResource*, p);
540 #endif /* mozilla_image_RasterImage_h */