Java Code Examples for com.facebook.common.references.CloseableReference#isValid()

The following examples show how to use com.facebook.common.references.CloseableReference#isValid() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StagingArea.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param key
 * @return value associated with given key or null if no value is associated
 */
public synchronized CloseableReference<PooledByteBuffer> get(final CacheKey key) {
  Preconditions.checkNotNull(key);
  CloseableReference<PooledByteBuffer> storedRef = mMap.get(key);
  if (storedRef != null) {
    synchronized (storedRef) {
      if (!CloseableReference.isValid(storedRef)) {
        // Reference is not valid, this means that someone cleared reference while it was still in
        // use. Log error
        // TODO: 3697790
        mMap.remove(key);
        FLog.w(
            TAG,
            "Found closed reference %d for key %s (%d)",
            System.identityHashCode(storedRef),
            key.toString(),
            System.identityHashCode(key));
        return null;
      }
      storedRef = storedRef.clone();
    }
  }
  return storedRef;
}
 
Example 2
Source File: DefaultBitmapFramePreparer.java    From fresco with MIT License 6 votes vote down vote up
private boolean renderFrameAndCache(
    int frameNumber,
    CloseableReference<Bitmap> bitmapReference,
    @BitmapAnimationBackend.FrameType int frameType) {
  // Check if the bitmap is valid
  if (!CloseableReference.isValid(bitmapReference)) {
    return false;
  }
  // Try to render the frame
  if (!mBitmapFrameRenderer.renderFrame(frameNumber, bitmapReference.get())) {
    return false;
  }
  FLog.v(TAG, "Frame %d ready.", mFrameNumber);
  // Cache the frame
  synchronized (mPendingFrameDecodeJobs) {
    mBitmapFrameCache.onFramePrepared(mFrameNumber, bitmapReference, frameType);
  }
  return true;
}
 
Example 3
Source File: BitmapAnimationBackend.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Helper method that draws the given bitmap on the canvas respecting the bounds (if set).
 *
 * <p>If rendering was successful, it notifies the cache that the frame has been rendered with the
 * given bitmap. In addition, it will notify the {@link FrameListener} if set.
 *
 * @param frameNumber the current frame number passed to the cache
 * @param bitmapReference the bitmap to draw
 * @param canvas the canvas to draw an
 * @param frameType the {@link FrameType} to be rendered
 * @return true if the bitmap has been drawn
 */
private boolean drawBitmapAndCache(
    int frameNumber,
    @Nullable CloseableReference<Bitmap> bitmapReference,
    Canvas canvas,
    @FrameType int frameType) {
  if (!CloseableReference.isValid(bitmapReference)) {
    return false;
  }
  if (mBounds == null) {
    canvas.drawBitmap(bitmapReference.get(), 0f, 0f, mPaint);
  } else {
    canvas.drawBitmap(bitmapReference.get(), null, mBounds, mPaint);
  }

  // Notify the cache that a frame has been rendered.
  // We should not cache fallback frames since they do not represent the actual frame.
  if (frameType != FRAME_TYPE_FALLBACK) {
    mBitmapFrameCache.onFrameRendered(frameNumber, bitmapReference, frameType);
  }

  if (mFrameListener != null) {
    mFrameListener.onFrameDrawn(this, frameNumber, frameType);
  }
  return true;
}
 
Example 4
Source File: FrescoFrameCache.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Converts the given image reference to a bitmap reference and closes the original image
 * reference.
 *
 * @param closeableImage the image to convert. It will be closed afterwards and will be invalid
 * @return the closeable bitmap reference to be used
 */
@VisibleForTesting
@Nullable
static CloseableReference<Bitmap> convertToBitmapReferenceAndClose(
    final @Nullable CloseableReference<CloseableImage> closeableImage) {
  try {
    if (CloseableReference.isValid(closeableImage)
        && closeableImage.get() instanceof CloseableStaticBitmap) {

      CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) closeableImage.get();
      if (closeableStaticBitmap != null) {
        // We return a clone of the underlying bitmap reference that has to be manually closed
        // and then close the passed CloseableStaticBitmap in order to preserve correct
        // cache size calculations.
        return closeableStaticBitmap.cloneUnderlyingBitmapReference();
      }
    }
    // Not a bitmap reference, so we return null
    return null;
  } finally {
    CloseableReference.closeSafely(closeableImage);
  }
}
 
