Java Code Examples for com.facebook.common.references.CloseableReference

The following examples show how to use com.facebook.common.references.CloseableReference. These examples are extracted from open source projects. 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 Project: fresco   Source File: LocalExifThumbnailProducer.java    License: MIT License 6 votes vote down vote up
private EncodedImage buildEncodedImage(PooledByteBuffer imageBytes, ExifInterface exifInterface) {
  Pair<Integer, Integer> dimensions =
      BitmapUtil.decodeDimensions(new PooledByteBufferInputStream(imageBytes));
  int rotationAngle = getRotationAngle(exifInterface);
  int width = dimensions != null ? dimensions.first : EncodedImage.UNKNOWN_WIDTH;
  int height = dimensions != null ? dimensions.second : EncodedImage.UNKNOWN_HEIGHT;
  EncodedImage encodedImage;
  CloseableReference<PooledByteBuffer> closeableByteBuffer = CloseableReference.of(imageBytes);
  try {
    encodedImage = new EncodedImage(closeableByteBuffer);
  } finally {
    CloseableReference.closeSafely(closeableByteBuffer);
  }
  encodedImage.setImageFormat(DefaultImageFormats.JPEG);
  encodedImage.setRotationAngle(rotationAngle);
  encodedImage.setWidth(width);
  encodedImage.setHeight(height);
  return encodedImage;
}
 
Example 2
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 * @param imageRequest the request to submit (what to execute).
 * @param bitmapCacheOnly whether to only look for the image in the bitmap cache
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier(
    final ImageRequest imageRequest,
    final Object callerContext,
    final boolean bitmapCacheOnly) {
  return new Supplier<DataSource<CloseableReference<CloseableImage>>>() {
    @Override
    public DataSource<CloseableReference<CloseableImage>> get() {
      if (bitmapCacheOnly) {
        return fetchImageFromBitmapCache(imageRequest, callerContext);
      } else {
        return fetchDecodedImage(imageRequest, callerContext);
      }
    }
    @Override
    public String toString() {
      return Objects.toStringHelper(this)
          .add("uri", imageRequest.getSourceUri())
          .toString();
    }
  };
}
 
Example 3
/**
 * Removes exclusively owned values from the cache until there is at most count of them
 * and they occupy no more than size bytes.
 */
private synchronized Collection<CloseableReference<V>> trimEvictionQueueTo(
    int count,
    long size) {
  Preconditions.checkArgument(count >= 0);
  Preconditions.checkArgument(size >= 0);

  List<CloseableReference<V>> evictedValues = Lists.newArrayList();
  while (mEvictionQueue.size() > count || mEvictionQueueSize > size) {
    CacheEntry<K, V> cacheEntry = mEvictionQueue.iterator().next();
    evictedValues.add(cacheEntry.value);
    removeFromEvictionQueue(cacheEntry);
    removeFromCachedEntries(cacheEntry);
    mMemoryCacheIndex.removeEntry(cacheEntry.key, cacheEntry.value);
  }
  return evictedValues;
}
 
Example 4
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 5
Source Project: fresco   Source File: PipelineDraweeController.java    License: MIT License 6 votes vote down vote up
/**
 * Initializes this controller with the new data source supplier, id and caller context. This
 * allows for reusing of the existing controller instead of instantiating a new one. This method
 * should be called when the controller is in detached state.
 *
 * @param dataSourceSupplier data source supplier
 * @param id unique id for this controller
 * @param callerContext tag and context for this controller
 */
public void initialize(
    Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
    String id,
    CacheKey cacheKey,
    Object callerContext,
    @Nullable ImmutableList<DrawableFactory> customDrawableFactories,
    @Nullable ImageOriginListener imageOriginListener) {
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.beginSection("PipelineDraweeController#initialize");
  }
  super.initialize(id, callerContext);
  init(dataSourceSupplier);
  mCacheKey = cacheKey;
  setCustomDrawableFactories(customDrawableFactories);
  clearImageOriginListeners();
  maybeUpdateDebugOverlay(null);
  addImageOriginListener(imageOriginListener);
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.endSection();
  }
}
 
