/// <inheritdoc />
        public ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            int horizontalSubsampling = _horizontalSubsampling;
            int verticalSubsampling   = _verticalSubsampling;

            if (horizontalSubsampling == 1 && verticalSubsampling == 1)
            {
                return(next.RunAsync(context));
            }

            if (_isPlanar)
            {
                ProcessPlanarData(context);
            }
            else
            {
                ProcessChunkyData(context);
            }

            return(next.RunAsync(context));
        }
Exemple #2
0
        public ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            TiffParallelDecodingState?state = context.GetService(typeof(TiffParallelDecodingState)) as TiffParallelDecodingState;

            if (state is null)
            {
                return(next.RunAsync(context));
            }

            return(new ValueTask(state.DispatchAsync(() => next.RunAsync(context), context.CancellationToken)));
        }
        /// <inheritdoc />
        public ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (_predictor == TiffPredictor.None)
            {
                return(next.RunAsync(context));
            }
            if (_predictor != TiffPredictor.HorizontalDifferencing)
            {
                throw new NotSupportedException("Predictor not supportted.");
            }

            int  skipped          = 0;
            bool isMultiplePlanar = _bytesPerScanlines.Count > 1;

            for (int planarIndex = 0; planarIndex < _bytesPerScanlines.Count; planarIndex++)
            {
                int bytesPerScanline = _bytesPerScanlines[planarIndex];

                // Current plane buffer
                Span <byte> plane = context.UncompressedData.Span.Slice(skipped, bytesPerScanline * context.SourceImageSize.Height);

                // Skip scanlines that are not to be decoded
                plane = plane.Slice(bytesPerScanline * context.SourceReadOffset.Y);

                TiffValueCollection <ushort> bitsPerSample = isMultiplePlanar ? TiffValueCollection.Single(_bitsPerSample[planarIndex]) : _bitsPerSample;

                for (int row = 0; row < context.ReadSize.Height; row++)
                {
                    // Process every scanline
                    Span <byte> scanline = plane.Slice(row * bytesPerScanline, bytesPerScanline);
                    UndoHorizontalDifferencingForScanline(scanline, bitsPerSample, context.SourceImageSize.Width);
                }

                skipped += bytesPerScanline * context.SourceImageSize.Height;
            }

            return(next.RunAsync(context));
        }
        public ValueTask RunAsync(TiffImageDecoderContext context)
        {
            ITiffImageDecoderMiddleware   middleware = Middleware;
            ITiffImageDecoderPipelineNode?next       = Next;

            context.CancellationToken.ThrowIfCancellationRequested();

            if (next is null)
            {
                return(middleware.InvokeAsync(context, EmptyImplementation.Instance));
            }
            else
            {
                return(middleware.InvokeAsync(context, next));
            }
        }
Exemple #5
0
        private void ProcessChunkyData(TiffImageDecoderContext context)
        {
            Memory <byte> decompressedData = context.UncompressedData;

            if (_horizontalSubsampling >= _verticalSubsampling)
            {
                ProcessChunkyData(context.SourceImageSize, decompressedData.Span, decompressedData.Span);
            }
            else
            {
                using IMemoryOwner <byte> bufferMemory = (context.MemoryPool ?? MemoryPool <byte> .Shared).Rent(decompressedData.Length);

                decompressedData.CopyTo(bufferMemory.Memory);
                ProcessChunkyData(context.SourceImageSize, bufferMemory.Memory.Span.Slice(0, decompressedData.Length), decompressedData.Span);
            }
        }
Exemple #6
0
        public void Write(TiffImageDecoderContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            TiffRgba32 fillColor = _fillColor;

            using TiffPixelBufferWriter <TiffRgba32> writer = context.GetWriter <TiffRgba32>();

            int rows = context.ReadSize.Height;

            for (int row = 0; row < rows; row++)
            {
                using TiffPixelSpanHandle <TiffRgba32> pixelSpanHandle = writer.GetRowSpan(row);
                pixelSpanHandle.GetSpan().Fill(fillColor);
            }
        }
        /// <inheritdoc />
        public ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (_orientation == 0 || _orientation == TiffOrientation.TopLeft)
            {
                return(next.RunAsync(context));
            }

            return(next.RunAsync(new TiffOrientatedImageDecoderContext(context, _orientation)));
        }
        public async ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            using var state = new TiffParallelDecodingState(_maxDegreeOfParallelism);

            using var mutexService = new ParallelMutexService();

            context.RegisterService(typeof(TiffParallelDecodingState), state);
            context.RegisterService(typeof(ITiffParallelMutexService), mutexService);

            state.LockTaskCompletion();

            await next.RunAsync(context).ConfigureAwait(false);

            state.ReleaseTaskCompletion();

            await state.Complete !.Task.ConfigureAwait(false);

            context.RegisterService(typeof(TiffParallelDecodingState), null);
            context.RegisterService(typeof(ITiffParallelMutexService), null);
        }
