Java Code Examples for com.facebook.common.memory.PooledByteBuffer

The following examples show how to use com.facebook.common.memory.PooledByteBuffer. 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: AnimatedImageFactoryImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Decodes a GIF into a CloseableImage.
 *
 * @param encodedImage encoded image (native byte array holding the encoded bytes and meta data)
 * @param options the options for the decode
 * @param bitmapConfig the Bitmap.Config used to generate the output bitmaps
 * @return a {@link CloseableImage} for the GIF image
 */
public CloseableImage decodeGif(
    final EncodedImage encodedImage,
    final ImageDecodeOptions options,
    final Bitmap.Config bitmapConfig) {
  if (sGifAnimatedImageDecoder == null) {
    throw new UnsupportedOperationException(
        "To encode animated gif please add the dependency " + "to the animated-gif module");
  }
  final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef();
  Preconditions.checkNotNull(bytesRef);
  try {
    final PooledByteBuffer input = bytesRef.get();
    AnimatedImage gifImage;
    if (input.getByteBuffer() != null) {
      gifImage = sGifAnimatedImageDecoder.decodeFromByteBuffer(input.getByteBuffer(), options);
    } else {
      gifImage =
          sGifAnimatedImageDecoder.decodeFromNativeMemory(
              input.getNativePtr(), input.size(), options);
    }
    return getCloseableImage(options, gifImage, bitmapConfig);
  } finally {
    CloseableReference.closeSafely(bytesRef);
  }
}
 
Example 2
Source Project: fresco   Source File: AnimatedImageFactoryImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Decode a WebP into a CloseableImage.
 *
 * @param encodedImage encoded image (native byte array holding the encoded bytes and meta data)
 * @param options the options for the decode
 * @param bitmapConfig the Bitmap.Config used to generate the output bitmaps
 * @return a {@link CloseableImage} for the WebP image
 */
public CloseableImage decodeWebP(
    final EncodedImage encodedImage,
    final ImageDecodeOptions options,
    final Bitmap.Config bitmapConfig) {
  if (sWebpAnimatedImageDecoder == null) {
    throw new UnsupportedOperationException(
        "To encode animated webp please add the dependency " + "to the animated-webp module");
  }
  final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef();
  Preconditions.checkNotNull(bytesRef);
  try {
    final PooledByteBuffer input = bytesRef.get();
    AnimatedImage webPImage;
    if (input.getByteBuffer() != null) {
      webPImage = sWebpAnimatedImageDecoder.decodeFromByteBuffer(input.getByteBuffer(), options);
    } else {
      webPImage =
          sWebpAnimatedImageDecoder.decodeFromNativeMemory(
              input.getNativePtr(), input.size(), options);
    }
    return getCloseableImage(options, webPImage, bitmapConfig);
  } finally {
    CloseableReference.closeSafely(bytesRef);
  }
}
 
Example 3
Source Project: fresco   Source File: EncodedImage.java    License: 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 Project: fresco   Source File: EncodedImage.java    License: MIT License 6 votes vote down vote up
/**
 * Returns an InputStream from the internal InputStream Supplier if it's not null. Otherwise
 * returns an InputStream for the internal buffer reference if valid and null otherwise.
 *
 * <p>The caller has to close the InputStream after using it.
 */
public @Nullable InputStream getInputStream() {
  if (mInputStreamSupplier != null) {
    return mInputStreamSupplier.get();
  }
  CloseableReference<PooledByteBuffer> pooledByteBufferRef =
      CloseableReference.cloneOrNull(mPooledByteBufferRef);
  if (pooledByteBufferRef != null) {
    try {
      return new PooledByteBufferInputStream(pooledByteBufferRef.get());
    } finally {
      CloseableReference.closeSafely(pooledByteBufferRef);
    }
  }
  return null;
}
 
Example 5
Source Project: fresco   Source File: EncodedImage.java    License: MIT License 6 votes vote down vote up
/**
 * Returns first n bytes of encoded image as hexbytes
 *
 * @param length the number of bytes to return
 */
