Cannot figure out correct color conversion

I trying to get correct color after iProcessor.unpack(), but was puzzled by contents of libraw_colordata_t structure. Suppose that I have already done demosaicing but still have color in camera color space. What formulas do I need to use to convert (R,G,B) -> (X,Y,Z)? I tried these without success:

X = (R - Black) * cam_xyz[0][0] + (G - Black) * cam_xyz[1][0] + (B - Black) * cam_xyz[2][0];
Y = (R - Black) * cam_xyz[0][1] + (G - Black) * cam_xyz[1][1] + (B - Black) * cam_xyz[2][1];
Z = (R - Black) * cam_xyz[0][2] + (G - Black) * cam_xyz[1][2] + (B - Black) * cam_xyz[2][2];

I also noticed cam_mul, pre_mul, cmatrix and rgb_cam member, but not sure how to use them.


1) Black should be subtracted

1) Black should be subtracted before demosaic
2) Look into convert_to_rgb code:
to get output matrix, the rgb_cam matrix is multiplied to color space matrix. The rgb_cam is produced by cam_xyz_coeff() call

-- Alex Tutubalin @LibRaw LLC