[SOLVED] How to store a YUV12 frame data before uploading it to a texture?

Hi there,

I need to store the information that will go into a SDL2 YUV12 texture before calling SDL_UpdateYUVTexture().
The texture is created like this:

    g_yuv_texture = SDL_CreateTexture(get_renderer(), SDL_PIXELFORMAT_YV12,
        SDL_TEXTUREACCESS_STREAMING, yuv_texture_width, yuv_texture_height);

I know SDL2 does not support YUV surfaces, nor do I need them because I can simply use my own allocated memory for someting like this, so for now I am allocating the memory for the YUV planes like this:

Ysize = width * height + (yuv_texture_width * yuv_texture_height / 2);
Usize = Ysize / 4;
Vsize = Ysize / 6;

Yplane = (uint8_t*) malloc (Ysize);
Uplane = (uint8_t*) malloc (Usize);
Vplane = (uint8_t*) malloc (Vsize);

…however, it’s pure speculation, and in fact, when I try to memcpy to these planes, I get segfaults on ARM but not on X86 (some kind of obscure alignment problem I don’t understand must be at play).
This is how I am trying to memcpy the planes to these addresses:

memcpy (Yplane, Yplane_src, Ysize);
memcpy (Uplane, Uplane_src, Usize);
memcpy (Vplane, Vplane_src, Vsize);

So, HOW MUCH memory should I exactly be allocating (and memcpy-ing) for each one of these planes, taking into account how the YUV texture is created?

Thanks!

Your size calculation looks off. The U and V planes have the same size.

num_pixels = yuv_texture_width * yuv_texture_height;
Ysize = num_pixels;
Usize = num_pixels / 4;
Vsize = num_pixels / 4;

Or if you want to have it in a packed format:

size_t num_pixels = yuv_texture_width * yuv_texture_height;
size_t texture_size = num_pixels * 3 / 2;
size_t Ysize = num_pixels;
size_t Usize = num_pixels / 4;
size_t Vsize = num_pixels / 4;

uint8_t* Yplane = (uint8_t*) malloc(texture_size);
uint8_t* Vplane = Yplane + num_pixels;
uint8_t* Uplane = Vplane + Vsize;

ARM does have a few instructions that require alignment, but I don’t think the compilers emit these if they know that the addresses might be unaligned. Are you perhaps type punning? It could also be that some optimized function uses NEON instructions. What does the debugger say exactly?

@ChliHug: Obviously, my calculations were wrong. I fixed them easily with your help, and everything is rocking now! Thanks!!
Marking as solved…