libultrahdr: correct srgb, p3 calculations and jpeg yuv handling

* Correct luminance calculation for sRGB to utilize actual luminance
  coefficients for the gamut, rather than 601 luma coefficients.
* Correct YUV<->RGB conversion for sRGB to utilize Rec.709 coefficients
  rather than Rec.601 coefficients as it was previously.
* New P3 YUV<->RGB conversion, which uses Rec.601 coefficients.
* Also ICC Profile fixes to make things work; more below.
* Update things to correctly convert to and from Rec.601 YUV for jpeg
  encoding; more below.

This setup for YUV<->RGB coefficients is chosen to match the
expectations of DataSpace when it comes to interpretting YUV encoding of
data. Generally, the interpretation is cued off of the color primaries,
since the specifications around color primaries generally also specify a
YUV interpretation.

Display-P3 is a bit of an outlier; the best specification of Display-P3
is in SMPTE EG 432-1, but EG 432-1 doesn't cover YUV interpretation. So,
since DataSpace interprets Display-P3 YUV data via the Rec.601
coefficients, we should do the same here.

ICC Profile fixes; ICC profiles we wrote were broken before this for a
variety of reasons:
* The endianness macro wasn't actually swapping endiannesas to provide
  the correct encoding in our output.
* We weren't writing out the identifier for the app segment, including
  the chunk count and ID.
* We were assuming input JPEGs have ICC data, which may not be the case.
* We also need to read in the ICC profile during decode to apply the map
  properly, and we didn't have any mechanism previously to read the ICC
  profile and determine the gamut of the encoded JPEGR file.
* Upon adding ICC reading code to our JPEG decoding, also remove some
  dead code from previous EXIF reading.
* Add a number of tests to verify all of this stuff stays fixed.

YUV interpretation and Rec.601:
* Previously, we were feeding YUV right into the JPEG encoder; this is
  problematic because JPEG encoders usually (and definitely in our
  specific case) expect Rec.601 YUV encoded input data, since this is by
  definition the format of JPEG YUV data according to ECMA TR/98.
* Now properly convert from Rec.709 or Rec.2100 YUV encoding to Rec.601
  (when necessary) prior to passing YUV data to the jpeg encoder.
* Also make sure we properly interpret decoded YUV output as Rec.601
  after decode.
* This involved added some new methods to facilitate these conversions.
* Added some new tests to verify these conversions.
* Note that to do these YUV conversions for subsampled 420 data, we take
  each set of 4 Y and 1 UV, and calculate the result against each
  combination. The new Y values each get the corresponding result, and
  the new UV value is equal to the average of the set.
* Note that none of this is a concern for gain map encoding/decoding via
  JPEG because gain maps are single channel.

Bug: 283143961
Test: added new tests, all tests pass
Change-Id: Ibc7b1779fc3a8244f85abb581c554963f57dc5a4
diff --git a/libs/ultrahdr/icc.cpp b/libs/ultrahdr/icc.cpp
index 32d08aa..1ab3c7c 100644
--- a/libs/ultrahdr/icc.cpp
+++ b/libs/ultrahdr/icc.cpp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+#ifndef USE_BIG_ENDIAN
+#define USE_BIG_ENDIAN true
+#endif
+
 #include <ultrahdr/icc.h>
 #include <ultrahdr/gainmapmath.h>
 #include <vector>
@@ -540,13 +544,21 @@
     size_t tag_table_size = kICCTagTableEntrySize * tags.size();
     size_t profile_size = kICCHeaderSize + tag_table_size + tag_data_size;
 
+    sp<DataStruct> dataStruct = sp<DataStruct>::make(profile_size + kICCIdentifierSize);
+
+    // Write identifier, chunk count, and chunk ID
+    if (!dataStruct->write(kICCIdentifier, sizeof(kICCIdentifier)) ||
+        !dataStruct->write8(1) || !dataStruct->write8(1)) {
+        ALOGE("writeIccProfile(): error in identifier");
+        return dataStruct;
+    }
+
     // Write the header.
     header.data_color_space = Endian_SwapBE32(Signature_RGB);
     header.pcs = Endian_SwapBE32(tf == ULTRAHDR_TF_PQ ? Signature_Lab : Signature_XYZ);
     header.size = Endian_SwapBE32(profile_size);
     header.tag_count = Endian_SwapBE32(tags.size());
 
-    sp<DataStruct> dataStruct = sp<DataStruct>::make(profile_size);
     if (!dataStruct->write(&header, sizeof(header))) {
         ALOGE("writeIccProfile(): error in header");
         return dataStruct;
@@ -582,4 +594,84 @@
     return dataStruct;
 }
 
