com.facebook.common.memory.PooledByteBuffer Java Examples
The following examples show how to use
com.facebook.common.memory.PooledByteBuffer.
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: ImagePipelineTest.java From fresco with MIT License | 6 votes |
@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 #2
Source File: EncodedImage.java From fresco with MIT License | 6 votes |
/** * 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 #3
Source File: ProducerSequenceFactory.java From fresco with MIT License | 6 votes |
/** 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 #4
Source File: EncodedMemoryCacheProducerTest.java From fresco with MIT License | 6 votes |
@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 #5
Source File: LocalAssetFetchProducerTest.java From fresco with MIT License | 6 votes |
@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 #6
Source File: ProducerSequenceFactory.java From fresco with MIT License | 6 votes |
/** * 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 #7
Source File: EncodedImage.java From fresco with MIT License | 6 votes |
/** * 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 #8
Source File: EncodedImage.java From fresco with MIT License | 6 votes |
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 #9
Source File: AnimatedImageFactoryImpl.java From fresco with MIT License | 6 votes |
/** * 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 #10
Source File: AnimatedImageFactoryImpl.java From fresco with MIT License | 6 votes |
/** * 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 #11
Source File: ProducerSequenceFactory.java From fresco with MIT License | 6 votes |
/** 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 #12
Source File: GingerbreadPurgeableDecoder.java From fresco with MIT License | 6 votes |
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 #13
Source File: QualifiedResourceFetchProducerTest.java From fresco with MIT License | 6 votes |
@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 #14
Source File: EncodedImageTest.java From fresco with MIT License | 6 votes |
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 #15
Source File: DalvikPurgeableDecoder.java From fresco with MIT License | 6 votes |
/** * 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 #16
Source File: BitmapProbeProducer.java From fresco with MIT License | 6 votes |
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 #17
Source File: LocalFileFetchProducerTest.java From fresco with MIT License | 6 votes |
@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 #18
Source File: AnimatedImageFactoryWebPImplTest.java From fresco with MIT License | 6 votes |
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 #19
Source File: BitmapProbeProducer.java From fresco with MIT License | 6 votes |
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 #20
Source File: LocalContentUriFetchProducerTest.java From fresco with MIT License | 6 votes |
@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 #21
Source File: EmptyJpegGenerator.java From fresco with MIT License | 6 votes |
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 #22
Source File: LocalFetchProducer.java From fresco with MIT License | 6 votes |
/** 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 #23
Source File: AddImageTransformMetaDataProducerTest.java From fresco with MIT License | 6 votes |
@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 File: RemoveImageTransformMetaDataProducerTest.java From fresco with MIT License | 6 votes |
@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 #25
Source File: NetworkFetchProducer.java From fresco with MIT License | 6 votes |
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 #26
Source File: KitKatPurgeableDecoder.java From fresco with MIT License | 6 votes |
/** * 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 #27
Source File: LocalResourceFetchProducerTest.java From fresco with MIT License | 6 votes |
@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 #28
Source File: ImagePipeline.java From fresco with MIT License | 5 votes |
public ImagePipeline( ProducerSequenceFactory producerSequenceFactory, Set<RequestListener> requestListeners, Set<RequestListener2> requestListener2s, Supplier<Boolean> isPrefetchEnabledSupplier, MemoryCache<CacheKey, CloseableImage> bitmapMemoryCache, MemoryCache<CacheKey, PooledByteBuffer> encodedMemoryCache, BufferedDiskCache mainBufferedDiskCache, BufferedDiskCache smallImageBufferedDiskCache, CacheKeyFactory cacheKeyFactory, ThreadHandoffProducerQueue threadHandoffProducerQueue, Supplier<Boolean> suppressBitmapPrefetchingSupplier, Supplier<Boolean> lazyDataSource, @Nullable CallerContextVerifier callerContextVerifier, ImagePipelineConfig config) { mIdCounter = new AtomicLong(); mProducerSequenceFactory = producerSequenceFactory; mRequestListener = new ForwardingRequestListener(requestListeners); mRequestListener2 = new ForwardingRequestListener2(requestListener2s); mIsPrefetchEnabledSupplier = isPrefetchEnabledSupplier; mBitmapMemoryCache = bitmapMemoryCache; mEncodedMemoryCache = encodedMemoryCache; mMainBufferedDiskCache = mainBufferedDiskCache; mSmallImageBufferedDiskCache = smallImageBufferedDiskCache; mCacheKeyFactory = cacheKeyFactory; mThreadHandoffProducerQueue = threadHandoffProducerQueue; mSuppressBitmapPrefetchingSupplier = suppressBitmapPrefetchingSupplier; mLazyDataSource = lazyDataSource; mCallerContextVerifier = callerContextVerifier; mConfig = config; }
Example #29
Source File: KitKatPurgeableDecoderTest.java From fresco with MIT License | 5 votes |
@Before public void setUp() { mFlexByteArrayPool = mock(FlexByteArrayPool.class); mBitmap = MockBitmapFactory.create(); mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT, MAX_BITMAP_SIZE); mockStatic(DalvikPurgeableDecoder.class); when(DalvikPurgeableDecoder.getBitmapFactoryOptions(anyInt(), any(Bitmap.Config.class))) .thenCallRealMethod(); when(DalvikPurgeableDecoder.endsWithEOI(any(CloseableReference.class), anyInt())) .thenCallRealMethod(); mockStatic(BitmapCounterProvider.class); when(BitmapCounterProvider.get()).thenReturn(mBitmapCounter); mockStatic(BitmapFactory.class); when(BitmapFactory.decodeByteArray( any(byte[].class), anyInt(), anyInt(), any(BitmapFactory.Options.class))) .thenReturn(mBitmap); mInputBuf = new byte[LENGTH]; PooledByteBuffer input = new TrivialPooledByteBuffer(mInputBuf, POINTER); mByteBufferRef = CloseableReference.of(input); mEncodedImage = new EncodedImage(mByteBufferRef); mDecodeBuf = new byte[LENGTH + 2]; mDecodeBufRef = CloseableReference.of(mDecodeBuf, mock(ResourceReleaser.class)); when(mFlexByteArrayPool.get(Integer.valueOf(LENGTH))).thenReturn(mDecodeBufRef); mockStatic(Bitmaps.class); mKitKatPurgeableDecoder = new KitKatPurgeableDecoder(mFlexByteArrayPool); }
Example #30
Source File: RemoveImageTransformMetaDataProducer.java From fresco with MIT License | 5 votes |
@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); } }