Exemple #1
0
        /// <summary>
        /// Creates a new instance with the specified stream.  Optionally sets to close the stream when disposed.
        /// </summary>
        /// <param name="stream">The stream to read.</param>
        /// <param name="closeOnDispose"><c>True</c> to close the stream when <see cref="Dispose"/> is called, otherwise <c>False</c>.</param>
        public ContainerReader(Stream stream, bool closeOnDispose)
        {
            _packetReaders = new Dictionary<int, PacketReader>();
            _disposedStreamSerials = new List<int>();

            _stream = (stream as BufferedReadStream) ?? new BufferedReadStream(stream) { CloseBaseStream = closeOnDispose };
        }
Exemple #2
0
        internal Packet(BufferedReadStream stream, long streamOffset, int length)
            : base(length)
        {
            _stream = stream;

            _offset = streamOffset;
            _length = length;
            _curOfs = 0;
        }
        public async Task ReadStreamDoesNotOverflowOnMoreThan2GB()
        {
            // This test should never fail with OverflowException
            var repeated = new byte["128 MB".ToSize()];

            Func <Task <ByteString> > producer = async() => await Task.FromResult(ByteString.CopyFrom(repeated));

            using (var readStream = new BufferedReadStream(producer))
            {
                var data = new byte["128 MB".ToSize()];
                while (readStream.Position < "4 GB".ToSize())
                {
                    await readStream.ReadAsync(data, 0, data.Length);
                }
            }
        }
Exemple #4
0
        public static IImageInfo Identify(
            this IImageDecoderInternals decoder,
            Configuration configuration,
            Stream stream)
        {
            using var bufferedReadStream = new BufferedReadStream(configuration, stream);

            try
            {
                return(decoder.Identify(bufferedReadStream, default));
            }
            catch (InvalidMemoryOperationException ex)
            {
                throw new InvalidImageContentException(decoder.Dimensions, ex);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HuffmanScanDecoder"/> class.
        /// </summary>
        /// <param name="stream">The input stream.</param>
        /// <param name="converter">Spectral to pixel converter.</param>
        /// <param name="cancellationToken">The token to monitor cancellation.</param>
        public HuffmanScanDecoder(
            BufferedReadStream stream,
            SpectralConverter converter,
            CancellationToken cancellationToken)
        {
            this.dctZigZag         = ZigZag.CreateUnzigTable();
            this.stream            = stream;
            this.spectralConverter = converter;
            this.cancellationToken = cancellationToken;

            // TODO: this is actually a variable value depending on component count
            const int maxTables = 4;

            this.dcHuffmanTables = new HuffmanTable[maxTables];
            this.acHuffmanTables = new HuffmanTable[maxTables];
        }
Exemple #6
0
        /// <inheritdoc/>
        protected override void Decompress(BufferedReadStream stream, int byteCount, int stripHeight, Span <byte> buffer)
        {
            using var bitReader = new ModifiedHuffmanBitReader(stream, this.FillOrder, byteCount, this.Allocator);

            buffer.Clear();
            uint bitsWritten   = 0;
            uint pixelsWritten = 0;

            while (bitReader.HasMoreData)
            {
                bitReader.ReadNextRun();

                if (bitReader.RunLength > 0)
                {
                    if (bitReader.IsWhiteRun)
                    {
                        BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.whiteValue);
                    }
                    else
                    {
                        BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.blackValue);
                    }

                    bitsWritten   += bitReader.RunLength;
                    pixelsWritten += bitReader.RunLength;
                }

                if (pixelsWritten == this.Width)
                {
                    bitReader.StartNewRow();
                    pixelsWritten = 0;

                    // Write padding bits, if necessary.
                    uint pad = 8 - (bitsWritten % 8);
                    if (pad != 8)
                    {
                        BitWriterUtils.WriteBits(buffer, (int)bitsWritten, pad, 0);
                        bitsWritten += pad;
                    }
                }

                if (pixelsWritten > this.Width)
                {
                    TiffThrowHelper.ThrowImageFormatException("ccitt compression parsing error, decoded more pixels then image width");
                }
            }
        }
