Exemplo n.º 1
0
 /// <summary>
 /// Wraps an existing contiguous memory area of 'width' x 'height' pixels,
 /// allowing to view/manipulate it as an <see cref="Image{TPixel}"/> instance.
 /// The ownership of the <paramref name="pixelMemoryOwner"/> is being transferred to the new <see cref="Image{TPixel}"/> instance,
 /// meaning that the caller is not allowed to dispose <paramref name="pixelMemoryOwner"/>.
 /// It will be disposed together with the result image.
 /// </summary>
 /// <typeparam name="TPixel">The pixel type</typeparam>
 /// <param name="pixelMemoryOwner">The <see cref="IMemoryOwner{T}"/> that is being transferred to the image.</param>
 /// <param name="width">The width of the memory image.</param>
 /// <param name="height">The height of the memory image.</param>
 /// <returns>An <see cref="Image{TPixel}"/> instance.</returns>
 public static Image <TPixel> WrapMemory <TPixel>(
     IMemoryOwner <TPixel> pixelMemoryOwner,
     int width,
     int height)
     where TPixel : unmanaged, IPixel <TPixel>
 => WrapMemory(Configuration.Default, pixelMemoryOwner, width, height);
Exemplo n.º 2
0
 public void Setup()
 {
     this.source      = Configuration.Default.MemoryAllocator.Allocate <TPixel>(this.Count);
     this.destination = Configuration.Default.MemoryAllocator.Allocate <Vector4>(this.Count);
 }
 internal void HandleOperationCompleted(IMemoryOwner <byte> data, ResponseStatus status)
 {
     //noop
 }
Exemplo n.º 4
0
 public void SettingMemory(IMemoryOwner <byte> memoryOwner, int writedLength)
 {
     this.writedLength = writedLength;
     this.memoryOwner  = memoryOwner;
 }
 public void Dispose()
 {
     _data?.Dispose();
     _data = null;
 }
Exemplo n.º 6
0
 public static ref T GetReference <T>(this IMemoryOwner <T> buffer)
     where T : struct =>
 ref MemoryMarshal.GetReference(buffer.GetSpan());
Exemplo n.º 7
0
 public void Setup()
 {
     this.configuration = Configuration.Default;
     this.destination   = this.configuration.MemoryAllocator.Allocate <TPixel>(this.Count);
     this.source        = this.configuration.MemoryAllocator.Allocate <byte>(this.Count * 4);
 }
Exemplo n.º 8
0
 internal IncomingMessage(IPEndPoint endpoint, IMemoryOwner <byte> owner, int messageLength)
 {
     this.Endpoint = endpoint;
     this.owner    = owner;
     this.Payload  = new ReadOnlySequence <byte>(owner.Memory.Slice(0, messageLength));
 }
Exemplo n.º 9
0
 internal IncomingMessage(IPEndPoint endpoint, ReadOnlySequence <byte> payload)
 {
     this.Endpoint = endpoint;
     this.owner    = null;
     this.Payload  = payload;
 }
 /// <inheritdoc cref="TypedMemoryOwnedContent(IMemoryOwner{byte},int,int,string)"/>
 public TypedMemoryOwnedContent(IMemoryOwner <byte> memoryOwner, int start, string contentType)
     : this(memoryOwner, memoryOwner.Memory[start..], contentType)
Exemplo n.º 11
0
 /// <summary>
 /// GetNext supporting memory pools
 /// </summary>
 /// <param name="pool">Memory pool</param>
 /// <param name="entry">Copy of entry, if found</param>
 /// <param name="entryLength">Actual length of entry</param>
 /// <param name="currentAddress">Logical address of entry</param>
 /// <returns></returns>
 public unsafe bool GetNext(MemoryPool <byte> pool, out IMemoryOwner <byte> entry, out int entryLength, out long currentAddress)
 {
     return(GetNext(pool, out entry, out entryLength, out currentAddress, out _));
 }