Example 6
Source Project: fresco   Source File: RepeatedPostprocessorProducerTest.java    License: MIT License 6 votes vote down vote up
private void verifyNewResultProcessed(int index, Bitmap destBitmap) {
  mInOrder
      .verify(mProducerListener)
      .onProducerStart(mProducerContext, PostprocessorProducer.NAME);
  mInOrder.verify(mPostprocessor).process(mSourceBitmap, mPlatformBitmapFactory);
  mInOrder
      .verify(mProducerListener)
      .requiresExtraMap(mProducerContext, PostprocessorProducer.NAME);
  mInOrder
      .verify(mProducerListener)
      .onProducerFinishWithSuccess(
          eq(mProducerContext), eq(PostprocessorProducer.NAME), eq(mExtraMap));
  mInOrder.verify(mConsumer).onNewResult(any(CloseableReference.class), eq(Consumer.NO_FLAGS));
  mInOrder.verifyNoMoreInteractions();

  assertEquals(index + 1, mResults.size());
  CloseableReference<CloseableImage> res0 = mResults.get(index);
  assertTrue(CloseableReference.isValid(res0));
  assertSame(destBitmap, ((CloseableStaticBitmap) res0.get()).getUnderlyingBitmap());
  res0.close();
  verify(mBitmapResourceReleaser).release(destBitmap);
}
 
Example 7
Source Project: fresco   Source File: FrescoControllerImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void onNewResult(
    FrescoState frescoState, DataSource<CloseableReference<CloseableImage>> dataSource) {
  if (dataSource != null && !dataSource.isClosed()) {
    final boolean shouldClose =
        mFrescoContext.getExperiments().closeDatasourceOnNewResult() && dataSource.isFinished();
    final CloseableReference<CloseableImage> result = dataSource.getResult();
    try {
      frescoState.setImageFetched(true);
      if (frescoState.isAttached()) {
        displayResultOrError(frescoState, result, false, dataSource);
      }
    } finally {
      CloseableReference.closeSafely(result);
      if (shouldClose) {
        dataSource.close();
      }
    }
  }
}
 
Example 8
Source Project: fresco   Source File: BitmapMemoryCacheProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testDontCacheIntermediateImageAsAlreadyHaveFullQuality() {
  setupBitmapMemoryCacheGetNotFound();
  setupInputProducerStreamingSuccess();
  CloseableImage closeableImage = mock(CloseableImage.class);
  when(closeableImage.getQualityInfo()).thenReturn(ImmutableQualityInfo.FULL_QUALITY);
  CloseableReference<CloseableImage> closeableImageRef = CloseableReference.of(closeableImage);
  setupBitmapMemoryCacheGetSuccessOnSecondRead(closeableImageRef);
  mBitmapMemoryCacheProducer.produceResults(mConsumer, mProducerContext);
  verify(mMemoryCache, never()).cache(mBitmapMemoryCacheKey, mIntermediateImageReference);
  verify(mMemoryCache).cache(mBitmapMemoryCacheKey, mFinalImageReference);
  verify(mConsumer).onNewResult(closeableImageRef, Consumer.NO_FLAGS);
  verify(mConsumer).onNewResult(mFinalImageReferenceClone, Consumer.IS_LAST);
  Assert.assertTrue(!mFinalImageReferenceClone.isValid());
  Assert.assertEquals(
      0, closeableImageRef.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  Map<String, String> extraMap =
      ImmutableMap.of(BitmapMemoryCacheProducer.EXTRA_CACHED_VALUE_FOUND, "false");
  verify(mProducerListener)
      .onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, extraMap);
  verify(mProducerListener, never())
      .onUltimateProducerReached(eq(mProducerContext), anyString(), anyBoolean());
}
 
Example 9
Source Project: fresco   Source File: ProducerSequenceFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a sequence that can be used for a request for a decoded image.
 *
 * @param imageRequest the request that will be submitted
 * @return the sequence that should be used to process the request
 */
