Skip to content

Commit

Permalink
Fix crash when resizing a video frame for encoding (closes #125, closes
Browse files Browse the repository at this point in the history
  • Loading branch information
radek-k committed Aug 6, 2023
1 parent fc56116 commit 7861330
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
23 changes: 22 additions & 1 deletion FFMediaToolkit/Common/Internal/ImageConverter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FFMediaToolkit.Common.Internal
{
using System;
using System.Drawing;
using FFMediaToolkit.Graphics;
using FFmpeg.AutoGen;
Expand All @@ -9,6 +10,11 @@
/// </summary>
internal unsafe class ImageConverter : Wrapper<SwsContext>
{
// sws_scale requires up to 16 extra bytes allocated in the input buffer when resizing an image
// (reference: https://www.ffmpeg.org/doxygen/6.0/frame_8h_source.html#l00340)
private const int BufferPaddingSize = 16;
private byte[] tmpBuffer = { };

private readonly Size destinationSize;
private readonly AVPixelFormat destinationFormat;
private Size lastSourceSize;
Expand All @@ -34,7 +40,22 @@ public ImageConverter(Size destinationSize, AVPixelFormat destinationFormat)
internal void FillAVFrame(ImageData bitmap, VideoFrame destinationFrame)
{
UpdateContext(bitmap.ImageSize, (AVPixelFormat)bitmap.PixelFormat);
fixed (byte* ptr = bitmap.Data)

var requiredBufferLength = (bitmap.Stride * bitmap.ImageSize.Height) + BufferPaddingSize;
var shouldUseTmpBuffer = bitmap.ImageSize != destinationSize && bitmap.Data.Length < requiredBufferLength;

if (shouldUseTmpBuffer)
{
if (tmpBuffer.Length < requiredBufferLength)
{
tmpBuffer = new byte[requiredBufferLength];
}

bitmap.Data.CopyTo(tmpBuffer);
}

var source = shouldUseTmpBuffer ? tmpBuffer : bitmap.Data;
fixed (byte* ptr = source)
{
var data = new byte*[4] { ptr, null, null, null };
var linesize = new int[4] { bitmap.Stride, 0, 0, 0 };
Expand Down
2 changes: 1 addition & 1 deletion FFMediaToolkit/Graphics/ImageData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
public ImageData(Span<byte> data, ImagePixelFormat pixelFormat, Size imageSize)
{
var size = EstimateStride(imageSize.Width, pixelFormat) * imageSize.Height;
if (data.Length != size)
if (data.Length < size)
{
throw new ArgumentException("Pixel buffer size doesn't match size required by this image format.");
}
Expand Down

0 comments on commit 7861330

Please sign in to comment.