/// <summary>
        /// Initializes a new instance of the <see cref="ImageFrame{TPixel}" /> class wrapping an existing buffer.
        /// </summary>
        /// <param name="configuration">The configuration providing initialization code which allows extending the library.</param>
        /// <param name="width">The width of the image in pixels.</param>
        /// <param name="height">The height of the image in pixels.</param>
        /// <param name="memorySource">The memory source.</param>
        /// <param name="metadata">The metadata.</param>
        internal ImageFrame(Configuration configuration, int width, int height, MemoryGroup <TPixel> memorySource, ImageFrameMetadata metadata)
            : base(configuration, width, height, metadata)
        {
            Guard.MustBeGreaterThan(width, 0, nameof(width));
            Guard.MustBeGreaterThan(height, 0, nameof(height));

            this.PixelBuffer = new Buffer2D <TPixel>(memorySource, width, height);
        }
Example #2
0
        public void DuplicateMemoryInGroup()
        {
            IWritableMemoryGroup testGroup = new MemoryGroup();
            MemoryProperty       prop      = new MemoryProperty("Property", new DataType("TestType", new MemoryProperty[0], new MemoryProperty[0]));
            MemoryItem           i         = new MemoryItem(prop);

            Assert.IsTrue(testGroup.Add(i), "Failed to add item.");
            Assert.IsFalse(testGroup.Add(i), "Duplicate was allowed to be added.");
        }
            public void WhenBlockAlignmentIsOverCapacity_Throws_InvalidMemoryOperationException()
            {
                this.MemoryAllocator.BufferCapacityInBytes = 84; // 42 * Int16

                Assert.Throws <InvalidMemoryOperationException>(() =>
                {
                    MemoryGroup <short> .Allocate(this.MemoryAllocator, 50, 43);
                });
            }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Image{TPixel}"/> class
 /// wrapping an external <see cref="MemoryGroup{T}"/>.
 /// </summary>
 /// <param name="configuration">The configuration providing initialization code which allows extending the library.</param>
 /// <param name="memoryGroup">The memory source.</param>
 /// <param name="width">The width of the image in pixels.</param>
 /// <param name="height">The height of the image in pixels.</param>
 /// <param name="metadata">The images metadata.</param>
 internal Image(
     Configuration configuration,
     MemoryGroup <TPixel> memoryGroup,
     int width,
     int height,
     ImageMetadata metadata)
     : base(configuration, PixelTypeInfo.Create <TPixel>(), metadata, width, height)
 {
     this.frames = new ImageFrameCollection <TPixel>(this, width, height, memoryGroup);
 }
        internal UInt64 GetValue(MemoryGroup group, MemoryType type)
        {
            UInt64 value;

            if (m_Data[(int)group].TryGetValue(type, out value))
            {
                return(value);
            }
            return(0);
        }
Example #6
0
            static void RunTest()
            {
                var  allocator        = MemoryAllocator.Create();
                long sixteenMegabytes = 16 * (1 << 20);

                // Should allocate 4 times 4MB discontiguos blocks:
                MemoryGroup <byte> g = allocator.AllocateGroup <byte>(sixteenMegabytes, 1024);

                Assert.Equal(4, g.Count);
            }
Example #7
0
        /// <summary>
        /// Builds the <see cref="IMemoryGroup"/>s for private and public properties as specified in the <see cref="DataType"/>.
        /// </summary>
        public void BuildMemory()
        {
            PublicProperties  = new MemoryGroup(DataType.PublicProperties);
            PrivateProperties = new MemoryGroup(DataType.PrivateProperties);

            MemoryStack = new MemoryStack();
            MemoryStack.Push(PublicProperties);
            MemoryStack.Push(PrivateProperties);

            //// TODO: Run the constructor to initialize property values...
        }
Example #8
0
        public void FillWithFastEnumerator()
        {
            using MemoryGroup <int> group = this.CreateTestGroup(100, 10, true);
            group.Fill(42);

            int[] expectedRow = Enumerable.Repeat(42, 10).ToArray();
            foreach (Memory <int> memory in group)
            {
                Assert.True(memory.Span.SequenceEqual(expectedRow));
            }
        }
