Add helper class for dealing with gralloc.

This reverts commit a485a7e60db95039df5de82119e47878372550ac
(which reverts the original version of this CL).

Fixed build errors - put reinterpret_cast around delete [] in
V4L2Gralloc destructor, and fixed missing parens around another
reinterpret cast.

BUG: 29335262
Change-Id: Iaa5a71afef8850ba499cb1a7159a831da4f7014a
diff --git a/modules/camera/3_4/V4L2Camera.cpp b/modules/camera/3_4/V4L2Camera.cpp
index e94a561..f27dc1f 100644
--- a/modules/camera/3_4/V4L2Camera.cpp
+++ b/modules/camera/3_4/V4L2Camera.cpp
@@ -28,6 +28,7 @@
 #include <nativehelper/ScopedFd.h>
 
 #include "Common.h"
+#include "V4L2Gralloc.h"
 
 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
 
@@ -53,6 +54,7 @@
       mOutStreamFormat(0),
       mOutStreamWidth(0),
       mOutStreamHeight(0),
+      mOutStreamBytesPerLine(0),
       mOutStreamMaxBuffers(0),
       mTemplatesInitialized(false),
       mCharacteristicsInitialized(false) {
@@ -112,6 +114,7 @@
   mOutStreamFormat = 0;
   mOutStreamWidth = 0;
   mOutStreamHeight = 0;
+  mOutStreamBytesPerLine = 0;
   mOutStreamMaxBuffers = 0;
 }
 
@@ -308,8 +311,9 @@
     return res;
   }
 
-  // V4L2 doesn't support querying this, so we generously assume up to 3 MB.
-  int32_t max_jpeg_size = 3000000;
+  // V4L2 doesn't support querying this,
+  // so instead use a constant (defined in V4L2Gralloc.h).
+  int32_t max_jpeg_size = V4L2_MAX_JPEG_SIZE;
   res = info.update(ANDROID_JPEG_MAX_SIZE,
                     &max_jpeg_size, 1);
   if (res != android::OK) {
@@ -718,6 +722,21 @@
   HAL_LOG_ENTER();
   int res;
 
+  // Initialize and check the gralloc module.
+  const hw_module_t* module;
+  res = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+  if (res) {
+    HAL_LOGE("Couldn't get gralloc module.");
+    return -ENODEV;
+  }
+  const gralloc_module_t* gralloc =
+      reinterpret_cast<const gralloc_module_t*>(module);
+  mGralloc = V4L2Gralloc(gralloc);
+  if (!mGralloc.isValid()) {
+    HAL_LOGE("Invalid gralloc module.");
+    return -ENODEV;
+  }
+
   // Templates should be set up if they haven't already been.
   if (!mTemplatesInitialized) {
     res = initTemplates();
@@ -1358,6 +1377,7 @@
   mOutStreamFormat = format.fmt.pix.pixelformat;
   mOutStreamWidth = format.fmt.pix.width;
   mOutStreamHeight = format.fmt.pix.height;
+  mOutStreamBytesPerLine = format.fmt.pix.bytesperline;
   // Since our format changed, our maxBuffers may be incorrect.
   mOutStreamMaxBuffers = 0;