public String getFirstBytesAsHexString(int length) {
  CloseableReference<PooledByteBuffer> imageBuffer = getByteBufferRef();
  if (imageBuffer == null) {
    return "";
  }
  int imageSize = getSize();
  int resultSampleSize = Math.min(imageSize, length);
  byte[] bytesBuffer = new byte[resultSampleSize];
  try {
    PooledByteBuffer pooledByteBuffer = imageBuffer.get();
    if (pooledByteBuffer == null) {
      return "";
    }
    pooledByteBuffer.read(0, bytesBuffer, 0, resultSampleSize);
  } finally {
    imageBuffer.close();
  }
  StringBuilder stringBuilder = new StringBuilder(bytesBuffer.length * 2);
  for (byte b : bytesBuffer) {
    stringBuilder.append(String.format("%02X", b));
  }
  return stringBuilder.toString();
}
 
Example 6
Source Project: fresco   Source File: EncodedImageTest.java    License: MIT License 6 votes vote down vote up
private void checkWebpImage(
    final String imagePath,
    final ImageFormat imageFormat,
    final int expectedWidth,
    final int expectedHeight)
    throws IOException {
  PooledByteBuffer buf =
      new TrivialPooledByteBuffer(
          ByteStreams.toByteArray(EncodedImageTest.class.getResourceAsStream(imagePath)));
  EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf));
  encodedImage.parseMetaData();
  assertSame(imageFormat, encodedImage.getImageFormat());
  assertEquals(expectedWidth, encodedImage.getWidth());
  assertEquals(expectedHeight, encodedImage.getHeight());
  assertEquals(0, encodedImage.getRotationAngle());
}
 
Example 7
Source Project: fresco   Source File: AnimatedImageFactoryWebPImplTest.java    License: MIT License 6 votes vote down vote up
private void testCreateDefaults(WebPImage mockWebPImage, PooledByteBuffer byteBuffer) {
  EncodedImage encodedImage =
      new EncodedImage(CloseableReference.of(byteBuffer, FAKE_RESOURCE_RELEASER));
  encodedImage.setImageFormat(ImageFormat.UNKNOWN);

  CloseableAnimatedImage closeableImage =
      (CloseableAnimatedImage)
          mAnimatedImageFactory.decodeWebP(
              encodedImage, ImageDecodeOptions.defaults(), DEFAULT_BITMAP_CONFIG);

  // Verify we got the right result
  AnimatedImageResult imageResult = closeableImage.getImageResult();
  assertSame(mockWebPImage, imageResult.getImage());
  assertNull(imageResult.getPreviewBitmap());
  assertFalse(imageResult.hasDecodedFrame(0));

  // Should not have interacted with these.
  verifyZeroInteractions(mMockAnimatedDrawableBackendProvider);
  verifyZeroInteractions(mMockBitmapFactory);
}
 
Example 8
Source Project: fresco   Source File: EmptyJpegGenerator.java    License: MIT License 6 votes vote down vote up
public CloseableReference<PooledByteBuffer> generate(short width, short height) {
  PooledByteBufferOutputStream os = null;
  try {
    os =
        mPooledByteBufferFactory.newOutputStream(
            EMPTY_JPEG_PREFIX.length + EMPTY_JPEG_SUFFIX.length + 4);
    os.write(EMPTY_JPEG_PREFIX);
    os.write((byte) (height >> 8));
    os.write((byte) (height & 0x00ff));
    os.write((byte) (width >> 8));
    os.write((byte) (width & 0x00ff));
    os.write(EMPTY_JPEG_SUFFIX);
    return CloseableReference.of(os.toByteBuffer());
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (os != null) {
      os.close();
    }
  }
}
 
Example 9
Source Project: fresco   Source File: NetworkFetchProducer.java    License: 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 10
Source Project: fresco   Source File: ImagePipelineTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchLocalEncodedImage() {
  Producer<CloseableReference<PooledByteBuffer>> encodedSequence = mock(Producer.class);
  when(mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest))
      .thenReturn(encodedSequence);
  when(mImageRequest.getSourceUri()).thenReturn(Uri.parse("file:///local/file"));
  DataSource<CloseableReference<PooledByteBuffer>> dataSource =
      mImagePipeline.fetchEncodedImage(mImageRequest, mCallerContext);
  assertFalse(dataSource.isFinished());
  ArgumentCaptor<ImageRequest> argumentCaptor = ArgumentCaptor.forClass(ImageRequest.class);
  verify(mRequestListener1)
      .onRequestStart(argumentCaptor.capture(), eq(mCallerContext), eq("0"), eq(false));
  ImageRequest capturedImageRequest = argumentCaptor.getValue();
  assertSame(mImageRequest.getSourceUri(), capturedImageRequest.getSourceUri());
  verify(mRequestListener2)
      .onRequestStart(argumentCaptor.capture(), eq(mCallerContext), eq("0"), eq(false));
  capturedImageRequest = argumentCaptor.getValue();
  assertSame(mImageRequest.getSourceUri(), capturedImageRequest.getSourceUri());
  ArgumentCaptor<ProducerContext> producerContextArgumentCaptor =
      ArgumentCaptor.forClass(ProducerContext.class);
  verify(encodedSequence)
      .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture());
  assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected());
  assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH);
}
 