public Producer<CloseableReference<CloseableImage>> getDecodedImageProducerSequence(
    ImageRequest imageRequest) {
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.beginSection("ProducerSequenceFactory#getDecodedImageProducerSequence");
  }
  Producer<CloseableReference<CloseableImage>> pipelineSequence =
      getBasicDecodedImageSequence(imageRequest);

  if (imageRequest.getPostprocessor() != null) {
    pipelineSequence = getPostprocessorSequence(pipelineSequence);
  }

  if (mUseBitmapPrepareToDraw) {
    pipelineSequence = getBitmapPrepareSequence(pipelineSequence);
  }
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.endSection();
  }
  return pipelineSequence;
}
 
Example 10
Source Project: fresco   Source File: FrescoController2Impl.java    License: 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 11
Source Project: fresco   Source File: PostprocessorProducer.java    License: MIT License 6 votes vote down vote up
@Override
public void produceResults(
    final Consumer<CloseableReference<CloseableImage>> consumer, ProducerContext context) {
  final ProducerListener2 listener = context.getProducerListener();
  final Postprocessor postprocessor = context.getImageRequest().getPostprocessor();
  final PostprocessorConsumer basePostprocessorConsumer =
      new PostprocessorConsumer(consumer, listener, postprocessor, context);
  final Consumer<CloseableReference<CloseableImage>> postprocessorConsumer;
  if (postprocessor instanceof RepeatedPostprocessor) {
    postprocessorConsumer =
        new RepeatedPostprocessorConsumer(
            basePostprocessorConsumer, (RepeatedPostprocessor) postprocessor, context);
  } else {
    postprocessorConsumer = new SingleUsePostprocessorConsumer(basePostprocessorConsumer);
  }
  mInputProducer.produceResults(postprocessorConsumer, context);
}
 
Example 12
Source Project: fresco   Source File: AnimatedFrameCacheTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  MemoryCacheParams params =
      new MemoryCacheParams(
          4 * ByteConstants.MB,
          256,
          Integer.MAX_VALUE,
          Integer.MAX_VALUE,
          Integer.MAX_VALUE,
          TimeUnit.MINUTES.toMillis(5));
  when(mMemoryCacheParamsSupplier.get()).thenReturn(params);
  CountingMemoryCache<CacheKey, CloseableImage> countingMemoryCache =
      BitmapCountingMemoryCacheFactory.get(
          mMemoryCacheParamsSupplier, mMemoryTrimmableRegistry, null);
  mCacheKey = new SimpleCacheKey("key");
  mAnimatedFrameCache = new AnimatedFrameCache(mCacheKey, countingMemoryCache);
  mFrame1 = CloseableReference.of(mock(CloseableImage.class));
  mFrame2 = CloseableReference.of(mock(CloseableImage.class));
}
 
Example 13
Source Project: fresco   Source File: CountingMemoryCacheTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testReuseExclusive_CacheSameItemWithDifferentKey() {
  CloseableReference<Integer> cachedRef =
      mCache.cache(KEY, newReference(100), mEntryStateObserver);
  cachedRef.close();
  verify(mEntryStateObserver).onExclusivityChanged(KEY, true);
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(1, 100);
  cachedRef = mCache.reuse(KEY);
  assertNotNull(cachedRef);
  verify(mEntryStateObserver).onExclusivityChanged(KEY, false);
  assertTotalSize(0, 0);
  assertExclusivelyOwnedSize(0, 0);
  CloseableReference<Integer> newItem = mCache.cache(KEYS[2], cachedRef);
  cachedRef.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  newItem.close();
  verify(mEntryStateObserver).onExclusivityChanged(KEY, true);
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(1, 100);
}
 
Example 14
Source Project: fresco   Source File: PostprocessorProducer.java    License: 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 15
Source Project: fresco   Source File: ImagePipeline.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 *
 * @param imageRequest the request to submit (what to execute).
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<PooledByteBuffer>>>
    getEncodedImageDataSourceSupplier(
        final ImageRequest imageRequest, final Object callerContext) {
  return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() {
    @Override
    public DataSource<CloseableReference<PooledByteBuffer>> get() {
      return fetchEncodedImage(imageRequest, callerContext);
    }

    @Override
    public String toString() {
      return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString();
    }
  };
}
 
