Interpretação YUV_420_888 no Samsung Galaxy S7 (Camera2)

Eu escrevi uma conversão de YUV_420_888 para Bitmap, considerando a seguinte lógica (como eu a entendo):

Para resumir a abordagem: as coordenadas xey do kernel são congruentes com xey da parte não preenchida do plano Y (alocação 2d) e xey do bitmap de saída. Os planos U e V, no entanto, possuem uma estrutura diferente da do plano Y, porque usam 1 byte para uma cobertura de 4 pixels e, além disso, podem ter um PixelStride que é mais de um, além de poderem também possui um preenchimento que pode ser diferente do do plano Y. Portanto, para acessar os U's e os Vs de forma eficiente pelo kernel, eu os coloquei em alocações 1-d e criei um índice "uvIndex" que fornece a posição dos U e V correspondentes nessa alocação 1-d, por dado ( x, y) coordenadas no plano Y (sem preenchimento) (e, portanto, no bitmap de saída).

Para manter o rs-Kernel enxuto, excluí a área de preenchimento no yPlane limitando o intervalo x via LaunchOptions (isso reflete o RowStride do plano y, que pode ser ignorado DENTRO do kernel). Portanto, basta considerar o uvPixelStride e o uvRowStride dentro do uvIndex, ou seja, o índice usado para acessar os valores u e v.

Este é o meu código:

Renderscript Kernel, chamado yuv420888.rs

  #pragma version(1)
  #pragma rs java_package_name(com.xxxyyy.testcamera2);
  #pragma rs_fp_relaxed

  int32_t width;
  int32_t height;

  uint picWidth, uvPixelStride, uvRowStride ;
  rs_allocation ypsIn,uIn,vIn;

 // The LaunchOptions ensure that the Kernel does not enter the padding  zone of Y, so yRowStride can be ignored WITHIN the Kernel.
 uchar4 __attribute__((kernel)) doConvert(uint32_t x, uint32_t y) {

 // index for accessing the uIn's and vIn's
uint uvIndex=  uvPixelStride * (x/2) + uvRowStride*(y/2);

// get the y,u,v values
uchar yps= rsGetElementAt_uchar(ypsIn, x, y);
uchar u= rsGetElementAt_uchar(uIn, uvIndex);
uchar v= rsGetElementAt_uchar(vIn, uvIndex);

// calc argb
int4 argb;
    argb.r = yps + v * 1436 / 1024 - 179;
    argb.g =  yps -u * 46549 / 131072 + 44 -v * 93604 / 131072 + 91;
    argb.b = yps +u * 1814 / 1024 - 227;
    argb.a = 255;

uchar4 out = convert_uchar4(clamp(argb, 0, 255));
return out;
}

Lado do Java:

    private Bitmap YUV_420_888_toRGB(Image image, int width, int height){
    // Get the three image planes
    Image.Plane[] planes = image.getPlanes();
    ByteBuffer buffer = planes[0].getBuffer();
    byte[] y = new byte[buffer.remaining()];
    buffer.get(y);

    buffer = planes[1].getBuffer();
    byte[] u = new byte[buffer.remaining()];
    buffer.get(u);

    buffer = planes[2].getBuffer();
    byte[] v = new byte[buffer.remaining()];
    buffer.get(v);

    // get the relevant RowStrides and PixelStrides
    // (we know from documentation that PixelStride is 1 for y)
    int yRowStride= planes[0].getRowStride();
    int uvRowStride= planes[1].getRowStride();  // we know from   documentation that RowStride is the same for u and v.
    int uvPixelStride= planes[1].getPixelStride();  // we know from   documentation that PixelStride is the same for u and v.


    // rs creation just for demo. Create rs just once in onCreate and use it again.
    RenderScript rs = RenderScript.create(this);
    //RenderScript rs = MainActivity.rs;
    ScriptC_yuv420888 mYuv420=new ScriptC_yuv420888 (rs);

    // Y,U,V are defined as global allocations, the out-Allocation is the Bitmap.
    // Note also that uAlloc and vAlloc are 1-dimensional while yAlloc is 2-dimensional.
    Type.Builder typeUcharY = new Type.Builder(rs, Element.U8(rs));
    typeUcharY.setX(yRowStride).setY(height);
    Allocation yAlloc = Allocation.createTyped(rs, typeUcharY.create());
    yAlloc.copyFrom(y);
    mYuv420.set_ypsIn(yAlloc);

    Type.Builder typeUcharUV = new Type.Builder(rs, Element.U8(rs));
    // note that the size of the u's and v's are as follows:
    //      (  (width/2)*PixelStride + padding  ) * (height/2)
    // =    (RowStride                          ) * (height/2)
    // but I noted that on the S7 it is 1 less...
    typeUcharUV.setX(u.length);
    Allocation uAlloc = Allocation.createTyped(rs, typeUcharUV.create());
    uAlloc.copyFrom(u);
    mYuv420.set_uIn(uAlloc);

    Allocation vAlloc = Allocation.createTyped(rs, typeUcharUV.create());
    vAlloc.copyFrom(v);
    mYuv420.set_vIn(vAlloc);

    // handover parameters
    mYuv420.set_picWidth(width);
    mYuv420.set_uvRowStride (uvRowStride);
    mYuv420.set_uvPixelStride (uvPixelStride);

    Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Allocation outAlloc = Allocation.createFromBitmap(rs, outBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);

    Script.LaunchOptions lo = new Script.LaunchOptions();
    lo.setX(0, width);  // by this we ignore the y’s padding zone, i.e. the right side of x between width and yRowStride
    lo.setY(0, height);

    mYuv420.forEach_doConvert(outAlloc,lo);
    outAlloc.copyTo(outBitmap);

    return outBitmap;
}

Testando no Nexus 7 (API 22), isso retorna bitmaps de cores agradáveis. Este dispositivo, no entanto, possui passada de pixel trivial (= 1) e nenhum preenchimento (isto é, linha de largada = largura). Testando na nova Samsung S7 (API 23), recebo fotos cujas cores não estão corretas - exceto as verdes. Mas a imagem não mostra um viés geral em relação ao verde, apenas parece que cores não verdes não são reproduzidas corretamente. Observe que o S7 aplica uma passada de pixel u / v de 2 e sem preenchimento.

Como a linha de código mais crucial está dentro do código rs, o acesso dos planos u / v uint uvIndex = (...) eu acho que poderia haver o problema, provavelmente com a consideração incorreta das passadas de pixel aqui. Alguém vê a solução? Obrigado.

UPDATE: Verifiquei tudo e tenho certeza de que o código referente ao acesso de y, u, v está correto. Portanto, o problema deve estar com os valores u e v. As cores não verdes têm uma inclinação roxa e, olhando para os valores u, v, elas parecem estar em uma faixa bastante estreita de cerca de 110-150. É realmente possível que precisemos lidar com conversões YUV -> RBG específicas do dispositivo ...?! Eu perdi alguma coisa?

ATUALIZAÇÃO 2: com o código corrigido, ele funciona agora, graças ao feedback do Eddy.

questionAnswers(5)

yourAnswerToTheQuestion