Example 11
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 12
Source Project: fresco   Source File: BitmapProbeProducer.java    License: MIT License 6 votes vote down vote up
public BitmapProbeProducer(
    MemoryCache<CacheKey, PooledByteBuffer> encodedMemoryCache,
    BufferedDiskCache defaultBufferedDiskCache,
    BufferedDiskCache smallImageBufferedDiskCache,
    CacheKeyFactory cacheKeyFactory,
    BoundedLinkedHashSet<CacheKey> encodedMemoryCacheHistory,
    BoundedLinkedHashSet<CacheKey> diskCacheHistory,
    Producer<CloseableReference<CloseableImage>> inputProducer) {
  mEncodedMemoryCache = encodedMemoryCache;
  mDefaultBufferedDiskCache = defaultBufferedDiskCache;
  mSmallImageBufferedDiskCache = smallImageBufferedDiskCache;
  mCacheKeyFactory = cacheKeyFactory;
  mEncodedMemoryCacheHistory = encodedMemoryCacheHistory;
  mDiskCacheHistory = diskCacheHistory;
  mInputProducer = inputProducer;
}
 
Example 13
Source Project: fresco   Source File: BitmapProbeProducer.java    License: MIT License 6 votes vote down vote up
public ProbeConsumer(
    Consumer<CloseableReference<CloseableImage>> consumer,
    ProducerContext producerContext,
    MemoryCache<CacheKey, PooledByteBuffer> encodedMemoryCache,
    BufferedDiskCache defaultBufferedDiskCache,
    BufferedDiskCache smallImageBufferedDiskCache,
    CacheKeyFactory cacheKeyFactory,
    BoundedLinkedHashSet<CacheKey> encodedMemoryCacheHistory,
    BoundedLinkedHashSet<CacheKey> diskCacheHistory) {
  super(consumer);
  mProducerContext = producerContext;
  mEncodedMemoryCache = encodedMemoryCache;
  mDefaultBufferedDiskCache = defaultBufferedDiskCache;
  mSmallImageBufferedDiskCache = smallImageBufferedDiskCache;
  mCacheKeyFactory = cacheKeyFactory;
  mEncodedMemoryCacheHistory = encodedMemoryCacheHistory;
  mDiskCacheHistory = diskCacheHistory;
}
 
Example 14
Source Project: fresco   Source File: DalvikPurgeableDecoder.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a bitmap from encoded JPEG bytes. Supports a partial JPEG image.
 *
 * @param encodedImage the encoded image with reference to the encoded bytes
 * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded
 *     Bitmap
 * @param regionToDecode optional image region to decode. currently not supported.
 * @param length the number of encoded bytes in the buffer
 * @param colorSpace the target color space of the decoded bitmap, must be one of the named color
 *     space in {@link android.graphics.ColorSpace.Named}. If null, then SRGB color space is
 *     assumed if the SDK version >= 26.
 * @return the bitmap
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
@Override
public CloseableReference<Bitmap> decodeJPEGFromEncodedImageWithColorSpace(
    final EncodedImage encodedImage,
    Bitmap.Config bitmapConfig,
    @Nullable Rect regionToDecode,
    int length,
    @Nullable final ColorSpace colorSpace) {
  BitmapFactory.Options options =
      getBitmapFactoryOptions(encodedImage.getSampleSize(), bitmapConfig);
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    OreoUtils.setColorSpace(options, colorSpace);
  }
  final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef();
  Preconditions.checkNotNull(bytesRef);
  try {
    Bitmap bitmap = decodeJPEGByteArrayAsPurgeable(bytesRef, length, options);
    return pinBitmap(bitmap);
  } finally {
    CloseableReference.closeSafely(bytesRef);
  }
}
 
