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

The following examples show how to use com.facebook.common.references.CloseableReference#clone() . 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: CompositionPostProcessor.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
public CompositionPostProcessor(
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull CloseableReference<CloseableImage> src,
  @Nonnull CacheKey srcCacheKey
) {
  super(config);

  InputConverter converter = new InputConverter(width, height);

  mWidth = width;
  mHeight = height;

  final PointF center = new PointF(0.5f, 0.5f);
  final Transform transform = new Transform(center, center, new Scale.WithMode(Scale.Mode.COVER), 0);

  mSrc = src.clone();
  mSrcCacheKey = srcCacheKey;
  mSrcTransform = converter.convertTransform(config, "srcTransform", transform);
  mDstTransform = converter.convertTransform(config, "dstTransform", transform);
  mResizeCanvasTo = converter.convertText(config, "resizeCanvasTo", null);
  mSwapImages = converter.convertBool(config, "swapImages", false);
}
 
Example 2
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 3
Source File: PostprocessorProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void onNewResultImpl(
    CloseableReference<CloseableImage> newResult, boolean isLast) {
  if (!isLast) {
    return;
  }
  if (!mCloseableImageCopier.isCloseableImageCopyable(newResult)) {
    mConsumer.onNewResult(newResult, true);
    return;
  }

  synchronized (RepeatedPostprocessorConsumer.this) {
    mOriginalImageRef = newResult.clone();
  }
  maybeExecuteCopyAndPostprocessBitmap();
}
 
Example 4
Source File: PostprocessorProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void onNewResultImpl(
    final CloseableReference<CloseableImage> newResult, final boolean isLast) {
  if (!isLast) {
    return;
  }
  if (!mCloseableImageCopier.isCloseableImageCopyable(newResult)) {
    mConsumer.onNewResult(newResult, true);
    return;
  }

  final CloseableReference<CloseableImage> clonedResult = newResult.clone();
  mExecutor.execute(
      new Runnable() {
        @Override
        public void run() {
          try {
            copyAndPostprocessBitmap(clonedResult, isLast);
          } finally {
            CloseableReference.closeSafely(clonedResult);
          }
        }
      });
}
 
