tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

RasterImage.h (18278B)


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