Example 5
Source File: FrescoControllerImpl.java    From fresco with MIT License 6 votes vote down vote up
@Nullable
private CloseableReference<CloseableImage> getCachedImage(@Nullable CacheKey cacheKey) {
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.beginSection("FrescoControllerImpl#getCachedImage");
  }
  try {
    CloseableReference<CloseableImage> cachedImageReference =
        mFrescoContext.getImagePipeline().getCachedImage(cacheKey);
    if (CloseableReference.isValid(cachedImageReference)) {
      return cachedImageReference;
    }
    return null;
  } finally {
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.endSection();
    }
  }
}
 
Example 6
Source File: FrescoController2Impl.java    From fresco with MIT License 6 votes vote down vote up
@Override
public void onNewResult(
    FrescoDrawable2 drawable,
    VitoImageRequest imageRequest,
    DataSource<CloseableReference<CloseableImage>> dataSource) {
  if (dataSource == null || !dataSource.hasResult()) {
    return;
  }

  CloseableReference<CloseableImage> image = dataSource.getResult();
  try {
    if (!CloseableReference.isValid(image)) {
      onFailure(drawable, imageRequest, dataSource);
    } else {
      setActualImage(drawable, imageRequest, image, false, dataSource);
    }
  } finally {
    CloseableReference.closeSafely(image);
  }
}
 
Example 7
Source File: PostprocessorProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
private void maybeExecuteCopyAndPostprocessBitmap() {
  boolean shouldExecutePostProcessing = false;
  synchronized (RepeatedPostprocessorConsumer.this) {
    mIsDirty = true;
    if (!mIsPostProcessingRunning && CloseableReference.isValid(mOriginalImageRef)) {
      mIsPostProcessingRunning = true;
      shouldExecutePostProcessing = true;
    }
  }
  if (shouldExecutePostProcessing) {
    executeCopyAndPostprocessBitmap();
  }
}
 
Example 8
Source File: BitmapAnimationBackend.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Try to render the frame to the given target bitmap. If the rendering fails, the target bitmap
 * reference will be closed and false is returned. If rendering succeeds, the target bitmap
 * reference can be drawn and has to be manually closed after drawing has been completed.
 *
 * @param frameNumber the frame number to render
 * @param targetBitmap the target bitmap
 * @return true if rendering successful
 */
private boolean renderFrameInBitmap(
    int frameNumber, @Nullable CloseableReference<Bitmap> targetBitmap) {
  if (!CloseableReference.isValid(targetBitmap)) {
    return false;
  }
  // Render the image
  boolean frameRendered = mBitmapFrameRenderer.renderFrame(frameNumber, targetBitmap.get());
  if (!frameRendered) {
    CloseableReference.closeSafely(targetBitmap);
  }
  return frameRendered;
}
 
Example 9
Source File: PostprocessorProducer.java    From fresco with MIT License 5 votes vote down vote up
@Override
protected void onNewResultImpl(
    CloseableReference<CloseableImage> newResult, @Status int status) {
  if (!CloseableReference.isValid(newResult)) {
    // try to propagate if the last result is invalid
    if (isLast(status)) {
      maybeNotifyOnNewResult(null, status);
    }
    // ignore if invalid
    return;
  }
  updateSourceImageRef(newResult, status);
}
 
