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

The following examples show how to use com.facebook.common.references.CloseableReference#closeSafely() . 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: MultiPostProcessor.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Override
public CloseableReference<Bitmap> process(
  Bitmap src,
  PlatformBitmapFactory bitmapFactory
) {
  CloseableReference<Bitmap> prevBitmap = null, nextBitmap = null;

  try {
    for (Postprocessor p : mPostProcessors) {
      nextBitmap = p.process(prevBitmap != null ? prevBitmap.get() : src, bitmapFactory);
      CloseableReference.closeSafely(prevBitmap);
      prevBitmap = nextBitmap.clone();
    }

    return nextBitmap == null ? super.process(src, bitmapFactory) : nextBitmap.clone();
  } finally {
    CloseableReference.closeSafely(nextBitmap);
  }
}
 
Example 2
Source File: DraweeSpan.java    From drawee-text-view with Apache License 2.0 6 votes vote down vote up
@Override
public void release() {
    mIsRequestSubmitted = false;
    mIsAttached = false;
    mAttachedView = null;
    if (mDataSource != null) {
        mDataSource.close();
        mDataSource = null;
    }
    if (mDrawable != null) {
        releaseDrawable(mDrawable);
    }
    mDrawable = null;
    if (mFetchedImage != null) {
        CloseableReference.closeSafely(mFetchedImage);
        mFetchedImage = null;
    }
}
 
Example 3
Source File: EncodedImage.java    From fresco with MIT License 6 votes vote down vote up
public @Nullable EncodedImage cloneOrNull() {
  EncodedImage encodedImage;
  if (mInputStreamSupplier != null) {
    encodedImage = new EncodedImage(mInputStreamSupplier, mStreamSize);
  } else {
    CloseableReference<PooledByteBuffer> pooledByteBufferRef =
        CloseableReference.cloneOrNull(mPooledByteBufferRef);
    try {
      encodedImage = (pooledByteBufferRef == null) ? null : new EncodedImage(pooledByteBufferRef);
    } finally {
      // Close the recently created reference since it will be cloned again in the constructor.
      CloseableReference.closeSafely(pooledByteBufferRef);
    }
  }
  if (encodedImage != null) {
    encodedImage.copyMetaDataFrom(this);
  }
  return encodedImage;
}
 
Example 4
Source File: FrescoVitoRegionDecoder.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Decodes a partial jpeg.
 *
 * @param encodedImage input image (encoded bytes plus meta data)
 * @param length if image type supports decoding incomplete image then determines where the image
 *     data should be cut for decoding.
 * @param qualityInfo quality information for the image
 * @param options options that can change decode behavior
 */
@Override
public CloseableImage decode(
    EncodedImage encodedImage, int length, QualityInfo qualityInfo, ImageDecodeOptions options) {

  Rect regionToDecode = computeRegionToDecode(encodedImage, options);

  CloseableReference<Bitmap> decodedBitmapReference =
      mPlatformDecoder.decodeJPEGFromEncodedImageWithColorSpace(
          encodedImage, options.bitmapConfig, regionToDecode, length, options.colorSpace);
  try {
    maybeApplyTransformation(options.bitmapTransformation, decodedBitmapReference);
    return new CloseableStaticBitmap(
        decodedBitmapReference,
        ImmutableQualityInfo.FULL_QUALITY,
        encodedImage.getRotationAngle(),
        encodedImage.getExifOrientation());
  } finally {
    CloseableReference.closeSafely(decodedBitmapReference);
  }
}
 
Example 5
Source File: BasePostprocessor.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Clients should override this method only if the post-processed bitmap has to be of a different
 * size than the source bitmap. If the post-processed bitmap is of the same size, clients should
 * override one of the other two methods.
 *
 * <p>The source bitmap must not be modified as it may be shared by the other clients. The
 * implementation must create a new bitmap that is safe to be modified and return a reference to
 * it. Clients should use <code>bitmapFactory</code> to create a new bitmap.
 *
 * @param sourceBitmap The source bitmap.
 * @param bitmapFactory The factory to create a destination bitmap.
 * @return a reference to the newly created bitmap
 */