-} // namespace android::ultrahdr
\ No newline at end of file
+bool IccHelper::tagsEqualToMatrix(const Matrix3x3& matrix,
+                                  const uint8_t* red_tag,
+                                  const uint8_t* green_tag,
+                                  const uint8_t* blue_tag) {
+    sp<DataStruct> red_tag_test = write_xyz_tag(matrix.vals[0][0], matrix.vals[1][0],
+                                                matrix.vals[2][0]);
+    sp<DataStruct> green_tag_test = write_xyz_tag(matrix.vals[0][1], matrix.vals[1][1],
+                                                  matrix.vals[2][1]);
+    sp<DataStruct> blue_tag_test = write_xyz_tag(matrix.vals[0][2], matrix.vals[1][2],
+                                                 matrix.vals[2][2]);
+    return memcmp(red_tag, red_tag_test->getData(), kColorantTagSize) == 0 &&
+           memcmp(green_tag, green_tag_test->getData(), kColorantTagSize) == 0 &&
+           memcmp(blue_tag, blue_tag_test->getData(), kColorantTagSize) == 0;
+}
+
+ultrahdr_color_gamut IccHelper::readIccColorGamut(void* icc_data, size_t icc_size) {
+    // Each tag table entry consists of 3 fields of 4 bytes each.
+    static const size_t kTagTableEntrySize = 12;
+
+    if (icc_data == nullptr || icc_size < sizeof(ICCHeader) + kICCIdentifierSize) {
+        return ULTRAHDR_COLORGAMUT_UNSPECIFIED;
+    }
+
+    if (memcmp(icc_data, kICCIdentifier, sizeof(kICCIdentifier)) != 0) {
+        return ULTRAHDR_COLORGAMUT_UNSPECIFIED;
+    }
+
+    uint8_t* icc_bytes = reinterpret_cast<uint8_t*>(icc_data) + kICCIdentifierSize;
+
+    ICCHeader* header = reinterpret_cast<ICCHeader*>(icc_bytes);
+
+    // Use 0 to indicate not found, since offsets are always relative to start
+    // of ICC data and therefore a tag offset of zero would never be valid.
+    size_t red_primary_offset = 0, green_primary_offset = 0, blue_primary_offset = 0;
+    size_t red_primary_size = 0, green_primary_size = 0, blue_primary_size = 0;
+    for (size_t tag_idx = 0; tag_idx < Endian_SwapBE32(header->tag_count); ++tag_idx) {
+        uint32_t* tag_entry_start = reinterpret_cast<uint32_t*>(
+            icc_bytes + sizeof(ICCHeader) + tag_idx * kTagTableEntrySize);
+        // first 4 bytes are the tag signature, next 4 bytes are the tag offset,
+        // last 4 bytes are the tag length in bytes.
+        if (red_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_rXYZ)) {
+            red_primary_offset = Endian_SwapBE32(*(tag_entry_start+1));
+            red_primary_size = Endian_SwapBE32(*(tag_entry_start+2));
+        } else if (green_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_gXYZ)) {
+            green_primary_offset = Endian_SwapBE32(*(tag_entry_start+1));
+            green_primary_size = Endian_SwapBE32(*(tag_entry_start+2));
+        } else if (blue_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_bXYZ)) {
+            blue_primary_offset = Endian_SwapBE32(*(tag_entry_start+1));
+            blue_primary_size = Endian_SwapBE32(*(tag_entry_start+2));
+        }
+    }
+
+    if (red_primary_offset == 0 || red_primary_size != kColorantTagSize ||
+        kICCIdentifierSize + red_primary_offset + red_primary_size > icc_size ||
+        green_primary_offset == 0 || green_primary_size != kColorantTagSize ||
+        kICCIdentifierSize + green_primary_offset + green_primary_size > icc_size ||
+        blue_primary_offset == 0 || blue_primary_size != kColorantTagSize ||
+        kICCIdentifierSize + blue_primary_offset + blue_primary_size > icc_size) {
+        return ULTRAHDR_COLORGAMUT_UNSPECIFIED;
+    }
+
+    uint8_t* red_tag = icc_bytes + red_primary_offset;
+    uint8_t* green_tag = icc_bytes + green_primary_offset;
+    uint8_t* blue_tag = icc_bytes + blue_primary_offset;
+
+    // Serialize tags as we do on encode and compare what we find to that to
+    // determine the gamut (since we don't have a need yet for full deserialize).
+    if (tagsEqualToMatrix(kSRGB, red_tag, green_tag, blue_tag)) {
+        return ULTRAHDR_COLORGAMUT_BT709;
+    } else if (tagsEqualToMatrix(kDisplayP3, red_tag, green_tag, blue_tag)) {
+        return ULTRAHDR_COLORGAMUT_P3;
+    } else if (tagsEqualToMatrix(kRec2020, red_tag, green_tag, blue_tag)) {
+        return ULTRAHDR_COLORGAMUT_BT2100;
+    }
+
+    // Didn't find a match to one of the profiles we write; indicate the gamut
+    // is unspecified since we don't understand it.
+    return ULTRAHDR_COLORGAMUT_UNSPECIFIED;
+}
+
+} // namespace android::ultrahdr