Example 10
Source File: FrescoFrameCache.java    From fresco with MIT License 5 votes vote down vote up
@Override
public synchronized void onFramePrepared(
    int frameNumber,
    CloseableReference<Bitmap> bitmapReference,
    @BitmapAnimationBackend.FrameType int frameType) {
  Preconditions.checkNotNull(bitmapReference);
  CloseableReference<CloseableImage> closableReference = null;
  try {
    closableReference = createImageReference(bitmapReference);
    if (closableReference == null) {
      return;
    }
    CloseableReference<CloseableImage> newReference =
        mAnimatedFrameCache.cache(frameNumber, closableReference);
    if (CloseableReference.isValid(newReference)) {
      CloseableReference<CloseableImage> oldReference = mPreparedPendingFrames.get(frameNumber);
      CloseableReference.closeSafely(oldReference);
      // For performance reasons, we don't clone the reference and close the original one
      // but cache the reference directly.
      mPreparedPendingFrames.put(frameNumber, newReference);
      FLog.v(
          TAG,
          "cachePreparedFrame(%d) cached. Pending frames: %s",
          frameNumber,
          mPreparedPendingFrames);
    }
  } finally {
    CloseableReference.closeSafely(closableReference);
  }
}
 
Example 11
Source File: FrescoFrameCache.java    From fresco with MIT License 5 votes vote down vote up
private static int getBitmapSizeBytes(
    @Nullable CloseableReference<CloseableImage> imageReference) {
  if (!CloseableReference.isValid(imageReference)) {
    return 0;
  }
  return getBitmapSizeBytes(imageReference.get());
}
 
Example 12
Source File: ImagePipeline.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Returns whether the image is stored in the bitmap memory cache.
 *
 * @param imageRequest the imageRequest for the image to be looked up.
 * @return true if the image was found in the bitmap memory cache, false otherwise.
 */
public boolean isInBitmapMemoryCache(final ImageRequest imageRequest) {
  if (imageRequest == null) {
    return false;
  }
  final CacheKey cacheKey = mCacheKeyFactory.getBitmapCacheKey(imageRequest, null);
  CloseableReference<CloseableImage> ref = mBitmapMemoryCache.get(cacheKey);
  try {
    return CloseableReference.isValid(ref);
  } finally {
    CloseableReference.closeSafely(ref);
  }
}
 
Example 13
Source File: NaiveCacheAllFramesCachingBackend.java    From fresco with MIT License 4 votes vote down vote up
@Override
public synchronized boolean contains(int frameNumber) {
  return CloseableReference.isValid(mBitmapSparseArray.get(frameNumber));
}
 
Example 14
Source File: NativePooledByteBuffer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Check if this bytebuffer is already closed
 * @return true if this bytebuffer is closed.
 */
@Override
public synchronized boolean isClosed() {
  return !CloseableReference.isValid(mBufRef);
}
 
Example 15
Source File: MemoryPooledByteBuffer.java    From fresco with MIT License 4 votes vote down vote up
@Override
public synchronized boolean isClosed() {
  return !CloseableReference.isValid(mBufRef);
}
 