Exemple #7
0
        public IEnumerable <Mp3Frame> GetFrames()
        {
            var request  = (HttpWebRequest)WebRequest.Create(_uri);
            var response = request.GetResponse();

            using (var s = response.GetResponseStream())
                using (var brs = new BufferedReadStream(s))
                {
                    Mp3Frame frame;
                    do
                    {
                        frame = Mp3Frame.LoadFromStream(brs);

                        yield return(frame);
                    } while (frame != null);
                }
        }
        /// <summary>
        /// Creates a stream that reads until it reaches the given boundary pattern.
        /// </summary>
        /// <param name="stream">The <see cref="BufferedReadStream"/>.</param>
        /// <param name="boundary">The boundary pattern to use.</param>
        /// <param name="bytePool">The ArrayPool pool to use for temporary byte arrays.</param>
        public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary, ArrayPool<byte> bytePool)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (boundary == null)
            {
                throw new ArgumentNullException(nameof(boundary));
            }

            _bytePool = bytePool;
            _innerStream = stream;
            _innerOffset = _innerStream.CanSeek ? _innerStream.Position : 0;
            _boundary = boundary;
        }
Exemple #9
0
        /// <summary>
        /// Read a decimal text value.
        /// </summary>
        /// <returns>The integer value of the decimal.</returns>
        public static int ReadDecimal(this BufferedReadStream stream)
        {
            int value = 0;

            while (true)
            {
                int current = stream.ReadByte() - 0x30;
                if ((uint)current > 9)
                {
                    break;
                }

                value = (value * 10) + current;
            }

            return(value);
        }
Exemple #10
0
    /// <summary>
    /// Creates a stream that reads until it reaches the given boundary pattern.
    /// </summary>
    /// <param name="stream">The <see cref="BufferedReadStream"/>.</param>
    /// <param name="boundary">The boundary pattern to use.</param>
    /// <param name="bytePool">The ArrayPool pool to use for temporary byte arrays.</param>
    public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary, ArrayPool <byte> bytePool)
    {
        if (stream == null)
        {
            throw new ArgumentNullException(nameof(stream));
        }

        if (boundary == null)
        {
            throw new ArgumentNullException(nameof(boundary));
        }

        _bytePool    = bytePool;
        _innerStream = stream;
        _innerOffset = _innerStream.CanSeek ? _innerStream.Position : 0;
        _boundary    = boundary;
    }
Exemple #11
0
        private static async Task <HttpResponseMessage> ReadNextChildResponseAsync(MultipartReader reader, CancellationToken cancellationToken = default(CancellationToken))
        {
            var section = await reader.ReadNextSectionAsync(cancellationToken).ConfigureAwait(false);

            if (section == null)
            {
                return(null);
            }

            var bufferedStream = new BufferedReadStream(section.Body, 4096);
            var line           = await bufferedStream.ReadLineAsync(MultipartReader.DefaultHeadersLengthLimit, cancellationToken).ConfigureAwait(false);

            var requestLineParts = line.Split(' ');

            if (requestLineParts.Length < 2)
            {
                throw new InvalidDataException("Invalid response line.");
            }

            var headers = await ApiInvoker.ReadHeadersAsync(bufferedStream, cancellationToken).ConfigureAwait(false);

            var response = new HttpResponseMessage();

            HttpStatusCode statusCode;

            if (Enum.TryParse(requestLineParts[0], out statusCode))
            {
                response.StatusCode = statusCode;
            }

            var contentStream = new MemoryStream();
            await bufferedStream.CopyToAsync(contentStream);

            contentStream.Position = 0;
            response.Content       = new StreamContent(contentStream);

            foreach (var header in headers)
            {
                if (!response.Content.Headers.Contains(header.Key))
                {
                    response.Content.Headers.Add(header.Key, header.Value.ToArray());
                }
            }

            return(response);
        }
        public void BufferedStreamCanReadMultipleBytesFromOrigin()
        {
            using (MemoryStream stream = this.CreateTestStream())
            {
                var    buffer   = new byte[2];
                byte[] expected = stream.ToArray();
                using (var reader = new BufferedReadStream(stream))
                {
                    Assert.Equal(2, reader.Read(buffer, 0, 2));
                    Assert.Equal(expected[0], buffer[0]);
                    Assert.Equal(expected[1], buffer[1]);

                    // We've read a whole chunk but increment by the buffer length in our reader.
                    Assert.Equal(stream.Position, BufferedReadStream.BufferLength);
                    Assert.Equal(buffer.Length, reader.Position);
                }
            }
        }
        public void BufferedStreamCanReadSingleByteFromOrigin()
        {
            using (MemoryStream stream = this.CreateTestStream())
            {
                byte[] expected = stream.ToArray();
                using (var reader = new BufferedReadStream(stream))
                {
                    Assert.Equal(expected[0], reader.ReadByte());

                    // We've read a whole chunk but increment by 1 in our reader.
                    Assert.Equal(BufferedReadStream.BufferLength, stream.Position);
                    Assert.Equal(1, reader.Position);
                }

                // Position of the stream should be reset on disposal.
                Assert.Equal(1, stream.Position);
            }
        }