Example 15
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 an encoded image from network. */
public Producer<CloseableReference<PooledByteBuffer>>
    getNetworkFetchEncodedImageProducerSequence() {
  synchronized (this) {
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.beginSection(
          "ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence");
    }
    if (mNetworkEncodedImageProducerSequence == null) {
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.beginSection(
            "ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence:init");
      }
      mNetworkEncodedImageProducerSequence =
          new RemoveImageTransformMetaDataProducer(
              getBackgroundNetworkFetchToEncodedMemorySequence());
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.endSection();
      }
    }
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.endSection();
    }
  }
  return mNetworkEncodedImageProducerSequence;
}
 
Example 16
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 an encoded image from a local file. */
public Producer<CloseableReference<PooledByteBuffer>>
    getLocalFileFetchEncodedImageProducerSequence() {
  synchronized (this) {
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.beginSection(
          "ProducerSequenceFactory#getLocalFileFetchEncodedImageProducerSequence");
    }
    if (mLocalFileEncodedImageProducerSequence == null) {
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.beginSection(
            "ProducerSequenceFactory#getLocalFileFetchEncodedImageProducerSequence:init");
      }
      mLocalFileEncodedImageProducerSequence =
          new RemoveImageTransformMetaDataProducer(
              getBackgroundLocalFileFetchToEncodeMemorySequence());
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.endSection();
      }
    }
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.endSection();
    }
  }
  return mLocalFileEncodedImageProducerSequence;
}
 
Example 17
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 an encoded image from a local content
 * uri.
 */
public Producer<CloseableReference<PooledByteBuffer>>
    getLocalContentUriFetchEncodedImageProducerSequence() {
  synchronized (this) {
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.beginSection(
          "ProducerSequenceFactory#getLocalContentUriFetchEncodedImageProducerSequence");
    }
    if (mLocalContentUriEncodedImageProducerSequence == null) {
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.beginSection(
            "ProducerSequenceFactory#getLocalContentUriFetchEncodedImageProducerSequence:init");
      }
      mLocalContentUriEncodedImageProducerSequence =
          new RemoveImageTransformMetaDataProducer(
              getBackgroundLocalContentUriFetchToEncodeMemorySequence());
      if (FrescoSystrace.isTracing()) {
        FrescoSystrace.endSection();
      }
    }
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.endSection();
    }
  }
  return mLocalContentUriEncodedImageProducerSequence;
}
 
Example 18
Source Project: fresco   Source File: LocalAssetFetchProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchAssetResource() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mAssetManager.open(eq(TEST_FILENAME), eq(AssetManager.ACCESS_STREAMING)))
      .thenReturn(new ByteArrayInputStream(new byte[TEST_DATA_LENGTH]));
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class), eq(TEST_DATA_LENGTH)))
      .thenReturn(pooledByteBuffer);

  mLocalAssetFetchProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();

  assertEquals(
      2,
      mCapturedEncodedImage
          .getByteBufferRef()
          .getUnderlyingReferenceTestOnly()
          .getRefCountTestOnly());
  assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  verify(mProducerListener).onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
  verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, true);
}
 
Example 19
Source Project: fresco   Source File: QualifiedResourceFetchProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testQualifiedResourceUri() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class)))
      .thenReturn(pooledByteBuffer);

  when(mContentResolver.openInputStream(mContentUri)).thenReturn(mock(InputStream.class));

  mQualifiedResourceFetchProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();

  verify(mPooledByteBufferFactory, times(1)).newByteBuffer(any(InputStream.class));
  verify(mContentResolver, times(1)).openInputStream(mContentUri);

  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  verify(mProducerListener).onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
}
 
Example 20
Source Project: fresco   Source File: LocalResourceFetchProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchLocalResource() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class), eq(TEST_DATA_LENGTH)))
      .thenReturn(pooledByteBuffer);
  when(mResources.openRawResource(eq(TEST_ID)))
      .thenReturn(new ByteArrayInputStream(new byte[TEST_DATA_LENGTH]));

  mLocalResourceFetchProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();

  assertEquals(
      2,
      mCapturedEncodedImage
          .getByteBufferRef()
          .getUnderlyingReferenceTestOnly()
          .getRefCountTestOnly());
  assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  verify(mProducerListener).onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
  verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, true);
}
 
Example 21
Source Project: fresco   Source File: KitKatPurgeableDecoder.java    License: MIT License 6 votes vote down vote up
/**
 * Decodes a byteArray containing jpeg encoded bytes into a purgeable bitmap
 *
 * <p>Adds a JFIF End-Of-Image marker if needed before decoding.
 *
 * @param bytesRef the byte buffer that contains the encoded bytes
 * @return
 */
