NV12及I420格式不再赘述,下面代码只适用width与stride相等的情况。如果stride与width不相等的时候,需要按照步长计算。
#include <cstdint>
void Nv12toI420(uint8_t nv12[], int width, int height, uint8_t** i420Frame)
{
int yByteSize = width * height;
int uvByteSize = width * height / 2;
i420Frame = new uint8_t[yByteSize + uvByteSize];
//copy y
memcpy(i420Frame, nv12, yByteSize);
//分别拷贝uv分量
for (int i = 0; i < uvByteSize / 2; i++)
{
//copy u
i420Frame[i420Frame + yByteSize + i] = nv12[yByteSize + 2i];
//copy v
i420Frame[i420Frame + yByteSize + uvByteSize / 2 + i] = nv12[yByteSize + 2i + 1];
}
}
- 思路2:交换NV12中V分量及U分量。input —>output 都是nv12 []
void Nv12toI420BySwap(uint8_t nv12[], int width, int height)
{
int yByteSize = width * height;
int uvByteSize = width * height / 2;
//分别找到需要交换的u v分量 index,执行swap
for (int i = 0; i < uvByteSize / 2; i++)
{
//v index 所有需要交换v的index
int vindex = nv12[yByteSize + 2 * i + 1];
//u index 所有需要交换 u
int uindex = nv12[yByteSize + uvByteSize / 2 + 2i];
//swap
std::swap(nv12[vindex], nv12[uindex]);
}
}
|