Exemple #14
0
        public static Image <TPixel> Decode <TPixel>(
            this IImageDecoderInternals decoder,
            Configuration configuration,
            Stream stream,
            Func <InvalidMemoryOperationException, Size, InvalidImageContentException> largeImageExceptionFactory)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            using var bufferedReadStream = new BufferedReadStream(configuration, stream);

            try
            {
                return(decoder.Decode <TPixel>(bufferedReadStream, default));
            }
            catch (InvalidMemoryOperationException ex)
            {
                throw largeImageExceptionFactory(ex, decoder.Dimensions);
            }
        }
        internal static JpegDecoderCore ParseJpegStream(string testFileName, bool metaDataOnly = false)
        {
            byte[] bytes = TestFile.Create(testFileName).Bytes;
            using var ms             = new MemoryStream(bytes);
            using var bufferedStream = new BufferedReadStream(Configuration.Default, ms);

            var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder());

            if (metaDataOnly)
            {
                decoder.Identify(bufferedStream, cancellationToken: default);
            }
            else
            {
                using Image <Rgba32> image = decoder.Decode <Rgba32>(bufferedStream, cancellationToken: default);
            }

            return(decoder);
        }
Exemple #16
0
        /// <inheritdoc />
        public Task <Image <TPixel> > DecodeAsync <TPixel>(Configuration configuration, Stream stream, CancellationToken cancellationToken)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(stream, nameof(stream));

            var decoder = new WebpDecoderCore(configuration, this);

            try
            {
                using var bufferedStream = new BufferedReadStream(configuration, stream);
                return(decoder.DecodeAsync <TPixel>(configuration, bufferedStream, cancellationToken));
            }
            catch (InvalidMemoryOperationException ex)
            {
                Size dims = decoder.Dimensions;

                throw new InvalidImageContentException($"Cannot decode image. Failed to allocate buffers for possibly degenerate dimensions: {dims.Width}x{dims.Height}.", ex);
            }
        }
        public static async Task <HttpApplicationResponseSection> ReadNextHttpApplicationResponseSectionAsync(
            this MultipartReader reader, CancellationToken cancellationToken = default)
        {
            var section = await reader.ReadNextSectionAsync(cancellationToken).ConfigureAwait(false);

            if (section == null)
            {
                return(null); // if null we're done
            }

            var contentTypeHeader = MediaTypeHeaderValue.Parse(section.ContentType);

            if (!contentTypeHeader.MediaType.HasValue ||
                !contentTypeHeader.MediaType.Equals("application/http", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidDataException("Invalid Content-Type.");
            }

            var param = contentTypeHeader.Parameters.SingleOrDefault(a =>
                                                                     a.Name.HasValue && a.Value.HasValue &&
                                                                     a.Name.Value.Equals("msgtype", StringComparison.OrdinalIgnoreCase) &&
                                                                     a.Value.Equals("response", StringComparison.OrdinalIgnoreCase));

            if (param == null)
            {
                throw new InvalidDataException("Invalid Content-Type.");
            }

            var bufferedStream = new BufferedReadStream(section.Body, SectionHelper.DefaultBufferSize);
            var responseLine   = await ReadResponseLineAsync(bufferedStream, cancellationToken).ConfigureAwait(false);

            if (responseLine.Length != 3)
            {
                throw new InvalidDataException("Invalid request line.");
            }

            var headers = await SectionHelper.ReadHeadersAsync(bufferedStream, cancellationToken).ConfigureAwait(false);

            return(new HttpApplicationResponseSection
            {
                ResponseFeature = new ResponseFeature(responseLine[0], int.Parse(responseLine[1]), responseLine[2], bufferedStream, new HeaderDictionary(headers))
            });
        }
Exemple #18
0
        /// <inheritdoc/>
        public async Task <Image <TPixel> > DecodeAsync <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(stream, nameof(stream));

            var decoder = new BmpDecoderCore(configuration, this);

            try
            {
                using var bufferedStream = new BufferedReadStream(configuration, stream);
                return(await decoder.DecodeAsync <TPixel>(bufferedStream).ConfigureAwait(false));
            }
            catch (InvalidMemoryOperationException ex)
            {
                Size dims = decoder.Dimensions;

                throw new InvalidImageContentException($"Cannot decode image. Failed to allocate buffers for possibly degenerate dimensions: {dims.Width}x{dims.Height}. This error can happen for very large RLE bitmaps, which are not supported.", ex);
            }
        }
        public void BufferedStreamCanReadMultipleBytesFromOrigin(int bufferSize)
        {
            this.configuration.StreamProcessingBufferSize = bufferSize;
            using (MemoryStream stream = this.CreateTestStream(bufferSize * 3))
            {
                var    buffer   = new byte[2];
                byte[] expected = stream.ToArray();
                using (var reader = new BufferedReadStream(this.configuration, stream))
                {
                    Assert.Equal(2, reader.Read(buffer, 0, 2));
                    Assert.Equal(expected[0], buffer[0]);
                    Assert.Equal(expected[1], buffer[1]);

                    // We've read a whole chunk but increment by the buffer length in our reader.
                    Assert.True(stream.Position >= bufferSize);
                    Assert.Equal(buffer.Length, reader.Position);
                }
            }
        }
        public void BufferedStreamCanReadSingleByteFromOrigin(int bufferSize)
        {
            this.configuration.StreamProcessingBufferSize = bufferSize;
            using (MemoryStream stream = this.CreateTestStream(bufferSize * 3))
            {
                byte[] expected = stream.ToArray();
                using (var reader = new BufferedReadStream(this.configuration, stream))
                {
                    Assert.Equal(expected[0], reader.ReadByte());

                    // We've read a whole chunk but increment by 1 in our reader.
                    Assert.True(stream.Position >= bufferSize);
                    Assert.Equal(1, reader.Position);
                }

                // Position of the stream should be reset on disposal.
                Assert.Equal(1, stream.Position);
            }
        }