@Override
protected Bitmap decodeJPEGByteArrayAsPurgeable(
    CloseableReference<PooledByteBuffer> bytesRef, int length, BitmapFactory.Options options) {
  byte[] suffix = endsWithEOI(bytesRef, length) ? null : EOI;
  final PooledByteBuffer pooledByteBuffer = bytesRef.get();
  Preconditions.checkArgument(length <= pooledByteBuffer.size());
  // allocate bigger array in case EOI needs to be added
  final CloseableReference<byte[]> encodedBytesArrayRef = mFlexByteArrayPool.get(length + 2);
  try {
    byte[] encodedBytesArray = encodedBytesArrayRef.get();
    pooledByteBuffer.read(0, encodedBytesArray, 0, length);
    if (suffix != null) {
      putEOI(encodedBytesArray, length);
      length += 2;
    }
    Bitmap bitmap = BitmapFactory.decodeByteArray(encodedBytesArray, 0, length, options);
    return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null");
  } finally {
    CloseableReference.closeSafely(encodedBytesArrayRef);
  }
}
 
Example 22
Source Project: fresco   Source File: RemoveImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  mRemoveMetaDataProducer = new RemoveImageTransformMetaDataProducer(mInputProducer);

  mIntermediateByteBuffer = mock(PooledByteBuffer.class);
  mFinalByteBuffer = mock(PooledByteBuffer.class);

  mIntermediateResult = CloseableReference.of(mIntermediateByteBuffer);
  mFinalResult = CloseableReference.of(mFinalByteBuffer);

  mRemoveMetaDataConsumer = null;
  doAnswer(
          new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
              mRemoveMetaDataConsumer = (Consumer<EncodedImage>) invocation.getArguments()[0];
              return null;
            }
          })
      .when(mInputProducer)
      .produceResults(any(Consumer.class), any(ProducerContext.class));
  mRemoveMetaDataProducer.produceResults(mConsumer, mProducerContext);
}
 
Example 23
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  PowerMockito.mockStatic(ImageFormatChecker.class, JfifUtil.class, BitmapUtil.class);

  mAddMetaDataProducer = new AddImageTransformMetaDataProducer(mInputProducer);

  mIntermediateResultBufferRef = CloseableReference.of(mock(PooledByteBuffer.class));
  mFinalResultBufferRef = CloseableReference.of(mock(PooledByteBuffer.class));

  mIntermediateResult = new EncodedImage(mIntermediateResultBufferRef);
  mFinalResult = new EncodedImage(mFinalResultBufferRef);

  mAddMetaDataConsumer = null;
  doAnswer(
          new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
              mAddMetaDataConsumer = (Consumer<EncodedImage>) invocation.getArguments()[0];
              return null;
            }
          })
      .when(mInputProducer)
      .produceResults(any(Consumer.class), any(ProducerContext.class));
  mAddMetaDataProducer.produceResults(mConsumer, mProducerContext);
}
 
Example 24
Source Project: fresco   Source File: LocalContentUriFetchProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchLocalContentUri() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class)))
      .thenReturn(pooledByteBuffer);

  when(mContentResolver.openInputStream(mContentUri)).thenReturn(mock(InputStream.class));
  mLocalContentUriFetchProducer.produceResults(mConsumer, mProducerContext);

  mExecutor.runUntilIdle();

  assertEquals(
      2,
      mCapturedEncodedImage
          .getByteBufferRef()
          .getUnderlyingReferenceTestOnly()
          .getRefCountTestOnly());
  assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, true);
}
 
Example 25
Source Project: fresco   Source File: LocalFileFetchProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFetchLocalFile() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class), eq(INPUT_STREAM_LENGTH)))
      .thenReturn(pooledByteBuffer);
  mLocalFileFetchProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();
  assertEquals(
      2,
      mCapturedEncodedImage
          .getByteBufferRef()
          .getUnderlyingReferenceTestOnly()
          .getRefCountTestOnly());
  assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  verify(mProducerListener).onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
  verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, true);
}
 