Exemple #9
0
        public async ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            IDisposable?lockObj      = null;
            var         mutexService = context.GetService(typeof(ITiffParallelMutexService)) as ITiffParallelMutexService;

            if (!(mutexService is null))
            {
                lockObj = await mutexService.LockAsync(context.CancellationToken).ConfigureAwait(false);
            }

            try
            {
                await next.RunAsync(context).ConfigureAwait(false);
            }
            finally
            {
                if (!(lockObj is null))
                {
                    lockObj.Dispose();
                }
            }
        }
        public ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            int           bitCount         = _bitCount;
            Span <ushort> uncompressedData = MemoryMarshal.Cast <byte, ushort>(context.UncompressedData.Span);

            for (int i = 0; i < uncompressedData.Length; i++)
            {
                uncompressedData[i] = (ushort)FastExpandBits(uncompressedData[i], bitCount);
            }

            return(next.RunAsync(new JpegDataEndianContextWrapper(context)));
        }
        private void ProcessPlanarData(TiffImageDecoderContext context)
        {
            int width  = context.SourceImageSize.Width;
            int height = context.SourceImageSize.Height;
            int horizontalSubsampling = _horizontalSubsampling;
            int verticalSubsampling   = _verticalSubsampling;

            int           planarByteCount  = sizeof(ushort) * width * height;
            Span <byte>   decompressedData = context.UncompressedData.Span;
            Span <ushort> planarCb         = MemoryMarshal.Cast <byte, ushort>(decompressedData.Slice(planarByteCount, planarByteCount));
            Span <ushort> planarCr         = MemoryMarshal.Cast <byte, ushort>(decompressedData.Slice(2 * planarByteCount, planarByteCount));

            for (int row = height - 1; row >= 0; row--)
            {
                for (int col = width - 1; col >= 0; col--)
                {
                    int offset          = row * width + col;
                    int subsampleOffset = (row / verticalSubsampling) * (width / horizontalSubsampling) + col / horizontalSubsampling;
                    planarCb[offset] = planarCb[subsampleOffset];
                    planarCr[offset] = planarCr[subsampleOffset];
                }
            }
        }
 public TiffImageEnumeratorDecoderContext(TiffImageDecoderContext innerContext) : base(innerContext)
 {
 }
        /// <inheritdoc />
        public async ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (_bytesPerScanlines.Count != context.PlanarRegions.Count)
            {
                throw new InvalidOperationException();
            }

            int planeCount = _bytesPerScanlines.Count;

            // calculate the uncompressed data buffer length
            int uncompressedDataLength = 0;
            int imageHeight            = context.SourceImageSize.Height;

            foreach (int bytesPerScanline in _bytesPerScanlines)
            {
                uncompressedDataLength += bytesPerScanline * imageHeight;
            }

            TiffEmptyStrileWriter?emptyWriter = null;

            // calculate the maximum buffer needed to read from stream
            int readCount = 0;

            foreach (TiffStreamRegion planarRegion in context.PlanarRegions)
            {
                int length = planarRegion.Length;
                if (length == 0)
                {
                    emptyWriter = new TiffEmptyStrileWriter(new TiffRgba32(255, 255, 255, 0));
                    break;
                }
                if (length > readCount)
                {
                    readCount = planarRegion.Length;
                }
            }

            if (!(emptyWriter is null))
            {
                emptyWriter.Write(context);
                return;
            }

            // allocate the raw data buffer and the uncompressed data buffer
            MemoryPool <byte> memoryPool = context.MemoryPool ?? MemoryPool <byte> .Shared;

            using IMemoryOwner <byte> bufferMemory = memoryPool.Rent(uncompressedDataLength);
            int planarUncompressedByteCount        = 0;
            TiffFileContentReader?reader           = context.ContentReader;

            if (reader is null)
            {
                throw new InvalidOperationException("Failed to acquire ContentReader.");
            }

            using (IMemoryOwner <byte> rawBuffer = memoryPool.Rent(readCount))
            {
                TiffDecompressionContext decompressionContext = new TiffDecompressionContext();

                // decompress each plane
                for (int i = 0; i < planeCount; i++)
                {
                    TiffStreamRegion region = context.PlanarRegions[i];

                    // Read from stream
                    readCount = await reader.ReadAsync(region.Offset, rawBuffer.Memory.Slice(0, region.Length), context.CancellationToken).ConfigureAwait(false);

                    if (readCount != region.Length)
                    {
                        throw new InvalidDataException();
                    }

                    // Decompress this plane
                    int bytesPerScanline = _bytesPerScanlines[i];
                    decompressionContext.MemoryPool = memoryPool;
                    decompressionContext.PhotometricInterpretation = _photometricInterpretation;
                    decompressionContext.BitsPerSample             = _bitsPerSample;
                    decompressionContext.ImageSize          = context.SourceImageSize;
                    decompressionContext.BytesPerScanline   = bytesPerScanline;
                    decompressionContext.SkippedScanlines   = context.SourceReadOffset.Y;
                    decompressionContext.RequestedScanlines = context.ReadSize.Height;
                    _decompressionAlgorithm.Decompress(decompressionContext, rawBuffer.Memory.Slice(0, readCount), bufferMemory.Memory.Slice(planarUncompressedByteCount, bytesPerScanline * imageHeight));
                    planarUncompressedByteCount += bytesPerScanline * imageHeight;
                }
            }

            // Pass down the data
            context.UncompressedData = bufferMemory.Memory.Slice(0, uncompressedDataLength);
            await next.RunAsync(context).ConfigureAwait(false);

            context.UncompressedData = default;
        }
 public JpegDataEndianContextWrapper(TiffImageDecoderContext innerContext) : base(innerContext)
 {
 }