Exemplo n.º 12
0
        public bool TryGet(OmniHash hash, out IMemoryOwner <byte>?memoryOwner)
        {
            if (!EnumHelper.IsValid(hash.AlgorithmType))
            {
                throw new ArgumentException($"Incorrect HashAlgorithmType: {hash.AlgorithmType}");
            }

            memoryOwner = null;
            bool success = false;

            try
            {
                lock (_lockObject)
                {
                    if (_clusterMetadataMap.TryGetValue(hash, out var clusterInfo))
                    {
                        clusterInfo = new ClusterMetadata(clusterInfo.Sectors.ToArray(), clusterInfo.Length, Timestamp.FromDateTime(DateTime.UtcNow));
                        _clusterMetadataMap[hash] = clusterInfo;
                    }

                    if (clusterInfo == null)
                    {
                        return(false);
                    }

                    memoryOwner = _bufferPool.Rent((int)clusterInfo.Length);

                    try
                    {
                        uint remain = clusterInfo.Length;

                        for (int i = 0; i < clusterInfo.Sectors.Count; i++, remain -= SectorSize)
                        {
                            ulong position = clusterInfo.Sectors[i] * SectorSize;

                            if (position > (ulong)_fileStream.Length)
                            {
                                _logger.Debug($"position too large: {position}");

                                return(false);
                            }

                            if ((ulong)_fileStream.Position != position)
                            {
                                _fileStream.Seek((long)position, SeekOrigin.Begin);
                            }

                            uint length = Math.Min(remain, SectorSize);

                            _fileStream.Read(_sectorBuffer, 0, _sectorBuffer.Length);
                            BytesOperations.Copy(_sectorBuffer, memoryOwner.Memory.Span.Slice((int)(SectorSize * i)), (int)length);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.Debug(e);

                        return(false);
                    }
                }

                if (hash.AlgorithmType == OmniHashAlgorithmType.Sha2_256 &&
                    BytesOperations.SequenceEqual(Sha2_256.ComputeHash(memoryOwner.Memory.Span), hash.Value.Span))
                {
                    success = true;

                    return(true);
                }
                else
                {
                    _logger.Debug("Broken block.");

                    return(false);
                }
            }
            finally
            {
                if (!success)
                {
                    if (memoryOwner != null)
                    {
                        memoryOwner.Dispose();
                        memoryOwner = null;
                    }

                    this.Remove(hash);
                }
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MemorySource{T}"/> struct
 /// by wrapping an existing <see cref="IMemoryOwner{T}"/>.
 /// </summary>
 /// <param name="memoryOwner">The <see cref="IMemoryOwner{T}"/> to wrap</param>
 /// <param name="isInternalMemorySource">
 /// A value indicating whether <paramref name="memoryOwner"/> is an internal memory source managed by ImageSharp.
 /// Eg. allocated by a <see cref="MemoryAllocator"/>.
 /// </param>
 public MemorySource(IMemoryOwner <T> memoryOwner, bool isInternalMemorySource)
 {
     this.MemoryOwner          = memoryOwner;
     this.Memory               = memoryOwner.Memory;
     this.HasSwappableContents = isInternalMemorySource;
 }
Exemplo n.º 14
0
 public BlockReader(IMemoryOwner <byte> owner)
 {
     _owner     = owner;
     _blockData = owner.Memory;
 }
Exemplo n.º 15
0
 public static Span <T> Slice <T>(this IMemoryOwner <T> buffer, int start, int length)
 {
     return(buffer.GetSpan().Slice(start, length));
 }
Exemplo n.º 16
0
        /// <inheritdoc/>
        protected override void OnFrameApply(ImageFrame <TPixel> source)
        {
            Rectangle     sourceRectangle = this.SourceRectangle;
            Configuration configuration   = this.Configuration;
            int           startX          = sourceRectangle.X;
            int           endX            = sourceRectangle.Right;
            int           startY          = sourceRectangle.Y;
            int           endY            = sourceRectangle.Bottom;

            // Align start/end positions.
            int minX = Math.Max(0, startX);
            int maxX = Math.Min(source.Width, endX);
            int minY = Math.Max(0, startY);
            int maxY = Math.Min(source.Height, endY);

            int width = maxX - minX;

            var workingRect = Rectangle.FromLTRB(minX, minY, maxX, maxY);

            IBrush          brush   = this.definition.Brush;
            GraphicsOptions options = this.definition.Options;

            // If there's no reason for blending, then avoid it.
            if (this.IsSolidBrushWithoutBlending(out SolidBrush solidBrush))
            {
                ParallelExecutionSettings parallelSettings = ParallelExecutionSettings.FromConfiguration(configuration)
                                                             .MultiplyMinimumPixelsPerTask(4);

                TPixel colorPixel = solidBrush.Color.ToPixel <TPixel>();

                ParallelHelper.IterateRows(
                    workingRect,
                    parallelSettings,
                    rows =>
                {
                    for (int y = rows.Min; y < rows.Max; y++)
                    {
                        source.GetPixelRowSpan(y).Slice(minX, width).Fill(colorPixel);
                    }
                });
            }
            else
            {
                // Reset offset if necessary.
                if (minX > 0)
                {
                    startX = 0;
                }

                if (minY > 0)
                {
                    startY = 0;
                }

                using (IMemoryOwner <float> amount = source.MemoryAllocator.Allocate <float>(width))
                    using (BrushApplicator <TPixel> applicator = brush.CreateApplicator(
                               configuration,
                               options,
                               source,
                               sourceRectangle))
                    {
                        amount.Memory.Span.Fill(1F);

                        ParallelHelper.IterateRows(
                            workingRect,
                            configuration,
                            rows =>
                        {
                            for (int y = rows.Min; y < rows.Max; y++)
                            {
                                int offsetY = y - startY;
                                int offsetX = minX - startX;

                                applicator.Apply(amount.Memory.Span, offsetX, offsetY);
                            }
                        });
                    }
            }
        }
Exemplo n.º 17
0
 public static void Clear <T>(this IMemoryOwner <T> buffer)
 {
     buffer.GetSpan().Clear();
 }
Exemplo n.º 18
0
        /// <inheritdoc/>
        protected override void OnFrameApply(ImageFrame <TPixel> source, Rectangle sourceRectangle, Configuration configuration)
        {
            int     startY        = sourceRectangle.Y;
            int     endY          = sourceRectangle.Bottom;
            int     startX        = sourceRectangle.X;
            int     endX          = sourceRectangle.Right;
            TPixel  vignetteColor = this.VignetteColor;
            Vector2 centre        = Rectangle.Center(sourceRectangle);

            Size  sourceSize   = source.Size();
            float finalRadiusX = this.RadiusX.Calculate(sourceSize);
            float finalRadiusY = this.RadiusY.Calculate(sourceSize);
            float rX           = finalRadiusX > 0 ? MathF.Min(finalRadiusX, sourceRectangle.Width * .5F) : sourceRectangle.Width * .5F;
            float rY           = finalRadiusY > 0 ? MathF.Min(finalRadiusY, sourceRectangle.Height * .5F) : sourceRectangle.Height * .5F;
            float maxDistance  = MathF.Sqrt((rX * rX) + (rY * rY));

            // Align start/end positions.
            int minX = Math.Max(0, startX);
            int maxX = Math.Min(source.Width, endX);
            int minY = Math.Max(0, startY);
            int maxY = Math.Min(source.Height, endY);

            // Reset offset if necessary.
            if (minX > 0)
            {
                startX = 0;
            }

            if (minY > 0)
            {
                startY = 0;
            }

            int width = maxX - minX;

            using (IMemoryOwner <TPixel> rowColors = source.MemoryAllocator.Allocate <TPixel>(width))
            {
                // Be careful! Do not capture rowColorsSpan in the lambda below!
                Span <TPixel> rowColorsSpan = rowColors.GetSpan();

                for (int i = 0; i < width; i++)
                {
                    rowColorsSpan[i] = vignetteColor;
                }

                ParallelFor.WithTemporaryBuffer <float>(
                    minY,
                    maxY,
                    configuration,
                    width,
                    (y, amounts) =>
                {
                    Span <float> amountsSpan = amounts.GetSpan();
                    int offsetY = y - startY;
                    int offsetX = minX - startX;
                    for (int i = 0; i < width; i++)
                    {
                        float distance = Vector2.Distance(centre, new Vector2(i + offsetX, offsetY));
                        amountsSpan[i] =
                            (this.GraphicsOptions.BlendPercentage * (.9F * (distance / maxDistance))).Clamp(
                                0,
                                1);
                    }

                    Span <TPixel> destination = source.GetPixelRowSpan(offsetY).Slice(offsetX, width);

                    this.blender.Blend(
                        source.MemoryAllocator,
                        destination,
                        destination,
                        rowColors.GetSpan(),
                        amountsSpan);
                });
            }
        }
Exemplo n.º 19
0
 public CustomMemoryOwner(IMemoryOwner <T> memoryOwner, int length)
 {
     _memoryOwner = memoryOwner;
     this.Memory  = _memoryOwner.Memory[..length];
Exemplo n.º 20
0
 public PooledMemory(IMemoryOwner <byte> owner, BufferMemoryPool pool)
 {
     _owner          = owner;
     _pool           = pool;
     _referenceCount = 1;
 }
Exemplo n.º 21
0
 public MediaBuffer(IMemoryOwner <byte> buffer, int length)
 {
     _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer));
     Length  = length;
 }
Exemplo n.º 22
0
 public void Set(IMemoryOwner <byte> owner)
 {
     _owner = owner;
 }
Exemplo n.º 23
0
 public WrappedMemory(IMemoryOwner <byte> memoryOwner, MemoryFlag flag) : this(flag)
 {
     this.memoryOwner = memoryOwner;
 }
Exemplo n.º 24
0
 public static void SpanPointsTo <T>(Span <T> span, IMemoryOwner <T> buffer, int bufferOffset = 0)
     where T : struct
 {
     ref T actual   = ref MemoryMarshal.GetReference(span);
 /// <summary>
 /// Sets the data for this instance, taking ownership of the data and responsibility for disposing.
 /// </summary>
 /// <param name="data">The <see cref="IMemoryOwner{T}"/>.</param>
 public void SetData(IMemoryOwner <byte> data)
 {
     _data = data ?? throw new ArgumentNullException(nameof(data));
 }
Exemplo n.º 26
0
 public static Span <T> GetSpan <T>(this IMemoryOwner <T> buffer)
 => buffer.Memory.Span;
Exemplo n.º 27
0
 public int Serialize(IMemoryOwner <byte> memoryOwner, int offset, JT808_0x0102 value)
 {
     offset += JT808BinaryExtensions.WriteStringLittle(memoryOwner, offset, value.Code);
     return(offset);
 }
Exemplo n.º 28
0
 public static int Length <T>(this IMemoryOwner <T> buffer)
 => buffer.GetSpan().Length;
Exemplo n.º 29
0
 public int Serialize(IMemoryOwner <byte> memoryOwner, int offset, JT808_0x8805 value)
 {
     offset += JT808BinaryExtensions.WriteInt32Little(memoryOwner, offset, value.MultimediaId);
     offset += JT808BinaryExtensions.WriteByteLittle(memoryOwner, offset, (byte)value.Deleted);
     return(offset);
 }
Exemplo n.º 30
0
 protected abstract void Deserialize(
     ReadOnlySpan <byte> span,
     MemoryPool <byte> memoryPool,
     out ReadOnlyMemory <byte> memory,
     out IMemoryOwner <byte> owner,
     out PublicKeyBytes publicKeyBytes);