Example #9
0
        public void Clear()
        {
            using MemoryGroup <int> group = this.CreateTestGroup(100, 10, true);
            group.Clear();

            var expectedRow = new int[10];

            foreach (Memory <int> memory in group)
            {
                Assert.True(memory.Span.SequenceEqual(expectedRow));
            }
        }
Example #10
0
        /// <summary>
        /// Wraps an existing contiguous memory area of 'width' x 'height' pixels,
        /// allowing to view/manipulate it as an ImageSharp <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="config">The <see cref="ImageSharp.Configuration"/></param>
        /// <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>
        /// <param name="metadata">The <see cref="ImageMetadata"/></param>
        /// <returns>An <see cref="Image{TPixel}"/> instance</returns>
        public static Image <TPixel> WrapMemory <TPixel>(
            Configuration config,
            IMemoryOwner <TPixel> pixelMemoryOwner,
            int width,
            int height,
            ImageMetadata metadata)
            where TPixel : struct, IPixel <TPixel>
        {
            var memorySource = MemoryGroup <TPixel> .Wrap(pixelMemoryOwner);

            return(new Image <TPixel>(config, memorySource, width, height, metadata));
        }
Example #11
0
        public void FillWithSlowGenericEnumerator()
        {
            using MemoryGroup <int> group = this.CreateTestGroup(100, 10, true);
            group.Fill(42);

            int[] expectedRow = Enumerable.Repeat(42, 10).ToArray();
            IReadOnlyList <Memory <int> > groupAsList = group;

            foreach (Memory <int> memory in groupAsList)
            {
                Assert.True(memory.Span.SequenceEqual(expectedRow));
            }
        }
        public override void OnRenderMap(ulong addressMin, ulong addressMax, int slot)
        {
            for (int i = 0; i < m_SnapshotMemoryRegion.Length; ++i)
            {
                if (m_SnapshotMemoryRegion[i].Type == RegionType.VirtualMemory && !GetDisplayElement(DisplayElements.VirtualMemory))
                {
                    continue;
                }

                ulong stripGroupAddrBegin = m_SnapshotMemoryRegion[i].AddressBegin.Clamp(addressMin, addressMax);
                ulong stripGroupAddrEnd   = m_SnapshotMemoryRegion[i].AddressEnd.Clamp(addressMin, addressMax);

                if (stripGroupAddrBegin == stripGroupAddrEnd)
                {
                    continue;
                }

                MemoryGroup group = m_Groups[m_SnapshotMemoryRegion[i].Group];

                RenderStrip(group, stripGroupAddrBegin, stripGroupAddrEnd, m_SnapshotMemoryRegion[i].ColorRegion);
            }

            for (int i = 0; i < m_Groups.Count; ++i)
            {
                ulong stripGroupAddrBegin = m_Groups[i].AddressBegin.Clamp(addressMin, addressMax);
                ulong stripGroupAddrEnd   = m_Groups[i].AddressEnd.Clamp(addressMin, addressMax);

                if (stripGroupAddrBegin == stripGroupAddrEnd)
                {
                    continue;
                }

                if (GetDisplayElement(DisplayElements.Allocations))
                {
                    Color32 color = m_ColorNative[(int)EntryColors.Allocation];
                    Render(m_Snapshot.SortedNativeAllocations, m_GroupsNativeAlloc, i, addressMin, addressMax, (Color32 c) => new Color32(color.r, color.g, color.b, c.a));
                }

                if (GetDisplayElement(DisplayElements.NativeObjects))
                {
                    Color32 color = m_ColorNative[(int)EntryColors.Object];
                    Render(m_Snapshot.SortedNativeObjects, m_GroupsNativeObj, i, addressMin, addressMax, (Color32 c) => new Color32(color.r, color.g, color.b, c.a));
                }

                if (GetDisplayElement(DisplayElements.MangedObjects))
                {
                    Color32 color = m_ColorManaged[(int)EntryColors.Object];
                    Render(m_Snapshot.SortedManagedObjects, m_GroupsMangedObj, i, addressMin, addressMax, (Color32 c) => new Color32(color.r, color.g, color.b, c.a));
                }
            }
        }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Image{TPixel}"/> class
        /// wrapping an external <see cref="MemoryGroup{T}"/>.
        /// </summary>
        /// <param name="configuration">The configuration providing initialization code which allows extending the library.</param>
        /// <param name="memoryGroup">The memory source.</param>
        /// <param name="width">The width of the image in pixels.</param>
        /// <param name="height">The height of the image in pixels.</param>
        /// <param name="metadata">The images metadata.</param>
        internal Image(
            Configuration configuration,
            MemoryGroup <TPixel> memoryGroup,
            int width,
            int height,
            ImageMetadata metadata)
            : base(configuration, PixelTypeInfo.Create <TPixel>(), metadata, width, height)
        {
            ArrayPoolMemoryAllocator memoryAllocator = (ArrayPoolMemoryAllocator)this.GetConfiguration().MemoryAllocator;

            memoryAllocator.LockingOnThread();
            this.Frames = new ImageFrameCollection <TPixel>(this, width, height, memoryGroup);
            memoryAllocator.Unlock();
        }