@Override
public CloseableReference<Bitmap> process(
    Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) {
  final Bitmap.Config sourceBitmapConfig = sourceBitmap.getConfig();
  CloseableReference<Bitmap> destBitmapRef =
      bitmapFactory.createBitmapInternal(
          sourceBitmap.getWidth(),
          sourceBitmap.getHeight(),
          sourceBitmapConfig != null ? sourceBitmapConfig : FALLBACK_BITMAP_CONFIGURATION);
  try {
    process(destBitmapRef.get(), sourceBitmap);
    return CloseableReference.cloneOrNull(destBitmapRef);
  } finally {
    CloseableReference.closeSafely(destBitmapRef);
  }
}
 
Example 6
Source File: PostprocessorProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
protected void copyAndPostprocessBitmap(
    CloseableReference<CloseableImage> sourceImageRef,
    boolean isLast) {
  mListener.onProducerStart(mRequestId, NAME);
  CloseableReference<CloseableImage> destRef = null;
  try {
    try {
      destRef = mCloseableImageCopier.copyCloseableImage(sourceImageRef);
      mListener.onProducerEvent(mRequestId, NAME, BITMAP_COPIED_EVENT);
      postprocessBitmap(destRef, mPostprocessor);
    } catch (Throwable t) {
      mListener.onProducerFinishWithFailure(
          mRequestId, NAME, t, getExtraMap(mListener, mRequestId, mPostprocessor));
      mConsumer.onFailure(t);
      return;
    }
    mListener.onProducerFinishWithSuccess(
        mRequestId, NAME, getExtraMap(mListener, mRequestId, mPostprocessor));
    mConsumer.onNewResult(destRef, isLast);
  } finally {
    CloseableReference.closeSafely(destRef);
  }
}
 
Example 7
Source File: NetworkFetchProducer.java    From fresco with MIT License 6 votes vote down vote up
protected static void notifyConsumer(
    PooledByteBufferOutputStream pooledOutputStream,
    @Consumer.Status int status,
    @Nullable BytesRange responseBytesRange,
    Consumer<EncodedImage> consumer,
    ProducerContext context) {
  CloseableReference<PooledByteBuffer> result =
      CloseableReference.of(pooledOutputStream.toByteBuffer());
  EncodedImage encodedImage = null;
  try {
    encodedImage = new EncodedImage(result);
    encodedImage.setBytesRange(responseBytesRange);
    encodedImage.parseMetaData();
    context.setEncodedImageOrigin(EncodedImageOrigin.NETWORK);
    consumer.onNewResult(encodedImage, status);
  } finally {
    EncodedImage.closeSafely(encodedImage);
    CloseableReference.closeSafely(result);
  }
}
 
Example 8
Source File: PostprocessorProducer.java    From fresco with MIT License 6 votes vote down vote up
private void updateSourceImageRef(
    @Nullable CloseableReference<CloseableImage> sourceImageRef, int status) {
  CloseableReference<CloseableImage> oldSourceImageRef;
  boolean shouldSubmit;
  synchronized (PostprocessorConsumer.this) {
    if (mIsClosed) {
      return;
    }
    oldSourceImageRef = mSourceImageRef;
    mSourceImageRef = CloseableReference.cloneOrNull(sourceImageRef);
    mStatus = status;
    mIsDirty = true;
    shouldSubmit = setRunningIfDirtyAndNotRunning();
  }
  CloseableReference.closeSafely(oldSourceImageRef);
  if (shouldSubmit) {
    submitPostprocessing();
  }
}
 
Example 9
Source File: CountingMemoryCache.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Caches the given key-value pair.
 *
 * <p>Important: the client should use the returned reference instead of the original one. It is
 * the caller's responsibility to close the returned reference once not needed anymore.
 *
 * @return the new reference to be used, null if the value cannot be cached
 */
public @Nullable CloseableReference<V> cache(
    final K key, final CloseableReference<V> valueRef, final EntryStateObserver<K> observer) {
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(valueRef);

  maybeUpdateCacheParams();

  Entry<K, V> oldExclusive;
  CloseableReference<V> oldRefToClose = null;
  CloseableReference<V> clientRef = null;
  synchronized (this) {
    // remove the old item (if any) as it is stale now
    oldExclusive = mExclusiveEntries.remove(key);
    Entry<K, V> oldEntry = mCachedEntries.remove(key);
    if (oldEntry != null) {
      makeOrphan(oldEntry);
      oldRefToClose = referenceToClose(oldEntry);
    }

    if (canCacheNewValue(valueRef.get())) {
      Entry<K, V> newEntry = Entry.of(key, valueRef, observer);
      mCachedEntries.put(key, newEntry);
      clientRef = newClientReference(newEntry);
    }
  }
  CloseableReference.closeSafely(oldRefToClose);
  maybeNotifyExclusiveEntryRemoval(oldExclusive);

  maybeEvictEntries();
  return clientRef;
}
 