Example 26
Source Project: fresco   Source File: GingerbreadPurgeableDecoder.java    License: MIT License 6 votes vote down vote up
private Bitmap decodeFileDescriptorAsPurgeable(
    CloseableReference<PooledByteBuffer> bytesRef,
    int inputLength,
    byte[] suffix,
    BitmapFactory.Options options) {
  MemoryFile memoryFile = null;
  try {
    memoryFile = copyToMemoryFile(bytesRef, inputLength, suffix);
    FileDescriptor fd = getMemoryFileDescriptor(memoryFile);
    if (mWebpBitmapFactory != null) {
      Bitmap bitmap = mWebpBitmapFactory.decodeFileDescriptor(fd, null, options);
      return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null");
    } else {
      throw new IllegalStateException("WebpBitmapFactory is null");
    }
  } catch (IOException e) {
    throw Throwables.propagate(e);
  } finally {
    if (memoryFile != null) {
      memoryFile.close();
    }
  }
}
 
Example 27
Source Project: fresco   Source File: EncodedMemoryCacheProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testEncodedMemoryCacheGetNotFoundInputProducerSuccess() {
  setupEncodedMemoryCacheGetNotFound();
  setupInputProducerStreamingSuccess();
  mEncodedMemoryCacheProducer.produceResults(mConsumer, mProducerContext);
  verify(mMemoryCache, never()).cache(mCacheKey, mIntermediateImageReference);
  ArgumentCaptor<CloseableReference> argumentCaptor =
      ArgumentCaptor.forClass(CloseableReference.class);
  verify(mMemoryCache).cache(eq(mCacheKey), argumentCaptor.capture());
  CloseableReference<PooledByteBuffer> capturedRef =
      (CloseableReference<PooledByteBuffer>) argumentCaptor.getValue();
  Assert.assertSame(
      mFinalImageReference.getUnderlyingReferenceTestOnly(),
      capturedRef.getUnderlyingReferenceTestOnly());
  verify(mConsumer).onNewResult(mIntermediateEncodedImage, Consumer.NO_FLAGS);
  verify(mConsumer).onNewResult(mFinalEncodedImage, Consumer.IS_LAST);
  Assert.assertTrue(EncodedImage.isValid(mFinalEncodedImageClone));
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  Map<String, String> extraMap =
      ImmutableMap.of(EncodedMemoryCacheProducer.EXTRA_CACHED_VALUE_FOUND, "false");
  verify(mProducerListener)
      .onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, extraMap);
  verify(mProducerListener, never())
      .onUltimateProducerReached(eq(mProducerContext), anyString(), anyBoolean());
}
 
Example 28
Source Project: fresco   Source File: EncodedImage.java    License: MIT License 5 votes vote down vote up
/**
 * Returns true if the image is a JPEG or DNG and its data is already complete at the specified
 * length, false otherwise.
 */
public boolean isCompleteAt(int length) {
  if (mImageFormat != DefaultImageFormats.JPEG && mImageFormat != DefaultImageFormats.DNG) {
    return true;
  }
  // If the image is backed by FileInputStreams return true since they will always be complete.
  if (mInputStreamSupplier != null) {
    return true;
  }
  // The image should be backed by a ByteBuffer
  Preconditions.checkNotNull(mPooledByteBufferRef);
  PooledByteBuffer buf = mPooledByteBufferRef.get();
  return (buf.read(length - 2) == (byte) JfifUtil.MARKER_FIRST_BYTE)
      && (buf.read(length - 1) == (byte) JfifUtil.MARKER_EOI);
}
 
Example 29
Source Project: fresco   Source File: ProducerSequenceFactoryTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testLocalFileFetchToEncodedMemory() {
  PowerMockito.when(mImageRequest.getSourceUriType()).thenReturn(SOURCE_TYPE_LOCAL_IMAGE_FILE);
  Producer<CloseableReference<PooledByteBuffer>> producer =
      mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest);
  assertSame(producer, mProducerSequenceFactory.mLocalFileEncodedImageProducerSequence);
  // Same for Video
  PowerMockito.when(mImageRequest.getSourceUriType()).thenReturn(SOURCE_TYPE_LOCAL_IMAGE_FILE);
  producer = mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest);
  assertSame(producer, mProducerSequenceFactory.mLocalFileEncodedImageProducerSequence);
}
 
Example 30
Source Project: fresco   Source File: EncodedImageTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
  mByteBufferRef = CloseableReference.of(mock(PooledByteBuffer.class));
  mInputStream = mock(FileInputStream.class);
  mInputStreamSupplier =
      new Supplier<FileInputStream>() {
        @Override
        public FileInputStream get() {
          return mInputStream;
        }
      };
}