Example #14
0
            public void WhenInvalid_CanNotUseMemberMemory()
            {
                Memory <int> memory;

                using (MemoryGroup <int> group = this.CreateTestGroup(240, 80, true))
                {
                    memory = group.View[0];
                }

                Assert.ThrowsAny <InvalidMemoryOperationException>(() =>
                {
                    _ = memory.Span;
                });
            }
Example #15
0
        /// <summary>
        /// Wraps an existing contiguous memory area of 'width' x 'height' pixels,
        /// allowing to view/manipulate it as an ImageSharp <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="configuration">The <see cref="Configuration"/></param>
        /// <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>
        /// <param name="metadata">The <see cref="ImageMetadata"/></param>
        /// <exception cref="ArgumentNullException">The configuration is null.</exception>
        /// <exception cref="ArgumentNullException">The metadata is null.</exception>
        /// <returns>An <see cref="Image{TPixel}"/> instance</returns>
        public static Image <TPixel> WrapMemory <TPixel>(
            Configuration configuration,
            IMemoryOwner <TPixel> pixelMemoryOwner,
            int width,
            int height,
            ImageMetadata metadata)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(configuration, nameof(configuration));
            Guard.NotNull(metadata, nameof(metadata));

            var memorySource = MemoryGroup <TPixel> .Wrap(pixelMemoryOwner);

            return(new Image <TPixel>(configuration, memorySource, width, height, metadata));
        }
Example #16
0
        public void TransformInplace(int totalLength, int bufferLength)
        {
            using MemoryGroup <int> src = this.CreateTestGroup(10, 20, true);

            src.TransformInplace(s => MultiplyAllBy2(s, s));

            int cnt = 1;

            for (MemoryGroupIndex i = src.MinIndex(); i < src.MaxIndex(); i += 1)
            {
                int val = src.GetElementAt(i);
                Assert.Equal(expected: cnt * 2, val);
                cnt++;
            }
        }
            public void GroupToSpan_Success(long totalLength, int bufferLength, int spanLength)
            {
                using MemoryGroup <int> src = this.CreateTestGroup(totalLength, bufferLength, true);
                var trg = new int[spanLength];

                src.CopyTo(trg);

                int expected = 1;

                foreach (int val in trg.AsSpan().Slice(0, (int)totalLength))
                {
                    Assert.Equal(expected, val);
                    expected++;
                }
            }