Exemple #21
0
        public IEnumerable<Mp3Frame> GetFrames()
        {
            var request = (HttpWebRequest)WebRequest.Create(_uri);
            var response = request.GetResponse();

            using (var s = response.GetResponseStream())
            using (var brs = new BufferedReadStream(s))
            {
                Mp3Frame frame;
                do
                {
                    frame = Mp3Frame.LoadFromStream(brs);

                    yield return frame;

                } while (frame != null);
            }
        
        }
        public void BufferedStreamCanReadSingleByteFromOffset()
        {
            using (MemoryStream stream = this.CreateTestStream())
            {
                byte[]    expected = stream.ToArray();
                const int offset   = 5;
                using (var reader = new BufferedReadStream(stream))
                {
                    reader.Position = offset;

                    Assert.Equal(expected[offset], reader.ReadByte());

                    // We've read a whole chunk but increment by 1 in our reader.
                    Assert.Equal(BufferedReadStream.BufferLength + offset, stream.Position);
                    Assert.Equal(offset + 1, reader.Position);
                }

                Assert.Equal(offset + 1, stream.Position);
            }
        }
        /// <inheritdoc/>
        public Image Decode(BufferedReadStream stream, CancellationToken cancellationToken)
        {
            this.ParseStream(stream, cancellationToken: cancellationToken);
            this.InitExifProfile();
            this.InitIccProfile();
            this.InitIptcProfile();
            this.InitDerivedMetadataProperties();

            // TODO: ロード処理
            var image = new Image(
                new Bitmap(),
                this.ImageWidth,
                this.ImageHeight,
                this.BitsPerPixel)
            {
                Metadata = this.Metadata
            };

            return(image);
        }