Exemple #15
0
        public TiffOrientatedImageDecoderContext(TiffImageDecoderContext innerContext, TiffOrientation orientation) : base(innerContext)
        {
            if (orientation == 0)
            {
                _isFlipOrOrientation = false;
                _flipLeftRigt        = false;
                _flipTopBottom       = false;
                return;
            }
            switch (orientation)
            {
            case TiffOrientation.TopLeft:
                _isFlipOrOrientation = false;
                _flipLeftRigt        = false;
                _flipTopBottom       = false;
                break;

            case TiffOrientation.TopRight:
                _isFlipOrOrientation = false;
                _flipLeftRigt        = true;
                _flipTopBottom       = false;
                break;

            case TiffOrientation.BottomRight:
                _isFlipOrOrientation = false;
                _flipLeftRigt        = true;
                _flipTopBottom       = true;
                break;

            case TiffOrientation.BottomLeft:
                _isFlipOrOrientation = false;
                _flipLeftRigt        = false;
                _flipTopBottom       = true;
                break;

            case TiffOrientation.LeftTop:
                _isFlipOrOrientation = true;
                _flipLeftRigt        = false;
                _flipTopBottom       = false;
                break;

            case TiffOrientation.RightTop:
                _isFlipOrOrientation = true;
                _flipLeftRigt        = true;
                _flipTopBottom       = false;
                break;

            case TiffOrientation.RightBottom:
                _isFlipOrOrientation = true;
                _flipLeftRigt        = true;
                _flipTopBottom       = true;
                break;

            case TiffOrientation.LeftBottom:
                _isFlipOrOrientation = true;
                _flipLeftRigt        = false;
                _flipTopBottom       = true;
                break;

            default:
                throw new InvalidDataException("Unknown orientation tag.");
            }
        }