Example #18
0
        /// <summary>
        /// <para>
        /// Wraps an existing contiguous memory area of 'width' x 'height' pixels allowing viewing/manipulation as
        /// an <see cref="Image{TPixel}"/> instance.
        /// </para>
        /// <para>
        /// Please note: using this method does not transfer the ownership of the underlying buffer of the input <see cref="Memory{T}"/>
        /// to the new <see cref="Image{TPixel}"/> instance. This means that consumers of this method must ensure that the input buffer
        /// is either self-contained, (for example, a <see cref="Memory{T}"/> instance wrapping a new array that was
        /// created), or that the owning object is not disposed until the returned <see cref="Image{TPixel}"/> is disposed.
        /// </para>
        /// <para>
        /// If the input <see cref="Memory{T}"/> instance is one retrieved from an <see cref="IMemoryOwner{T}"/> instance
        /// rented from a memory pool (such as <see cref="MemoryPool{T}"/>), and that owning instance is disposed while the image is still
        /// in use, this will lead to undefined behavior and possibly runtime crashes (as the same buffer might then be modified by other
        /// consumers while the returned image is still working on it). Make sure to control the lifetime of the input buffers appropriately.
        /// </para>
        /// </summary>
        /// <typeparam name="TPixel">The pixel type</typeparam>
        /// <param name="configuration">The <see cref="Configuration"/></param>
        /// <param name="pixelMemory">The pixel memory.</param>
        /// <param name="width">The width of the memory image.</param>
        /// <param name="height">The height of the memory image.</param>
        /// <param name="metadata">The <see cref="ImageMetadata"/>.</param>
        /// <exception cref="ArgumentNullException">The configuration is null.</exception>
        /// <exception cref="ArgumentNullException">The metadata is null.</exception>
        /// <returns>An <see cref="Image{TPixel}"/> instance</returns>
        public static Image <TPixel> WrapMemory <TPixel>(
            Configuration configuration,
            Memory <TPixel> pixelMemory,
            int width,
            int height,
            ImageMetadata metadata)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(configuration, nameof(configuration));
            Guard.NotNull(metadata, nameof(metadata));
            Guard.IsTrue(pixelMemory.Length == width * height, nameof(pixelMemory), "The length of the input memory doesn't match the specified image size");

            var memorySource = MemoryGroup <TPixel> .Wrap(pixelMemory);

            return(new Image <TPixel>(configuration, memorySource, width, height, metadata));
        }
Example #19
0
        public void GetBoundedSlice_WhenArgsAreCorrect(long totalLength, int bufferLength, long start, int length)
        {
            using MemoryGroup <int> group = this.CreateTestGroup(totalLength, bufferLength, true);

            Memory <int> slice = group.GetBoundedSlice(start, length);

            Assert.Equal(length, slice.Length);

            int expected = (int)start + 1;

            foreach (int val in slice.Span)
            {
                Assert.Equal(expected, val);
                expected++;
            }
        }
Example #20
0
        internal override void CopyPixelsTo <TDestinationPixel>(MemoryGroup <TDestinationPixel> destination)
        {
            if (typeof(TPixel) == typeof(TDestinationPixel))
            {
                this.PixelBuffer.FastMemoryGroup.TransformTo(destination, (s, d) =>
                {
                    Span <TPixel> d1 = MemoryMarshal.Cast <TDestinationPixel, TPixel>(d);
                    s.CopyTo(d1);
                });
                return;
            }

            this.PixelBuffer.FastMemoryGroup.TransformTo(destination, (s, d) =>
            {
                PixelOperations <TPixel> .Instance.To(this.GetConfiguration(), s, d);
            });
        }
Example #21
0
            public void WhenDestIsNotMemoryOwner_DifferentSize_Throws(bool sourceIsOwner)
            {
                var data  = new Rgba32[21];
                var color = new Rgba32(1, 2, 3, 4);

                using var destOwner = new TestMemoryManager <Rgba32>(data);
                using var dest      = new Buffer2D <Rgba32>(MemoryGroup <Rgba32> .Wrap(destOwner.Memory), 21, 1);

                using Buffer2D <Rgba32> source = this.MemoryAllocator.Allocate2D <Rgba32>(22, 1);

                source.FastMemoryGroup[0].Span[10] = color;

                // Act:
                Assert.ThrowsAny <InvalidOperationException>(() => Buffer2D <Rgba32> .SwapOrCopyContent(dest, source));

                Assert.Equal(color, source.MemoryGroup[0].Span[10]);
                Assert.NotEqual(color, dest.MemoryGroup[0].Span[10]);
            }
