/// <summary>
 /// Creates a new reference for the client.
 /// </summary>
 private CloseableReference <V> NewClientReference(Entry entry)
 {
     IncreaseClientCount(entry);
     return(CloseableReference <V> .of(
                entry.ValueRef.Get(),
                new ResourceReleaserImpl <V>(v => ReleaseClientReference(entry))));
 }
        public void Initialize()
        {
            _byteBufferRef = CloseableReference <IPooledByteBuffer> .of(
                new TrivialPooledByteBuffer(new byte[] { }), _releaser);

            _inputStreamSupplier = new MockSupplier <FileStream>(_inputStream);
        }
        /// <summary>
        /// Creates a memory-backed encoded image from the stream.
        /// The stream is closed.
        /// </summary>
        protected EncodedImage GetByteBufferBackedEncodedImage(Stream inputStream, int length)
        {
            var reference = default(CloseableReference <IPooledByteBuffer>);

            try
            {
                if (length <= 0)
                {
                    reference = CloseableReference <IPooledByteBuffer> .of(
                        _pooledByteBufferFactory.NewByteBuffer(inputStream));
                }
                else
                {
                    reference = CloseableReference <IPooledByteBuffer> .of(
                        _pooledByteBufferFactory.NewByteBuffer(inputStream, length));
                }

                return(new EncodedImage(reference));
            }
            finally
            {
                Closeables.CloseQuietly(inputStream);
                CloseableReference <IPooledByteBuffer> .CloseSafely(reference);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Creates a bitmap of the specified width and height. This is intended for ImagePipeline's
 /// internal use only.
 ///
 /// <param name="width">the width of the bitmap</param>
 /// <param name="height">the height of the bitmap</param>
 /// <param name="bitmapConfig">the Bitmap.Config used to create the Bitmap</param>
 /// <returns>a reference to the bitmap</returns>
 /// <exception cref="OutOfMemoryException">if the Bitmap cannot be allocated</exception>
 /// </summary>
 public override CloseableReference <SoftwareBitmap> CreateBitmapInternal(
     int width,
     int height,
     BitmapPixelFormat bitmapConfig)
 {
     _bitmap = new SoftwareBitmap(bitmapConfig, width, height);
     return(CloseableReference <SoftwareBitmap> .of(_bitmap, BITMAP_RESOURCE_RELEASER));
 }
Exemplo n.º 5
0
 /// <summary>
 /// Construct a new instance of this output stream with this
 /// initial capacity.
 /// It is not an error to have this initial capacity be inaccurate.
 /// If the actual contents end up being larger than the
 /// initialCapacity, then we will reallocate memory if needed.
 /// If the actual contents are smaller, then we'll end up wasting
 /// some memory.
 /// </summary>
 /// <param name="pool">The pool to use.</param>
 /// <param name="initialCapacity">
 /// Initial capacity to allocate for this stream.
 /// </param>
 public NativePooledByteBufferOutputStream(
     NativeMemoryChunkPool pool,
     int initialCapacity)
 {
     Preconditions.CheckArgument(initialCapacity > 0);
     _pool   = Preconditions.CheckNotNull(pool);
     _count  = 0;
     _bufRef = CloseableReference <NativeMemoryChunk> .of(_pool.Get(initialCapacity), _pool);
 }
        /// <summary>
        /// Creates a bitmap of the specified width and height.
        /// </summary>
        /// <param name="width">The width of the bitmap.</param>
        /// <param name="height">The height of the bitmap.</param>
        /// <param name="bitmapConfig">
        /// The <see cref="BitmapPixelFormat"/> used to create the
        /// decoded Bitmap.
        /// </param>
        /// <returns>A reference to the bitmap.</returns>
        /// <exception cref="OutOfMemoryException">
        /// if the Bitmap cannot be allocated.
        /// </exception>
        public override CloseableReference <SoftwareBitmap> CreateBitmapInternal(
            int width,
            int height,
            BitmapPixelFormat bitmapConfig)
        {
            SoftwareBitmap bitmap = new SoftwareBitmap(
                bitmapConfig, width, height, BitmapAlphaMode.Premultiplied);

            return(CloseableReference <SoftwareBitmap> .of(bitmap, SimpleBitmapReleaser.Instance));
        }
        private Task <EncodedImage> GetAsync(ICacheKey key, AtomicBoolean isCancelled)
        {
            try
            {
                if (isCancelled.Value)
                {
                    throw new OperationCanceledException();
                }

                EncodedImage result = _stagingArea.Get(key);
                if (result != null)
                {
                    Debug.WriteLine($"Found image for { key.ToString() } in staging area");
                    _imageCacheStatsTracker.OnStagingAreaHit();
                }
                else
                {
                    Debug.WriteLine($"Did not find image for { key.ToString() } in staging area");
                    _imageCacheStatsTracker.OnStagingAreaMiss();
                    try
                    {
                        IPooledByteBuffer buffer = ReadFromDiskCache(key);
                        if (buffer == null)
                        {
                            return(Task.FromResult(default(EncodedImage)));
                        }

                        CloseableReference <IPooledByteBuffer> reference =
                            CloseableReference <IPooledByteBuffer> .of(buffer);

                        try
                        {
                            result = new EncodedImage(reference);
                        }
                        finally
                        {
                            CloseableReference <IPooledByteBuffer> .CloseSafely(reference);
                        }
                    }
                    catch (Exception)
                    {
                        return(Task.FromResult(default(EncodedImage)));
                    }
                }

                return(Task.FromResult(result));
            }
            catch (Exception)
            {
                // Log failure
                // TODO: 3697790
                Debug.WriteLine($"Failed to schedule disk-cache read for { key.ToString() }");
                throw;
            }
        }
Exemplo n.º 8
0
        public void Initialize()
        {
            _stagingArea        = StagingArea.Instance;
            _closeableReference = CloseableReference <IPooledByteBuffer> .of(new TrivialPooledByteBuffer(BYTES));

            _closeableReference2 = CloseableReference <IPooledByteBuffer> .of(new TrivialPooledByteBuffer(BYTES));

            _encodedImage       = new EncodedImage(_closeableReference);
            _secondEncodedImage = new EncodedImage(_closeableReference2);
            _cacheKey           = new SimpleCacheKey("http://this.is/uri");
            _stagingArea.Put(_cacheKey, _encodedImage);
        }
        public void TestIsJpegCompleteAt_Complete()
        {
            byte[] encodedBytes = new byte[ENCODED_BYTES_LENGTH];
            encodedBytes[ENCODED_BYTES_LENGTH - 2] = JfifUtil.MARKER_FIRST_BYTE;
            encodedBytes[ENCODED_BYTES_LENGTH - 1] = JfifUtil.MARKER_EOI;
            IPooledByteBuffer buf          = new TrivialPooledByteBuffer(encodedBytes);
            EncodedImage      encodedImage = new EncodedImage(
                CloseableReference <IPooledByteBuffer> .of(buf, _releaser));

            encodedImage.Format = ImageFormat.JPEG;
            Assert.IsTrue(encodedImage.IsCompleteAt(ENCODED_BYTES_LENGTH));
        }
        public void Initialize()
        {
            _chunk = new FakeNativeMemoryChunk(BYTES.Length);
            _chunk.Write(0, BYTES, 0, BYTES.Length);
            _pool = new FakeNativeMemoryChunkPool();
            var poolRef = CloseableReference <NativeMemoryChunk> .of(_chunk, _pool);

            _pooledByteBuffer = new NativePooledByteBuffer(
                poolRef,
                BUFFER_LENGTH);

            poolRef.Dispose();
        }
Exemplo n.º 11
0
            /// <summary>
            /// Notifies consumer of new result and finishes if the result
            /// is final.
            /// </summary>
            private void HandleResult(CloseableImage decodedImage, bool isFinal)
            {
                var decodedImageRef = CloseableReference <CloseableImage> .of(decodedImage);

                try
                {
                    MaybeFinish(isFinal);
                    Consumer.OnNewResult(decodedImageRef, isFinal);
                }
                finally
                {
                    CloseableReference <CloseableImage> .CloseSafely(decodedImageRef);
                }
            }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a new IPooledByteBuffer instance of given size.
        /// </summary>
        public IPooledByteBuffer NewByteBuffer(int size)
        {
            Preconditions.CheckArgument(size > 0);
            var chunkRef = CloseableReference <NativeMemoryChunk> .of(_pool.Get(size), _pool);

            try
            {
                return(new NativePooledByteBuffer(chunkRef, size));
            }
            finally
            {
                chunkRef.Dispose();
            }
        }
        /// <summary>
        /// Creates a new instance of a CloseableStaticBitmap.
        /// </summary>
        public CloseableStaticBitmap(
            SoftwareBitmap bitmap,
            IResourceReleaser <SoftwareBitmap> resourceReleaser,
            IQualityInfo qualityInfo,
            int rotationAngle)
        {
            _bitmap          = Preconditions.CheckNotNull(bitmap);
            _bitmapReference = CloseableReference <SoftwareBitmap> .of(
                _bitmap,
                Preconditions.CheckNotNull(resourceReleaser));

            _qualityInfo   = qualityInfo;
            _rotationAngle = rotationAngle;
        }
Exemplo n.º 14
0
        public void Initialize()
        {
            // Initializes the IFileCache
            _fileCacheFactory = new DiskStorageCacheFactory(new DynamicDefaultDiskStorageFactory());
            _fileCache        = _fileCacheFactory.Get(DiskCacheConfig.NewBuilder().Build());

            // Initializes the IPooledByteBufferFactory and PooledByteStreams
            _poolFactory       = new PoolFactory(PoolConfig.NewBuilder().Build());
            _byteBufferFactory = _poolFactory.PooledByteBufferFactory;
            _pooledByteStreams = _poolFactory.PooledByteStreams;

            // Initializes the IPooledByteBuffer from an image
            var file = StorageFile.GetFileFromApplicationUriAsync(
                new Uri("ms-appx:///Assets/SplashScreen.scale-200.png")).GetAwaiter().GetResult();

            using (var stream = file.OpenReadAsync().GetAwaiter().GetResult())
            {
                _pooledByteBuffer = _byteBufferFactory.NewByteBuffer(
                    ByteStreams.ToByteArray(stream.AsStream()));
            }

            _closeableReference = CloseableReference <IPooledByteBuffer> .of(_pooledByteBuffer);

            _encodedImage           = new EncodedImage(_closeableReference);
            _stagingArea            = StagingArea.Instance;
            _imageCacheStatsTracker = NoOpImageCacheStatsTracker.Instance;

            // Initializes the cache keys
            IList <ICacheKey> keys = new List <ICacheKey>();

            keys.Add(new SimpleCacheKey("http://test.uri"));
            keys.Add(new SimpleCacheKey("http://tyrone.uri"));
            keys.Add(new SimpleCacheKey("http://ian.uri"));
            _cacheKey = new MultiCacheKey(keys);

            // Initializes the executors
            _isCancelled           = new AtomicBoolean(false);
            _readPriorityExecutor  = Executors.NewFixedThreadPool(1);
            _writePriorityExecutor = Executors.NewFixedThreadPool(1);

            // Initializes the disk cache
            _bufferedDiskCache = new BufferedDiskCache(
                _fileCache,
                _byteBufferFactory,
                _pooledByteStreams,
                _readPriorityExecutor,
                _writePriorityExecutor,
                _imageCacheStatsTracker);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Reallocate the local buffer to hold the new length specified.
        /// Also copy over existing data to this new buffer.
        /// </summary>
        /// <param name="newLength">New length of buffer.</param>
        /// <exception cref="InvalidStreamException">
        /// If the stream is invalid.
        /// </exception>
        /// <exception cref="SizeTooLargeException">
        /// If the allocation from the pool fails.
        /// </exception>
        internal void Realloc(int newLength)
        {
            EnsureValid();
            /* Can the buffer handle @i more bytes, if not expand it */
            if (newLength <= _bufRef.Get().Size)
            {
                return;
            }

            NativeMemoryChunk newbuf = _pool.Get(newLength);

            _bufRef.Get().Copy(0, newbuf, 0, _count);
            _bufRef.Dispose();
            _bufRef = CloseableReference <NativeMemoryChunk> .of(newbuf, _pool);
        }
        /// <summary>
        /// Get exclusive access to the byte array of size greater or
        /// equal to the passed one.
        ///
        /// <para />Under the hood this method acquires an exclusive
        /// lock that is released when the returned reference is closed.
        /// </summary>
        public CloseableReference <byte[]> Get(int size)
        {
            Preconditions.CheckArgument(size > 0, "Size must be greater than zero");
            Preconditions.CheckArgument(size <= _maxByteArraySize, "Requested size is too big");
            _semaphore.Wait();

            try
            {
                byte[] byteArray = GetByteArray(size);
                return(CloseableReference <byte[]> .of(byteArray, _resourceReleaser));
            }
            catch (Exception)
            {
                _semaphore.Release();
                throw;
            }
        }
Exemplo n.º 17
0
        public void Initialize()
        {
            _resourceReleaser    = new ResourceReleaserImpl <int>(_ => { });
            _dataSubscriber      = new MockDataSubscriber <IList <CloseableReference <int> > >();
            _settableDataSource1 = SettableDataSource <int> .Create <int>();

            _settableDataSource2 = SettableDataSource <int> .Create <int>();

            _listDataSource = ListDataSource <int> .Create(_settableDataSource1, _settableDataSource2);

            _ref1 = CloseableReference <int> .of(1, _resourceReleaser);

            _ref2 = CloseableReference <int> .of(2, _resourceReleaser);

            _runtimeException = new Exception();
            _listDataSource.Subscribe(_dataSubscriber, CallerThreadExecutor.Instance);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Associates bitmaps with the bitmap counter.
        /// <para />If this method throws TooManyBitmapsException,
        /// the code will have called<see cref="SoftwareBitmap.Dispose"/>
        /// on the bitmaps.
        /// </summary>
        /// <param name="bitmaps">The bitmaps to associate.</param>
        /// <returns>
        /// The references to the bitmaps that are now tied to the
        /// bitmap pool.
        /// </returns>
        /// <exception cref="TooManyBitmapsException">
        /// If the pool is full.
        /// </exception>
        public IList <CloseableReference <SoftwareBitmap> > AssociateBitmapsWithBitmapCounter(
            IList <SoftwareBitmap> bitmaps)
        {
            int countedBitmaps = 0;

            try
            {
                for (; countedBitmaps < bitmaps.Count; ++countedBitmaps)
                {
                    SoftwareBitmap bitmap = bitmaps[countedBitmaps];

                    if (!Increase(bitmap))
                    {
                        throw new TooManyBitmapsException();
                    }
                }

                List <CloseableReference <SoftwareBitmap> > ret = new List <CloseableReference <SoftwareBitmap> >(bitmaps.Count);
                foreach (var bitmap in bitmaps)
                {
                    ret.Add(CloseableReference <SoftwareBitmap> .of(bitmap, _unpooledBitmapsReleaser));
                }

                return(ret);
            }
            catch (Exception)
            {
                if (bitmaps != null)
                {
                    foreach (var bitmap in bitmaps)
                    {
                        if (countedBitmaps-- > 0)
                        {
                            Decrease(bitmap);
                        }

                        bitmap.Dispose();
                    }
                }

                throw;
            }
        }
        public void Initialize()
        {
            _releaseCallCount = 0;
            _releaseValues    = new List <int>();
            _releaser         = new ResourceReleaserImpl <int>(
                v =>
            {
                ++_releaseCallCount;
                _releaseValues.Add(v);
            });

            _onExclusivityChangedCallCount = 0;
            _isExclusive        = null;
            _entryStateObserver = new EntryStateObserverImpl <string>(
                (v, b) =>
            {
                ++_onExclusivityChangedCallCount;
                _isExclusive = b;
            });

            _cacheTrimStrategy = new CacheTrimStrategyImpl(v => _trimRatio);
            _valueDescriptor   = new ValueDescriptorImpl <int>(v => v);
            _params            = new MemoryCacheParams(
                CACHE_MAX_SIZE,
                CACHE_MAX_COUNT,
                CACHE_EVICTION_QUEUE_MAX_SIZE,
                CACHE_EVICTION_QUEUE_MAX_COUNT,
                CACHE_ENTRY_MAX_SIZE);

            _paramsSupplier        = new MockSupplier <MemoryCacheParams>(_params);
            _platformBitmapFactory = new MockPlatformBitmapFactory();
            _bitmap          = new SoftwareBitmap(BitmapPixelFormat.Rgba8, 50, 50);
            _bitmapReference = CloseableReference <SoftwareBitmap> .of(
                _bitmap, BITMAP_RESOURCE_RELEASER);

            _cache = new CountingMemoryCache <string, int>(
                _valueDescriptor,
                _cacheTrimStrategy,
                _paramsSupplier,
                _platformBitmapFactory,
                true);
        }
        public async Task TestParseMetaData_PNG()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(
                new Uri("ms-appx:///Assets/ImagePipeline/Images/image.png"));

            using (var stream = await file.OpenReadAsync())
            {
                IPooledByteBuffer buf = new TrivialPooledByteBuffer(
                    ByteStreams.ToByteArray(stream.AsStream()));

                EncodedImage encodedImage = new EncodedImage(
                    CloseableReference <IPooledByteBuffer> .of(buf, _releaser));

                await encodedImage.ParseMetaDataAsync();

                Assert.AreEqual(ImageFormat.PNG, encodedImage.Format);
                Assert.AreEqual(800, encodedImage.Width);
                Assert.AreEqual(600, encodedImage.Height);
            }
        }
        private async Task <EncodedImage> BuildEncodedImage(
            IPooledByteBuffer imageBytes,
            IRandomAccessStream imageStream)
        {
            using (var stream = imageStream.AsStream())
            {
                Tuple <int, int> dimensions = await BitmapUtil
                                              .DecodeDimensionsAsync(stream)
                                              .ConfigureAwait(false);

                int rotationAngle = GetRotationAngle(stream);
                int width         = dimensions != default(Tuple <int, int>) ?
                                    dimensions.Item1 :
                                    EncodedImage.UNKNOWN_WIDTH;

                int height = dimensions != default(Tuple <int, int>) ?
                             dimensions.Item2 :
                             EncodedImage.UNKNOWN_HEIGHT;

                EncodedImage encodedImage;
                CloseableReference <IPooledByteBuffer> closeableByteBuffer =
                    CloseableReference <IPooledByteBuffer> .of(imageBytes);

                try
                {
                    encodedImage = new EncodedImage(closeableByteBuffer);
                }
                finally
                {
                    CloseableReference <IPooledByteBuffer> .CloseSafely(
                        closeableByteBuffer);
                }

                encodedImage.Format        = ImageFormat.JPEG;
                encodedImage.RotationAngle = rotationAngle;
                encodedImage.Width         = width;
                encodedImage.Height        = height;

                return(encodedImage);
            }
        }
Exemplo n.º 22
0
            private CloseableReference <CloseableImage> PostprocessInternal(CloseableImage sourceImage)
            {
                CloseableStaticBitmap staticBitmap            = (CloseableStaticBitmap)sourceImage;
                SoftwareBitmap        sourceBitmap            = staticBitmap.UnderlyingBitmap;
                CloseableReference <SoftwareBitmap> bitmapRef =
                    _postprocessor.Process(
                        sourceBitmap,
                        _parent._bitmapFactory,
                        _parent._flexByteArrayPool);

                int rotationAngle = staticBitmap.RotationAngle;

                try
                {
                    return(CloseableReference <CloseableImage> .of(
                               new CloseableStaticBitmap(bitmapRef, sourceImage.QualityInfo, rotationAngle)));
                }
                finally
                {
                    CloseableReference <SoftwareBitmap> .CloseSafely(bitmapRef);
                }
            }
        private void NotifyConsumer(
            PooledByteBufferOutputStream pooledOutputStream,
            bool isFinal,
            IConsumer <EncodedImage> consumer)
        {
            CloseableReference <IPooledByteBuffer> result =
                CloseableReference <IPooledByteBuffer> .of(pooledOutputStream.ToByteBuffer());

            EncodedImage encodedImage = null;

            try
            {
                encodedImage = new EncodedImage(result);
                encodedImage.ParseMetaDataAsync().Wait();
                consumer.OnNewResult(encodedImage, isFinal);
            }
            finally
            {
                EncodedImage.CloseSafely(encodedImage);
                CloseableReference <IPooledByteBuffer> .CloseSafely(result);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a bitmap from encoded bytes.
        /// Supports JPEG but callers should use DecodeJPEGFromEncodedImage
        /// for partial JPEGs.
        /// </summary>
        /// <param name="encodedImage">
        /// The reference to the encoded image with the reference to the
        /// encoded bytes.
        /// </param>
        /// <param name="bitmapConfig">
        /// The <see cref="BitmapPixelFormat"/> used to create the decoded
        /// SoftwareBitmap.
        /// </param>
        /// <returns>The bitmap.</returns>
        /// <exception cref="OutOfMemoryException">
        /// If the Bitmap cannot be allocated.
        /// </exception>
        public Task <CloseableReference <SoftwareBitmap> > DecodeFromEncodedImageAsync(
            EncodedImage encodedImage, BitmapPixelFormat bitmapConfig)
        {
            Stream inputStream = encodedImage.GetInputStream();

            Preconditions.CheckNotNull(inputStream);
            return(_executor.Execute(async() =>
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(
                    inputStream.AsRandomAccessStream())
                                        .AsTask()
                                        .ConfigureAwait(false);

                SoftwareBitmap bitmap = await decoder
                                        .GetSoftwareBitmapAsync(bitmapConfig, BitmapAlphaMode.Premultiplied)
                                        .AsTask()
                                        .ConfigureAwait(false);

                return CloseableReference <SoftwareBitmap> .of(bitmap);
            })
                   .Unwrap());
        }
Exemplo n.º 25
0
        /// <summary>
        /// Creates a bitmap from encoded JPEG bytes.
        /// Supports a partial JPEG image.
        /// </summary>
        /// <param name="encodedImage">
        /// The reference to the encoded image with the reference to the
        /// encoded bytes.
        /// </param>
        /// <param name="bitmapConfig">
        /// The <see cref="BitmapPixelFormat"/> used to create the decoded
        /// SoftwareBitmap.
        /// </param>
        /// <param name="length">
        /// The number of encoded bytes in the buffer.
        /// </param>
        /// <returns>The bitmap.</returns>
        /// <exception cref="OutOfMemoryException">
        /// If the Bitmap cannot be allocated.
        /// </exception>
        public Task <CloseableReference <SoftwareBitmap> > DecodeJPEGFromEncodedImageAsync(
            EncodedImage encodedImage, BitmapPixelFormat bitmapConfig, int length)
        {
            return(_executor.Execute(async() =>
            {
                bool isJpegComplete = encodedImage.IsCompleteAt(length);
                Stream jpegDataStream = encodedImage.GetInputStream();

                // At this point the Stream from the encoded image should not
                // be null since in the pipeline,this comes from a call stack where
                // this was checked before. Also this method needs the Stream to
                // decode the image so this can't be null.
                Preconditions.CheckNotNull(jpegDataStream);
                if (encodedImage.Size > length)
                {
                    jpegDataStream = new LimitedInputStream(jpegDataStream, length);
                }

                if (!isJpegComplete)
                {
                    jpegDataStream = new TailAppendingInputStream(jpegDataStream, EOI_TAIL);
                }

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(
                    jpegDataStream.AsRandomAccessStream())
                                        .AsTask()
                                        .ConfigureAwait(false);

                SoftwareBitmap bitmap = await decoder
                                        .GetSoftwareBitmapAsync(bitmapConfig, BitmapAlphaMode.Premultiplied)
                                        .AsTask()
                                        .ConfigureAwait(false);

                return CloseableReference <SoftwareBitmap> .of(bitmap);
            })
                   .Unwrap());
        }
Exemplo n.º 26
0
            private async Task DoTransform(EncodedImage encodedImage, bool isLast)
            {
                _producerContext.Listener.OnProducerStart(_producerContext.Id, PRODUCER_NAME);
                ImageRequest imageRequest = _producerContext.ImageRequest;
                PooledByteBufferOutputStream outputStream =
                    _parent._pooledByteBufferFactory.NewOutputStream();

                IDictionary <string, string> extraMap = default(IDictionary <string, string>);
                EncodedImage ret         = default(EncodedImage);
                Stream       inputStream = default(Stream);

                try
                {
                    int numerator = GetScaleNumerator(imageRequest, encodedImage);
                    extraMap    = GetExtraMap(encodedImage, imageRequest, numerator);
                    inputStream = encodedImage.GetInputStream();
#if HAS_LIBJPEGTURBO
                    JpegTranscoder.TranscodeJpeg(
                        inputStream.AsIStream(),
                        outputStream.AsIStream(),
                        GetRotationAngle(imageRequest, encodedImage),
                        numerator,
                        DEFAULT_JPEG_QUALITY);
#else // HAS_LIBJPEGTURBO
                    inputStream.CopyTo(outputStream);
#endif // HAS_LIBJPEGTURBO

                    CloseableReference <IPooledByteBuffer> reference =
                        CloseableReference <IPooledByteBuffer> .of(outputStream.ToByteBuffer());

                    try
                    {
                        ret        = new EncodedImage(reference);
                        ret.Format = ImageFormat.JPEG;

                        try
                        {
                            await ret.ParseMetaDataAsync().ConfigureAwait(false);

                            _producerContext.Listener.OnProducerFinishWithSuccess(
                                _producerContext.Id, PRODUCER_NAME, extraMap);

                            Consumer.OnNewResult(ret, isLast);
                        }
                        finally
                        {
                            EncodedImage.CloseSafely(ret);
                        }
                    }
                    finally
                    {
                        CloseableReference <IPooledByteBuffer> .CloseSafely(reference);
                    }
                }
                catch (Exception e)
                {
                    _producerContext.Listener.OnProducerFinishWithFailure(
                        _producerContext.Id, PRODUCER_NAME, e, extraMap);

                    Consumer.OnFailure(e);
                    return;
                }
                finally
                {
                    Closeables.CloseQuietly(inputStream);
                    outputStream.Dispose();
                }
            }
 private CloseableReference <int> NewReference(int size)
 {
     return(CloseableReference <int> .of(size, _releaser));
 }
 /// <summary>
 /// Constructs a CloseableReference of byte[] with provided.
 /// </summary>
 /// <param name="size">Byte array size.</param>
 /// <returns>CloseableReference of byte[].</returns>
 public CloseableReference <byte[]> Get(int size)
 {
     return(CloseableReference <byte[]> .of(_delegatePool.Get(size), _resourceReleaser));
 }
Exemplo n.º 29
0
        public void Initialize()
        {
            // Initializes the mock RequestListener
            ProducerListenerImpl producerListener = new ProducerListenerImpl(
                (_, __) => { },
                (_, __, ___) => { },
                (_, __, ___) => { },
                (_, __, ___, ____) => { },
                (_, __, ___) => { },
                (_) => { return(false); });

            _requestListener = new RequestListenerImpl(
                producerListener,
                (imageRequest, callerContext, requestId, isPrefetch) =>
            {
                _onRequestStartInvocation = true;
                _internalImageRequest     = imageRequest;
                _internalCallerContext    = callerContext;
                _internalRequestId        = requestId;
                _internalIsPrefetch       = isPrefetch;
            },
                (imageRequest, requestId, isPrefetch) =>
            {
                _onRequestSuccessInvocation = true;
                _internalImageRequest       = imageRequest;
                _internalRequestId          = requestId;
                _internalIsPrefetch         = isPrefetch;
            },
                (imageRequest, requestId, exception, isPrefetch) =>
            {
                _onRequestFailureInvocation = true;
                _internalImageRequest       = imageRequest;
                _internalRequestId          = requestId;
                _internalException          = exception;
                _internalIsPrefetch         = isPrefetch;
            },
                (requestId) =>
            {
                _onRequestCancellationInvocation = true;
                _internalRequestId = requestId;
            });
            _resourceReleaser = new ResourceReleaserImpl <object>(_ => { });
            _resultRef1       = CloseableReference <object> .of(new object(), _resourceReleaser);

            _resultRef2 = CloseableReference <object> .of(new object(), _resourceReleaser);

            _resultRef3 = CloseableReference <object> .of(new object(), _resourceReleaser);

            _dataSubscriber1 = new MockDataSubscriber <CloseableReference <object> >();
            _dataSubscriber2 = new MockDataSubscriber <CloseableReference <object> >();

            _internalIsPrefetch      = true;
            _settableProducerContext = new SettableProducerContext(
                IMAGE_REQUEST,
                REQUEST_ID,
                producerListener,
                CALLER_CONTEXT,
                RequestLevel.FULL_FETCH,
                IS_PREFETCH,
                true,
                Priority.HIGH);
            _producer = new ProducerImpl <CloseableReference <object> >(
                (consumer, _) =>
            {
                _internalConsumer = consumer;
            });
            _dataSource = CloseableProducerToDataSourceAdapter <object> .Create(
                _producer,
                _settableProducerContext,
                _requestListener);

            Assert.IsTrue(_onRequestStartInvocation);
            Assert.AreSame(_internalImageRequest, IMAGE_REQUEST);
            Assert.AreSame(_internalCallerContext, CALLER_CONTEXT);
            Assert.AreSame(_internalRequestId, REQUEST_ID);
            Assert.IsFalse(_internalIsPrefetch);
            Assert.IsNotNull(_internalConsumer);
            _onRequestStartInvocation = false;

            _dataSource.Subscribe(_dataSubscriber1, CallerThreadExecutor.Instance);
        }
Exemplo n.º 30
0
 public void Initialize()
 {
     _mockCloseable      = new MockDisposable();
     _closeableReference = CloseableReference <IDisposable> .of(_mockCloseable);
 }