ImageWriter: Do not override UNKNOWN format twice

Currently when application calls ImageWriter.newInstance(Surface, int,
int), the default format of UNKNOWN is overridden to surface format in
Java side before being overridden again to user specified format (from
RGBA to IMPLEMENTATION_DEFINED). This breaks backward compatibility with
certain gralloc implementations.

Do not override UNKNOWN format in Java side.

Test: testWriterFormatOverride
Bug: 143637345
Change-Id: Ie61157bca11f623eff2b8c0ed2a988c86da07cb2
diff --git a/media/java/android/media/ImageWriter.java b/media/java/android/media/ImageWriter.java
index f813d1b..7bc2b31 100644
--- a/media/java/android/media/ImageWriter.java
+++ b/media/java/android/media/ImageWriter.java
@@ -192,13 +192,15 @@
 
         mMaxImages = maxImages;
 
-        if (format == ImageFormat.UNKNOWN) {
-            format = SurfaceUtils.getSurfaceFormat(surface);
-        }
         // Note that the underlying BufferQueue is working in synchronous mode
         // to avoid dropping any buffers.
         mNativeContext = nativeInit(new WeakReference<>(this), surface, maxImages, format);
 
+        // nativeInit internally overrides UNKNOWN format. So does surface format query after
+        // nativeInit and before getEstimatedNativeAllocBytes().
+        if (format == ImageFormat.UNKNOWN) {
+            format = SurfaceUtils.getSurfaceFormat(surface);
+        }
         // Estimate the native buffer allocation size and register it so it gets accounted for
         // during GC. Note that this doesn't include the buffers required by the buffer queue
         // itself and the buffers requested by the producer.