Example 10
Source File: RemoveImageTransformMetaDataProducer.java    From fresco with MIT License 5 votes vote down vote up
@Override
protected void onNewResultImpl(EncodedImage newResult, @Status int status) {
  CloseableReference<PooledByteBuffer> ret = null;
  try {
    if (EncodedImage.isValid(newResult)) {
      ret = newResult.getByteBufferRef();
    }
    getConsumer().onNewResult(ret, status);
  } finally {
    CloseableReference.closeSafely(ret);
  }
}
 
Example 11
Source File: ImagePipelineBitmapFactoryFragment.java    From fresco with MIT License 5 votes vote down vote up
private void initDisplayedBitmap(CreateOptions createOptions) {
  final CloseableReference<Bitmap> oldDisplayedReference = mDisplayedBitmap;

  final int originalW = mOriginalBitmap.get().getWidth();
  final int originalH = mOriginalBitmap.get().getHeight();

  switch (createOptions) {
    case BASIC:
      mDisplayedBitmap = mPlatformBitmapFactory.createBitmap(mOriginalBitmap.get());
      break;
    case CROPPED:
      mDisplayedBitmap =
          mPlatformBitmapFactory.createBitmap(
              mOriginalBitmap.get(), 0, 0, originalW / 2, originalH / 2);
      break;
    case SCALED:
      mDisplayedBitmap =
          mPlatformBitmapFactory.createScaledBitmap(mOriginalBitmap.get(), 4, 4, true);
      break;
    case TRANSFORMED:
      mDisplayedBitmap =
          mPlatformBitmapFactory.createBitmap(
              mOriginalBitmap.get(), 0, 0, originalW, originalH, getMatrix(2f, 3f, 60.0f), true);
      break;
  }

  mImageView.setImageBitmap(mDisplayedBitmap.get());
  CloseableReference.closeSafely(oldDisplayedReference);
}
 
Example 12
Source File: MultiplexProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
public void onNextResult(
    final ForwardingConsumer consumer,
    final CloseableReference<T> closeableReference,
    final boolean isFinal) {
  Iterator<Pair<Consumer<CloseableReference<T>>, ProducerContext>> iterator;
  synchronized (Multiplexer.this) {
    // check for late callbacks
    if (mForwardingConsumer != consumer) {
      return;
    }

    CloseableReference.closeSafely(mLastIntermediateResult);
    mLastIntermediateResult = null;

    iterator = mConsumerContextPairs.iterator();
    if (!isFinal) {
      mLastIntermediateResult = closeableReference.clone();
    } else {
      mConsumerContextPairs.clear();
      removeMultiplexer(mKey, this);
    }
  }

  while (iterator.hasNext()) {
    Pair<Consumer<CloseableReference<T>>, ProducerContext> pair = iterator.next();
    synchronized (pair) {
      pair.first.onNewResult(closeableReference, isFinal);
    }
  }
}
 
Example 13
Source File: MultiPostprocessor.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public CloseableReference<Bitmap>	process(Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) {
  CloseableReference<Bitmap> prevBitmap = null, nextBitmap = null;

  try {
    for (Postprocessor p : mPostprocessors) {
      nextBitmap = p.process(prevBitmap != null ? prevBitmap.get() : sourceBitmap, bitmapFactory);
      CloseableReference.closeSafely(prevBitmap);
      prevBitmap = nextBitmap.clone();
    }
    return nextBitmap.clone();
  } finally {
    CloseableReference.closeSafely(nextBitmap);
  }
}
 
Example 14
Source File: FrescoFrameCache.java    From fresco with MIT License 5 votes vote down vote up
private synchronized void removePreparedReference(int frameNumber) {
  CloseableReference<CloseableImage> existingPendingReference =
      mPreparedPendingFrames.get(frameNumber);
  if (existingPendingReference != null) {
    mPreparedPendingFrames.delete(frameNumber);
    CloseableReference.closeSafely(existingPendingReference);
    FLog.v(
        TAG,
        "removePreparedReference(%d) removed. Pending frames: %s",
        frameNumber,
        mPreparedPendingFrames);
  }
}
 
