Search Unity

Reading pixel data from Texture2D on GPU

Discussion in 'General Graphics' started by Flag74, Jul 26, 2019.

  1. Flag74

    Flag74

    Joined:
    May 31, 2017
    Posts:
    128
    Hi,
    I need to read pixel data from a Texture2d, each frame, that I need to pass to an enconding mp4 plugin.
    Unfortunately texture data is on GPU only, therefore I cannot simply use GetPixels32().
    What's the best way, suitable for 25 fps streaming that won't cause big cpu/gpu spikes?
    At the moment I do this, but I'm not sure it's the best method:

    Code (CSharp):
    1. List<AsyncGPUReadbackRequest> requests = new List<AsyncGPUReadbackRequest>();
    2. void Update()
    3. {
    4.   var request = AsyncGPUReadback.Request(textureToEncode);
    5.   requests.Add(request);
    6.   for (int i = 0; i < requests.Count; i++)
    7.   {
    8.     AsyncGPUReadbackRequest r = requests[i];
    9.     if (r.done)
    10.     {
    11.       videoRecorder.CommitFrame(r.GetData<byte>().ToArray(), clock.Timestamp);//ToArray() is bad
    12.       requests.RemoveAt(i);//resize maybe could be optimized?
    13.       break;
    14.     }
    15.   }
    16. }
    Any suggestions?
    Also not all devices support asynchronous readback so it would be better to go for another way as fallback. Which one?I think a small cpu stall would be reasonable..
     
    Last edited: Jul 26, 2019