Example 16
Source Project: fresco   Source File: LocalFetchProducer.java    License: MIT License 6 votes vote down vote up
/** Creates a memory-backed encoded image from the stream. The stream is closed. */
protected EncodedImage getByteBufferBackedEncodedImage(InputStream inputStream, int length)
    throws IOException {
  CloseableReference<PooledByteBuffer> ref = null;
  try {
    if (length <= 0) {
      ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream));
    } else {
      ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream, length));
    }
    return new EncodedImage(ref);
  } finally {
    Closeables.closeQuietly(inputStream);
    CloseableReference.closeSafely(ref);
  }
}
 
Example 17
Source Project: fresco   Source File: ImagePipelineTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchFromBitmapCacheDueToImageRequest() {
  Producer<CloseableReference<CloseableImage>> bitmapCacheSequence = mock(Producer.class);
  when(mImageRequest.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
  when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest))
      .thenReturn(bitmapCacheSequence);
  mImagePipeline.fetchDecodedImage(mImageRequest, mCallerContext);
  verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false);
  verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false);
  ArgumentCaptor<ProducerContext> producerContextArgumentCaptor =
      ArgumentCaptor.forClass(ProducerContext.class);
  verify(bitmapCacheSequence)
      .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture());
  assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected());
  assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH);
  assertEquals(
      producerContextArgumentCaptor.getValue().getLowestPermittedRequestLevel(),
      ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
}
 
Example 18
/**
 * Returns a sequence that can be used for a request that just requires a bitmap cache lookup.
 *
 * <p> Sequence is: bitmap cache get -> null producer
 * @return the sequence that should be used to process the request.
 */
public synchronized Producer<CloseableReference<CloseableImage>> getBitmapCacheGetOnlySequence() {
  if (mBitmapCacheGetOnlySequence == null) {
    mBitmapCacheGetOnlySequence =
        mProducerFactory.newBitmapMemoryCacheGetProducer(
            mProducerFactory.<CloseableReference<CloseableImage>>newNullProducer());
  }
  return mBitmapCacheGetOnlySequence;
}
 
Example 19
Source Project: fresco   Source File: BitmapMemoryCacheProducerTest.java    License: MIT License 5 votes vote down vote up
private void setupInputProducerNotFound() {
  final List<CloseableReference<CloseableImage>> nullArray =
      new ArrayList<CloseableReference<CloseableImage>>(1);
  nullArray.add(null);
  doAnswer(new ProduceResultsNewResultAnswer(Consumer.NO_FLAGS, nullArray))
      .when(mInputProducer)
      .produceResults(any(Consumer.class), eq(mProducerContext));
}
 
Example 20
/**
 * Decodes a partial jpeg.
 *
 * @param pooledByteBufferRef
 * @param length amount of currently available data in bytes
 * @param qualityInfo quality info for the image
 * @return a CloseableStaticBitmap
 */
public synchronized CloseableStaticBitmap decodeJpeg(
    final CloseableReference<PooledByteBuffer> pooledByteBufferRef,
    int length,
    QualityInfo qualityInfo) {
  CloseableReference<Bitmap> bitmapReference =
      mBitmapFactoryWithPool.decodeJPEGFromPooledByteBuffer(pooledByteBufferRef, length);
  try {
    return new CloseableStaticBitmap(bitmapReference, qualityInfo);
  } finally {
    bitmapReference.close();
  }
}
 
Example 21
public PipelineDraweeController newController(
    Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
    String id,
    Object callerContext) {
  return new PipelineDraweeController(
      mResources,
      mDeferredReleaser,
      mAnimatedDrawableFactory,
      mUiThreadExecutor,
      dataSourceSupplier,
      id,
      callerContext);
}
 