Exemple #24
0
        public void VerifySpectralCorrectness <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            if (!TestEnvironment.IsWindows)
            {
                return;
            }

            var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder());

            byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes;

            using var ms             = new MemoryStream(sourceBytes);
            using var bufferedStream = new BufferedReadStream(Configuration.Default, ms);
            decoder.ParseStream(bufferedStream);

            var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder);

            this.VerifySpectralCorrectnessImpl(provider, imageSharpData);
        }
        private static string ReadPartialEndData(BufferedReadStream stream)
        {
            byte[] endPartialBuffer = new byte[EndExtraDisplayLength];
            int    bytesRead        = 0;

            while (stream.TryReadNext(out byte nextByte) && bytesRead < EndExtraDisplayLength)
            {
                endPartialBuffer[bytesRead] = nextByte;
                ++bytesRead;
            }

            if (bytesRead == EndExtraDisplayLength)
            {
                return(Convert.ToString(endPartialBuffer));
            }
            else
            {
                return(Convert.ToString(endPartialBuffer) + "...");
            }
        }
Exemple #26
0
        /// <inheritdoc/>
        public async Task <Image <TPixel> > DecodeAsync <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            var decoder = new PngDecoderCore(configuration, this);

            try
            {
                using var bufferedStream = new BufferedReadStream(configuration, stream);
                return(await decoder.DecodeAsync <TPixel>(bufferedStream).ConfigureAwait(false));
            }
            catch (InvalidMemoryOperationException ex)
            {
                Size dims = decoder.Dimensions;

                PngThrowHelper.ThrowInvalidImageContentException($"Cannot decode image. Failed to allocate buffers for possibly degenerate dimensions: {dims.Width}x{dims.Height}.", ex);

                // Not reachable, as the previous statement will throw a exception.
                return(null);
            }
        }
        public void BufferedStreamReadsSmallStream()
        {
            // Create a stream smaller than the default buffer length
            using (MemoryStream stream = this.CreateTestStream(BufferedReadStream.BufferLength / 4))
            {
                byte[]    expected = stream.ToArray();
                const int offset   = 5;
                using (var reader = new BufferedReadStream(stream))
                {
                    reader.Position = offset;

                    Assert.Equal(expected[offset], reader.ReadByte());

                    // We've read a whole length of the stream but increment by 1 in our reader.
                    Assert.Equal(BufferedReadStream.BufferLength / 4, stream.Position);
                    Assert.Equal(offset + 1, reader.Position);
                }

                Assert.Equal(offset + 1, stream.Position);
            }
        }
Exemple #28
0
        /// <inheritdoc/>
        public async Task <Image <TPixel> > DecodeAsync <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(stream, nameof(stream));

            using var decoder = new JpegDecoderCore(configuration, this);
            try
            {
                using var bufferedStream = new BufferedReadStream(configuration, stream);
                return(await decoder.DecodeAsync <TPixel>(bufferedStream).ConfigureAwait(false));
            }
            catch (InvalidMemoryOperationException ex)
            {
                (int w, int h) = (decoder.ImageWidth, decoder.ImageHeight);

                JpegThrowHelper.ThrowInvalidImageContentException($"Cannot decode image. Failed to allocate buffers for possibly degenerate dimensions: {w}x{h}.", ex);

                // Not reachable, as the previous statement will throw a exception.
                return(null);
            }
        }
        public void BufferedStreamCanReadSingleByteFromOffset(int bufferSize)
        {
            this.configuration.StreamProcessingBufferSize = bufferSize;
            using (MemoryStream stream = this.CreateTestStream(bufferSize * 3))
            {
                byte[] expected = stream.ToArray();
                int    offset   = expected.Length / 2;
                using (var reader = new BufferedReadStream(this.configuration, stream))
                {
                    reader.Position = offset;

                    Assert.Equal(expected[offset], reader.ReadByte());

                    // We've read a whole chunk but increment by 1 in our reader.
                    Assert.Equal(bufferSize + offset, stream.Position);
                    Assert.Equal(offset + 1, reader.Position);
                }

                Assert.Equal(offset + 1, stream.Position);
            }
        }