Example 16
Source File: FrescoController2Impl.java    From fresco with MIT License 4 votes vote down vote up
@Override
public boolean fetch(
    final FrescoDrawable2 frescoDrawable,
    final VitoImageRequest imageRequest,
    final @Nullable Object callerContext,
    final @Nullable ImageListener listener,
    final @Nullable Rect viewportDimensions) {
  // Save viewport dimension for future use
  frescoDrawable.setViewportDimensions(viewportDimensions);

  // Check if we already fetched the image
  if (frescoDrawable.getDrawableDataSubscriber() == this
      && frescoDrawable.isFetchSubmitted()
      && imageRequest.equals(frescoDrawable.getImageRequest())) {
    frescoDrawable.cancelReleaseNextFrame();
    frescoDrawable.cancelReleaseDelayed();
    return true; // already set
  }
  // We didn't -> Reset everything
  frescoDrawable.close();
  // Basic setup
  frescoDrawable.setDrawableDataSubscriber(this);
  frescoDrawable.setImageRequest(imageRequest);
  frescoDrawable.setCallerContext(callerContext);
  frescoDrawable.setImageListener(listener);
  frescoDrawable.setVitoImageRequestListener(mGlobalImageListener);

  // Set layers that are always visible
  mHierarcher.setupOverlayDrawable(
      frescoDrawable, imageRequest.resources, imageRequest.imageOptions, null);

  // We're fetching a new image, so we're updating the ID
  final long imageId = VitoUtils.generateIdentifier();
  frescoDrawable.setImageId(imageId);

  // Notify listeners that we're about to fetch an image
  frescoDrawable
      .getImageListener()
      .onSubmit(imageId, imageRequest, callerContext, obtainExtras(null, null, frescoDrawable));

  // Check if the image is in cache
  CloseableReference<CloseableImage> cachedImage = mImagePipeline.getCachedImage(imageRequest);
  try {
    if (CloseableReference.isValid(cachedImage)) {
      frescoDrawable.setImageOrigin(ImageOrigin.MEMORY_BITMAP_SHORTCUT);
      // Immediately display the actual image.
      setActualImage(frescoDrawable, imageRequest, cachedImage, true, null);
      frescoDrawable.setFetchSubmitted(true);
      mDebugOverlayFactory.update(frescoDrawable);

      return true;
    }
  } finally {
    CloseableReference.closeSafely(cachedImage);
  }

  // The image is not in cache -> Set up layers visible until the image is available
  frescoDrawable.setProgressDrawable(
      mHierarcher.buildProgressDrawable(imageRequest.resources, imageRequest.imageOptions));
  Drawable placeholder =
      mHierarcher.buildPlaceholderDrawable(imageRequest.resources, imageRequest.imageOptions);
  frescoDrawable.setPlaceholderDrawable(placeholder);
  frescoDrawable.setImageDrawable(null);

  frescoDrawable.getImageListener().onPlaceholderSet(imageId, imageRequest, placeholder);

  // Fetch the image
  final Runnable fetchRunnable =
      new Runnable() {
        @Override
        public void run() {
          if (imageId != frescoDrawable.getImageId()) {
            return; // We're trying to load a different image -> ignore
          }
          DataSource<CloseableReference<CloseableImage>> dataSource =
              mImagePipeline.fetchDecodedImage(
                  imageRequest, callerContext, frescoDrawable.getImageOriginListener(), imageId);
          frescoDrawable.setDataSource(dataSource);
          dataSource.subscribe(frescoDrawable, mUiThreadExecutor);
        }
      };

  if (mConfig.submitFetchOnBgThread()) {
    mLightweightBackgroundThreadExecutor.execute(fetchRunnable);
  } else {
    fetchRunnable.run();
  }
  frescoDrawable.setFetchSubmitted(true);

  mDebugOverlayFactory.update(frescoDrawable);

  return false;
}
 
Example 17
Source File: KeepLastFrameCache.java    From fresco with MIT License 4 votes vote down vote up
@Override
public synchronized boolean contains(int frameNumber) {
  return frameNumber == mLastFrameNumber && CloseableReference.isValid(mLastBitmapReference);
}
 
Example 18
Source File: NativePooledByteBufferOutputStream.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Ensure that the current stream is valid, that is underlying closeable reference is not null
 * and is valid
 * @throws InvalidStreamException if the stream is invalid
 */
private void ensureValid() {
  if (!CloseableReference.isValid(mBufRef)) {
    throw new InvalidStreamException();
  }
}
 
Example 19
Source File: MemoryPooledByteBufferOutputStream.java    From fresco with MIT License 2 votes vote down vote up
/**
 * Ensure that the current stream is valid, that is underlying closeable reference is not null and
 * is valid
 *
 * @throws InvalidStreamException if the stream is invalid
 */
private void ensureValid() {
  if (!CloseableReference.isValid(mBufRef)) {
    throw new InvalidStreamException();
  }
}
 
Example 20
Source File: EncodedImage.java    From fresco with MIT License 2 votes vote down vote up
/**
 * Returns true if the internal buffer reference is valid or the InputStream Supplier is not null,
 * false otherwise.
 */
public synchronized boolean isValid() {
  return CloseableReference.isValid(mPooledByteBufferRef) || mInputStreamSupplier != null;
}