Example 22
/**
 * Closes the stream. Owned resources are released back to the pool. It is not allowed to call
 * toByteBuffer after call to this method.
 * @throws IOException
 */
@Override
public void close() {
  CloseableReference.closeSafely(mBufRef);
  mBufRef = null;
  mCount = -1;
  super.close();
}
 
Example 23
Source Project: fresco   Source File: SwallowResultProducerTest.java    License: MIT License 5 votes vote down vote up
private void setupInputProducerNotFound() {
  final List<CloseableReference<CloseableImage>> empty =
      new ArrayList<CloseableReference<CloseableImage>>(1);
  empty.add(null);
  doAnswer(new ProduceResultsNewResultAnswer(empty))
      .when(mInputProducer)
      .produceResults(any(Consumer.class), eq(mProducerContext));
}
 
Example 24
Source Project: fresco   Source File: FrescoFrameCache.java    License: 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 25
Source Project: react-native-image-filter-kit   Source File: TempFileUtils.java    License: 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 26
public DestinationATopCompositingPostProcessor(
  final int width,
  final int height,
  final @Nullable JSONObject config,
  final @Nonnull CloseableReference<CloseableImage> src,
  final @Nonnull CacheKey srcCacheKey,
  final @Nonnull Context context
) {
  super(width, height, config, src, srcCacheKey, context);
}
 
Example 27
Source Project: fresco   Source File: ImagePipelineBitmapFactoryFragment.java    License: MIT License 5 votes vote down vote up
@Override
public void onStop() {
  super.onStop();

  // close bitmaps
  mImageView.setImageBitmap(null);
  CloseableReference.closeSafely(mOriginalBitmap);
  CloseableReference.closeSafely(mDisplayedBitmap);
}
 
Example 28
Source Project: fresco   Source File: ImagePipelineMultiUriHelper.java    License: MIT License 5 votes vote down vote up
private static Supplier<DataSource<CloseableReference<CloseableImage>>>
    getFirstAvailableDataSourceSupplier(
        final ImagePipeline imagePipeline,
        final Object callerContext,
        final @Nullable RequestListener requestListener,
        ImageRequest[] imageRequests,
        boolean tryBitmapCacheOnlyFirst,
        final @Nullable String uiComponentId) {
  List<Supplier<DataSource<CloseableReference<CloseableImage>>>> suppliers =
      new ArrayList<>(imageRequests.length * 2);
  if (tryBitmapCacheOnlyFirst) {
    // we first add bitmap-cache-only suppliers, then the full-fetch ones
    for (int i = 0; i < imageRequests.length; i++) {
      suppliers.add(
          getImageRequestDataSourceSupplier(
              imagePipeline,
              imageRequests[i],
              callerContext,
              ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE,
              requestListener,
              uiComponentId));
    }
  }
  for (int i = 0; i < imageRequests.length; i++) {
    suppliers.add(
        getImageRequestDataSourceSupplier(
            imagePipeline, imageRequests[i], callerContext, requestListener, uiComponentId));
  }
  return FirstAvailableDataSourceSupplier.create(suppliers);
}
 
Example 29
@Override
public CloseableReference<Bitmap> process(
    Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) {
  long startTime = System.nanoTime();
  CloseableReference<Bitmap> result = mPostprocessor.process(sourceBitmap, bitmapFactory);
  showDuration(System.nanoTime() - startTime);
  return result;
}
 
Example 30
private synchronized void maybeCacheRenderedBitmap(
    int frameNumber,
    CloseableReference<Bitmap> bitmapReference) {
  if (!mBitmapsToKeepCached.get(frameNumber)) {
    return;
  }

  int existingIndex = mCachedBitmaps.indexOfKey(frameNumber);
  if (existingIndex >= 0) {
    CloseableReference<Bitmap> oldReference = mCachedBitmaps.valueAt(existingIndex);
    oldReference.close();
    mCachedBitmaps.removeAt(existingIndex);
  }
  mCachedBitmaps.put(frameNumber, bitmapReference.clone());
}