Example 15
Source File: ImagePipelineRegionDecodingFragment.java    From fresco with MIT License 5 votes vote down vote up
@Override
public CloseableImage decode(
    EncodedImage encodedImage,
    int length,
    QualityInfo qualityInfo,
    ImageDecodeOptions options) {
  CloseableReference<Bitmap> decodedBitmapReference =
      mPlatformDecoder.decodeJPEGFromEncodedImageWithColorSpace(
          encodedImage, options.bitmapConfig, mRegion, length, options.colorSpace);
  try {
    return new CloseableStaticBitmap(decodedBitmapReference, qualityInfo, 0);
  } finally {
    CloseableReference.closeSafely(decodedBitmapReference);
  }
}
 
Example 16
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 17
Source File: PostprocessorProducer.java    From fresco with MIT License 5 votes vote down vote up
private void setSourceImageRef(CloseableReference<CloseableImage> sourceImageRef) {
  CloseableReference<CloseableImage> oldSourceImageRef;
  synchronized (RepeatedPostprocessorConsumer.this) {
    if (mIsClosed) {
      return;
    }
    oldSourceImageRef = mSourceImageRef;
    mSourceImageRef = CloseableReference.cloneOrNull(sourceImageRef);
  }
  CloseableReference.closeSafely(oldSourceImageRef);
}
 
Example 18
Source File: BitmapMemoryCacheProducer.java    From fresco with MIT License 4 votes vote down vote up
protected Consumer<CloseableReference<CloseableImage>> wrapConsumer(
    final Consumer<CloseableReference<CloseableImage>> consumer,
    final CacheKey cacheKey,
    final boolean isMemoryCacheEnabled) {
  return new DelegatingConsumer<
      CloseableReference<CloseableImage>, CloseableReference<CloseableImage>>(consumer) {
    @Override
    public void onNewResultImpl(
        CloseableReference<CloseableImage> newResult, @Status int status) {
      try {
        if (FrescoSystrace.isTracing()) {
          FrescoSystrace.beginSection("BitmapMemoryCacheProducer#onNewResultImpl");
        }
        final boolean isLast = isLast(status);
        // ignore invalid intermediate results and forward the null result if last
        if (newResult == null) {
          if (isLast) {
            getConsumer().onNewResult(null, status);
          }
          return;
        }
        // stateful and partial results cannot be cached and are just forwarded
        if (newResult.get().isStateful() || statusHasFlag(status, IS_PARTIAL_RESULT)) {
          getConsumer().onNewResult(newResult, status);
          return;
        }
        // if the intermediate result is not of a better quality than the cached result,
        // forward the already cached result and don't cache the new result.
        if (!isLast) {
          CloseableReference<CloseableImage> currentCachedResult = mMemoryCache.get(cacheKey);
          if (currentCachedResult != null) {
            try {
              QualityInfo newInfo = newResult.get().getQualityInfo();
              QualityInfo cachedInfo = currentCachedResult.get().getQualityInfo();
              if (cachedInfo.isOfFullQuality()
                  || cachedInfo.getQuality() >= newInfo.getQuality()) {
                getConsumer().onNewResult(currentCachedResult, status);
                return;
              }
            } finally {
              CloseableReference.closeSafely(currentCachedResult);
            }
          }
        }
        // cache, if needed, and forward the new result
        CloseableReference<CloseableImage> newCachedResult = null;
        if (isMemoryCacheEnabled) {
          newCachedResult = mMemoryCache.cache(cacheKey, newResult);
        }
        try {
          if (isLast) {
            getConsumer().onProgressUpdate(1f);
          }
          getConsumer()
              .onNewResult((newCachedResult != null) ? newCachedResult : newResult, status);
        } finally {
          CloseableReference.closeSafely(newCachedResult);
        }
      } finally {
        if (FrescoSystrace.isTracing()) {
          FrescoSystrace.endSection();
        }
      }
    }
  };
}
 
Example 19
Source File: CountingMemoryCacheInspector.java    From fresco with MIT License 4 votes vote down vote up
public void release() {
  CloseableReference.closeSafely(value);
}
 
Example 20
Source File: WebpTranscodeProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void closeReturnValue(CloseableReference<PooledByteBuffer> returnValue) {
  CloseableReference.closeSafely(returnValue);
}