unity3d - Unity:使用 FFmpeg 将 Texture2D 转换为 YUV420P
问题描述
我正在尝试在 Unity 中创建一个游戏,其中每一帧都被渲染成纹理,然后使用 FFmpeg 组合成一个视频。FFmpeg 创建的输出最终应该通过网络发送到客户端 UI。但是,我主要在处理捕获帧的部分,并将其作为字节数组传递给不安全的方法,FFmpeg 应该进一步处理它。我使用的包装器是FFmpeg.AutoGen。
渲染到纹理方法:
private IEnumerator CaptureFrame()
{
yield return new WaitForEndOfFrame();
RenderTexture.active = rt;
frame.ReadPixels(rect, 0, 0);
frame.Apply();
bytes = frame.GetRawTextureData();
EncodeAndWrite(bytes, bytes.Length);
}
到目前为止不安全的编码方法:
private unsafe void EncodeAndWrite(byte[] bytes, int size)
{
GCHandle pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
IntPtr address = pinned.AddrOfPinnedObject();
sbyte** inData = (sbyte**)address;
fixed(int* lineSize = new int[1])
{
lineSize[0] = 4 * textureWidth;
// Convert RGBA to YUV420P
ffmpeg.sws_scale(sws, inData, lineSize, 0, codecContext->width, inputFrame->extended_data, inputFrame->linesize);
}
inputFrame->pts = frameCounter++;
if(ffmpeg.avcodec_send_frame(codecContext, inputFrame) < 0)
throw new ApplicationException("Error sending a frame for encoding!");
pkt = new AVPacket();
fixed(AVPacket* packet = &pkt)
ffmpeg.av_init_packet(packet);
pkt.data = null;
pkt.size = 0;
pinned.Free();
...
}
sws_scale
将 asbyte**
作为第二个参数,因此我试图将输入字节数组转换为sbyte**
,首先将其固定,GCHandle
然后进行显式类型转换。不过,我不知道这是否是正确的方法。
此外,条件if(ffmpeg.avcodec_send_frame(codecContext, inputFrame) < 0)
总是抛出 ApplicationException,我也真的不知道为什么会发生这种情况。codecContext
分别inputFrame
是我的 AVCodecContext 和 AVFrame 对象,字段定义如下:
编解码器上下文
codecContext = ffmpeg.avcodec_alloc_context3(codec);
codecContext->bit_rate = 400000;
codecContext->width = textureWidth;
codecContext->height = textureHeight;
AVRational timeBase = new AVRational();
timeBase.num = 1;
timeBase.den = (int)fps;
codecContext->time_base = timeBase;
videoAVStream->time_base = timeBase;
AVRational frameRate = new AVRational();
frameRate.num = (int)fps;
frameRate.den = 1;
codecContext->framerate = frameRate;
codecContext->gop_size = 10;
codecContext->max_b_frames = 1;
codecContext->pix_fmt = AVPixelFormat.AV_PIX_FMT_YUV420P;
输入框
inputFrame = ffmpeg.av_frame_alloc();
inputFrame->format = (int)codecContext->pix_fmt;
inputFrame->width = textureWidth;
inputFrame->height = textureHeight;
inputFrame->linesize[0] = inputFrame->width;
任何解决问题的帮助将不胜感激:)
解决方案
在这里查看示例:https ://github.com/FFmpeg/FFmpeg/tree/master/doc/examples
特别是scaling_video.c
。在 FFmpeg 中缩放和像素格式转换是相同的操作(保持大小参数相同,只是像素格式转换)。
这些例子很容易理解。试试看。
推荐阅读
- android - 如何在sqlite表和android中获取特定的行项?
- bash - 为什么我在修改 .bash_profile 以在 macOS Catalina 上安装 Tensorflow + OpenCV 时出现这些语法错误?
- c# - 为什么这个脚本可以在没有实例化的情况下访问另一个脚本?
- cmake - pkg_check_modules 无法解析,因为依赖项没有 .pc 文件
- c# - 为什么这个 C# 代码没有按预期运行?
- c# - 构建用于生产的角度应用程序时未加载图像
- arrays - 我无法在我的 C++ 代码中找到导致分段错误的原因
- python - 从 setup.py 安装时,无法在 Google Colab 中导入 Tensorflow 2.2.0rc2
- python-3.x - 计算赚取特定金额作为利息的时间
- c - 结构有问题,字符串 anf gtkwidget