Example #22
0
        /// <summary>
        /// <para>
        /// Wraps an existing contiguous memory area of 'width' x 'height' pixels allowing viewing/manipulation as
        /// an <see cref="Image{TPixel}"/> instance.
        /// </para>
        /// <para>
        /// Please note: this method relies on callers to carefully manage the target memory area being referenced by the
        /// pointer and that the lifetime of such a memory area is at least equal to that of the returned
        /// <see cref="Image{TPixel}"/> instance. For example, if the input pointer references an unmanaged memory area,
        /// callers must ensure that the memory area is not freed as long as the returned <see cref="Image{TPixel}"/> is
        /// in use and not disposed. The same applies if the input memory area points to a pinned managed object, as callers
        /// must ensure that objects will remain pinned as long as the <see cref="Image{TPixel}"/> instance is in use.
        /// Failing to do so constitutes undefined behavior and will likely lead to memory corruption and runtime crashes.
        /// </para>
        /// <para>
        /// Note also that if you have a <see cref="Memory{T}"/> or an array (which can be cast to <see cref="Memory{T}"/>) of
        /// either <see cref="byte"/> or <typeparamref name="TPixel"/> values, it is highly recommended to use one of the other
        /// available overloads of this method instead (such as <see cref="WrapMemory{TPixel}(Configuration, Memory{byte}, int, int)"/>
        /// or <see cref="WrapMemory{TPixel}(Configuration, Memory{TPixel}, int, int)"/>, to make the resulting code less error
        /// prone and avoid having to pin the underlying memory buffer in use. This method is primarily meant to be used when
        /// doing interop or working with buffers that are located in unmanaged memory.
        /// </para>
        /// </summary>
        /// <typeparam name="TPixel">The pixel type</typeparam>
        /// <param name="configuration">The <see cref="Configuration"/></param>
        /// <param name="pointer">The pointer to the target memory buffer to wrap.</param>
        /// <param name="width">The width of the memory image.</param>
        /// <param name="height">The height of the memory image.</param>
        /// <param name="metadata">The <see cref="ImageMetadata"/>.</param>
        /// <exception cref="ArgumentNullException">The configuration is null.</exception>
        /// <exception cref="ArgumentNullException">The metadata is null.</exception>
        /// <returns>An <see cref="Image{TPixel}"/> instance</returns>
        public static unsafe Image <TPixel> WrapMemory <TPixel>(
            Configuration configuration,
            void *pointer,
            int width,
            int height,
            ImageMetadata metadata)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.IsFalse(pointer == null, nameof(pointer), "Pointer must be not null");
            Guard.NotNull(configuration, nameof(configuration));
            Guard.NotNull(metadata, nameof(metadata));

            var memoryManager = new UnmanagedMemoryManager <TPixel>(pointer, width * height);

            var memorySource = MemoryGroup <TPixel> .Wrap(memoryManager.Memory);

            return(new Image <TPixel>(configuration, memorySource, width, height, metadata));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="JpegImagePostProcessor"/> class.
        /// </summary>
        /// <param name="configuration">The <see cref="Configuration"/> to configure internal operations.</param>
        /// <param name="rawJpeg">The <see cref="IRawJpegData"/> representing the uncompressed spectral Jpeg data</param>
        public JpegImagePostProcessor(IRawJpegData rawJpeg)
        {
            this.RawJpeg = rawJpeg;
            IJpegComponent c0 = rawJpeg.Components[0];

            this.NumberOfPostProcessorSteps = c0.SizeInBlocks.Height / BlockRowsPerStep;
            this.PostProcessorBufferSize    = new Size(c0.SizeInBlocks.Width * 8, PixelRowsPerStep);

            this.ComponentProcessors = new JpegComponentPostProcessor[rawJpeg.Components.Length];
            for (int i = 0; i < rawJpeg.Components.Length; i++)
            {
                this.ComponentProcessors[i] = new JpegComponentPostProcessor(this, rawJpeg.Components[i]);
            }

            this.rgbaBuffer = MemoryGroup <Vector4> .Allocate(rawJpeg.ImageSizeInPixels.Width);

            this.colorConverter = JpegColorConverter.GetConverter(rawJpeg.ColorSpace, rawJpeg.Precision);
        }