Exemple #30
0
            public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (_reader == null)
                {
                    if (_message.Properties.ContainsKey(BufferedReadStream.BufferedReadStreamPropertyName))
                    {
                        _bufferedReadStream =
                            _message.Properties[BufferedReadStream.BufferedReadStreamPropertyName] as BufferedReadStream;
                    }
                }

                using (TaskHelpers.RunTaskContinuationsOnOurThreads())
                {
                    if (_bufferedReadStream != null)
                    {
                        await _bufferedReadStream.PreReadBufferAsync(cancellationToken);
                    }

                    return(Read(buffer, offset, count));
                }
            }
        public IReadOnlyList <PositionalDifference> Compare()
        {
            List <PositionalDifference> differenceList = new List <PositionalDifference>();
            PositionalDifference        endDifference;
            bool unhandledDifference = false;

            using (FileStream baselineStream = File.Open(_baselineFilePath, FileMode.Open))
                using (FileStream secondaryStream = File.Open(_secondaryFilePath, FileMode.Open))
                {
                    _baselineData  = new BufferedReadStream(baselineStream);
                    _secondaryData = new BufferedReadStream(secondaryStream);

                    do
                    {
                        if (_baselineData.TryReadNext(out byte baselineByte) && _secondaryData.TryReadNext(out byte secondaryByte))
                        {
                            if (baselineByte != secondaryByte)
                            {
                                if (TryFindDifferenceAtPosition(baselineByte, secondaryByte, out PositionalDifference difference))
                                {
                                    differenceList.Add(difference);
                                }
                                else
                                {
                                    PositionalDifference tooLongDifference = SetupExplicitlyTypedDifference(DifferenceCheckWindowSize, DifferenceCheckWindowSize, baselineByte, secondaryByte, DifferenceDatatype.TooLong, 0);
                                    differenceList.Add(tooLongDifference);
                                    unhandledDifference = true;
                                }
                            }
                        }
                    } while (!IsDoneReading(out endDifference) && !unhandledDifference);
                }

            if (endDifference != null)
            {
                differenceList.Add(endDifference);
            }

            return(differenceList);
        }