Example 5
Source File: TempFileUtils.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
static void writeFile(
  @NonNull final ReactContext context,
  @NonNull final CloseableReference<CloseableImage> ref,
  @NonNull final Functor.Arity1<String> sendUri,
  @NonNull final Functor.Arity1<String> sendError
) {
  CloseableReference<CloseableImage> cloned = ref.clone();

  Task.callInBackground((Callable<Void>) () -> {
    try {
      final File outputFile = createFile(context);
      final FileOutputStream fos = new FileOutputStream(outputFile);
      final Bitmap bitmap = ((CloseableBitmap) cloned.get()).getUnderlyingBitmap();

      bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

      final String path = Uri.fromFile(outputFile).toString();

      FLog.w(ReactConstants.TAG, "ImageFilterKit: created file " + path);

      Task.call((Callable<Void>) () -> {
        sendUri.call(path);

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } catch (Exception e) {
      Task.call((Callable<Void>) () -> {
        sendError.call(e.getMessage());

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } finally {
      CloseableReference.closeSafely(cloned);
    }

    return null;
  });
}
 
Example 6
Source File: CountingMemoryCacheTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testCachingSameKeyTwice() {
  CloseableReference<Integer> originalRef1 = newReference(110);
  CloseableReference<Integer> cachedRef1 = mCache.cache(KEY, originalRef1);
  CloseableReference<Integer> cachedRef2a = mCache.get(KEY);
  CloseableReference<Integer> cachedRef2b = cachedRef2a.clone();
  CloseableReference<Integer> cachedRef3 = mCache.get(KEY);
  CountingMemoryCache.Entry<String, Integer> entry1 = mCache.mCachedEntries.get(KEY);

  CloseableReference<Integer> cachedRef2 = mCache.cache(KEY, newReference(120));
  CountingMemoryCache.Entry<String, Integer> entry2 = mCache.mCachedEntries.get(KEY);
  assertNotSame(entry1, entry2);
  assertOrphanWithCount(entry1, 3);
  assertSharedWithCount(KEY, 120, 1);

  // release the orphaned reference only when all clients are gone
  originalRef1.close();
  cachedRef2b.close();
  assertOrphanWithCount(entry1, 3);
  cachedRef2a.close();
  assertOrphanWithCount(entry1, 2);
  cachedRef1.close();
  assertOrphanWithCount(entry1, 1);
  verify(mReleaser, never()).release(anyInt());
  cachedRef3.close();
  assertOrphanWithCount(entry1, 0);
  verify(mReleaser).release(110);
}
 
Example 7
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 8
Source File: DecodeProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
protected synchronized void updateStoredIntermediateImage(
    CloseableReference<PooledByteBuffer> intermediateImageBytesRef,
    int intermediateImageBestScanEnd,
    ImageFormat intermediateImageFormat,
    QualityInfo intermediateImageQualityInfo) {
  closeStoredIntermediateImageBytes();
  mStoredIntermediateImageBytesRef = intermediateImageBytesRef.clone();
  mStoredIntermediateImageBestScanEnd = intermediateImageBestScanEnd;
  mStoredIntermediateImageFormat = intermediateImageFormat;
  mStoredIntermediateImageQualityInfo = intermediateImageQualityInfo;
}
 
Example 9
Source File: BufferedDiskCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Associates byteBuffer with given key in disk cache. Disk write is performed on background
 * thread, so the caller of this method is not blocked
 */
public void put(
    final CacheKey key,
    CloseableReference<PooledByteBuffer> byteBuffer) {
  Preconditions.checkNotNull(key);
  Preconditions.checkArgument(CloseableReference.isValid(byteBuffer));

  // Store byteBuffer in staging area
  mStagingArea.put(key, byteBuffer);

  // Write to disk cache. This will be executed on background thread, so increment the ref count.
  // When this write completes (with success/failure), then we will bump down the ref count
  // again.
  final CloseableReference<PooledByteBuffer> finalByteBuffer = byteBuffer.clone();
  try {
    mWriteExecutor.execute(
        new Runnable() {
          @Override
          public void run() {
            try {
              writeToDiskCache(key, finalByteBuffer.get());
            } finally {
              mStagingArea.remove(key, finalByteBuffer);
              finalByteBuffer.close();
            }
          }
        });
  } catch (Exception exception) {
    // We failed to enqueue cache write. Log failure and decrement ref count
    // TODO: 3697790
    FLog.w(
        TAG,
        exception,
        "Failed to schedule disk-cache write for %s",
        key.toString());
    mStagingArea.remove(key, byteBuffer);
    finalByteBuffer.close();
  }
}
 
Example 10
Source File: ReactImageView.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public CloseableReference<Bitmap> process(Bitmap source, PlatformBitmapFactory bitmapFactory) {
  final Rect destRect = new Rect(0, 0, getWidth(), getHeight());

  mScaleType.getTransform(
    sTileMatrix,
    destRect,
    source.getWidth(),
    source.getHeight(),
    0.0f,
    0.0f);

  Paint paint = new Paint();
  paint.setAntiAlias(true);
  Shader shader = new BitmapShader(source, mTileMode, mTileMode);
  shader.setLocalMatrix(sTileMatrix);
  paint.setShader(shader);

  CloseableReference<Bitmap> output = bitmapFactory.createBitmap(getWidth(), getHeight());
  try {
    Canvas canvas = new Canvas(output.get());
    canvas.drawRect(destRect, paint);
    return output.clone();
  } finally {
    CloseableReference.closeSafely(output);
  }
}
 
Example 11
Source File: CountingMemoryCacheInspector.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
public DumpInfoEntry(
    final K key,
    final CloseableReference<V> value) {
  this.key = Preconditions.checkNotNull(key);
  this.value = value.clone();
}
 
Example 12
Source File: DecodeProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
protected void scheduleImageDecode(
    final CloseableReference<PooledByteBuffer> imageBytesRef,
    final int length,
    @Nullable final ImageFormat imageFormat,
    final QualityInfo qualityInfo,
    final boolean isFinal) {
  final CloseableReference<PooledByteBuffer> imageBytesRefCopy = imageBytesRef.clone();
  final long startTime = SystemClock.elapsedRealtime();
  mExecutor.execute(
      new Runnable() {
        @Override
        public void run() {
          final long queueTime = SystemClock.elapsedRealtime() - startTime;
          try {
            if (isFinished()) {
              return;
            }
            mProducerListener.onProducerStart(mProducerContext.getId(), PRODUCER_NAME);
            CloseableImage decodedImage = mImageDecoder.decodeImage(
                imageBytesRefCopy,
                imageFormat,
                length,
                qualityInfo,
                mImageDecodeOptions);
            mProducerListener.onProducerFinishWithSuccess(
                mProducerContext.getId(),
                PRODUCER_NAME,
                getExtraMap(queueTime, qualityInfo, isFinal));
            handleResult(decodedImage, isFinal);
          } catch (Exception e) {
            mProducerListener.onProducerFinishWithFailure(
                mProducerContext.getId(),
                PRODUCER_NAME,
                e,
                getExtraMap(queueTime, qualityInfo, isFinal));
            handleError(e);
          } finally {
            imageBytesRefCopy.close();
          }
        }
      });
}
 
Example 13
Source File: WebpTranscodeProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected CloseableReference<PooledByteBuffer> getImageCopy(
    CloseableReference<PooledByteBuffer> originalResult) {
  return originalResult.clone();
}
 
Example 14
Source File: MultiplexProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Tries to add consumer to set of consumers participating in multiplexing. If successful and
 * appropriate intermediate result is already known, then it will be passed to the consumer.
 *
 * <p> This function will fail and return false if the multiplexer is not present in
 * mMultiplexers map.
 *
 * @return true if consumer was added successfully
 */
public boolean addNewConsumer(
    final Consumer<CloseableReference<T>> consumer,
    final ProducerContext producerContext) {
  final Pair<Consumer<CloseableReference<T>>, ProducerContext> consumerContextPair =
      Pair.create(consumer, producerContext);
  CloseableReference<T> lastIntermediateResult;

  // Check if Multiplexer is still in mMultiplexers map, and if so add new consumer.
  // Also store current intermediate result - we will notify consumer after acquiring
  // appropriate lock.
  synchronized (Multiplexer.this) {
    if (getExistingMultiplexer(mKey) != this) {
      return false;
    }
    mConsumerContextPairs.add(consumerContextPair);
    if (mMultiplexProducerContext != null) {
      if (mMultiplexProducerContext.isPrefetch()) {
        mMultiplexProducerContext.setIsPrefetch(consumerContextPair.second.isPrefetch());
      }
      if (!mMultiplexProducerContext.isIntermediateResultExpected()) {
        mMultiplexProducerContext.setIsIntermediateResultExpected(
            consumerContextPair.second.isIntermediateResultExpected());
      }
      mMultiplexProducerContext.setPriority(
          Priority.getHigherPriority(
              mMultiplexProducerContext.getPriority(),
              consumerContextPair.second.getPriority()));
    }
    lastIntermediateResult = mLastIntermediateResult;
  }

  synchronized (consumerContextPair) {
    // check if last result changed in the mean time. In such case we should not propagate it
    synchronized (Multiplexer.this) {
      if (lastIntermediateResult != mLastIntermediateResult) {
        lastIntermediateResult = null;
      } else if (lastIntermediateResult != null) {
        lastIntermediateResult = lastIntermediateResult.clone();
      }
    }

    if (lastIntermediateResult != null) {
      consumer.onNewResult(lastIntermediateResult, false);
      lastIntermediateResult.close();
    }
  }

  addCallbacks(consumerContextPair, producerContext);
  return true;
}
 
Example 15
Source File: NativePooledByteBuffer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
public NativePooledByteBuffer(CloseableReference<NativeMemoryChunk> bufRef, int size) {
  Preconditions.checkNotNull(bufRef);
  Preconditions.checkArgument(size >= 0 && size <= bufRef.get().getSize());
  mBufRef = bufRef.clone();
  mSize = size;
}
 
Example 16
Source File: EncodedImage.java    From fresco with MIT License 4 votes vote down vote up
public EncodedImage(CloseableReference<PooledByteBuffer> pooledByteBufferRef) {
  Preconditions.checkArgument(CloseableReference.isValid(pooledByteBufferRef));
  this.mPooledByteBufferRef = pooledByteBufferRef.clone();
  this.mInputStreamSupplier = null;
}
 
Example 17
Source File: CountingMemoryCacheTest.java    From fresco with MIT License 4 votes vote down vote up
@Test
public void testInUseCount() {
  CloseableReference<Integer> cachedRef1 = mCache.cache(KEY, newReference(100));

  CloseableReference<Integer> cachedRef2a = mCache.get(KEY);
  CloseableReference<Integer> cachedRef2b = cachedRef2a.clone();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 2);

  CloseableReference<Integer> cachedRef3a = mCache.get(KEY);
  CloseableReference<Integer> cachedRef3b = cachedRef3a.clone();
  CloseableReference<Integer> cachedRef3c = cachedRef3b.clone();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 3);

  cachedRef1.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 2);

  // all copies of cachedRef2a need to be closed for usage count to drop
  cachedRef2a.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 2);
  cachedRef2b.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 1);

  // all copies of cachedRef3a need to be closed for usage count to drop
  cachedRef3c.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 1);
  cachedRef3b.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  assertSharedWithCount(KEY, 100, 1);
  cachedRef3a.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(1, 100);
  assertExclusivelyOwned(KEY, 100);
}
 
Example 18
Source File: MemoryPooledByteBuffer.java    From fresco with MIT License 4 votes vote down vote up
public MemoryPooledByteBuffer(CloseableReference<MemoryChunk> bufRef, int size) {
  Preconditions.checkNotNull(bufRef);
  Preconditions.checkArgument(size >= 0 && size <= bufRef.get().getSize());
  mBufRef = bufRef.clone();
  mSize = size;
}