Example #24
0
        public void Wrap()
        {
            int[] data0 = { 1, 2, 3, 4 };
            int[] data1 = { 5, 6, 7, 8 };
            int[] data2 = { 9, 10 };
            using var mgr0 = new TestMemoryManager <int>(data0);
            using var mgr1 = new TestMemoryManager <int>(data1);

            using var group = MemoryGroup <int> .Wrap(mgr0.Memory, mgr1.Memory, data2);

            Assert.Equal(3, group.Count);
            Assert.Equal(4, group.BufferLength);
            Assert.Equal(10, group.TotalLength);

            Assert.True(group[0].Span.SequenceEqual(data0));
            Assert.True(group[1].Span.SequenceEqual(data1));
            Assert.True(group[2].Span.SequenceEqual(data2));
        }
Example #25
0
        /// <summary>
        /// Wraps an existing contiguous memory area of at least 'width' x 'height' pixels,
        /// allowing to view/manipulate it as an <see cref="Image{TPixel}"/> instance.
        /// The ownership of the <paramref name="byteMemoryOwner"/> is being transferred to the new <see cref="Image{TPixel}"/> instance,
        /// meaning that the caller is not allowed to dispose <paramref name="byteMemoryOwner"/>.
        /// It will be disposed together with the result image.
        /// </summary>
        /// <typeparam name="TPixel">The pixel type</typeparam>
        /// <param name="configuration">The <see cref="Configuration"/></param>
        /// <param name="byteMemoryOwner">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>
        /// <param name="metadata">The <see cref="ImageMetadata"/></param>
        /// <exception cref="ArgumentNullException">The configuration is null.</exception>
        /// <exception cref="ArgumentNullException">The metadata is null.</exception>
        /// <returns>An <see cref="Image{TPixel}"/> instance</returns>
        public static Image <TPixel> WrapMemory <TPixel>(
            Configuration configuration,
            IMemoryOwner <byte> byteMemoryOwner,
            int width,
            int height,
            ImageMetadata metadata)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(configuration, nameof(configuration));
            Guard.NotNull(metadata, nameof(metadata));

            var pixelMemoryOwner = new ByteMemoryOwner <TPixel>(byteMemoryOwner);

            Guard.IsTrue(pixelMemoryOwner.Memory.Length >= (long)width * height, nameof(pixelMemoryOwner), "The length of the input memory is less than the specified image size");

            var memorySource = MemoryGroup <TPixel> .Wrap(pixelMemoryOwner);

            return(new Image <TPixel>(configuration, memorySource, width, height, metadata));
        }
            public void WhenSourceBufferIsShorterOrEqual(int srcTotal, int srcBufLen, int trgTotal, int trgBufLen)
            {
                using MemoryGroup <int> src = this.CreateTestGroup(srcTotal, srcBufLen, true);
                using MemoryGroup <int> trg = this.CreateTestGroup(trgTotal, trgBufLen, false);

                src.CopyTo(trg);

                int pos            = 0;
                MemoryGroupIndex i = src.MinIndex();
                MemoryGroupIndex j = trg.MinIndex();

                for (; i < src.MaxIndex(); i += 1, j += 1, pos++)
                {
                    int a = src.GetElementAt(i);
                    int b = trg.GetElementAt(j);

                    Assert.True(a == b, $"Mismatch @ {pos} Expected: {a} Actual: {b}");
                }
            }