Exemple #32
0
        /// <inheritdoc/>
        public Image <TPixel> Decode <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(stream, nameof(stream));

            var decoder = new TgaDecoderCore(configuration, this);

            try
            {
                using var bufferedStream = new BufferedReadStream(stream);
                return(decoder.Decode <TPixel>(bufferedStream));
            }
            catch (InvalidMemoryOperationException ex)
            {
                Size dims = decoder.Dimensions;

                TgaThrowHelper.ThrowInvalidImageContentException($"Cannot decode image. Failed to allocate buffers for possibly degenerate dimensions: {dims.Width}x{dims.Height}.", ex);

                // Not reachable, as the previous statement will throw a exception.
                return(null);
            }
        }
        public void BufferedStreamReadsSmallStream(int bufferSize)
        {
            this.configuration.StreamProcessingBufferSize = bufferSize;

            // Create a stream smaller than the default buffer length
            using (MemoryStream stream = this.CreateTestStream(Math.Max(1, bufferSize / 4)))
            {
                byte[] expected = stream.ToArray();
                int    offset   = expected.Length / 2;
                using (var reader = new BufferedReadStream(this.configuration, stream))
                {
                    reader.Position = offset;

                    Assert.Equal(expected[offset], reader.ReadByte());

                    // We've read a whole length of the stream but increment by 1 in our reader.
                    Assert.Equal(Math.Max(1, bufferSize / 4), stream.Position);
                    Assert.Equal(offset + 1, reader.Position);
                }

                Assert.Equal(offset + 1, stream.Position);
            }
        }
        /// <inheritdoc/>
        public Image <TPixel> Decode <TPixel>(BufferedReadStream stream, CancellationToken cancellationToken)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            this.inputStream = stream;
            var reader = new DirectoryReader(stream, this.Configuration.MemoryAllocator);

            IEnumerable <ExifProfile> directories = reader.Read();

            this.byteOrder = reader.ByteOrder;
            this.isBigTiff = reader.IsBigTiff;

            var frames = new List <ImageFrame <TPixel> >();

            foreach (ExifProfile ifd in directories)
            {
                cancellationToken.ThrowIfCancellationRequested();
                ImageFrame <TPixel> frame = this.DecodeFrame <TPixel>(ifd, cancellationToken);
                frames.Add(frame);
            }

            ImageMetadata metadata = TiffDecoderMetadataCreator.Create(frames, this.ignoreMetadata, reader.ByteOrder, reader.IsBigTiff);

            // TODO: Tiff frames can have different sizes
            ImageFrame <TPixel> root = frames[0];

            this.Dimensions = root.Size();
            foreach (ImageFrame <TPixel> frame in frames)
            {
                if (frame.Size() != root.Size())
                {
                    TiffThrowHelper.ThrowNotSupported("Images with different sizes are not supported");
                }
            }

            return(new Image <TPixel>(this.Configuration, metadata, frames));
        }
 internal SmtpReplyReaderFactory(Stream stream)
 {
     _bufferedStream = new BufferedReadStream(stream);
 }
 /// <summary>
 /// Creates a stream that reads until it reaches the given boundary pattern.
 /// </summary>
 /// <param name="stream">The <see cref="BufferedReadStream"/>.</param>
 /// <param name="boundary">The boundary pattern to use.</param>
 public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary)
     : this(stream, boundary, ArrayPool<byte>.Shared)
 {
 }
        private async Task<Stream> GetStreamAsync()
        {
            var content = _httpResponseMessage.Content;
            Stream contentStream = null;
            _contentLength = -1;
            if (content != null)
            {
                contentStream = await content.ReadAsStreamAsync();
                _contentLength = content.Headers.ContentLength.HasValue ? content.Headers.ContentLength.Value : -1;
                if (_contentLength <= 0)
                {
                    var preReadBuffer = new byte[1];
                    if (await contentStream.ReadAsync(preReadBuffer, 0, 1) == 0)
                    {
                        preReadBuffer = null;
                        contentStream.Dispose();
                        contentStream = null;
                    }
                    else
                    {
                        var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                        await bufferedStream.PreReadBufferAsync(preReadBuffer[0], CancellationToken.None);
                        contentStream = bufferedStream;
                    }
                }
                else if(TransferModeHelper.IsResponseStreamed(_factory.TransferMode))
                {
                    // If _contentLength > 0, then the message was sent buffered but we might still
                    // be receiving it streamed. In which case we need a buffered reading stream.
                    var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                    await bufferedStream.PreReadBufferAsync(CancellationToken.None);
                    contentStream = bufferedStream;
                }
            }

            return contentStream;
        }
Exemple #38
0
            public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (_reader == null)
                {
                    if (_message.Properties.ContainsKey(BufferedReadStream.BufferedReadStreamPropertyName))
                    {
                        _bufferedReadStream =
                            _message.Properties[BufferedReadStream.BufferedReadStreamPropertyName] as BufferedReadStream;
                    }
                }

                using (TaskHelpers.RunTaskContinuationsOnOurThreads())
                {
                    if (_bufferedReadStream != null)
                    {
                        await _bufferedReadStream.PreReadBufferAsync(cancellationToken);
                    }

                    return Read(buffer, offset, count);
                }
            }