Exemple #16
0
        /// <inheritdoc />
        public async ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (context.ContentReader is null)
            {
                throw new ArgumentException("ContentReader is not provided in the TiffImageDecoderContext instance.");
            }
            if (context.OperationContext is null)
            {
                throw new ArgumentException("OperationContext is not provided in the TiffImageDecoderContext instance.");
            }

            bool isParallel = !(context.GetService(typeof(TiffParallelDecodingState)) is null);

            // Initialize the cache
            TiffFieldReader?      reader = null;
            TiffStrileOffsetCache cache;

            if (_lazyLoad)
            {
                reader = new TiffFieldReader(context.ContentReader, context.OperationContext, leaveOpen: true);
                cache  = new TiffStrileOffsetCache(reader, _tileOffsetsEntry, _tileByteCountsEntry, CacheSize);
            }
            else
            {
                cache = new TiffStrileOffsetCache(_tileOffsets, _tileByteCounts);
            }

            int tileWidth  = _tileWidth;
            int tileHeight = _tileHeight;

            try
            {
                int tileAcross = (context.SourceImageSize.Width + tileWidth - 1) / tileWidth;
                int tileDown   = (context.SourceImageSize.Height + tileHeight - 1) / tileHeight;
                int tileCount  = tileAcross * tileDown;
                CancellationToken cancellationToken = context.CancellationToken;

                // Make sure the region to read is in the image boundary.
                if (context.SourceReadOffset.X >= context.SourceImageSize.Width || context.SourceReadOffset.Y >= context.SourceImageSize.Height)
                {
                    return;
                }
                context.ReadSize = new TiffSize(Math.Min(context.ReadSize.Width, context.SourceImageSize.Width - context.SourceReadOffset.X), Math.Min(context.ReadSize.Height, context.SourceImageSize.Height - context.SourceReadOffset.Y));
                if (context.ReadSize.IsAreaEmpty)
                {
                    return;
                }

                int planeCount = _planaCount;
                TiffImageEnumeratorDecoderContext?            wrapperContext = null;
                TiffMutableValueCollection <TiffStreamRegion> planarRegions  = default;
                if (!isParallel)
                {
                    wrapperContext = new TiffImageEnumeratorDecoderContext(context);
                    planarRegions  = new TiffMutableValueCollection <TiffStreamRegion>(planeCount);
                }

                // loop through all the tiles overlapping with the region to read.
                int colStart = context.SourceReadOffset.X / tileWidth;
                int colEnd   = (context.SourceReadOffset.X + context.ReadSize.Width + tileWidth - 1) / tileWidth;
                int rowStart = context.SourceReadOffset.Y / tileHeight;
                int rowEnd   = (context.SourceReadOffset.Y + context.ReadSize.Height + tileHeight - 1) / tileHeight;

                for (int row = rowStart; row < rowEnd; row++)
                {
                    // Calculate coordinates on the y direction for the tiles on this row.
                    int currentYOffset     = row * tileHeight;
                    int skippedScanlines   = Math.Max(0, context.SourceReadOffset.Y - currentYOffset);
                    int requestedScanlines = Math.Min(tileHeight - skippedScanlines, context.SourceReadOffset.Y + context.ReadSize.Height - currentYOffset - skippedScanlines);

                    for (int col = colStart; col < colEnd; col++)
                    {
                        if (isParallel)
                        {
                            wrapperContext = new TiffImageEnumeratorDecoderContext(context);
                            planarRegions  = new TiffMutableValueCollection <TiffStreamRegion>(planeCount);
                        }

                        wrapperContext !.SourceImageSize = new TiffSize(tileWidth, tileHeight);

                        // Calculate coordinates on the y direction for this tile.
                        int currentXOffset = col * tileWidth;
                        int skippedXOffset = Math.Max(0, context.SourceReadOffset.X - currentXOffset);
                        int requestedWidth = Math.Min(tileWidth - skippedXOffset, context.SourceReadOffset.X + context.ReadSize.Width - currentXOffset - skippedXOffset);

                        // Update size info of this tile
                        wrapperContext.SourceReadOffset = new TiffPoint(skippedXOffset, skippedScanlines);
                        wrapperContext.ReadSize         = new TiffSize(requestedWidth, requestedScanlines);

                        // Update size info of the destination buffer
                        wrapperContext.SetCropSize(new TiffPoint(Math.Max(0, currentXOffset - context.SourceReadOffset.X), Math.Max(0, currentYOffset - context.SourceReadOffset.Y)), context.ReadSize);

                        // Check to see if there is any region area to be read
                        if (wrapperContext.ReadSize.IsAreaEmpty)
                        {
                            continue;
                        }

                        // Prepare stream regions of this tile
                        for (int planarIndex = 0; planarIndex < planeCount; planarIndex++)
                        {
                            int tileIndex = planarIndex * tileCount + row * tileAcross + col;
                            planarRegions[planarIndex] = await cache.GetOffsetAndCountAsync(tileIndex, cancellationToken).ConfigureAwait(false);
                        }
                        wrapperContext.PlanarRegions = planarRegions.GetReadOnlyView();

                        cancellationToken.ThrowIfCancellationRequested();

                        // Pass down the data
                        await next.RunAsync(wrapperContext).ConfigureAwait(false);
                    }
                }
            }
            finally
            {
                ((IDisposable)cache).Dispose();
                reader?.Dispose();
            }
        }
 public ValueTask RunAsync(TiffImageDecoderContext context)
 {
     return(default);
        /// <inheritdoc />
        public async ValueTask InvokeAsync(TiffImageDecoderContext context, ITiffImageDecoderPipelineNode next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (context.ContentReader is null)
            {
                throw new ArgumentException("ContentReader is not provided in the TiffImageDecoderContext instance.");
            }
            if (context.OperationContext is null)
            {
                throw new ArgumentException("OperationContext is not provided in the TiffImageDecoderContext instance.");
            }

            bool isParallel = !(context.GetService(typeof(TiffParallelDecodingState)) is null);

            // Initialize the cache
            TiffFieldReader?      reader = null;
            TiffStrileOffsetCache cache;

            if (_lazyLoad)
            {
                reader = new TiffFieldReader(context.ContentReader, context.OperationContext, leaveOpen: true);
                cache  = new TiffStrileOffsetCache(reader, _stripOffsetsEntry, _stripsByteCountEntry, CacheSize);
            }
            else
            {
                cache = new TiffStrileOffsetCache(_stripOffsets, _stripsByteCount);
            }

            try
            {
                int rowsPerStrip = _rowsPerStrip;
                CancellationToken cancellationToken = context.CancellationToken;

                // Special case for mailformed file.
                if (rowsPerStrip <= 0 && _stripCount == 1)
                {
                    rowsPerStrip = context.SourceImageSize.Height;
                }

                // Make sure the region to read is in the image boundary.
                if (context.SourceReadOffset.X >= context.SourceImageSize.Width || context.SourceReadOffset.Y >= context.SourceImageSize.Height)
                {
                    return;
                }
                context.ReadSize = new TiffSize(Math.Min(context.ReadSize.Width, context.SourceImageSize.Width - context.SourceReadOffset.X), Math.Min(context.ReadSize.Height, context.SourceImageSize.Height - context.SourceReadOffset.Y));
                if (context.ReadSize.IsAreaEmpty)
                {
                    return;
                }

                // Create a wrapped context
                int planeCount = _planeCount;
                TiffImageEnumeratorDecoderContext?            wrapperContext = null;
                TiffMutableValueCollection <TiffStreamRegion> planarRegions  = default;
                if (!isParallel)
                {
                    wrapperContext = new TiffImageEnumeratorDecoderContext(context);
                    planarRegions  = new TiffMutableValueCollection <TiffStreamRegion>(planeCount);
                }

                // loop through all the strips overlapping with the region to read
                int stripStart       = context.SourceReadOffset.Y / rowsPerStrip;
                int stripEnd         = (context.SourceReadOffset.Y + context.ReadSize.Height + rowsPerStrip - 1) / rowsPerStrip;
                int actualStripCount = _stripCount / _planeCount;
                for (int stripIndex = stripStart; stripIndex < stripEnd; stripIndex++)
                {
                    if (isParallel)
                    {
                        wrapperContext = new TiffImageEnumeratorDecoderContext(context);
                        planarRegions  = new TiffMutableValueCollection <TiffStreamRegion>(planeCount);
                    }

                    // Calculate size info of this strip
                    int currentYOffset     = stripIndex * rowsPerStrip;
                    int stripImageHeight   = Math.Min(rowsPerStrip, context.SourceImageSize.Height - currentYOffset);
                    int skippedScanlines   = Math.Max(0, context.SourceReadOffset.Y - currentYOffset);
                    int requestedScanlines = Math.Min(stripImageHeight - skippedScanlines, context.SourceReadOffset.Y + context.ReadSize.Height - currentYOffset - skippedScanlines);
                    wrapperContext !.SourceImageSize = new TiffSize(context.SourceImageSize.Width, stripImageHeight);
                    wrapperContext.SourceReadOffset  = new TiffPoint(context.SourceReadOffset.X, skippedScanlines);
                    wrapperContext.ReadSize          = new TiffSize(context.ReadSize.Width, requestedScanlines);

                    // Update size info of the destination buffer
                    wrapperContext.SetCropSize(new TiffPoint(0, Math.Max(0, currentYOffset - context.SourceReadOffset.Y)), context.ReadSize);

                    // Check to see if there is any region area to be read
                    if (wrapperContext.ReadSize.IsAreaEmpty)
                    {
                        continue;
                    }

                    // Prepare stream regions of this strip
                    for (int planarIndex = 0; planarIndex < planeCount; planarIndex++)
                    {
                        int accessIndex = planarIndex * actualStripCount + stripIndex;
                        planarRegions[planarIndex] = await cache.GetOffsetAndCountAsync(accessIndex, cancellationToken).ConfigureAwait(false);
                    }
                    wrapperContext.PlanarRegions = planarRegions.GetReadOnlyView();

                    cancellationToken.ThrowIfCancellationRequested();

                    // Pass down the data
                    await next.RunAsync(wrapperContext).ConfigureAwait(false);
                }
            }
            finally
            {
                ((IDisposable)cache).Dispose();
                reader?.Dispose();
            }
        }
Exemple #19
0
 public TiffDelegatingImageDecoderContext(TiffImageDecoderContext innerContext)
 {
     Debug.Assert(innerContext != null);
     _innerContext = innerContext !;
 }