Example #27
0
        public Image <TPixel> Decode <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, ImageSharp.PixelFormats.IPixel <TPixel>
        {
            var bmpReadDefines = new BmpReadDefines
            {
                IgnoreFileSize = !this.validate
            };

            var settings = new MagickReadSettings();

            settings.SetDefines(bmpReadDefines);

            using var magickImageCollection = new MagickImageCollection(stream, settings);
            var framesList = new List <ImageFrame <TPixel> >();

            foreach (IMagickImage <ushort> magicFrame in magickImageCollection)
            {
                var frame = new ImageFrame <TPixel>(configuration, magicFrame.Width, magicFrame.Height);
                framesList.Add(frame);

                MemoryGroup <TPixel> framePixels = frame.PixelBuffer.FastMemoryGroup;

                using IUnsafePixelCollection <ushort> pixels = magicFrame.GetPixelsUnsafe();
                if (magicFrame.Depth == 8 || magicFrame.Depth == 1)
                {
                    byte[] data = pixels.ToByteArray(PixelMapping.RGBA);

                    FromRgba32Bytes(configuration, data, framePixels);
                }
                else if (magicFrame.Depth == 16)
                {
                    ushort[]    data  = pixels.ToShortArray(PixelMapping.RGBA);
                    Span <byte> bytes = MemoryMarshal.Cast <ushort, byte>(data.AsSpan());
                    FromRgba64Bytes(configuration, bytes, framePixels);
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }

            return(new Image <TPixel>(configuration, new ImageMetadata(), framesList));
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JpegComponentPostProcessor"/> class.
        /// </summary>
        public JpegComponentPostProcessor(JpegImagePostProcessor imagePostProcessor, IJpegComponent component)
        {
            Buffer2D <float> Allocate2DOveraligned()
            {
                long groupLength = (long)imagePostProcessor.PostProcessorBufferSize.Width * imagePostProcessor.PostProcessorBufferSize.Height;
                MemoryGroup <float> memoryGroup = MemoryGroup <float> .Allocate(
                    groupLength,
                    imagePostProcessor.PostProcessorBufferSize.Width *this.blockAreaSize.Height);

                return(new Buffer2D <float>(memoryGroup, imagePostProcessor.PostProcessorBufferSize.Width, imagePostProcessor.PostProcessorBufferSize.Height));
            }

            this.Component          = component;
            this.ImagePostProcessor = imagePostProcessor;
            this.blockAreaSize      = this.Component.SubSamplingDivisors * 8;
            this.ColorBuffer        = Allocate2DOveraligned();

            this.BlockRowsPerStep = JpegImagePostProcessor.BlockRowsPerStep / this.Component.SubSamplingDivisors.Height;
        }
        /// <summary>
        /// Create a group, either uninitialized or filled with incrementing numbers starting with 1.
        /// </summary>
        internal MemoryGroup <int> CreateTestGroup(long totalLength, int bufferLength, bool fillSequence = false)
        {
            this.MemoryAllocator.BufferCapacityInBytes = bufferLength * sizeof(int);
            var g = MemoryGroup <int> .Allocate(this.MemoryAllocator, totalLength, bufferLength);

            if (!fillSequence)
            {
                return(g);
            }

            int j = 1;

            for (MemoryGroupIndex i = g.MinIndex(); i < g.MaxIndex(); i += 1)
            {
                g.SetElementAt(i, j);
                j++;
            }

            return(g);
        }
            public void SpanToGroup_Success(long totalLength, int bufferLength, int spanLength)
            {
                var src = new int[spanLength];

                for (int i = 0; i < src.Length; i++)
                {
                    src[i] = i + 1;
                }

                using MemoryGroup <int> trg = this.CreateTestGroup(totalLength, bufferLength);
                src.AsSpan().CopyTo(trg);

                int position = 0;

                for (MemoryGroupIndex i = trg.MinIndex(); position < spanLength; i += 1, position++)
                {
                    int expected = position + 1;
                    Assert.Equal(expected, trg.GetElementAt(i));
                }
            }