/src/mozilla-central/image/RasterImage.h
Line | Count | Source (jump to first uncovered line) |
1 | | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
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/. */ |
6 | | |
7 | | /** @file |
8 | | * This file declares the RasterImage class, which |
9 | | * handles static and animated rasterized images. |
10 | | * |
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> |
15 | | */ |
16 | | |
17 | | #ifndef mozilla_image_RasterImage_h |
18 | | #define mozilla_image_RasterImage_h |
19 | | |
20 | | #include "Image.h" |
21 | | #include "nsCOMPtr.h" |
22 | | #include "imgIContainer.h" |
23 | | #include "nsIProperties.h" |
24 | | #include "nsTArray.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 "nsIObserver.h" |
33 | | #include "mozilla/Attributes.h" |
34 | | #include "mozilla/Maybe.h" |
35 | | #include "mozilla/MemoryReporting.h" |
36 | | #include "mozilla/NotNull.h" |
37 | | #include "mozilla/TimeStamp.h" |
38 | | #include "mozilla/WeakPtr.h" |
39 | | #include "mozilla/UniquePtr.h" |
40 | | #include "ImageContainer.h" |
41 | | #include "PlaybackType.h" |
42 | | #ifdef DEBUG |
43 | | #include "imgIContainerDebug.h" |
44 | | #endif |
45 | | |
46 | | class nsIInputStream; |
47 | | class nsIRequest; |
48 | | |
49 | | #define NS_RASTERIMAGE_CID \ |
50 | | { /* 376ff2c1-9bf6-418a-b143-3340c00112f7 */ \ |
51 | | 0x376ff2c1, \ |
52 | | 0x9bf6, \ |
53 | | 0x418a, \ |
54 | | {0xb1, 0x43, 0x33, 0x40, 0xc0, 0x01, 0x12, 0xf7} \ |
55 | | } |
56 | | |
57 | | /** |
58 | | * Handles static and animated image containers. |
59 | | * |
60 | | * |
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. |
66 | | * |
67 | | * @par |
68 | | * StartAnimation() initializes the animation helper object and sets the time |
69 | | * the first frame was displayed to the current clock time. |
70 | | * |
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(). |
78 | | * |
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. |
85 | | * |
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. |
90 | | * |
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. |
98 | | * |
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. |
102 | | * |
103 | | * @note |
104 | | * <li> "Mask", "Alpha", and "Alpha Level" are interchangeable phrases in |
105 | | * respects to RasterImage. |
106 | | * |
107 | | * @par |
108 | | * <li> GIFs never have more than a 1 bit alpha. |
109 | | * <li> APNGs may have a full alpha channel. |
110 | | * |
111 | | * @par |
112 | | * <li> Background color specified in GIF is ignored by web browsers. |
113 | | * |
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. |
121 | | * |
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. |
125 | | */ |
126 | | |
127 | | namespace mozilla { |
128 | | |
129 | | namespace layers { |
130 | | class ImageContainer; |
131 | | class Image; |
132 | | class LayersManager; |
133 | | } // namespace layers |
134 | | |
135 | | namespace image { |
136 | | |
137 | | class Decoder; |
138 | | struct DecoderFinalStatus; |
139 | | struct DecoderTelemetry; |
140 | | class ImageMetadata; |
141 | | class SourceBuffer; |
142 | | |
143 | | class RasterImage final : public ImageResource |
144 | | , public nsIProperties |
145 | | , public SupportsWeakPtr<RasterImage> |
146 | | #ifdef DEBUG |
147 | | , public imgIContainerDebug |
148 | | #endif |
149 | | { |
150 | | // (no public constructor - use ImageFactory) |
151 | | virtual ~RasterImage(); |
152 | | |
153 | | public: |
154 | | MOZ_DECLARE_WEAKREFERENCE_TYPENAME(RasterImage) |
155 | | NS_DECL_THREADSAFE_ISUPPORTS |
156 | | NS_DECL_NSIPROPERTIES |
157 | | NS_DECL_IMGICONTAINER |
158 | | #ifdef DEBUG |
159 | | NS_DECL_IMGICONTAINERDEBUG |
160 | | #endif |
161 | | |
162 | | nsresult GetNativeSizes(nsTArray<gfx::IntSize>& aNativeSizes) const override; |
163 | | size_t GetNativeSizesLength() const override; |
164 | | virtual nsresult StartAnimation() override; |
165 | | virtual nsresult StopAnimation() override; |
166 | | |
167 | | // Methods inherited from Image |
168 | | virtual void OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) override; |
169 | | |
170 | | virtual size_t SizeOfSourceWithComputedFallback(SizeOfState& aState) |
171 | | const override; |
172 | | virtual void CollectSizeOfSurfaces(nsTArray<SurfaceMemoryCounter>& aCounters, |
173 | | MallocSizeOf aMallocSizeOf) const override; |
174 | | |
175 | | /* Triggers discarding. */ |
176 | | void Discard(); |
177 | | |
178 | | |
179 | | ////////////////////////////////////////////////////////////////////////////// |
180 | | // Decoder callbacks. |
181 | | ////////////////////////////////////////////////////////////////////////////// |
182 | | |
183 | | /** |
184 | | * Sends the provided progress notifications to ProgressTracker. |
185 | | * |
186 | | * Main-thread only. |
187 | | * |
188 | | * @param aProgress The progress notifications to send. |
189 | | * @param aInvalidRect An invalidation rect to send. |
190 | | * @param aFrameCount If Some(), an updated count of the number of frames of |
191 | | * animation the decoder has finished decoding so far. This |
192 | | * is a lower bound for the total number of animation |
193 | | * frames this image has. |
194 | | * @param aDecoderFlags The decoder flags used by the decoder that generated |
195 | | * these notifications, or DefaultDecoderFlags() if the |
196 | | * notifications don't come from a decoder. |
197 | | * @param aSurfaceFlags The surface flags used by the decoder that generated |
198 | | * these notifications, or DefaultSurfaceFlags() if the |
199 | | * notifications don't come from a decoder. |
200 | | */ |
201 | | void NotifyProgress(Progress aProgress, |
202 | | const gfx::IntRect& aInvalidRect = nsIntRect(), |
203 | | const Maybe<uint32_t>& aFrameCount = Nothing(), |
204 | | DecoderFlags aDecoderFlags = DefaultDecoderFlags(), |
205 | | SurfaceFlags aSurfaceFlags = DefaultSurfaceFlags()); |
206 | | |
207 | | /** |
208 | | * Records decoding results, sends out any final notifications, updates the |
209 | | * state of this image, and records telemetry. |
210 | | * |
211 | | * Main-thread only. |
212 | | * |
213 | | * @param aStatus Final status information about the decoder. (Whether it |
214 | | * encountered an error, etc.) |
215 | | * @param aMetadata Metadata about this image that the decoder gathered. |
216 | | * @param aTelemetry Telemetry data about the decoder. |
217 | | * @param aProgress Any final progress notifications to send. |
218 | | * @param aInvalidRect Any final invalidation rect to send. |
219 | | * @param aFrameCount If Some(), a final updated count of the number of frames |
220 | | * of animation the decoder has finished decoding so far. |
221 | | * This is a lower bound for the total number of animation |
222 | | * frames this image has. |
223 | | * @param aDecoderFlags The decoder flags used by the decoder. |
224 | | * @param aSurfaceFlags The surface flags used by the decoder. |
225 | | */ |
226 | | void NotifyDecodeComplete(const DecoderFinalStatus& aStatus, |
227 | | const ImageMetadata& aMetadata, |
228 | | const DecoderTelemetry& aTelemetry, |
229 | | Progress aProgress, |
230 | | const gfx::IntRect& aInvalidRect, |
231 | | const Maybe<uint32_t>& aFrameCount, |
232 | | DecoderFlags aDecoderFlags, |
233 | | SurfaceFlags aSurfaceFlags); |
234 | | |
235 | | // Helper method for NotifyDecodeComplete. |
236 | | void ReportDecoderError(); |
237 | | |
238 | | |
239 | | ////////////////////////////////////////////////////////////////////////////// |
240 | | // Network callbacks. |
241 | | ////////////////////////////////////////////////////////////////////////////// |
242 | | |
243 | | virtual nsresult OnImageDataAvailable(nsIRequest* aRequest, |
244 | | nsISupports* aContext, |
245 | | nsIInputStream* aInStr, |
246 | | uint64_t aSourceOffset, |
247 | | uint32_t aCount) override; |
248 | | virtual nsresult OnImageDataComplete(nsIRequest* aRequest, |
249 | | nsISupports* aContext, |
250 | | nsresult aStatus, |
251 | | bool aLastPart) override; |
252 | | |
253 | | void NotifyForLoadEvent(Progress aProgress); |
254 | | |
255 | | /** |
256 | | * A hint of the number of bytes of source data that the image contains. If |
257 | | * called early on, this can help reduce copying and reallocations by |
258 | | * appropriately preallocating the source data buffer. |
259 | | * |
260 | | * We take this approach rather than having the source data management code do |
261 | | * something more complicated (like chunklisting) because HTTP is by far the |
262 | | * dominant source of images, and the Content-Length header is quite reliable. |
263 | | * Thus, pre-allocation simplifies code and reduces the total number of |
264 | | * allocations. |
265 | | */ |
266 | | nsresult SetSourceSizeHint(uint32_t aSizeHint); |
267 | | |
268 | 0 | nsCString GetURIString() { |
269 | 0 | nsCString spec; |
270 | 0 | if (GetURI()) { |
271 | 0 | GetURI()->GetSpec(spec); |
272 | 0 | } |
273 | 0 | return spec; |
274 | 0 | } |
275 | | |
276 | | private: |
277 | | nsresult Init(const char* aMimeType, uint32_t aFlags); |
278 | | |
279 | | /** |
280 | | * Tries to retrieve a surface for this image with size @aSize, surface flags |
281 | | * matching @aFlags, and a playback type of @aPlaybackType. |
282 | | * |
283 | | * If @aFlags specifies FLAG_SYNC_DECODE and we already have all the image |
284 | | * data, we'll attempt a sync decode if no matching surface is found. If |
285 | | * FLAG_SYNC_DECODE was not specified and no matching surface was found, we'll |
286 | | * kick off an async decode so that the surface is (hopefully) available next |
287 | | * time it's requested. |
288 | | * |
289 | | * @return a drawable surface, which may be empty if the requested surface |
290 | | * could not be found. |
291 | | */ |
292 | | LookupResult LookupFrame(const gfx::IntSize& aSize, |
293 | | uint32_t aFlags, |
294 | | PlaybackType aPlaybackType); |
295 | | |
296 | | /// Helper method for LookupFrame(). |
297 | | LookupResult LookupFrameInternal(const gfx::IntSize& aSize, |
298 | | uint32_t aFlags, |
299 | | PlaybackType aPlaybackType); |
300 | | |
301 | | ImgDrawResult DrawInternal(DrawableSurface&& aFrameRef, |
302 | | gfxContext* aContext, |
303 | | const nsIntSize& aSize, |
304 | | const ImageRegion& aRegion, |
305 | | gfx::SamplingFilter aSamplingFilter, |
306 | | uint32_t aFlags, |
307 | | float aOpacity); |
308 | | |
309 | | Tuple<ImgDrawResult, gfx::IntSize, RefPtr<gfx::SourceSurface>> |
310 | | GetFrameInternal(const gfx::IntSize& aSize, |
311 | | const Maybe<SVGImageContext>& aSVGContext, |
312 | | uint32_t aWhichFrame, |
313 | | uint32_t aFlags) override; |
314 | | |
315 | | Tuple<ImgDrawResult, gfx::IntSize> |
316 | | GetImageContainerSize(layers::LayerManager* aManager, |
317 | | const gfx::IntSize& aSize, |
318 | | uint32_t aFlags) override; |
319 | | |
320 | | ////////////////////////////////////////////////////////////////////////////// |
321 | | // Decoding. |
322 | | ////////////////////////////////////////////////////////////////////////////// |
323 | | |
324 | | /** |
325 | | * Creates and runs a decoder, either synchronously or asynchronously |
326 | | * according to @aFlags. Decodes at the provided target size @aSize, using |
327 | | * decode flags @aFlags. Performs a single-frame decode of this image unless |
328 | | * we know the image is animated *and* @aPlaybackType is |
329 | | * PlaybackType::eAnimated. |
330 | | * |
331 | | * It's an error to call Decode() before this image's intrinsic size is |
332 | | * available. A metadata decode must successfully complete first. |
333 | | * |
334 | | * Returns true of the decode was run synchronously. |
335 | | */ |
336 | | bool Decode(const gfx::IntSize& aSize, |
337 | | uint32_t aFlags, |
338 | | PlaybackType aPlaybackType); |
339 | | |
340 | | /** |
341 | | * Creates and runs a metadata decoder, either synchronously or |
342 | | * asynchronously according to @aFlags. |
343 | | */ |
344 | | NS_IMETHOD DecodeMetadata(uint32_t aFlags); |
345 | | |
346 | | /** |
347 | | * Sets the size, inherent orientation, animation metadata, and other |
348 | | * information about the image gathered during decoding. |
349 | | * |
350 | | * This function may be called multiple times, but will throw an error if |
351 | | * subsequent calls do not match the first. |
352 | | * |
353 | | * @param aMetadata The metadata to set on this image. |
354 | | * @param aFromMetadataDecode True if this metadata came from a metadata |
355 | | * decode; false if it came from a full decode. |
356 | | * @return |true| unless a catastrophic failure was discovered. If |false| is |
357 | | * returned, it indicates that the image is corrupt in a way that requires all |
358 | | * surfaces to be discarded to recover. |
359 | | */ |
360 | | bool SetMetadata(const ImageMetadata& aMetadata, bool aFromMetadataDecode); |
361 | | |
362 | | /** |
363 | | * In catastrophic circumstances like a GPU driver crash, the contents of our |
364 | | * frames may become invalid. If the information we gathered during the |
365 | | * metadata decode proves to be wrong due to image corruption, the frames we |
366 | | * have may violate this class's invariants. Either way, we need to |
367 | | * immediately discard the invalid frames and redecode so that callers don't |
368 | | * perceive that we've entered an invalid state. |
369 | | * |
370 | | * RecoverFromInvalidFrames discards all existing frames and redecodes using |
371 | | * the provided @aSize and @aFlags. |
372 | | */ |
373 | | void RecoverFromInvalidFrames(const nsIntSize& aSize, uint32_t aFlags); |
374 | | |
375 | | void OnSurfaceDiscardedInternal(bool aAnimatedFramesDiscarded); |
376 | | |
377 | | private: // data |
378 | | nsIntSize mSize; |
379 | | nsTArray<nsIntSize> mNativeSizes; |
380 | | Orientation mOrientation; |
381 | | |
382 | | /// If this has a value, we're waiting for SetSize() to send the load event. |
383 | | Maybe<Progress> mLoadProgress; |
384 | | |
385 | | nsCOMPtr<nsIProperties> mProperties; |
386 | | |
387 | | /// If this image is animated, a FrameAnimator which manages its animation. |
388 | | UniquePtr<FrameAnimator> mFrameAnimator; |
389 | | |
390 | | /// Animation timeline and other state for animation images. |
391 | | Maybe<AnimationState> mAnimationState; |
392 | | |
393 | | // Image locking. |
394 | | uint32_t mLockCount; |
395 | | |
396 | | // The type of decoder this image needs. Computed from the MIME type in Init(). |
397 | | DecoderType mDecoderType; |
398 | | |
399 | | // How many times we've decoded this image. |
400 | | // This is currently only used for statistics |
401 | | int32_t mDecodeCount; |
402 | | |
403 | | #ifdef DEBUG |
404 | | uint32_t mFramesNotified; |
405 | | #endif |
406 | | |
407 | | // The source data for this image. |
408 | | NotNull<RefPtr<SourceBuffer>> mSourceBuffer; |
409 | | |
410 | | // Boolean flags (clustered together to conserve space): |
411 | | bool mHasSize:1; // Has SetSize() been called? |
412 | | bool mTransient:1; // Is the image short-lived? |
413 | | bool mSyncLoad:1; // Are we loading synchronously? |
414 | | bool mDiscardable:1; // Is container discardable? |
415 | | bool mSomeSourceData:1; // Do we have some source data? |
416 | | bool mAllSourceData:1; // Do we have all the source data? |
417 | | bool mHasBeenDecoded:1; // Decoded at least once? |
418 | | |
419 | | // Whether we're waiting to start animation. If we get a StartAnimation() call |
420 | | // but we don't yet have more than one frame, mPendingAnimation is set so that |
421 | | // we know to start animation later if/when we have more frames. |
422 | | bool mPendingAnimation:1; |
423 | | |
424 | | // Whether the animation can stop, due to running out |
425 | | // of frames, or no more owning request |
426 | | bool mAnimationFinished:1; |
427 | | |
428 | | // Whether, once we are done doing a metadata decode, we should immediately |
429 | | // kick off a full decode. |
430 | | bool mWantFullDecode:1; |
431 | | |
432 | | TimeStamp mDrawStartTime; |
433 | | |
434 | | |
435 | | ////////////////////////////////////////////////////////////////////////////// |
436 | | // Scaling. |
437 | | ////////////////////////////////////////////////////////////////////////////// |
438 | | |
439 | | // Determines whether we can downscale during decode with the given |
440 | | // parameters. |
441 | | bool CanDownscaleDuringDecode(const nsIntSize& aSize, uint32_t aFlags); |
442 | | |
443 | | |
444 | | // Error handling. |
445 | | void DoError(); |
446 | | |
447 | | class HandleErrorWorker : public Runnable |
448 | | { |
449 | | public: |
450 | | /** |
451 | | * Called from decoder threads when DoError() is called, since errors can't |
452 | | * be handled safely off-main-thread. Dispatches an event which reinvokes |
453 | | * DoError on the main thread if there isn't one already pending. |
454 | | */ |
455 | | static void DispatchIfNeeded(RasterImage* aImage); |
456 | | |
457 | | NS_IMETHOD Run() override; |
458 | | |
459 | | private: |
460 | | explicit HandleErrorWorker(RasterImage* aImage); |
461 | | |
462 | | RefPtr<RasterImage> mImage; |
463 | | }; |
464 | | |
465 | | // Helpers |
466 | | bool CanDiscard(); |
467 | | |
468 | | bool IsOpaque(); |
469 | | |
470 | | DrawableSurface RequestDecodeForSizeInternal(const gfx::IntSize& aSize, uint32_t aFlags); |
471 | | |
472 | | protected: |
473 | | explicit RasterImage(nsIURI* aURI = nullptr); |
474 | | |
475 | | bool ShouldAnimate() override; |
476 | | |
477 | | friend class ImageFactory; |
478 | | }; |
479 | | |
480 | | inline NS_IMETHODIMP |
481 | 0 | RasterImage::GetAnimationMode(uint16_t* aAnimationMode) { |
482 | 0 | return GetAnimationModeInternal(aAnimationMode); |
483 | 0 | } |
484 | | |
485 | | } // namespace image |
486 | | } // namespace mozilla |
487 | | |
488 | | /** |
489 | | * Casting RasterImage to nsISupports is ambiguous. This method handles that. |
490 | | */ |
491 | | inline nsISupports* |
492 | | ToSupports(mozilla::image::RasterImage* p) |
493 | 0 | { |
494 | 0 | return NS_ISUPPORTS_CAST(mozilla::image::ImageResource*, p); |
495 | 0 | } |
496 | | |
497 | | #endif /* mozilla_image_RasterImage_h */ |