Revert^2 "Move some image/9patch code to androidfw"

This reverts commit 917043bc2586743afda5a21386893fa8c787800b.

Reason for revert: Roll forward with fix

Test: Automatic
Bug: 296324826
Change-Id: I42a0b48c02fd497b2174c0c65f300265202f7ab1
diff --git a/libs/androidfw/Android.bp b/libs/androidfw/Android.bp
index 47a7f35..2f28363 100644
--- a/libs/androidfw/Android.bp
+++ b/libs/androidfw/Android.bp
@@ -63,15 +63,21 @@
         "AssetsProvider.cpp",
         "AttributeResolution.cpp",
         "BigBuffer.cpp",
+        "BigBufferStream.cpp",
         "ChunkIterator.cpp",
         "ConfigDescription.cpp",
+        "FileStream.cpp",
         "Idmap.cpp",
         "LoadedArsc.cpp",
         "Locale.cpp",
         "LocaleData.cpp",
         "misc.cpp",
+        "NinePatch.cpp",
         "ObbFile.cpp",
         "PosixUtils.cpp",
+        "Png.cpp",
+        "PngChunkFilter.cpp",
+        "PngCrunch.cpp",
         "ResourceTimer.cpp",
         "ResourceTypes.cpp",
         "ResourceUtils.cpp",
@@ -84,7 +90,10 @@
     ],
     export_include_dirs: ["include"],
     export_shared_lib_headers: ["libz"],
-    static_libs: ["libincfs-utils"],
+    static_libs: [
+        "libincfs-utils",
+        "libpng",
+    ],
     whole_static_libs: [
         "libandroidfw_pathutils",
         "libincfs-utils",
@@ -198,9 +207,11 @@
         "tests/ConfigDescription_test.cpp",
         "tests/ConfigLocale_test.cpp",
         "tests/DynamicRefTable_test.cpp",
+        "tests/FileStream_test.cpp",
         "tests/Idmap_test.cpp",
         "tests/LoadedArsc_test.cpp",
         "tests/Locale_test.cpp",
+        "tests/NinePatch_test.cpp",
         "tests/ResourceTimer_test.cpp",
         "tests/ResourceUtils_test.cpp",
         "tests/ResTable_test.cpp",
diff --git a/tools/aapt2/io/BigBufferStream.cpp b/libs/androidfw/BigBufferStream.cpp
similarity index 69%
rename from tools/aapt2/io/BigBufferStream.cpp
rename to libs/androidfw/BigBufferStream.cpp
index 9704caa..f18199c 100644
--- a/tools/aapt2/io/BigBufferStream.cpp
+++ b/libs/androidfw/BigBufferStream.cpp
@@ -14,10 +14,11 @@
  * limitations under the License.
  */
 
-#include "io/BigBufferStream.h"
+#include "androidfw/BigBufferStream.h"
 
-namespace aapt {
-namespace io {
+#include <algorithm>
+
+namespace android {
 
 //
 // BigBufferInputStream
@@ -76,6 +77,34 @@
   return buffer_->size();
 }
 
+bool BigBufferInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) {
+  if (byte_count == 0) {
+    return true;
+  }
+  if (offset < 0) {
+    return false;
+  }
+  if (offset > std::numeric_limits<off64_t>::max() - byte_count) {
+    return false;
+  }
+  if (offset + byte_count > buffer_->size()) {
+    return false;
+  }
+  auto p = reinterpret_cast<uint8_t*>(data);
+  for (auto iter = buffer_->begin(); iter != buffer_->end() && byte_count > 0; ++iter) {
+    if (offset < iter->size) {
+      size_t to_read = std::min(byte_count, (size_t)(iter->size - offset));
+      memcpy(p, iter->buffer.get() + offset, to_read);
+      byte_count -= to_read;
+      p += to_read;
+      offset = 0;
+    } else {
+      offset -= iter->size;
+    }
+  }
+  return byte_count == 0;
+}
+
 //
 // BigBufferOutputStream
 //
@@ -97,5 +126,4 @@
   return false;
 }
 
-}  // namespace io
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/io/FileStream.cpp b/libs/androidfw/FileStream.cpp
similarity index 95%
rename from tools/aapt2/io/FileStream.cpp
rename to libs/androidfw/FileStream.cpp
index 27529bc..b86c9cb 100644
--- a/tools/aapt2/io/FileStream.cpp
+++ b/libs/androidfw/FileStream.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "io/FileStream.h"
+#include "androidfw/FileStream.h"
 
 #include <errno.h>   // for errno
 #include <fcntl.h>   // for O_RDONLY
@@ -34,8 +34,7 @@
 using ::android::base::SystemErrorCodeToString;
 using ::android::base::unique_fd;
 
-namespace aapt {
-namespace io {
+namespace android {
 
 FileInputStream::FileInputStream(const std::string& path, size_t buffer_capacity)
     : buffer_capacity_(buffer_capacity) {
@@ -108,6 +107,10 @@
   return error_;
 }
 
+bool FileInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) {
+  return base::ReadFullyAtOffset(fd_, data, byte_count, offset);
+}
+
 FileOutputStream::FileOutputStream(const std::string& path, size_t buffer_capacity)
     : buffer_capacity_(buffer_capacity) {
   int mode = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY;
@@ -199,5 +202,4 @@
   return error_;
 }
 
-}  // namespace io
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/compile/NinePatch.cpp b/libs/androidfw/NinePatch.cpp
similarity index 80%
rename from tools/aapt2/compile/NinePatch.cpp
rename to libs/androidfw/NinePatch.cpp
index 4538ecc..1fdbebf 100644
--- a/tools/aapt2/compile/NinePatch.cpp
+++ b/libs/androidfw/NinePatch.cpp
@@ -14,20 +14,17 @@
  * limitations under the License.
  */
 
-#include "compile/Image.h"
-
 #include <sstream>
 #include <string>
 #include <vector>
 
+#include "androidfw/Image.h"
 #include "androidfw/ResourceTypes.h"
 #include "androidfw/StringPiece.h"
 
-#include "util/Util.h"
-
 using android::StringPiece;
 
-namespace aapt {
+namespace android {
 
 // Colors in the format 0xAARRGGBB (the way 9-patch expects it).
 constexpr static const uint32_t kColorOpaqueWhite = 0xffffffffu;
@@ -90,10 +87,8 @@
 // };
 //
 template <typename ImageLine>
-static bool FillRanges(const ImageLine* image_line,
-                       const ColorValidator* color_validator,
-                       std::vector<Range>* primary_ranges,
-                       std::vector<Range>* secondary_ranges,
+static bool FillRanges(const ImageLine* image_line, const ColorValidator* color_validator,
+                       std::vector<Range>* primary_ranges, std::vector<Range>* secondary_ranges,
                        std::string* out_err) {
   const int32_t length = image_line->GetLength();
 
@@ -133,11 +128,13 @@
  */
 class HorizontalImageLine {
  public:
-  explicit HorizontalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset,
-                               int32_t length)
-      : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {}
+  explicit HorizontalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t length)
+      : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {
+  }
 
-  inline int32_t GetLength() const { return length_; }
+  inline int32_t GetLength() const {
+    return length_;
+  }
 
   inline uint32_t GetColor(int32_t idx) const {
     return NinePatch::PackRGBA(rows_[yoffset_] + (idx + xoffset_) * 4);
@@ -156,11 +153,13 @@
  */
 class VerticalImageLine {
  public:
-  explicit VerticalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset,
-                             int32_t length)
-      : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {}
+  explicit VerticalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t length)
+      : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {
+  }
 
-  inline int32_t GetLength() const { return length_; }
+  inline int32_t GetLength() const {
+    return length_;
+  }
 
   inline uint32_t GetColor(int32_t idx) const {
     return NinePatch::PackRGBA(rows_[yoffset_ + idx] + (xoffset_ * 4));
@@ -175,20 +174,22 @@
 
 class DiagonalImageLine {
  public:
-  explicit DiagonalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset,
-                             int32_t xstep, int32_t ystep, int32_t length)
+  explicit DiagonalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t xstep,
+                             int32_t ystep, int32_t length)
       : rows_(rows),
         xoffset_(xoffset),
         yoffset_(yoffset),
         xstep_(xstep),
         ystep_(ystep),
-        length_(length) {}
+        length_(length) {
+  }
 
-  inline int32_t GetLength() const { return length_; }
+  inline int32_t GetLength() const {
+    return length_;
+  }
 
   inline uint32_t GetColor(int32_t idx) const {
-    return NinePatch::PackRGBA(rows_[yoffset_ + (idx * ystep_)] +
-                               ((idx + xoffset_) * xstep_) * 4);
+    return NinePatch::PackRGBA(rows_[yoffset_ + (idx * ystep_)] + ((idx + xoffset_) * xstep_) * 4);
   }
 
  private:
@@ -243,8 +244,7 @@
 
   if (layout_bounds.size() > 2) {
     std::stringstream err_stream;
-    err_stream << "too many layout bounds sections on " << edge_name
-               << " border";
+    err_stream << "too many layout bounds sections on " << edge_name << " border";
     *out_err = err_stream.str();
     return false;
   }
@@ -258,8 +258,7 @@
     // end at length.
     if (range.start != 0 && range.end != length) {
       std::stringstream err_stream;
-      err_stream << "layout bounds on " << edge_name
-                 << " border must start at edge";
+      err_stream << "layout bounds on " << edge_name << " border must start at edge";
       *out_err = err_stream.str();
       return false;
     }
@@ -269,8 +268,7 @@
       const Range& range = layout_bounds.back();
       if (range.end != length) {
         std::stringstream err_stream;
-        err_stream << "layout bounds on " << edge_name
-                   << " border must start at edge";
+        err_stream << "layout bounds on " << edge_name << " border must start at edge";
         *out_err = err_stream.str();
         return false;
       }
@@ -280,8 +278,7 @@
   return true;
 }
 
-static int32_t CalculateSegmentCount(const std::vector<Range>& stretch_regions,
-                                     int32_t length) {
+static int32_t CalculateSegmentCount(const std::vector<Range>& stretch_regions, int32_t length) {
   if (stretch_regions.size() == 0) {
     return 0;
   }
@@ -299,8 +296,7 @@
 
 static uint32_t GetRegionColor(uint8_t** rows, const Bounds& region) {
   // Sample the first pixel to compare against.
-  const uint32_t expected_color =
-      NinePatch::PackRGBA(rows[region.top] + region.left * 4);
+  const uint32_t expected_color = NinePatch::PackRGBA(rows[region.top] + region.left * 4);
   for (int32_t y = region.top; y < region.bottom; y++) {
     const uint8_t* row = rows[y];
     for (int32_t x = region.left; x < region.right; x++) {
@@ -336,10 +332,11 @@
 // the indices must be offset by 1.
 //
 // width and height also include the 9-patch 1px border.
-static void CalculateRegionColors(
-    uint8_t** rows, const std::vector<Range>& horizontal_stretch_regions,
-    const std::vector<Range>& vertical_stretch_regions, const int32_t width,
-    const int32_t height, std::vector<uint32_t>* out_colors) {
+static void CalculateRegionColors(uint8_t** rows,
+                                  const std::vector<Range>& horizontal_stretch_regions,
+                                  const std::vector<Range>& vertical_stretch_regions,
+                                  const int32_t width, const int32_t height,
+                                  std::vector<uint32_t>* out_colors) {
   int32_t next_top = 0;
   Bounds bounds;
   auto row_iter = vertical_stretch_regions.begin();
@@ -401,8 +398,7 @@
 // alpha value begins
 // (on both sides).
 template <typename ImageLine>
-static void FindOutlineInsets(const ImageLine* image_line, int32_t* out_start,
-                              int32_t* out_end) {
+static void FindOutlineInsets(const ImageLine* image_line, int32_t* out_start, int32_t* out_end) {
   *out_start = 0;
   *out_end = 0;
 
@@ -455,10 +451,8 @@
   return (pixel[3] << 24) | (pixel[0] << 16) | (pixel[1] << 8) | pixel[2];
 }
 
-std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows,
-                                             const int32_t width,
-                                             const int32_t height,
-                                             std::string* out_err) {
+std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width,
+                                             const int32_t height, std::string* out_err) {
   if (width < 3 || height < 3) {
     *out_err = "image must be at least 3x3 (1x1 image with 1 pixel border)";
     return {};
@@ -472,12 +466,11 @@
   std::unique_ptr<ColorValidator> color_validator;
 
   if (rows[0][3] == 0) {
-    color_validator = util::make_unique<TransparentNeutralColorValidator>();
+    color_validator = std::make_unique<TransparentNeutralColorValidator>();
   } else if (PackRGBA(rows[0]) == kColorOpaqueWhite) {
-    color_validator = util::make_unique<WhiteNeutralColorValidator>();
+    color_validator = std::make_unique<WhiteNeutralColorValidator>();
   } else {
-    *out_err =
-        "top-left corner pixel must be either opaque white or transparent";
+    *out_err = "top-left corner pixel must be either opaque white or transparent";
     return {};
   }
 
@@ -485,9 +478,8 @@
   auto nine_patch = std::unique_ptr<NinePatch>(new NinePatch());
 
   HorizontalImageLine top_row(rows, 0, 0, width);
-  if (!FillRanges(&top_row, color_validator.get(),
-                  &nine_patch->horizontal_stretch_regions, &unexpected_ranges,
-                  out_err)) {
+  if (!FillRanges(&top_row, color_validator.get(), &nine_patch->horizontal_stretch_regions,
+                  &unexpected_ranges, out_err)) {
     return {};
   }
 
@@ -501,9 +493,8 @@
   }
 
   VerticalImageLine left_col(rows, 0, 0, height);
-  if (!FillRanges(&left_col, color_validator.get(),
-                  &nine_patch->vertical_stretch_regions, &unexpected_ranges,
-                  out_err)) {
+  if (!FillRanges(&left_col, color_validator.get(), &nine_patch->vertical_stretch_regions,
+                  &unexpected_ranges, out_err)) {
     return {};
   }
 
@@ -522,32 +513,28 @@
   }
 
   if (!PopulateBounds(horizontal_padding, horizontal_layout_bounds,
-                      nine_patch->horizontal_stretch_regions, width - 2,
-                      &nine_patch->padding.left, &nine_patch->padding.right,
-                      &nine_patch->layout_bounds.left,
+                      nine_patch->horizontal_stretch_regions, width - 2, &nine_patch->padding.left,
+                      &nine_patch->padding.right, &nine_patch->layout_bounds.left,
                       &nine_patch->layout_bounds.right, "bottom", out_err)) {
     return {};
   }
 
   VerticalImageLine right_col(rows, width - 1, 0, height);
-  if (!FillRanges(&right_col, color_validator.get(), &vertical_padding,
-                  &vertical_layout_bounds, out_err)) {
+  if (!FillRanges(&right_col, color_validator.get(), &vertical_padding, &vertical_layout_bounds,
+                  out_err)) {
     return {};
   }
 
   if (!PopulateBounds(vertical_padding, vertical_layout_bounds,
-                      nine_patch->vertical_stretch_regions, height - 2,
-                      &nine_patch->padding.top, &nine_patch->padding.bottom,
-                      &nine_patch->layout_bounds.top,
+                      nine_patch->vertical_stretch_regions, height - 2, &nine_patch->padding.top,
+                      &nine_patch->padding.bottom, &nine_patch->layout_bounds.top,
                       &nine_patch->layout_bounds.bottom, "right", out_err)) {
     return {};
   }
 
   // Fill the region colors of the 9-patch.
-  const int32_t num_rows =
-      CalculateSegmentCount(nine_patch->horizontal_stretch_regions, width - 2);
-  const int32_t num_cols =
-      CalculateSegmentCount(nine_patch->vertical_stretch_regions, height - 2);
+  const int32_t num_rows = CalculateSegmentCount(nine_patch->horizontal_stretch_regions, width - 2);
+  const int32_t num_cols = CalculateSegmentCount(nine_patch->vertical_stretch_regions, height - 2);
   if ((int64_t)num_rows * (int64_t)num_cols > 0x7f) {
     *out_err = "too many regions in 9-patch";
     return {};
@@ -555,40 +542,35 @@
 
   nine_patch->region_colors.reserve(num_rows * num_cols);
   CalculateRegionColors(rows, nine_patch->horizontal_stretch_regions,
-                        nine_patch->vertical_stretch_regions, width - 2,
-                        height - 2, &nine_patch->region_colors);
+                        nine_patch->vertical_stretch_regions, width - 2, height - 2,
+                        &nine_patch->region_colors);
 
   // Compute the outline based on opacity.
 
   // Find left and right extent of 9-patch content on center row.
   HorizontalImageLine mid_row(rows, 1, height / 2, width - 2);
-  FindOutlineInsets(&mid_row, &nine_patch->outline.left,
-                    &nine_patch->outline.right);
+  FindOutlineInsets(&mid_row, &nine_patch->outline.left, &nine_patch->outline.right);
 
   // Find top and bottom extent of 9-patch content on center column.
   VerticalImageLine mid_col(rows, width / 2, 1, height - 2);
-  FindOutlineInsets(&mid_col, &nine_patch->outline.top,
-                    &nine_patch->outline.bottom);
+  FindOutlineInsets(&mid_col, &nine_patch->outline.top, &nine_patch->outline.bottom);
 
-  const int32_t outline_width =
-      (width - 2) - nine_patch->outline.left - nine_patch->outline.right;
+  const int32_t outline_width = (width - 2) - nine_patch->outline.left - nine_patch->outline.right;
   const int32_t outline_height =
       (height - 2) - nine_patch->outline.top - nine_patch->outline.bottom;
 
   // Find the largest alpha value within the outline area.
-  HorizontalImageLine outline_mid_row(
-      rows, 1 + nine_patch->outline.left,
-      1 + nine_patch->outline.top + (outline_height / 2), outline_width);
-  VerticalImageLine outline_mid_col(
-      rows, 1 + nine_patch->outline.left + (outline_width / 2),
-      1 + nine_patch->outline.top, outline_height);
+  HorizontalImageLine outline_mid_row(rows, 1 + nine_patch->outline.left,
+                                      1 + nine_patch->outline.top + (outline_height / 2),
+                                      outline_width);
+  VerticalImageLine outline_mid_col(rows, 1 + nine_patch->outline.left + (outline_width / 2),
+                                    1 + nine_patch->outline.top, outline_height);
   nine_patch->outline_alpha =
       std::max(FindMaxAlpha(&outline_mid_row), FindMaxAlpha(&outline_mid_col));
 
   // Assuming the image is a round rect, compute the radius by marching
   // diagonally from the top left corner towards the center.
-  DiagonalImageLine diagonal(rows, 1 + nine_patch->outline.left,
-                             1 + nine_patch->outline.top, 1, 1,
+  DiagonalImageLine diagonal(rows, 1 + nine_patch->outline.left, 1 + nine_patch->outline.top, 1, 1,
                              std::min(outline_width, outline_height));
   int32_t top_left, bottom_right;
   FindOutlineInsets(&diagonal, &top_left, &bottom_right);
@@ -614,10 +596,9 @@
   data.paddingBottom = padding.bottom;
 
   auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[data.serializedSize()]);
-  android::Res_png_9patch::serialize(
-      data, (const int32_t*)horizontal_stretch_regions.data(),
-      (const int32_t*)vertical_stretch_regions.data(), region_colors.data(),
-      buffer.get());
+  android::Res_png_9patch::serialize(data, (const int32_t*)horizontal_stretch_regions.data(),
+                                     (const int32_t*)vertical_stretch_regions.data(),
+                                     region_colors.data(), buffer.get());
   // Convert to file endianness.
   reinterpret_cast<android::Res_png_9patch*>(buffer.get())->deviceToFile();
 
@@ -625,8 +606,7 @@
   return buffer;
 }
 
-std::unique_ptr<uint8_t[]> NinePatch::SerializeLayoutBounds(
-    size_t* out_len) const {
+std::unique_ptr<uint8_t[]> NinePatch::SerializeLayoutBounds(size_t* out_len) const {
   size_t chunk_len = sizeof(uint32_t) * 4;
   auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[chunk_len]);
   uint8_t* cursor = buffer.get();
@@ -647,8 +627,7 @@
   return buffer;
 }
 
-std::unique_ptr<uint8_t[]> NinePatch::SerializeRoundedRectOutline(
-    size_t* out_len) const {
+std::unique_ptr<uint8_t[]> NinePatch::SerializeRoundedRectOutline(size_t* out_len) const {
   size_t chunk_len = sizeof(uint32_t) * 6;
   auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[chunk_len]);
   uint8_t* cursor = buffer.get();
@@ -679,20 +658,25 @@
 }
 
 ::std::ostream& operator<<(::std::ostream& out, const Bounds& bounds) {
-  return out << "l=" << bounds.left << " t=" << bounds.top
-             << " r=" << bounds.right << " b=" << bounds.bottom;
+  return out << "l=" << bounds.left << " t=" << bounds.top << " r=" << bounds.right
+             << " b=" << bounds.bottom;
+}
+
+template <typename T>
+std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
+  for (int i = 0; i < v.size(); ++i) {
+    os << v[i];
+    if (i != v.size() - 1) os << " ";
+  }
+  return os;
 }
 
 ::std::ostream& operator<<(::std::ostream& out, const NinePatch& nine_patch) {
-  return out << "horizontalStretch:"
-             << util::Joiner(nine_patch.horizontal_stretch_regions, " ")
-             << " verticalStretch:"
-             << util::Joiner(nine_patch.vertical_stretch_regions, " ")
-             << " padding: " << nine_patch.padding
-             << ", bounds: " << nine_patch.layout_bounds
-             << ", outline: " << nine_patch.outline
-             << " rad=" << nine_patch.outline_radius
+  return out << "horizontalStretch:" << nine_patch.horizontal_stretch_regions
+             << " verticalStretch:" << nine_patch.vertical_stretch_regions
+             << " padding: " << nine_patch.padding << ", bounds: " << nine_patch.layout_bounds
+             << ", outline: " << nine_patch.outline << " rad=" << nine_patch.outline_radius
              << " alpha=" << nine_patch.outline_alpha;
 }
 
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/compile/Png.cpp b/libs/androidfw/Png.cpp
similarity index 77%
rename from tools/aapt2/compile/Png.cpp
rename to libs/androidfw/Png.cpp
index 76db815..fb45cd9 100644
--- a/tools/aapt2/compile/Png.cpp
+++ b/libs/androidfw/Png.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "Png.h"
+#include "androidfw/Png.h"
 
 #include <png.h>
 #include <zlib.h>
@@ -24,13 +24,12 @@
 #include <string>
 #include <vector>
 
+#include "android-base/strings.h"
 #include "androidfw/BigBuffer.h"
 #include "androidfw/ResourceTypes.h"
 #include "androidfw/Source.h"
-#include "trace/TraceBuffer.h"
-#include "util/Util.h"
 
-namespace aapt {
+namespace android {
 
 constexpr bool kDebug = false;
 
@@ -47,9 +46,8 @@
   }
 
   void* serialize9Patch() {
-    void* serialized = android::Res_png_9patch::serialize(info9Patch, xDivs,
-                                                          yDivs, colors.data());
-    reinterpret_cast<android::Res_png_9patch*>(serialized)->deviceToFile();
+    void* serialized = Res_png_9patch::serialize(info9Patch, xDivs, yDivs, colors.data());
+    reinterpret_cast<Res_png_9patch*>(serialized)->deviceToFile();
     return serialized;
   }
 
@@ -58,7 +56,7 @@
   std::vector<png_bytep> rows;
 
   bool is9Patch = false;
-  android::Res_png_9patch info9Patch;
+  Res_png_9patch info9Patch;
   int32_t* xDivs = nullptr;
   int32_t* yDivs = nullptr;
   std::vector<uint32_t> colors;
@@ -79,34 +77,30 @@
   uint8_t outlineAlpha;
 };
 
-static void readDataFromStream(png_structp readPtr, png_bytep data,
-                               png_size_t length) {
-  std::istream* input =
-      reinterpret_cast<std::istream*>(png_get_io_ptr(readPtr));
+static void readDataFromStream(png_structp readPtr, png_bytep data, png_size_t length) {
+  std::istream* input = reinterpret_cast<std::istream*>(png_get_io_ptr(readPtr));
   if (!input->read(reinterpret_cast<char*>(data), length)) {
     png_error(readPtr, strerror(errno));
   }
 }
 
-static void writeDataToStream(png_structp writePtr, png_bytep data,
-                              png_size_t length) {
-  android::BigBuffer* outBuffer = reinterpret_cast<android::BigBuffer*>(png_get_io_ptr(writePtr));
+static void writeDataToStream(png_structp writePtr, png_bytep data, png_size_t length) {
+  BigBuffer* outBuffer = reinterpret_cast<BigBuffer*>(png_get_io_ptr(writePtr));
   png_bytep buf = outBuffer->NextBlock<png_byte>(length);
   memcpy(buf, data, length);
 }
 
-static void flushDataToStream(png_structp /*writePtr*/) {}
-
-static void logWarning(png_structp readPtr, png_const_charp warningMessage) {
-  android::IDiagnostics* diag =
-      reinterpret_cast<android::IDiagnostics*>(png_get_error_ptr(readPtr));
-  diag->Warn(android::DiagMessage() << warningMessage);
+static void flushDataToStream(png_structp /*writePtr*/) {
 }
 
-static bool readPng(android::IDiagnostics* diag, png_structp readPtr, png_infop infoPtr,
-                    PngInfo* outInfo) {
+static void logWarning(png_structp readPtr, png_const_charp warningMessage) {
+  IDiagnostics* diag = reinterpret_cast<IDiagnostics*>(png_get_error_ptr(readPtr));
+  diag->Warn(DiagMessage() << warningMessage);
+}
+
+static bool readPng(IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, PngInfo* outInfo) {
   if (setjmp(png_jmpbuf(readPtr))) {
-    diag->Error(android::DiagMessage() << "failed reading png");
+    diag->Error(DiagMessage() << "failed reading png");
     return false;
   }
 
@@ -114,8 +108,8 @@
   png_read_info(readPtr, infoPtr);
 
   int colorType, bitDepth, interlaceType, compressionType;
-  png_get_IHDR(readPtr, infoPtr, &outInfo->width, &outInfo->height, &bitDepth,
-               &colorType, &interlaceType, &compressionType, nullptr);
+  png_get_IHDR(readPtr, infoPtr, &outInfo->width, &outInfo->height, &bitDepth, &colorType,
+               &interlaceType, &compressionType, nullptr);
 
   if (colorType == PNG_COLOR_TYPE_PALETTE) {
     png_set_palette_to_rgb(readPtr);
@@ -137,8 +131,7 @@
     png_set_add_alpha(readPtr, 0xFF, PNG_FILLER_AFTER);
   }
 
-  if (colorType == PNG_COLOR_TYPE_GRAY ||
-      colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
+  if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
     png_set_gray_to_rgb(readPtr);
   }
 
@@ -156,12 +149,11 @@
   return true;
 }
 
-static void checkNinePatchSerialization(android::Res_png_9patch* inPatch,
-                                        void* data) {
+static void checkNinePatchSerialization(Res_png_9patch* inPatch, void* data) {
   size_t patchSize = inPatch->serializedSize();
   void* newData = malloc(patchSize);
   memcpy(newData, data, patchSize);
-  android::Res_png_9patch* outPatch = inPatch->deserialize(newData);
+  Res_png_9patch* outPatch = inPatch->deserialize(newData);
   outPatch->fileToDevice();
   // deserialization is done in place, so outPatch == newData
   assert(outPatch == newData);
@@ -244,10 +236,9 @@
 #define MAX(a, b) ((a) > (b) ? (a) : (b))
 #define ABS(a) ((a) < 0 ? -(a) : (a))
 
-static void analyze_image(android::IDiagnostics* diag, const PngInfo& imageInfo,
-                          int grayscaleTolerance, png_colorp rgbPalette, png_bytep alphaPalette,
-                          int* paletteEntries, bool* hasTransparency, int* colorType,
-                          png_bytepp outRows) {
+static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int grayscaleTolerance,
+                          png_colorp rgbPalette, png_bytep alphaPalette, int* paletteEntries,
+                          bool* hasTransparency, int* colorType, png_bytepp outRows) {
   int w = imageInfo.width;
   int h = imageInfo.height;
   int i, j, rr, gg, bb, aa, idx;
@@ -284,8 +275,8 @@
       maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
       if (maxGrayDeviation > odev) {
         if (kDebug) {
-          printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
-                 maxGrayDeviation, i, j, rr, gg, bb, aa);
+          printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n", maxGrayDeviation, i, j,
+                 rr, gg, bb, aa);
         }
       }
 
@@ -293,8 +284,7 @@
       if (isGrayscale) {
         if (rr != gg || rr != bb) {
           if (kDebug) {
-            printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", i, j,
-                   rr, gg, bb, aa);
+            printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", i, j, rr, gg, bb, aa);
           }
           isGrayscale = false;
         }
@@ -304,8 +294,7 @@
       if (isOpaque) {
         if (aa != 0xff) {
           if (kDebug) {
-            printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", i, j,
-                   rr, gg, bb, aa);
+            printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", i, j, rr, gg, bb, aa);
           }
           isOpaque = false;
         }
@@ -349,10 +338,9 @@
     printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
     printf("isOpaque = %s\n", isOpaque ? "true" : "false");
     printf("isPalette = %s\n", isPalette ? "true" : "false");
-    printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", paletteSize,
-           2 * w * h, bpp * w * h);
-    printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation,
-           grayscaleTolerance);
+    printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", paletteSize, 2 * w * h,
+           bpp * w * h);
+    printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
   }
 
   // Choose the best color type for the image.
@@ -381,8 +369,8 @@
     *colorType = PNG_COLOR_TYPE_PALETTE;
   } else {
     if (maxGrayDeviation <= grayscaleTolerance) {
-      diag->Note(android::DiagMessage()
-                 << "forcing image to gray (max deviation = " << maxGrayDeviation << ")");
+      diag->Note(DiagMessage() << "forcing image to gray (max deviation = " << maxGrayDeviation
+                               << ")");
       *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
     } else {
       *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
@@ -404,8 +392,7 @@
       rgbPalette[idx].blue = (png_byte)((col >> 8) & 0xff);
       alphaPalette[idx] = (png_byte)(col & 0xff);
     }
-  } else if (*colorType == PNG_COLOR_TYPE_GRAY ||
-             *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
+  } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
     // If the image is gray or gray + alpha, compact the pixels into outRows
     for (j = 0; j < h; j++) {
       const png_byte* row = imageInfo.rows[j];
@@ -429,10 +416,10 @@
   }
 }
 
-static bool writePng(android::IDiagnostics* diag, png_structp writePtr, png_infop infoPtr,
-                     PngInfo* info, int grayScaleTolerance) {
+static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr, PngInfo* info,
+                     int grayScaleTolerance) {
   if (setjmp(png_jmpbuf(writePtr))) {
-    diag->Error(android::DiagMessage() << "failed to write png");
+    diag->Error(DiagMessage() << "failed to write png");
     return false;
   }
 
@@ -444,8 +431,7 @@
   unknowns[1].data = nullptr;
   unknowns[2].data = nullptr;
 
-  png_bytepp outRows =
-      (png_bytepp)malloc((int)info->height * sizeof(png_bytep));
+  png_bytepp outRows = (png_bytepp)malloc((int)info->height * sizeof(png_bytep));
   if (outRows == (png_bytepp)0) {
     printf("Can't allocate output buffer!\n");
     exit(1);
@@ -461,8 +447,7 @@
   png_set_compression_level(writePtr, Z_BEST_COMPRESSION);
 
   if (kDebug) {
-    diag->Note(android::DiagMessage()
-               << "writing image: w = " << info->width << ", h = " << info->height);
+    diag->Note(DiagMessage() << "writing image: w = " << info->width << ", h = " << info->height);
   }
 
   png_color rgbPalette[256];
@@ -470,48 +455,45 @@
   bool hasTransparency;
   int paletteEntries;
 
-  analyze_image(diag, *info, grayScaleTolerance, rgbPalette, alphaPalette,
-                &paletteEntries, &hasTransparency, &colorType, outRows);
+  analyze_image(diag, *info, grayScaleTolerance, rgbPalette, alphaPalette, &paletteEntries,
+                &hasTransparency, &colorType, outRows);
 
   // If the image is a 9-patch, we need to preserve it as a ARGB file to make
   // sure the pixels will not be pre-dithered/clamped until we decide they are
-  if (info->is9Patch &&
-      (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY ||
-       colorType == PNG_COLOR_TYPE_PALETTE)) {
+  if (info->is9Patch && (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY ||
+                         colorType == PNG_COLOR_TYPE_PALETTE)) {
     colorType = PNG_COLOR_TYPE_RGB_ALPHA;
   }
 
   if (kDebug) {
     switch (colorType) {
       case PNG_COLOR_TYPE_PALETTE:
-        diag->Note(android::DiagMessage() << "has " << paletteEntries << " colors"
-                                          << (hasTransparency ? " (with alpha)" : "")
-                                          << ", using PNG_COLOR_TYPE_PALLETTE");
+        diag->Note(DiagMessage() << "has " << paletteEntries << " colors"
+                                 << (hasTransparency ? " (with alpha)" : "")
+                                 << ", using PNG_COLOR_TYPE_PALLETTE");
         break;
       case PNG_COLOR_TYPE_GRAY:
-        diag->Note(android::DiagMessage() << "is opaque gray, using PNG_COLOR_TYPE_GRAY");
+        diag->Note(DiagMessage() << "is opaque gray, using PNG_COLOR_TYPE_GRAY");
         break;
       case PNG_COLOR_TYPE_GRAY_ALPHA:
-        diag->Note(android::DiagMessage() << "is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA");
+        diag->Note(DiagMessage() << "is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA");
         break;
       case PNG_COLOR_TYPE_RGB:
-        diag->Note(android::DiagMessage() << "is opaque RGB, using PNG_COLOR_TYPE_RGB");
+        diag->Note(DiagMessage() << "is opaque RGB, using PNG_COLOR_TYPE_RGB");
         break;
       case PNG_COLOR_TYPE_RGB_ALPHA:
-        diag->Note(android::DiagMessage() << "is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA");
+        diag->Note(DiagMessage() << "is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA");
         break;
     }
   }
 
-  png_set_IHDR(writePtr, infoPtr, info->width, info->height, 8, colorType,
-               PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
-               PNG_FILTER_TYPE_DEFAULT);
+  png_set_IHDR(writePtr, infoPtr, info->width, info->height, 8, colorType, PNG_INTERLACE_NONE,
+               PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
 
   if (colorType == PNG_COLOR_TYPE_PALETTE) {
     png_set_PLTE(writePtr, infoPtr, rgbPalette, paletteEntries);
     if (hasTransparency) {
-      png_set_tRNS(writePtr, infoPtr, alphaPalette, paletteEntries,
-                   (png_color_16p)0);
+      png_set_tRNS(writePtr, infoPtr, alphaPalette, paletteEntries, (png_color_16p)0);
     }
     png_set_filter(writePtr, 0, PNG_NO_FILTERS);
   } else {
@@ -526,13 +508,12 @@
 
     // Chunks ordered thusly because older platforms depend on the base 9 patch
     // data being last
-    png_bytep chunkNames = info->haveLayoutBounds
-                               ? (png_bytep) "npOl\0npLb\0npTc\0"
-                               : (png_bytep) "npOl\0npTc";
+    png_bytep chunkNames =
+        info->haveLayoutBounds ? (png_bytep) "npOl\0npLb\0npTc\0" : (png_bytep) "npOl\0npTc";
 
     // base 9 patch data
     if (kDebug) {
-      diag->Note(android::DiagMessage() << "adding 9-patch info..");
+      diag->Note(DiagMessage() << "adding 9-patch info..");
     }
     memcpy((char*)unknowns[pIndex].name, "npTc", 5);
     unknowns[pIndex].data = (png_byte*)info->serialize9Patch();
@@ -563,8 +544,7 @@
     for (int i = 0; i < chunkCount; i++) {
       unknowns[i].location = PNG_HAVE_PLTE;
     }
-    png_set_keep_unknown_chunks(writePtr, PNG_HANDLE_CHUNK_ALWAYS, chunkNames,
-                                chunkCount);
+    png_set_keep_unknown_chunks(writePtr, PNG_HANDLE_CHUNK_ALWAYS, chunkNames, chunkCount);
     png_set_unknown_chunks(writePtr, infoPtr, unknowns, chunkCount);
 
 #if PNG_LIBPNG_VER < 10600
@@ -579,8 +559,7 @@
   png_write_info(writePtr, infoPtr);
 
   png_bytepp rows;
-  if (colorType == PNG_COLOR_TYPE_RGB ||
-      colorType == PNG_COLOR_TYPE_RGB_ALPHA) {
+  if (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_RGB_ALPHA) {
     if (colorType == PNG_COLOR_TYPE_RGB) {
       png_set_filler(writePtr, 0, PNG_FILLER_AFTER);
     }
@@ -605,14 +584,13 @@
   free(unknowns[1].data);
   free(unknowns[2].data);
 
-  png_get_IHDR(writePtr, infoPtr, &width, &height, &bitDepth, &colorType,
-               &interlaceType, &compressionType, nullptr);
+  png_get_IHDR(writePtr, infoPtr, &width, &height, &bitDepth, &colorType, &interlaceType,
+               &compressionType, nullptr);
 
   if (kDebug) {
-    diag->Note(android::DiagMessage()
-               << "image written: w = " << width << ", h = " << height << ", d = " << bitDepth
-               << ", colors = " << colorType << ", inter = " << interlaceType
-               << ", comp = " << compressionType);
+    diag->Note(DiagMessage() << "image written: w = " << width << ", h = " << height
+                             << ", d = " << bitDepth << ", colors = " << colorType
+                             << ", inter = " << interlaceType << ", comp = " << compressionType);
   }
   return true;
 }
@@ -673,9 +651,8 @@
 
 enum class TickState { kStart, kInside1, kOutside1 };
 
-static bool getHorizontalTicks(png_bytep row, int width, bool transparent,
-                               bool required, int32_t* outLeft,
-                               int32_t* outRight, const char** outError,
+static bool getHorizontalTicks(png_bytep row, int width, bool transparent, bool required,
+                               int32_t* outLeft, int32_t* outRight, const char** outError,
                                uint8_t* outDivs, bool multipleAllowed) {
   *outLeft = *outRight = -1;
   TickState state = TickState::kStart;
@@ -683,8 +660,7 @@
 
   for (int i = 1; i < width - 1; i++) {
     if (tickType(row + i * 4, transparent, outError) == TickType::kTick) {
-      if (state == TickState::kStart ||
-          (state == TickState::kOutside1 && multipleAllowed)) {
+      if (state == TickState::kStart || (state == TickState::kOutside1 && multipleAllowed)) {
         *outLeft = i - 1;
         *outRight = width - 2;
         found = true;
@@ -719,18 +695,16 @@
   return true;
 }
 
-static bool getVerticalTicks(png_bytepp rows, int offset, int height,
-                             bool transparent, bool required, int32_t* outTop,
-                             int32_t* outBottom, const char** outError,
-                             uint8_t* outDivs, bool multipleAllowed) {
+static bool getVerticalTicks(png_bytepp rows, int offset, int height, bool transparent,
+                             bool required, int32_t* outTop, int32_t* outBottom,
+                             const char** outError, uint8_t* outDivs, bool multipleAllowed) {
   *outTop = *outBottom = -1;
   TickState state = TickState::kStart;
   bool found = false;
 
   for (int i = 1; i < height - 1; i++) {
     if (tickType(rows[i] + offset, transparent, outError) == TickType::kTick) {
-      if (state == TickState::kStart ||
-          (state == TickState::kOutside1 && multipleAllowed)) {
+      if (state == TickState::kStart || (state == TickState::kOutside1 && multipleAllowed)) {
         *outTop = i - 1;
         *outBottom = height - 2;
         found = true;
@@ -765,10 +739,8 @@
   return true;
 }
 
-static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width,
-                                           bool transparent,
-                                           bool /* required */,
-                                           int32_t* outLeft, int32_t* outRight,
+static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, bool transparent,
+                                           bool /* required */, int32_t* outLeft, int32_t* outRight,
                                            const char** outError) {
   *outLeft = *outRight = 0;
 
@@ -779,23 +751,20 @@
     while (i < width - 1) {
       (*outLeft)++;
       i++;
-      if (tickType(row + i * 4, transparent, outError) !=
-          TickType::kLayoutBounds) {
+      if (tickType(row + i * 4, transparent, outError) != TickType::kLayoutBounds) {
         break;
       }
     }
   }
 
   // Look for right tick
-  if (tickType(row + (width - 2) * 4, transparent, outError) ==
-      TickType::kLayoutBounds) {
+  if (tickType(row + (width - 2) * 4, transparent, outError) == TickType::kLayoutBounds) {
     // Ending with a layout padding tick
     int i = width - 2;
     while (i > 1) {
       (*outRight)++;
       i--;
-      if (tickType(row + i * 4, transparent, outError) !=
-          TickType::kLayoutBounds) {
+      if (tickType(row + i * 4, transparent, outError) != TickType::kLayoutBounds) {
         break;
       }
     }
@@ -803,38 +772,32 @@
   return true;
 }
 
-static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset,
-                                         int height, bool transparent,
-                                         bool /* required */, int32_t* outTop,
-                                         int32_t* outBottom,
+static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset, int height, bool transparent,
+                                         bool /* required */, int32_t* outTop, int32_t* outBottom,
                                          const char** outError) {
   *outTop = *outBottom = 0;
 
   // Look for top tick
-  if (tickType(rows[1] + offset, transparent, outError) ==
-      TickType::kLayoutBounds) {
+  if (tickType(rows[1] + offset, transparent, outError) == TickType::kLayoutBounds) {
     // Starting with a layout padding tick
     int i = 1;
     while (i < height - 1) {
       (*outTop)++;
       i++;
-      if (tickType(rows[i] + offset, transparent, outError) !=
-          TickType::kLayoutBounds) {
+      if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) {
         break;
       }
     }
   }
 
   // Look for bottom tick
-  if (tickType(rows[height - 2] + offset, transparent, outError) ==
-      TickType::kLayoutBounds) {
+  if (tickType(rows[height - 2] + offset, transparent, outError) == TickType::kLayoutBounds) {
     // Ending with a layout padding tick
     int i = height - 2;
     while (i > 1) {
       (*outBottom)++;
       i--;
-      if (tickType(rows[i] + offset, transparent, outError) !=
-          TickType::kLayoutBounds) {
+      if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) {
         break;
       }
     }
@@ -842,13 +805,12 @@
   return true;
 }
 
-static void findMaxOpacity(png_bytepp rows, int startX, int startY, int endX,
-                           int endY, int dX, int dY, int* outInset) {
+static void findMaxOpacity(png_bytepp rows, int startX, int startY, int endX, int endY, int dX,
+                           int dY, int* outInset) {
   uint8_t maxOpacity = 0;
   int inset = 0;
   *outInset = 0;
-  for (int x = startX, y = startY; x != endX && y != endY;
-       x += dX, y += dY, inset++) {
+  for (int x = startX, y = startY; x != endX && y != endY; x += dX, y += dY, inset++) {
     png_byte* color = rows[y] + x * 4;
     uint8_t opacity = color[3];
     if (opacity > maxOpacity) {
@@ -868,8 +830,7 @@
   return maxAlpha;
 }
 
-static uint8_t maxAlphaOverCol(png_bytepp rows, int offsetX, int startY,
-                               int endY) {
+static uint8_t maxAlphaOverCol(png_bytepp rows, int offsetX, int startY, int endY) {
   uint8_t maxAlpha = 0;
   for (int y = startY; y < endY; y++) {
     uint8_t alpha = (rows[y] + offsetX * 4)[3];
@@ -886,10 +847,8 @@
 
   // find left and right extent of nine patch content on center row
   if (image->width > 4) {
-    findMaxOpacity(image->rows.data(), 1, midY, midX, -1, 1, 0,
-                   &image->outlineInsetsLeft);
-    findMaxOpacity(image->rows.data(), endX, midY, midX, -1, -1, 0,
-                   &image->outlineInsetsRight);
+    findMaxOpacity(image->rows.data(), 1, midY, midX, -1, 1, 0, &image->outlineInsetsLeft);
+    findMaxOpacity(image->rows.data(), endX, midY, midX, -1, -1, 0, &image->outlineInsetsRight);
   } else {
     image->outlineInsetsLeft = 0;
     image->outlineInsetsRight = 0;
@@ -897,10 +856,8 @@
 
   // find top and bottom extent of nine patch content on center column
   if (image->height > 4) {
-    findMaxOpacity(image->rows.data(), midX, 1, -1, midY, 0, 1,
-                   &image->outlineInsetsTop);
-    findMaxOpacity(image->rows.data(), midX, endY, -1, midY, 0, -1,
-                   &image->outlineInsetsBottom);
+    findMaxOpacity(image->rows.data(), midX, 1, -1, midY, 0, 1, &image->outlineInsetsTop);
+    findMaxOpacity(image->rows.data(), midX, endY, -1, midY, 0, -1, &image->outlineInsetsBottom);
   } else {
     image->outlineInsetsTop = 0;
     image->outlineInsetsBottom = 0;
@@ -915,13 +872,13 @@
 
   // assuming the image is a round rect, compute the radius by marching
   // diagonally from the top left corner towards the center
-  image->outlineAlpha = std::max(
-      maxAlphaOverRow(image->rows[innerMidY], innerStartX, innerEndX),
-      maxAlphaOverCol(image->rows.data(), innerMidX, innerStartY, innerStartY));
+  image->outlineAlpha =
+      std::max(maxAlphaOverRow(image->rows[innerMidY], innerStartX, innerEndX),
+               maxAlphaOverCol(image->rows.data(), innerMidX, innerStartY, innerStartY));
 
   int diagonalInset = 0;
-  findMaxOpacity(image->rows.data(), innerStartX, innerStartY, innerMidX,
-                 innerMidY, 1, 1, &diagonalInset);
+  findMaxOpacity(image->rows.data(), innerStartX, innerStartY, innerMidX, innerMidY, 1, 1,
+                 &diagonalInset);
 
   /* Determine source radius based upon inset:
    *     sqrt(r^2 + r^2) = sqrt(i^2 + i^2) + r
@@ -932,19 +889,17 @@
   image->outlineRadius = 3.4142f * diagonalInset;
 
   if (kDebug) {
-    printf("outline insets %d %d %d %d, rad %f, alpha %x\n",
-           image->outlineInsetsLeft, image->outlineInsetsTop,
-           image->outlineInsetsRight, image->outlineInsetsBottom,
+    printf("outline insets %d %d %d %d, rad %f, alpha %x\n", image->outlineInsetsLeft,
+           image->outlineInsetsTop, image->outlineInsetsRight, image->outlineInsetsBottom,
            image->outlineRadius, image->outlineAlpha);
   }
 }
 
-static uint32_t getColor(png_bytepp rows, int left, int top, int right,
-                         int bottom) {
+static uint32_t getColor(png_bytepp rows, int left, int top, int right, int bottom) {
   png_bytep color = rows[top] + left * 4;
 
   if (left > right || top > bottom) {
-    return android::Res_png_9patch::TRANSPARENT_COLOR;
+    return Res_png_9patch::TRANSPARENT_COLOR;
   }
 
   while (top <= bottom) {
@@ -952,18 +907,17 @@
       png_bytep p = rows[top] + i * 4;
       if (color[3] == 0) {
         if (p[3] != 0) {
-          return android::Res_png_9patch::NO_COLOR;
+          return Res_png_9patch::NO_COLOR;
         }
-      } else if (p[0] != color[0] || p[1] != color[1] || p[2] != color[2] ||
-                 p[3] != color[3]) {
-        return android::Res_png_9patch::NO_COLOR;
+      } else if (p[0] != color[0] || p[1] != color[1] || p[2] != color[2] || p[3] != color[3]) {
+        return Res_png_9patch::NO_COLOR;
       }
     }
     top++;
   }
 
   if (color[3] == 0) {
-    return android::Res_png_9patch::TRANSPARENT_COLOR;
+    return Res_png_9patch::TRANSPARENT_COLOR;
   }
   return (color[3] << 24) | (color[0] << 16) | (color[1] << 8) | color[2];
 }
@@ -1014,23 +968,22 @@
   }
 
   // Validate frame...
-  if (!transparent &&
-      (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
+  if (!transparent && (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
     errorMsg = "Must have one-pixel frame that is either transparent or white";
     goto getout;
   }
 
   // Find left and right of sizing areas...
-  if (!getHorizontalTicks(p, W, transparent, true, &xDivs[0], &xDivs[1],
-                          &errorMsg, &numXDivs, true)) {
+  if (!getHorizontalTicks(p, W, transparent, true, &xDivs[0], &xDivs[1], &errorMsg, &numXDivs,
+                          true)) {
     errorPixel = xDivs[0];
     errorEdge = "top";
     goto getout;
   }
 
   // Find top and bottom of sizing areas...
-  if (!getVerticalTicks(image->rows.data(), 0, H, transparent, true, &yDivs[0],
-                        &yDivs[1], &errorMsg, &numYDivs, true)) {
+  if (!getVerticalTicks(image->rows.data(), 0, H, transparent, true, &yDivs[0], &yDivs[1],
+                        &errorMsg, &numYDivs, true)) {
     errorPixel = yDivs[0];
     errorEdge = "left";
     goto getout;
@@ -1041,10 +994,8 @@
   image->info9Patch.numYDivs = numYDivs;
 
   // Find left and right of padding area...
-  if (!getHorizontalTicks(image->rows[H - 1], W, transparent, false,
-                          &image->info9Patch.paddingLeft,
-                          &image->info9Patch.paddingRight, &errorMsg, nullptr,
-                          false)) {
+  if (!getHorizontalTicks(image->rows[H - 1], W, transparent, false, &image->info9Patch.paddingLeft,
+                          &image->info9Patch.paddingRight, &errorMsg, nullptr, false)) {
     errorPixel = image->info9Patch.paddingLeft;
     errorEdge = "bottom";
     goto getout;
@@ -1052,9 +1003,8 @@
 
   // Find top and bottom of padding area...
   if (!getVerticalTicks(image->rows.data(), (W - 1) * 4, H, transparent, false,
-                        &image->info9Patch.paddingTop,
-                        &image->info9Patch.paddingBottom, &errorMsg, nullptr,
-                        false)) {
+                        &image->info9Patch.paddingTop, &image->info9Patch.paddingBottom, &errorMsg,
+                        nullptr, false)) {
     errorPixel = image->info9Patch.paddingTop;
     errorEdge = "right";
     goto getout;
@@ -1062,22 +1012,18 @@
 
   // Find left and right of layout padding...
   getHorizontalLayoutBoundsTicks(image->rows[H - 1], W, transparent, false,
-                                 &image->layoutBoundsLeft,
-                                 &image->layoutBoundsRight, &errorMsg);
+                                 &image->layoutBoundsLeft, &image->layoutBoundsRight, &errorMsg);
 
-  getVerticalLayoutBoundsTicks(image->rows.data(), (W - 1) * 4, H, transparent,
-                               false, &image->layoutBoundsTop,
-                               &image->layoutBoundsBottom, &errorMsg);
+  getVerticalLayoutBoundsTicks(image->rows.data(), (W - 1) * 4, H, transparent, false,
+                               &image->layoutBoundsTop, &image->layoutBoundsBottom, &errorMsg);
 
-  image->haveLayoutBounds =
-      image->layoutBoundsLeft != 0 || image->layoutBoundsRight != 0 ||
-      image->layoutBoundsTop != 0 || image->layoutBoundsBottom != 0;
+  image->haveLayoutBounds = image->layoutBoundsLeft != 0 || image->layoutBoundsRight != 0 ||
+                            image->layoutBoundsTop != 0 || image->layoutBoundsBottom != 0;
 
   if (image->haveLayoutBounds) {
     if (kDebug) {
-      printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft,
-             image->layoutBoundsTop, image->layoutBoundsRight,
-             image->layoutBoundsBottom);
+      printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
+             image->layoutBoundsRight, image->layoutBoundsBottom);
     }
   }
 
@@ -1189,7 +1135,7 @@
       c = getColor(image->rows.data(), left, top, right - 1, bottom - 1);
       image->colors[colorIndex++] = c;
       if (kDebug) {
-        if (c != android::Res_png_9patch::NO_COLOR) {
+        if (c != Res_png_9patch::NO_COLOR) {
           hasColor = true;
         }
       }
@@ -1214,8 +1160,7 @@
     if (errorEdge) {
       err << "." << std::endl;
       if (errorPixel >= 0) {
-        err << "Found at pixel #" << errorPixel << " along " << errorEdge
-            << " edge";
+        err << "Found at pixel #" << errorPixel << " along " << errorEdge << " edge";
       } else {
         err << "Found along " << errorEdge << " edge";
       }
@@ -1226,20 +1171,19 @@
   return true;
 }
 
-bool Png::process(const android::Source& source, std::istream* input, android::BigBuffer* outBuffer,
+bool Png::process(const Source& source, std::istream* input, BigBuffer* outBuffer,
                   const PngOptions& options) {
-  TRACE_CALL();
   png_byte signature[kPngSignatureSize];
 
   // Read the PNG signature first.
   if (!input->read(reinterpret_cast<char*>(signature), kPngSignatureSize)) {
-    mDiag->Error(android::DiagMessage() << strerror(errno));
+    mDiag->Error(DiagMessage() << strerror(errno));
     return false;
   }
 
   // If the PNG signature doesn't match, bail early.
   if (png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
-    mDiag->Error(android::DiagMessage() << "not a valid png file");
+    mDiag->Error(DiagMessage() << "not a valid png file");
     return false;
   }
 
@@ -1252,18 +1196,17 @@
 
   readPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr);
   if (!readPtr) {
-    mDiag->Error(android::DiagMessage() << "failed to allocate read ptr");
+    mDiag->Error(DiagMessage() << "failed to allocate read ptr");
     goto bail;
   }
 
   infoPtr = png_create_info_struct(readPtr);
   if (!infoPtr) {
-    mDiag->Error(android::DiagMessage() << "failed to allocate info ptr");
+    mDiag->Error(DiagMessage() << "failed to allocate info ptr");
     goto bail;
   }
 
-  png_set_error_fn(readPtr, reinterpret_cast<png_voidp>(mDiag), nullptr,
-                   logWarning);
+  png_set_error_fn(readPtr, reinterpret_cast<png_voidp>(mDiag), nullptr, logWarning);
 
   // Set the read function to read from std::istream.
   png_set_read_fn(readPtr, (png_voidp)input, readDataFromStream);
@@ -1272,35 +1215,32 @@
     goto bail;
   }
 
-  if (util::EndsWith(source.path, ".9.png")) {
+  if (android::base::EndsWith(source.path, ".9.png")) {
     std::string errorMsg;
     if (!do9Patch(&pngInfo, &errorMsg)) {
-      mDiag->Error(android::DiagMessage() << errorMsg);
+      mDiag->Error(DiagMessage() << errorMsg);
       goto bail;
     }
   }
 
-  writePtr =
-      png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr);
+  writePtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr);
   if (!writePtr) {
-    mDiag->Error(android::DiagMessage() << "failed to allocate write ptr");
+    mDiag->Error(DiagMessage() << "failed to allocate write ptr");
     goto bail;
   }
 
   writeInfoPtr = png_create_info_struct(writePtr);
   if (!writeInfoPtr) {
-    mDiag->Error(android::DiagMessage() << "failed to allocate write info ptr");
+    mDiag->Error(DiagMessage() << "failed to allocate write info ptr");
     goto bail;
   }
 
   png_set_error_fn(writePtr, nullptr, nullptr, logWarning);
 
   // Set the write function to write to std::ostream.
-  png_set_write_fn(writePtr, (png_voidp)outBuffer, writeDataToStream,
-                   flushDataToStream);
+  png_set_write_fn(writePtr, (png_voidp)outBuffer, writeDataToStream, flushDataToStream);
 
-  if (!writePng(mDiag, writePtr, writeInfoPtr, &pngInfo,
-                options.grayscale_tolerance)) {
+  if (!writePng(mDiag, writePtr, writeInfoPtr, &pngInfo, options.grayscale_tolerance)) {
     goto bail;
   }
 
@@ -1316,4 +1256,4 @@
   return result;
 }
 
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/compile/PngChunkFilter.cpp b/libs/androidfw/PngChunkFilter.cpp
similarity index 95%
rename from tools/aapt2/compile/PngChunkFilter.cpp
rename to libs/androidfw/PngChunkFilter.cpp
index 2e55d0c..331b948 100644
--- a/tools/aapt2/compile/PngChunkFilter.cpp
+++ b/libs/androidfw/PngChunkFilter.cpp
@@ -14,25 +14,22 @@
  * limitations under the License.
  */
 
-#include "compile/Png.h"
-
 #include "android-base/stringprintf.h"
+#include "android-base/strings.h"
+#include "androidfw/Png.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
 
-#include "io/Io.h"
-
-using ::android::StringPiece;
 using ::android::base::StringPrintf;
 
-namespace aapt {
+namespace android {
 
 static constexpr const char* kPngSignature = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a";
 
 // Useful helper function that encodes individual bytes into a uint32
 // at compile time.
 constexpr uint32_t u32(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
-  return (((uint32_t)a) << 24) | (((uint32_t)b) << 16) | (((uint32_t)c) << 8) |
-         ((uint32_t)d);
+  return (((uint32_t)a) << 24) | (((uint32_t)b) << 16) | (((uint32_t)c) << 8) | ((uint32_t)d);
 }
 
 // Allow list of PNG chunk types that we want to keep in the resulting PNG.
@@ -71,7 +68,7 @@
 }
 
 PngChunkFilter::PngChunkFilter(StringPiece data) : data_(data) {
-  if (util::StartsWith(data_, kPngSignature)) {
+  if (android::base::StartsWith(data_, kPngSignature)) {
     window_start_ = 0;
     window_end_ = kPngSignatureSize;
   } else {
@@ -176,5 +173,4 @@
   window_end_ = kPngSignatureSize;
   return true;
 }
-
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/compile/PngCrunch.cpp b/libs/androidfw/PngCrunch.cpp
similarity index 87%
rename from tools/aapt2/compile/PngCrunch.cpp
rename to libs/androidfw/PngCrunch.cpp
index 4ef87ba..cf3c0ee 100644
--- a/tools/aapt2/compile/PngCrunch.cpp
+++ b/libs/androidfw/PngCrunch.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#include "compile/Png.h"
-
 #include <png.h>
 #include <zlib.h>
 
@@ -26,16 +24,16 @@
 #include "android-base/errors.h"
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "androidfw/Png.h"
 
-#include "trace/TraceBuffer.h"
-
-namespace aapt {
+namespace android {
 
 // Custom deleter that destroys libpng read and info structs.
 class PngReadStructDeleter {
  public:
   PngReadStructDeleter(png_structp read_ptr, png_infop info_ptr)
-      : read_ptr_(read_ptr), info_ptr_(info_ptr) {}
+      : read_ptr_(read_ptr), info_ptr_(info_ptr) {
+  }
 
   ~PngReadStructDeleter() {
     png_destroy_read_struct(&read_ptr_, &info_ptr_, nullptr);
@@ -52,7 +50,8 @@
 class PngWriteStructDeleter {
  public:
   PngWriteStructDeleter(png_structp write_ptr, png_infop info_ptr)
-      : write_ptr_(write_ptr), info_ptr_(info_ptr) {}
+      : write_ptr_(write_ptr), info_ptr_(info_ptr) {
+  }
 
   ~PngWriteStructDeleter() {
     png_destroy_write_struct(&write_ptr_, &info_ptr_);
@@ -83,7 +82,7 @@
 }
 
 static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
-  io::InputStream* in = (io::InputStream*)png_get_io_ptr(png_ptr);
+  InputStream* in = (InputStream*)png_get_io_ptr(png_ptr);
 
   const void* in_buffer;
   size_t in_len;
@@ -108,7 +107,7 @@
 }
 
 static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
-  io::OutputStream* out = (io::OutputStream*)png_get_io_ptr(png_ptr);
+  OutputStream* out = (OutputStream*)png_get_io_ptr(png_ptr);
 
   void* out_buffer;
   size_t out_len;
@@ -143,28 +142,22 @@
   }
 }
 
-std::unique_ptr<Image> ReadPng(IAaptContext* context, const android::Source& source,
-                               io::InputStream* in) {
-  TRACE_CALL();
-  // Create a diagnostics that has the source information encoded.
-  android::SourcePathDiagnostics source_diag(source, context->GetDiagnostics());
-
+std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) {
   // Read the first 8 bytes of the file looking for the PNG signature.
   // Bail early if it does not match.
   const png_byte* signature;
   size_t buffer_size;
   if (!in->Next((const void**)&signature, &buffer_size)) {
     if (in->HadError()) {
-      source_diag.Error(android::DiagMessage()
-                        << "failed to read PNG signature: " << in->GetError());
+      diag->Error(android::DiagMessage() << "failed to read PNG signature: " << in->GetError());
     } else {
-      source_diag.Error(android::DiagMessage() << "not enough data for PNG signature");
+      diag->Error(android::DiagMessage() << "not enough data for PNG signature");
     }
     return {};
   }
 
   if (buffer_size < kPngSignatureSize || png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
-    source_diag.Error(android::DiagMessage() << "file signature does not match PNG signature");
+    diag->Error(android::DiagMessage() << "file signature does not match PNG signature");
     return {};
   }
 
@@ -176,14 +169,14 @@
   // version of libpng.
   png_structp read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
   if (read_ptr == nullptr) {
-    source_diag.Error(android::DiagMessage() << "failed to create libpng read png_struct");
+    diag->Error(android::DiagMessage() << "failed to create libpng read png_struct");
     return {};
   }
 
   // Create and initialize the memory for image header and data.
   png_infop info_ptr = png_create_info_struct(read_ptr);
   if (info_ptr == nullptr) {
-    source_diag.Error(android::DiagMessage() << "failed to create libpng read png_info");
+    diag->Error(android::DiagMessage() << "failed to create libpng read png_info");
     png_destroy_read_struct(&read_ptr, nullptr, nullptr);
     return {};
   }
@@ -199,7 +192,7 @@
   }
 
   // Handle warnings ourselves via IDiagnostics.
-  png_set_error_fn(read_ptr, (png_voidp)&source_diag, LogError, LogWarning);
+  png_set_error_fn(read_ptr, (png_voidp)&diag, LogError, LogWarning);
 
   // Set up the read functions which read from our custom data sources.
   png_set_read_fn(read_ptr, (png_voidp)in, ReadDataFromStream);
@@ -213,8 +206,8 @@
   // Extract image meta-data from the various chunk headers.
   uint32_t width, height;
   int bit_depth, color_type, interlace_method, compression_method, filter_method;
-  png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
-               &interlace_method, &compression_method, &filter_method);
+  png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_method,
+               &compression_method, &filter_method);
 
   // When the image is read, expand it so that it is in RGBA 8888 format
   // so that image handling is uniform.
@@ -239,8 +232,7 @@
     png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
   }
 
-  if (color_type == PNG_COLOR_TYPE_GRAY ||
-      color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
+  if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
     png_set_gray_to_rgb(read_ptr);
   }
 
@@ -256,12 +248,12 @@
   // something
   // that can always be represented by 9-patch.
   if (width > std::numeric_limits<int32_t>::max() || height > std::numeric_limits<int32_t>::max()) {
-    source_diag.Error(android::DiagMessage()
-                      << "PNG image dimensions are too large: " << width << "x" << height);
+    diag->Error(android::DiagMessage()
+                << "PNG image dimensions are too large: " << width << "x" << height);
     return {};
   }
 
-  std::unique_ptr<Image> output_image = util::make_unique<Image>();
+  std::unique_ptr<Image> output_image = std::make_unique<Image>();
   output_image->width = static_cast<int32_t>(width);
   output_image->height = static_cast<int32_t>(height);
 
@@ -272,7 +264,7 @@
   output_image->data = std::unique_ptr<uint8_t[]>(new uint8_t[height * row_bytes]);
 
   // Create an array of rows that index into the data block.
-  output_image->rows = std::unique_ptr<uint8_t* []>(new uint8_t*[height]);
+  output_image->rows = std::unique_ptr<uint8_t*[]>(new uint8_t*[height]);
   for (uint32_t h = 0; h < height; h++) {
     output_image->rows[h] = output_image->data.get() + (h * row_bytes);
   }
@@ -332,8 +324,7 @@
       // This grayscale has alpha and can fit within a palette.
       // See if it is worth fitting into a palette.
       const size_t palette_threshold = palette_chunk_size + alpha_chunk_size +
-                                       palette_data_chunk_size +
-                                       kPaletteOverheadConstant;
+                                       palette_data_chunk_size + kPaletteOverheadConstant;
       if (grayscale_alpha_data_chunk_size > palette_threshold) {
         return PNG_COLOR_TYPE_PALETTE;
       }
@@ -343,16 +334,14 @@
 
   if (color_palette_size <= 256 && !has_nine_patch) {
     // This image can fit inside a palette. Let's see if it is worth it.
-    size_t total_size_with_palette =
-        palette_data_chunk_size + palette_chunk_size;
+    size_t total_size_with_palette = palette_data_chunk_size + palette_chunk_size;
     size_t total_size_without_palette = color_data_chunk_size;
     if (alpha_palette_size > 0) {
       total_size_with_palette += alpha_palette_size;
       total_size_without_palette = color_alpha_data_chunk_size;
     }
 
-    if (total_size_without_palette >
-        total_size_with_palette + kPaletteOverheadConstant) {
+    if (total_size_without_palette > total_size_with_palette + kPaletteOverheadConstant) {
       return PNG_COLOR_TYPE_PALETTE;
     }
   }
@@ -482,26 +471,22 @@
   png_set_unknown_chunks(write_ptr, write_info_ptr, unknown_chunks, index);
 }
 
-bool WritePng(IAaptContext* context, const Image* image,
-              const NinePatch* nine_patch, io::OutputStream* out,
-              const PngOptions& options) {
-  TRACE_CALL();
+bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out,
+              const PngOptions& options, IDiagnostics* diag, bool verbose) {
   // Create and initialize the write png_struct with the default error and
   // warning handlers.
   // The header version is also passed in to ensure that this was built against the same
   // version of libpng.
   png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
   if (write_ptr == nullptr) {
-    context->GetDiagnostics()->Error(android::DiagMessage()
-                                     << "failed to create libpng write png_struct");
+    diag->Error(android::DiagMessage() << "failed to create libpng write png_struct");
     return false;
   }
 
   // Allocate memory to store image header data.
   png_infop write_info_ptr = png_create_info_struct(write_ptr);
   if (write_info_ptr == nullptr) {
-    context->GetDiagnostics()->Error(android::DiagMessage()
-                                     << "failed to create libpng write png_info");
+    diag->Error(android::DiagMessage() << "failed to create libpng write png_info");
     png_destroy_write_struct(&write_ptr, nullptr);
     return false;
   }
@@ -516,7 +501,7 @@
   }
 
   // Handle warnings with our IDiagnostics.
-  png_set_error_fn(write_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning);
+  png_set_error_fn(write_ptr, (png_voidp)&diag, LogError, LogWarning);
 
   // Set up the write functions which write to our custom data sources.
   png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr);
@@ -578,22 +563,21 @@
     }
   }
 
-  if (context->IsVerbose()) {
+  if (verbose) {
     android::DiagMessage msg;
-    msg << " paletteSize=" << color_palette.size()
-        << " alphaPaletteSize=" << alpha_palette.size()
+    msg << " paletteSize=" << color_palette.size() << " alphaPaletteSize=" << alpha_palette.size()
         << " maxGrayDeviation=" << max_gray_deviation
         << " grayScale=" << (grayscale ? "true" : "false");
-    context->GetDiagnostics()->Note(msg);
+    diag->Note(msg);
   }
 
   const bool convertible_to_grayscale = max_gray_deviation <= options.grayscale_tolerance;
 
-  const int new_color_type = PickColorType(
-      image->width, image->height, grayscale, convertible_to_grayscale,
-      nine_patch != nullptr, color_palette.size(), alpha_palette.size());
+  const int new_color_type =
+      PickColorType(image->width, image->height, grayscale, convertible_to_grayscale,
+                    nine_patch != nullptr, color_palette.size(), alpha_palette.size());
 
-  if (context->IsVerbose()) {
+  if (verbose) {
     android::DiagMessage msg;
     msg << "encoding PNG ";
     if (nine_patch) {
@@ -619,12 +603,11 @@
         msg << "unknown type " << new_color_type;
         break;
     }
-    context->GetDiagnostics()->Note(msg);
+    diag->Note(msg);
   }
 
-  png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8,
-               new_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
-               PNG_FILTER_TYPE_DEFAULT);
+  png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8, new_color_type,
+               PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
 
   if (new_color_type & PNG_COLOR_MASK_PALETTE) {
     // Assigns indices to the palette, and writes the encoded palette to the
@@ -666,11 +649,9 @@
       }
       png_write_row(write_ptr, out_row.get());
     }
-  } else if (new_color_type == PNG_COLOR_TYPE_GRAY ||
-             new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
+  } else if (new_color_type == PNG_COLOR_TYPE_GRAY || new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
     const size_t bpp = new_color_type == PNG_COLOR_TYPE_GRAY ? 1 : 2;
-    auto out_row =
-        std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
+    auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
 
     for (int32_t y = 0; y < image->height; y++) {
       png_const_bytep in_row = image->rows[y];
@@ -691,8 +672,7 @@
           // The image is convertible to grayscale, use linear-luminance of
           // sRGB colorspace:
           // https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale
-          out_row[x * bpp] =
-              (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
+          out_row[x * bpp] = (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
         }
 
         if (bpp == 2) {
@@ -747,4 +727,4 @@
   return true;
 }
 
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/io/BigBufferStream.h b/libs/androidfw/include/androidfw/BigBufferStream.h
similarity index 74%
rename from tools/aapt2/io/BigBufferStream.h
rename to libs/androidfw/include/androidfw/BigBufferStream.h
index 63a5e57..e55fe0d 100644
--- a/tools/aapt2/io/BigBufferStream.h
+++ b/libs/androidfw/include/androidfw/BigBufferStream.h
@@ -14,18 +14,16 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_IO_BIGBUFFERSTREAM_H
-#define AAPT_IO_BIGBUFFERSTREAM_H
+#pragma once
 
-#include "androidfw/BigBuffer.h"
-#include "io/Io.h"
+#include "BigBuffer.h"
+#include "Streams.h"
 
-namespace aapt {
-namespace io {
+namespace android {
 
 class BigBufferInputStream : public KnownSizeInputStream {
  public:
-  inline explicit BigBufferInputStream(const android::BigBuffer* buffer)
+  inline explicit BigBufferInputStream(const BigBuffer* buffer)
       : buffer_(buffer), iter_(buffer->begin()) {
   }
   virtual ~BigBufferInputStream() = default;
@@ -44,18 +42,20 @@
 
   size_t TotalSize() const override;
 
+  bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(BigBufferInputStream);
 
-  const android::BigBuffer* buffer_;
-  android::BigBuffer::const_iterator iter_;
+  const BigBuffer* buffer_;
+  BigBuffer::const_iterator iter_;
   size_t offset_ = 0;
   size_t bytes_read_ = 0;
 };
 
 class BigBufferOutputStream : public OutputStream {
  public:
-  inline explicit BigBufferOutputStream(android::BigBuffer* buffer) : buffer_(buffer) {
+  inline explicit BigBufferOutputStream(BigBuffer* buffer) : buffer_(buffer) {
   }
   virtual ~BigBufferOutputStream() = default;
 
@@ -70,10 +70,7 @@
  private:
   DISALLOW_COPY_AND_ASSIGN(BigBufferOutputStream);
 
-  android::BigBuffer* buffer_;
+  BigBuffer* buffer_;
 };
 
-}  // namespace io
-}  // namespace aapt
-
-#endif  // AAPT_IO_BIGBUFFERSTREAM_H
+}  // namespace android
\ No newline at end of file
diff --git a/tools/aapt2/io/FileStream.h b/libs/androidfw/include/androidfw/FileStream.h
similarity index 93%
rename from tools/aapt2/io/FileStream.h
rename to libs/androidfw/include/androidfw/FileStream.h
index 62d910f..fb84a91 100644
--- a/tools/aapt2/io/FileStream.h
+++ b/libs/androidfw/include/androidfw/FileStream.h
@@ -14,19 +14,16 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_IO_FILESTREAM_H
-#define AAPT_IO_FILESTREAM_H
-
-#include "io/Io.h"
+#pragma once
 
 #include <memory>
 #include <string>
 
+#include "Streams.h"
 #include "android-base/macros.h"
 #include "android-base/unique_fd.h"
 
-namespace aapt {
-namespace io {
+namespace android {
 
 constexpr size_t kDefaultBufferCapacity = 4096u;
 
@@ -48,6 +45,8 @@
 
   std::string GetError() const override;
 
+  bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(FileInputStream);
 
@@ -101,7 +100,4 @@
   size_t total_byte_count_ = 0u;
 };
 
-}  // namespace io
-}  // namespace aapt
-
-#endif  // AAPT_IO_FILESTREAM_H
+}  // namespace android
\ No newline at end of file
diff --git a/tools/aapt2/compile/Image.h b/libs/androidfw/include/androidfw/Image.h
similarity index 92%
rename from tools/aapt2/compile/Image.h
rename to libs/androidfw/include/androidfw/Image.h
index db0b945..c18c34c 100644
--- a/tools/aapt2/compile/Image.h
+++ b/libs/androidfw/include/androidfw/Image.h
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_COMPILE_IMAGE_H
-#define AAPT_COMPILE_IMAGE_H
+#pragma once
 
 #include <cstdint>
 #include <memory>
@@ -24,7 +23,7 @@
 
 #include "android-base/macros.h"
 
-namespace aapt {
+namespace android {
 
 /**
  * An in-memory image, loaded from disk, with pixels in RGBA_8888 format.
@@ -37,7 +36,7 @@
    * A `height` sized array of pointers, where each element points to a
    * `width` sized row of RGBA_8888 pixels.
    */
-  std::unique_ptr<uint8_t* []> rows;
+  std::unique_ptr<uint8_t*[]> rows;
 
   /**
    * The width of the image in RGBA_8888 pixels. This is int32_t because of
@@ -72,7 +71,8 @@
   int32_t end = 0;
 
   explicit Range() = default;
-  inline explicit Range(int32_t s, int32_t e) : start(s), end(e) {}
+  inline explicit Range(int32_t s, int32_t e) : start(s), end(e) {
+  }
 };
 
 inline bool operator==(const Range& left, const Range& right) {
@@ -93,7 +93,8 @@
 
   explicit Bounds() = default;
   inline explicit Bounds(int32_t l, int32_t t, int32_t r, int32_t b)
-      : left(l), top(t), right(r), bottom(b) {}
+      : left(l), top(t), right(r), bottom(b) {
+  }
 
   bool nonZero() const;
 };
@@ -103,8 +104,8 @@
 }
 
 inline bool operator==(const Bounds& left, const Bounds& right) {
-  return left.left == right.left && left.top == right.top &&
-         left.right == right.right && left.bottom == right.bottom;
+  return left.left == right.left && left.top == right.top && left.right == right.right &&
+         left.bottom == right.bottom;
 }
 
 /**
@@ -115,8 +116,7 @@
 class NinePatch {
  public:
   static std::unique_ptr<NinePatch> Create(uint8_t** rows, const int32_t width,
-                                           const int32_t height,
-                                           std::string* err_out);
+                                           const int32_t height, std::string* err_out);
 
   /**
    * Packs the RGBA_8888 data pointed to by pixel into a uint32_t
@@ -204,6 +204,4 @@
 ::std::ostream& operator<<(::std::ostream& out, const Bounds& bounds);
 ::std::ostream& operator<<(::std::ostream& out, const NinePatch& nine_patch);
 
-}  // namespace aapt
-
-#endif /* AAPT_COMPILE_IMAGE_H */
+}  // namespace android
\ No newline at end of file
diff --git a/tools/aapt2/compile/Png.h b/libs/androidfw/include/androidfw/Png.h
similarity index 62%
rename from tools/aapt2/compile/Png.h
rename to libs/androidfw/include/androidfw/Png.h
index a8b7dd1..2ece43e 100644
--- a/tools/aapt2/compile/Png.h
+++ b/libs/androidfw/include/androidfw/Png.h
@@ -14,22 +14,18 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_PNG_H
-#define AAPT_PNG_H
+#pragma once
 
-#include <iostream>
 #include <string>
 
+#include "BigBuffer.h"
+#include "IDiagnostics.h"
+#include "Image.h"
+#include "Source.h"
+#include "Streams.h"
 #include "android-base/macros.h"
-#include "androidfw/BigBuffer.h"
-#include "androidfw/IDiagnostics.h"
-#include "androidfw/Source.h"
-#include "compile/Image.h"
-#include "io/Io.h"
-#include "process/IResourceTableConsumer.h"
 
-namespace aapt {
-
+namespace android {
 // Size in bytes of the PNG signature.
 constexpr size_t kPngSignatureSize = 8u;
 
@@ -42,32 +38,36 @@
  */
 class Png {
  public:
-  explicit Png(android::IDiagnostics* diag) : mDiag(diag) {
+  explicit Png(IDiagnostics* diag) : mDiag(diag) {
   }
 
-  bool process(const android::Source& source, std::istream* input, android::BigBuffer* outBuffer,
+  bool process(const Source& source, std::istream* input, BigBuffer* outBuffer,
                const PngOptions& options);
 
  private:
   DISALLOW_COPY_AND_ASSIGN(Png);
 
-  android::IDiagnostics* mDiag;
+  IDiagnostics* mDiag;
 };
 
 /**
  * An InputStream that filters out unimportant PNG chunks.
  */
-class PngChunkFilter : public io::InputStream {
+class PngChunkFilter : public InputStream {
  public:
-  explicit PngChunkFilter(android::StringPiece data);
+  explicit PngChunkFilter(StringPiece data);
   virtual ~PngChunkFilter() = default;
 
   bool Next(const void** buffer, size_t* len) override;
   void BackUp(size_t count) override;
 
-  bool CanRewind() const override { return true; }
+  bool CanRewind() const override {
+    return true;
+  }
   bool Rewind() override;
-  size_t ByteCount() const override { return window_start_; }
+  size_t ByteCount() const override {
+    return window_start_;
+  }
 
   bool HadError() const override {
     return !error_msg_.empty();
@@ -81,26 +81,20 @@
 
   bool ConsumeWindow(const void** buffer, size_t* len);
 
-  android::StringPiece data_;
+  StringPiece data_;
   size_t window_start_ = 0;
   size_t window_end_ = 0;
   std::string error_msg_;
 };
-
 /**
  * Reads a PNG from the InputStream into memory as an RGBA Image.
  */
-std::unique_ptr<Image> ReadPng(IAaptContext* context, const android::Source& source,
-                               io::InputStream* in);
+std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag);
 
 /**
  * Writes the RGBA Image, with optional 9-patch meta-data, into the OutputStream
  * as a PNG.
  */
-bool WritePng(IAaptContext* context, const Image* image,
-              const NinePatch* nine_patch, io::OutputStream* out,
-              const PngOptions& options);
-
-}  // namespace aapt
-
-#endif  // AAPT_PNG_H
+bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out,
+              const PngOptions& options, IDiagnostics* diag, bool verbose);
+}  // namespace android
\ No newline at end of file
diff --git a/tools/aapt2/io/Io.h b/libs/androidfw/include/androidfw/Streams.h
similarity index 86%
rename from tools/aapt2/io/Io.h
rename to libs/androidfw/include/androidfw/Streams.h
index e1df23a6..2daf0e2 100644
--- a/tools/aapt2/io/Io.h
+++ b/libs/androidfw/include/androidfw/Streams.h
@@ -14,13 +14,12 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_IO_IO_H
-#define AAPT_IO_IO_H
+#pragma once
 
 #include <string>
+#include "android-base/off64_t.h"
 
-namespace aapt {
-namespace io {
+namespace android {
 
 // InputStream interface that mimics protobuf's ZeroCopyInputStream,
 // with added error handling methods to better report issues.
@@ -41,21 +40,34 @@
   virtual void BackUp(size_t count) = 0;
 
   // Returns true if this InputStream can rewind. If so, Rewind() can be called.
-  virtual bool CanRewind() const { return false; };
+  virtual bool CanRewind() const {
+    return false;
+  };
 
   // Rewinds the stream to the beginning so it can be read again.
   // Returns true if the rewind succeeded.
   // This does nothing if CanRewind() returns false.
-  virtual bool Rewind() { return false; }
+  virtual bool Rewind() {
+    return false;
+  }
 
   // Returns the number of bytes that have been read from the stream.
   virtual size_t ByteCount() const = 0;
 
   // Returns an error message if HadError() returned true.
-  virtual std::string GetError() const { return {}; }
+  virtual std::string GetError() const {
+    return {};
+  }
 
   // Returns true if an error occurred. Errors are permanent.
   virtual bool HadError() const = 0;
+
+  virtual bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) {
+    (void)data;
+    (void)byte_count;
+    (void)offset;
+    return false;
+  }
 };
 
 // A sub-InputStream interface that knows the total size of its stream.
@@ -87,13 +99,12 @@
   virtual size_t ByteCount() const = 0;
 
   // Returns an error message if HadError() returned true.
-  virtual std::string GetError() const { return {}; }
+  virtual std::string GetError() const {
+    return {};
+  }
 
   // Returns true if an error occurred. Errors are permanent.
   virtual bool HadError() const = 0;
 };
 
-}  // namespace io
-}  // namespace aapt
-
-#endif /* AAPT_IO_IO_H */
+}  // namespace android
\ No newline at end of file
diff --git a/tools/aapt2/io/FileStream_test.cpp b/libs/androidfw/tests/FileStream_test.cpp
similarity index 95%
rename from tools/aapt2/io/FileStream_test.cpp
rename to libs/androidfw/tests/FileStream_test.cpp
index cc9cd28..9785975 100644
--- a/tools/aapt2/io/FileStream_test.cpp
+++ b/libs/androidfw/tests/FileStream_test.cpp
@@ -14,20 +14,21 @@
  * limitations under the License.
  */
 
-#include "io/FileStream.h"
+#include "androidfw/FileStream.h"
+#include "androidfw/StringPiece.h"
 
 #include "android-base/file.h"
 #include "android-base/macros.h"
 
-#include "test/Test.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
 
 using ::android::StringPiece;
 using ::testing::Eq;
 using ::testing::NotNull;
 using ::testing::StrEq;
 
-namespace aapt {
-namespace io {
+namespace android {
 
 TEST(FileInputStreamTest, NextAndBackup) {
   std::string input = "this is a cool string";
@@ -123,5 +124,4 @@
   EXPECT_THAT(actual, StrEq(input));
 }
 
-}  // namespace io
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/compile/NinePatch_test.cpp b/libs/androidfw/tests/NinePatch_test.cpp
similarity index 69%
rename from tools/aapt2/compile/NinePatch_test.cpp
rename to libs/androidfw/tests/NinePatch_test.cpp
index f54bb2e..7ee8e9e 100644
--- a/tools/aapt2/compile/NinePatch_test.cpp
+++ b/libs/androidfw/tests/NinePatch_test.cpp
@@ -14,11 +14,11 @@
  * limitations under the License.
  */
 
-#include "compile/Image.h"
+#include "androidfw/Image.h"
+#include "androidfw/ResourceTypes.h"
+#include "gtest/gtest.h"
 
-#include "test/Test.h"
-
-namespace aapt {
+namespace android {
 
 // Pixels are in RGBA_8888 packing.
 
@@ -33,16 +33,19 @@
 #define TRANS "\x00\x00\x00\x00"
 
 static uint8_t* k2x2[] = {
-    (uint8_t*)WHITE WHITE, (uint8_t*)WHITE WHITE,
+    (uint8_t*)WHITE WHITE,
+    (uint8_t*)WHITE WHITE,
 };
 
 static uint8_t* kMixedNeutralColor3x3[] = {
-    (uint8_t*)WHITE BLACK TRANS, (uint8_t*)TRANS RED TRANS,
+    (uint8_t*)WHITE BLACK TRANS,
+    (uint8_t*)TRANS RED TRANS,
     (uint8_t*)WHITE WHITE WHITE,
 };
 
 static uint8_t* kTransparentNeutralColor3x3[] = {
-    (uint8_t*)TRANS BLACK TRANS, (uint8_t*)BLACK RED BLACK,
+    (uint8_t*)TRANS BLACK TRANS,
+    (uint8_t*)BLACK RED BLACK,
     (uint8_t*)TRANS BLACK TRANS,
 };
 
@@ -66,55 +69,44 @@
 };
 
 static uint8_t* kPadding6x5[] = {
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE BLACK,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE BLACK, (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE,
     (uint8_t*)WHITE WHITE BLACK BLACK WHITE WHITE,
 };
 
 static uint8_t* kLayoutBoundsWrongEdge3x3[] = {
-    (uint8_t*)WHITE RED WHITE, (uint8_t*)RED WHITE WHITE,
+    (uint8_t*)WHITE RED WHITE,
+    (uint8_t*)RED WHITE WHITE,
     (uint8_t*)WHITE WHITE WHITE,
 };
 
 static uint8_t* kLayoutBoundsNotEdgeAligned5x5[] = {
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE RED,   (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
     (uint8_t*)WHITE WHITE RED WHITE WHITE,
 };
 
 static uint8_t* kLayoutBounds5x5[] = {
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED,
     (uint8_t*)WHITE RED WHITE RED WHITE,
 };
 
 static uint8_t* kAsymmetricLayoutBounds5x5[] = {
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
     (uint8_t*)WHITE RED WHITE WHITE WHITE,
 };
 
 static uint8_t* kPaddingAndLayoutBounds5x5[] = {
-    (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
-    (uint8_t*)WHITE WHITE WHITE WHITE BLACK,
-    (uint8_t*)WHITE WHITE WHITE WHITE RED,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED,
+    (uint8_t*)WHITE WHITE WHITE WHITE BLACK, (uint8_t*)WHITE WHITE WHITE WHITE RED,
     (uint8_t*)WHITE RED BLACK RED WHITE,
 };
 
 static uint8_t* kColorfulImage5x5[] = {
-    (uint8_t*)WHITE BLACK WHITE BLACK WHITE,
-    (uint8_t*)BLACK RED BLUE GREEN WHITE,
-    (uint8_t*)BLACK RED GREEN GREEN WHITE,
-    (uint8_t*)WHITE TRANS BLUE GREEN WHITE,
+    (uint8_t*)WHITE BLACK WHITE BLACK WHITE, (uint8_t*)BLACK RED BLUE GREEN WHITE,
+    (uint8_t*)BLACK RED GREEN GREEN WHITE,   (uint8_t*)WHITE TRANS BLUE GREEN WHITE,
     (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
 };
 
@@ -145,33 +137,21 @@
 };
 
 static uint8_t* kOutlineOffsetTranslucent12x10[] = {
-    (uint8_t*)
-        WHITE WHITE WHITE BLACK BLACK BLACK BLACK BLACK BLACK BLACK BLACK WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE,
-    (uint8_t*)
-        WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE,
+    (uint8_t*)WHITE WHITE WHITE BLACK BLACK BLACK BLACK BLACK BLACK BLACK BLACK WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE,
+    (uint8_t*)WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE,
+    (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE,
 };
 
 static uint8_t* kOutlineRadius5x5[] = {
-    (uint8_t*)WHITE BLACK BLACK BLACK WHITE,
-    (uint8_t*)BLACK TRANS GREEN TRANS WHITE,
-    (uint8_t*)BLACK GREEN GREEN GREEN WHITE,
-    (uint8_t*)BLACK TRANS GREEN TRANS WHITE,
+    (uint8_t*)WHITE BLACK BLACK BLACK WHITE, (uint8_t*)BLACK TRANS GREEN TRANS WHITE,
+    (uint8_t*)BLACK GREEN GREEN GREEN WHITE, (uint8_t*)BLACK TRANS GREEN TRANS WHITE,
     (uint8_t*)WHITE WHITE WHITE WHITE WHITE,
 };
 
@@ -195,14 +175,12 @@
 
 TEST(NinePatchTest, TransparentNeutralColor) {
   std::string err;
-  EXPECT_NE(nullptr,
-            NinePatch::Create(kTransparentNeutralColor3x3, 3, 3, &err));
+  EXPECT_NE(nullptr, NinePatch::Create(kTransparentNeutralColor3x3, 3, 3, &err));
 }
 
 TEST(NinePatchTest, SingleStretchRegion) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kSingleStretch7x6, 7, 6, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kSingleStretch7x6, 7, 6, &err);
   ASSERT_NE(nullptr, nine_patch);
 
   ASSERT_EQ(1u, nine_patch->horizontal_stretch_regions.size());
@@ -214,8 +192,7 @@
 
 TEST(NinePatchTest, MultipleStretchRegions) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kMultipleStretch10x7, 10, 7, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kMultipleStretch10x7, 10, 7, &err);
   ASSERT_NE(nullptr, nine_patch);
 
   ASSERT_EQ(3u, nine_patch->horizontal_stretch_regions.size());
@@ -231,16 +208,14 @@
 
 TEST(NinePatchTest, InferPaddingFromStretchRegions) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kMultipleStretch10x7, 10, 7, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kMultipleStretch10x7, 10, 7, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(1, 0, 1, 0), nine_patch->padding);
 }
 
 TEST(NinePatchTest, Padding) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kPadding6x5, 6, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kPadding6x5, 6, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->padding);
 }
@@ -253,15 +228,13 @@
 
 TEST(NinePatchTest, LayoutBoundsMustTouchEdges) {
   std::string err;
-  EXPECT_EQ(nullptr,
-            NinePatch::Create(kLayoutBoundsNotEdgeAligned5x5, 5, 5, &err));
+  EXPECT_EQ(nullptr, NinePatch::Create(kLayoutBoundsNotEdgeAligned5x5, 5, 5, &err));
   EXPECT_FALSE(err.empty());
 }
 
 TEST(NinePatchTest, LayoutBounds) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kLayoutBounds5x5, 5, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kLayoutBounds5x5, 5, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->layout_bounds);
 
@@ -272,8 +245,7 @@
 
 TEST(NinePatchTest, PaddingAndLayoutBounds) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kPaddingAndLayoutBounds5x5, 5, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kPaddingAndLayoutBounds5x5, 5, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->padding);
   EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->layout_bounds);
@@ -281,25 +253,20 @@
 
 TEST(NinePatchTest, RegionColorsAreCorrect) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kColorfulImage5x5, 5, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kColorfulImage5x5, 5, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
 
   std::vector<uint32_t> expected_colors = {
-      NinePatch::PackRGBA((uint8_t*)RED),
-      (uint32_t)android::Res_png_9patch::NO_COLOR,
-      NinePatch::PackRGBA((uint8_t*)GREEN),
-      (uint32_t)android::Res_png_9patch::TRANSPARENT_COLOR,
-      NinePatch::PackRGBA((uint8_t*)BLUE),
-      NinePatch::PackRGBA((uint8_t*)GREEN),
+      NinePatch::PackRGBA((uint8_t*)RED),   (uint32_t)android::Res_png_9patch::NO_COLOR,
+      NinePatch::PackRGBA((uint8_t*)GREEN), (uint32_t)android::Res_png_9patch::TRANSPARENT_COLOR,
+      NinePatch::PackRGBA((uint8_t*)BLUE),  NinePatch::PackRGBA((uint8_t*)GREEN),
   };
   EXPECT_EQ(expected_colors, nine_patch->region_colors);
 }
 
 TEST(NinePatchTest, OutlineFromOpaqueImage) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kOutlineOpaque10x10, 10, 10, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineOpaque10x10, 10, 10, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(2, 2, 2, 2), nine_patch->outline);
   EXPECT_EQ(0x000000ffu, nine_patch->outline_alpha);
@@ -308,8 +275,7 @@
 
 TEST(NinePatchTest, OutlineFromTranslucentImage) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kOutlineTranslucent10x10, 10, 10, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineTranslucent10x10, 10, 10, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(3, 3, 3, 3), nine_patch->outline);
   EXPECT_EQ(0x000000b3u, nine_patch->outline_alpha);
@@ -337,8 +303,7 @@
 
 TEST(NinePatchTest, OutlineRadius) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kOutlineRadius5x5, 5, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineRadius5x5, 5, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
   EXPECT_EQ(Bounds(0, 0, 0, 0), nine_patch->outline);
   EXPECT_EQ(3.4142f, nine_patch->outline_radius);
@@ -353,8 +318,7 @@
 
 TEST(NinePatchTest, SerializePngEndianness) {
   std::string err;
-  std::unique_ptr<NinePatch> nine_patch =
-      NinePatch::Create(kStretchAndPadding5x5, 5, 5, &err);
+  std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kStretchAndPadding5x5, 5, 5, &err);
   ASSERT_NE(nullptr, nine_patch);
 
   size_t len;
@@ -374,4 +338,4 @@
   EXPECT_TRUE(BigEndianOne(cursor + 12));
 }
 
-}  // namespace aapt
+}  // namespace android
diff --git a/tools/aapt2/Android.bp b/tools/aapt2/Android.bp
index 412aa9b..275a0e2 100644
--- a/tools/aapt2/Android.bp
+++ b/tools/aapt2/Android.bp
@@ -92,10 +92,6 @@
     srcs: [
         "compile/IdAssigner.cpp",
         "compile/InlineXmlFormatParser.cpp",
-        "compile/NinePatch.cpp",
-        "compile/Png.cpp",
-        "compile/PngChunkFilter.cpp",
-        "compile/PngCrunch.cpp",
         "compile/PseudolocaleGenerator.cpp",
         "compile/Pseudolocalizer.cpp",
         "compile/XmlIdCollector.cpp",
@@ -112,9 +108,7 @@
         "format/binary/XmlFlattener.cpp",
         "format/proto/ProtoDeserialize.cpp",
         "format/proto/ProtoSerialize.cpp",
-        "io/BigBufferStream.cpp",
         "io/File.cpp",
-        "io/FileStream.cpp",
         "io/FileSystem.cpp",
         "io/StringStream.cpp",
         "io/Util.cpp",
diff --git a/tools/aapt2/LoadedApk.cpp b/tools/aapt2/LoadedApk.cpp
index 6b1fd9f..d6502d8 100644
--- a/tools/aapt2/LoadedApk.cpp
+++ b/tools/aapt2/LoadedApk.cpp
@@ -18,12 +18,12 @@
 
 #include "ResourceValues.h"
 #include "ValueVisitor.h"
+#include "androidfw/BigBufferStream.h"
 #include "format/Archive.h"
 #include "format/binary/TableFlattener.h"
 #include "format/binary/XmlFlattener.h"
 #include "format/proto/ProtoDeserialize.h"
 #include "format/proto/ProtoSerialize.h"
-#include "io/BigBufferStream.h"
 #include "io/Util.h"
 #include "xml/XmlDom.h"
 
@@ -48,7 +48,7 @@
     }
 
     // First try in proto format.
-    std::unique_ptr<io::InputStream> manifest_in = manifest_file->OpenInputStream();
+    std::unique_ptr<android::InputStream> manifest_in = manifest_file->OpenInputStream();
     if (manifest_in != nullptr) {
       pb::XmlNode pb_node;
       io::ProtoInputStreamReader proto_reader(manifest_in.get());
@@ -102,7 +102,7 @@
   io::IFile* table_file = collection->FindFile(kProtoResourceTablePath);
   if (table_file != nullptr) {
     pb::ResourceTable pb_table;
-    std::unique_ptr<io::InputStream> in = table_file->OpenInputStream();
+    std::unique_ptr<android::InputStream> in = table_file->OpenInputStream();
     if (in == nullptr) {
       diag->Error(android::DiagMessage(source) << "failed to open " << kProtoResourceTablePath);
       return {};
@@ -129,7 +129,7 @@
     return {};
   }
 
-  std::unique_ptr<io::InputStream> manifest_in = manifest_file->OpenInputStream();
+  std::unique_ptr<android::InputStream> manifest_in = manifest_file->OpenInputStream();
   if (manifest_in == nullptr) {
     diag->Error(android::DiagMessage(source) << "failed to open " << kAndroidManifestPath);
     return {};
@@ -262,7 +262,7 @@
         return false;
       }
 
-      io::BigBufferInputStream input_stream(&buffer);
+      android::BigBufferInputStream input_stream(&buffer);
       if (!io::CopyInputStreamToArchive(context,
                                         &input_stream,
                                         path,
@@ -296,7 +296,7 @@
       }
 
       uint32_t compression_flags = file->WasCompressed() ? ArchiveEntry::kCompress : 0u;
-      io::BigBufferInputStream manifest_buffer_in(&buffer);
+      android::BigBufferInputStream manifest_buffer_in(&buffer);
       if (!io::CopyInputStreamToArchive(context, &manifest_buffer_in, path, compression_flags,
                                         writer)) {
         return false;
@@ -321,7 +321,7 @@
 
   std::unique_ptr<xml::XmlResource> doc;
   if (format_ == ApkFormat::kProto) {
-    std::unique_ptr<io::InputStream> in = file->OpenInputStream();
+    std::unique_ptr<android::InputStream> in = file->OpenInputStream();
     if (!in) {
       diag->Error(android::DiagMessage() << "failed to open file");
       return nullptr;
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index a0b4dab..b351d6e 100644
--- a/tools/aapt2/Main.cpp
+++ b/tools/aapt2/Main.cpp
@@ -27,6 +27,7 @@
 #include "Diagnostics.h"
 #include "android-base/stringprintf.h"
 #include "android-base/utf8.h"
+#include "androidfw/FileStream.h"
 #include "androidfw/IDiagnostics.h"
 #include "androidfw/StringPiece.h"
 #include "cmd/ApkInfo.h"
@@ -37,7 +38,6 @@
 #include "cmd/Dump.h"
 #include "cmd/Link.h"
 #include "cmd/Optimize.h"
-#include "io/FileStream.h"
 #include "trace/TraceBuffer.h"
 #include "util/Files.h"
 #include "util/Util.h"
@@ -99,7 +99,7 @@
  */
 class DaemonCommand : public Command {
  public:
-  explicit DaemonCommand(io::FileOutputStream* out, android::IDiagnostics* diagnostics)
+  explicit DaemonCommand(android::FileOutputStream* out, android::IDiagnostics* diagnostics)
       : Command("daemon", "m"), out_(out), diagnostics_(diagnostics) {
     SetDescription("Runs aapt in daemon mode. Each subsequent line is a single parameter to the\n"
         "command. The end of an invocation is signaled by providing an empty line.");
@@ -147,7 +147,7 @@
   }
 
  private:
-  io::FileOutputStream* out_;
+  android::FileOutputStream* out_;
   android::IDiagnostics* diagnostics_;
   std::optional<std::string> trace_folder_;
 };
@@ -167,7 +167,7 @@
 
   // Use a smaller buffer so that there is less latency for printing to stdout.
   constexpr size_t kStdOutBufferSize = 1024u;
-  aapt::io::FileOutputStream fout(STDOUT_FILENO, kStdOutBufferSize);
+  android::FileOutputStream fout(STDOUT_FILENO, kStdOutBufferSize);
   aapt::text::Printer printer(&fout);
 
   aapt::StdErrDiagnostics diagnostics;
diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp
index 728ba8a..031dd5b 100644
--- a/tools/aapt2/cmd/Compile.cpp
+++ b/tools/aapt2/cmd/Compile.cpp
@@ -25,13 +25,16 @@
 #include "android-base/errors.h"
 #include "android-base/file.h"
 #include "android-base/utf8.h"
+#include "androidfw/BigBufferStream.h"
 #include "androidfw/ConfigDescription.h"
+#include "androidfw/FileStream.h"
 #include "androidfw/IDiagnostics.h"
+#include "androidfw/Image.h"
+#include "androidfw/Png.h"
 #include "androidfw/StringPiece.h"
 #include "cmd/Util.h"
 #include "compile/IdAssigner.h"
 #include "compile/InlineXmlFormatParser.h"
-#include "compile/Png.h"
 #include "compile/PseudolocaleGenerator.h"
 #include "compile/XmlIdCollector.h"
 #include "format/Archive.h"
@@ -39,8 +42,6 @@
 #include "format/proto/ProtoSerialize.h"
 #include "google/protobuf/io/coded_stream.h"
 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
-#include "io/BigBufferStream.h"
-#include "io/FileStream.h"
 #include "io/FileSystem.h"
 #include "io/StringStream.h"
 #include "io/Util.h"
@@ -52,9 +53,9 @@
 #include "xml/XmlDom.h"
 #include "xml/XmlPullParser.h"
 
-using ::aapt::io::FileInputStream;
 using ::aapt::text::Printer;
 using ::android::ConfigDescription;
+using ::android::FileInputStream;
 using ::android::StringPiece;
 using ::android::base::SystemErrorCodeToString;
 using ::google::protobuf::io::CopyingOutputStreamAdaptor;
@@ -241,7 +242,7 @@
   }
 
   if (options.generate_text_symbols_path) {
-    io::FileOutputStream fout_text(options.generate_text_symbols_path.value());
+    android::FileOutputStream fout_text(options.generate_text_symbols_path.value());
 
     if (fout_text.HadError()) {
       context->GetDiagnostics()->Error(android::DiagMessage()
@@ -307,7 +308,7 @@
 }
 
 static bool WriteHeaderAndDataToWriter(StringPiece output_path, const ResourceFile& file,
-                                       io::KnownSizeInputStream* in, IArchiveWriter* writer,
+                                       android::KnownSizeInputStream* in, IArchiveWriter* writer,
                                        android::IDiagnostics* diag) {
   TRACE_CALL();
   // Start the entry so we can write the header.
@@ -448,7 +449,7 @@
   }
 
   if (options.generate_text_symbols_path) {
-    io::FileOutputStream fout_text(options.generate_text_symbols_path.value());
+    android::FileOutputStream fout_text(options.generate_text_symbols_path.value());
 
     if (fout_text.HadError()) {
       context->GetDiagnostics()->Error(android::DiagMessage()
@@ -498,21 +499,22 @@
     }
 
     android::BigBuffer crunched_png_buffer(4096);
-    io::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer);
+    android::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer);
 
     // Ensure that we only keep the chunks we care about if we end up
     // using the original PNG instead of the crunched one.
     const StringPiece content(reinterpret_cast<const char*>(data->data()), data->size());
-    PngChunkFilter png_chunk_filter(content);
-    std::unique_ptr<Image> image = ReadPng(context, path_data.source, &png_chunk_filter);
+    android::PngChunkFilter png_chunk_filter(content);
+    android::SourcePathDiagnostics source_diag(path_data.source, context->GetDiagnostics());
+    auto image = android::ReadPng(&png_chunk_filter, &source_diag);
     if (!image) {
       return false;
     }
 
-    std::unique_ptr<NinePatch> nine_patch;
+    std::unique_ptr<android::NinePatch> nine_patch;
     if (path_data.extension == "9.png") {
       std::string err;
-      nine_patch = NinePatch::Create(image->rows.get(), image->width, image->height, &err);
+      nine_patch = android::NinePatch::Create(image->rows.get(), image->width, image->height, &err);
       if (!nine_patch) {
         context->GetDiagnostics()->Error(android::DiagMessage() << err);
         return false;
@@ -537,7 +539,8 @@
     }
 
     // Write the crunched PNG.
-    if (!WritePng(context, image.get(), nine_patch.get(), &crunched_png_buffer_out, {})) {
+    if (!android::WritePng(image.get(), nine_patch.get(), &crunched_png_buffer_out, {},
+                           &source_diag, context->IsVerbose())) {
       return false;
     }
 
@@ -557,7 +560,7 @@
 
       png_chunk_filter.Rewind();
       android::BigBuffer filtered_png_buffer(4096);
-      io::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer);
+      android::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer);
       io::Copy(&filtered_png_buffer_out, &png_chunk_filter);
       buffer.AppendBuffer(std::move(filtered_png_buffer));
     }
@@ -567,7 +570,7 @@
       // This will help catch exotic cases where the new code may generate larger PNGs.
       std::stringstream legacy_stream{std::string(content)};
       android::BigBuffer legacy_buffer(4096);
-      Png png(context->GetDiagnostics());
+      android::Png png(context->GetDiagnostics());
       if (!png.process(path_data.source, &legacy_stream, &legacy_buffer, {})) {
         return false;
       }
@@ -578,7 +581,7 @@
     }
   }
 
-  io::BigBufferInputStream buffer_in(&buffer);
+  android::BigBufferInputStream buffer_in(&buffer);
   return WriteHeaderAndDataToWriter(output_path, res_file, &buffer_in, writer,
       context->GetDiagnostics());
 }
diff --git a/tools/aapt2/cmd/Compile_test.cpp b/tools/aapt2/cmd/Compile_test.cpp
index 8880089..9337cb9 100644
--- a/tools/aapt2/cmd/Compile_test.cpp
+++ b/tools/aapt2/cmd/Compile_test.cpp
@@ -341,7 +341,7 @@
   // Check resources.pb contains relative sources.
   io::IFile* proto_file =
       apk.get()->GetFileCollection()->FindFile("resources.pb");
-  std::unique_ptr<io::InputStream> proto_stream = proto_file->OpenInputStream();
+  std::unique_ptr<android::InputStream> proto_stream = proto_file->OpenInputStream();
   io::ProtoInputStreamReader proto_reader(proto_stream.get());
   pb::ResourceTable pb_table;
   proto_reader.ReadMessage(&pb_table);
diff --git a/tools/aapt2/cmd/Convert.cpp b/tools/aapt2/cmd/Convert.cpp
index 387dcfe..c132792 100644
--- a/tools/aapt2/cmd/Convert.cpp
+++ b/tools/aapt2/cmd/Convert.cpp
@@ -24,13 +24,13 @@
 #include "android-base/file.h"
 #include "android-base/macros.h"
 #include "android-base/stringprintf.h"
+#include "androidfw/BigBufferStream.h"
 #include "androidfw/StringPiece.h"
 #include "cmd/Util.h"
 #include "format/binary/TableFlattener.h"
 #include "format/binary/XmlFlattener.h"
 #include "format/proto/ProtoDeserialize.h"
 #include "format/proto/ProtoSerialize.h"
-#include "io/BigBufferStream.h"
 #include "io/Util.h"
 #include "process/IResourceTableConsumer.h"
 #include "process/SymbolTable.h"
@@ -80,7 +80,7 @@
       return false;
     }
 
-    io::BigBufferInputStream input_stream(&buffer);
+    android::BigBufferInputStream input_stream(&buffer);
     return io::CopyInputStreamToArchive(context_, &input_stream, path, compression_flags, writer);
   }
 
@@ -91,14 +91,14 @@
       return false;
     }
 
-    io::BigBufferInputStream input_stream(&buffer);
+    android::BigBufferInputStream input_stream(&buffer);
     return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
                                         ArchiveEntry::kAlign, writer);
   }
 
   bool SerializeFile(FileReference* file, IArchiveWriter* writer) override {
     if (file->type == ResourceFile::Type::kProtoXml) {
-      unique_ptr<io::InputStream> in = file->file->OpenInputStream();
+      unique_ptr<android::InputStream> in = file->file->OpenInputStream();
       if (in == nullptr) {
         context_->GetDiagnostics()->Error(android::DiagMessage(source_)
                                           << "failed to open file " << *file->path);
diff --git a/tools/aapt2/cmd/Dump.cpp b/tools/aapt2/cmd/Dump.cpp
index 864af06..6fa9ecb 100644
--- a/tools/aapt2/cmd/Dump.cpp
+++ b/tools/aapt2/cmd/Dump.cpp
@@ -19,19 +19,18 @@
 #include <cinttypes>
 #include <vector>
 
-#include "android-base/stringprintf.h"
-#include "androidfw/ConfigDescription.h"
-#include "androidfw/StringPiece.h"
-
 #include "Debug.h"
 #include "Diagnostics.h"
 #include "LoadedApk.h"
 #include "Util.h"
+#include "android-base/stringprintf.h"
+#include "androidfw/ConfigDescription.h"
+#include "androidfw/FileStream.h"
+#include "androidfw/StringPiece.h"
 #include "format/Container.h"
 #include "format/binary/BinaryResourceParser.h"
 #include "format/binary/XmlFlattener.h"
 #include "format/proto/ProtoDeserialize.h"
-#include "io/FileStream.h"
 #include "io/ZipArchive.h"
 #include "process/IResourceTableConsumer.h"
 #include "text/Printer.h"
@@ -145,7 +144,7 @@
 
   bool error = false;
   for (auto container : args) {
-    io::FileInputStream input(container);
+    android::FileInputStream input(container);
     if (input.HadError()) {
       context.GetDiagnostics()->Error(android::DiagMessage(container)
                                       << "failed to open file: " << input.GetError());
diff --git a/tools/aapt2/cmd/Dump.h b/tools/aapt2/cmd/Dump.h
index 76d33d7..119a59b 100644
--- a/tools/aapt2/cmd/Dump.h
+++ b/tools/aapt2/cmd/Dump.h
@@ -17,7 +17,7 @@
 #ifndef AAPT2_DUMP_H
 #define AAPT2_DUMP_H
 
-#include <io/FileStream.h>
+#include <androidfw/FileStream.h>
 #include <io/ZipArchive.h>
 
 #include "Command.h"
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
index c638873..9ca546f 100644
--- a/tools/aapt2/cmd/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -35,6 +35,8 @@
 #include "android-base/expected.h"
 #include "android-base/file.h"
 #include "android-base/stringprintf.h"
+#include "androidfw/BigBufferStream.h"
+#include "androidfw/FileStream.h"
 #include "androidfw/IDiagnostics.h"
 #include "androidfw/Locale.h"
 #include "androidfw/StringPiece.h"
@@ -48,8 +50,6 @@
 #include "format/binary/XmlFlattener.h"
 #include "format/proto/ProtoDeserialize.h"
 #include "format/proto/ProtoSerialize.h"
-#include "io/BigBufferStream.h"
-#include "io/FileStream.h"
 #include "io/FileSystem.h"
 #include "io/Util.h"
 #include "io/ZipArchive.h"
@@ -73,8 +73,8 @@
 #include "util/Files.h"
 #include "xml/XmlDom.h"
 
-using ::aapt::io::FileInputStream;
 using ::android::ConfigDescription;
+using ::android::FileInputStream;
 using ::android::StringPiece;
 using ::android::base::expected;
 using ::android::base::StringPrintf;
@@ -263,7 +263,7 @@
         return false;
       }
 
-      io::BigBufferInputStream input_stream(&buffer);
+      android::BigBufferInputStream input_stream(&buffer);
       return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
                                           writer);
     } break;
@@ -284,7 +284,7 @@
 static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
                                                  android::IDiagnostics* diag) {
   TRACE_CALL();
-  FileInputStream fin(path);
+  android::FileInputStream fin(path);
   if (fin.HadError()) {
     diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
     return {};
@@ -687,7 +687,7 @@
 static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
                                    const std::unordered_map<ResourceName, ResourceId>& id_map,
                                    const std::string& id_map_path) {
-  io::FileOutputStream fout(id_map_path);
+  android::FileOutputStream fout(id_map_path);
   if (fout.HadError()) {
     diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
     return false;
@@ -1197,7 +1197,7 @@
           return false;
         }
 
-        io::BigBufferInputStream input_stream(&buffer);
+        android::BigBufferInputStream input_stream(&buffer);
         return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
                                             ArchiveEntry::kAlign, writer);
       } break;
@@ -1221,7 +1221,7 @@
     }
 
     std::string out_path;
-    std::unique_ptr<io::FileOutputStream> fout;
+    std::unique_ptr<android::FileOutputStream> fout;
     if (options_.generate_java_class_path) {
       out_path = options_.generate_java_class_path.value();
       file::AppendPath(&out_path, file::PackageToPath(out_package));
@@ -1233,7 +1233,7 @@
 
       file::AppendPath(&out_path, "R.java");
 
-      fout = util::make_unique<io::FileOutputStream>(out_path);
+      fout = util::make_unique<android::FileOutputStream>(out_path);
       if (fout->HadError()) {
         context_->GetDiagnostics()->Error(android::DiagMessage()
                                           << "failed writing to '" << out_path
@@ -1242,9 +1242,9 @@
       }
     }
 
-    std::unique_ptr<io::FileOutputStream> fout_text;
+    std::unique_ptr<android::FileOutputStream> fout_text;
     if (out_text_symbols_path) {
-      fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
+      fout_text = util::make_unique<android::FileOutputStream>(out_text_symbols_path.value());
       if (fout_text->HadError()) {
         context_->GetDiagnostics()->Error(android::DiagMessage()
                                           << "failed writing to '" << out_text_symbols_path.value()
@@ -1386,7 +1386,7 @@
 
     file::AppendPath(&out_path, "Manifest.java");
 
-    io::FileOutputStream fout(out_path);
+    android::FileOutputStream fout(out_path);
     if (fout.HadError()) {
       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
                                                                << "': " << fout.GetError());
@@ -1412,7 +1412,7 @@
     }
 
     const std::string& out_path = out.value();
-    io::FileOutputStream fout(out_path);
+    android::FileOutputStream fout(out_path);
     if (fout.HadError()) {
       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
                                                                << "': " << fout.GetError());
@@ -1601,7 +1601,7 @@
       }
     }
 
-    std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
+    std::unique_ptr<android::InputStream> input_stream = file->OpenInputStream();
     if (input_stream == nullptr) {
       context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
       return false;
diff --git a/tools/aapt2/cmd/Optimize.cpp b/tools/aapt2/cmd/Optimize.cpp
index f045dad..762441e 100644
--- a/tools/aapt2/cmd/Optimize.cpp
+++ b/tools/aapt2/cmd/Optimize.cpp
@@ -30,6 +30,7 @@
 #include "ValueVisitor.h"
 #include "android-base/file.h"
 #include "android-base/stringprintf.h"
+#include "androidfw/BigBufferStream.h"
 #include "androidfw/ConfigDescription.h"
 #include "androidfw/IDiagnostics.h"
 #include "androidfw/ResourceTypes.h"
@@ -39,7 +40,6 @@
 #include "filter/AbiFilter.h"
 #include "format/binary/TableFlattener.h"
 #include "format/binary/XmlFlattener.h"
-#include "io/BigBufferStream.h"
 #include "io/Util.h"
 #include "optimize/MultiApkGenerator.h"
 #include "optimize/Obfuscator.h"
@@ -249,7 +249,7 @@
       return false;
     }
 
-    io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
+    android::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
     if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
                                       ArchiveEntry::kCompress, writer)) {
       return false;
@@ -297,7 +297,7 @@
       return false;
     }
 
-    io::BigBufferInputStream table_buffer_in(&table_buffer);
+    android::BigBufferInputStream table_buffer_in(&table_buffer);
     return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
                                         ArchiveEntry::kAlign, writer);
   }
diff --git a/tools/aapt2/dump/DumpManifest.cpp b/tools/aapt2/dump/DumpManifest.cpp
index a2b4818..a596229 100644
--- a/tools/aapt2/dump/DumpManifest.cpp
+++ b/tools/aapt2/dump/DumpManifest.cpp
@@ -29,8 +29,8 @@
 #include "SdkConstants.h"
 #include "ValueVisitor.h"
 #include "androidfw/ConfigDescription.h"
+#include "androidfw/FileStream.h"
 #include "io/File.h"
-#include "io/FileStream.h"
 #include "process/IResourceTableConsumer.h"
 #include "xml/XmlDom.h"
 
diff --git a/tools/aapt2/format/Archive.cpp b/tools/aapt2/format/Archive.cpp
index e9a93d8..91768a0 100644
--- a/tools/aapt2/format/Archive.cpp
+++ b/tools/aapt2/format/Archive.cpp
@@ -91,7 +91,7 @@
     return true;
   }
 
-  bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override {
+  bool WriteFile(StringPiece path, uint32_t flags, android::InputStream* in) override {
     if (!StartEntry(path, flags)) {
       return false;
     }
@@ -182,7 +182,7 @@
     return true;
   }
 
-  bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override {
+  bool WriteFile(StringPiece path, uint32_t flags, android::InputStream* in) override {
     while (true) {
       if (!StartEntry(path, flags)) {
         return false;
diff --git a/tools/aapt2/format/Archive.h b/tools/aapt2/format/Archive.h
index 6cde753..3c3d0ab 100644
--- a/tools/aapt2/format/Archive.h
+++ b/tools/aapt2/format/Archive.h
@@ -24,9 +24,9 @@
 
 #include "androidfw/BigBuffer.h"
 #include "androidfw/IDiagnostics.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
-#include "io/Io.h"
 #include "util/Files.h"
 
 namespace aapt {
@@ -46,7 +46,7 @@
  public:
   virtual ~IArchiveWriter() = default;
 
-  virtual bool WriteFile(android::StringPiece path, uint32_t flags, io::InputStream* in) = 0;
+  virtual bool WriteFile(android::StringPiece path, uint32_t flags, android::InputStream* in) = 0;
 
   // Starts a new entry and allows caller to write bytes to it sequentially.
   // Only use StartEntry if code you do not control needs to write to a CopyingOutputStream.
diff --git a/tools/aapt2/format/Archive_test.cpp b/tools/aapt2/format/Archive_test.cpp
index fd50af9..df105f8 100644
--- a/tools/aapt2/format/Archive_test.cpp
+++ b/tools/aapt2/format/Archive_test.cpp
@@ -95,7 +95,7 @@
 
 void VerifyZipFile(const std::string& output_path, const std::string& file, const uint8_t array[]) {
   std::unique_ptr<io::ZipFileCollection> zip = io::ZipFileCollection::Create(output_path, nullptr);
-  std::unique_ptr<io::InputStream> stream = zip->FindFile(file)->OpenInputStream();
+  std::unique_ptr<android::InputStream> stream = zip->FindFile(file)->OpenInputStream();
 
   std::vector<uint8_t> buffer;
   const void* data;
diff --git a/tools/aapt2/format/Container.cpp b/tools/aapt2/format/Container.cpp
index 1ff6c49..cb4a225 100644
--- a/tools/aapt2/format/Container.cpp
+++ b/tools/aapt2/format/Container.cpp
@@ -94,7 +94,7 @@
 }
 
 bool ContainerWriter::AddResFileEntry(const pb::internal::CompiledFile& file,
-                                      io::KnownSizeInputStream* in) {
+                                      android::KnownSizeInputStream* in) {
   if (current_entry_count_ >= total_entry_count_) {
     error_ = "too many entries being serialized";
     return false;
@@ -264,7 +264,7 @@
   return reader_->GetError();
 }
 
-ContainerReader::ContainerReader(io::InputStream* in)
+ContainerReader::ContainerReader(android::InputStream* in)
     : in_(in),
       adaptor_(in),
       coded_in_(&adaptor_),
diff --git a/tools/aapt2/format/Container.h b/tools/aapt2/format/Container.h
index 121c592..c5d5676 100644
--- a/tools/aapt2/format/Container.h
+++ b/tools/aapt2/format/Container.h
@@ -22,9 +22,9 @@
 #include "Resources.pb.h"
 #include "ResourcesInternal.pb.h"
 #include "androidfw/BigBuffer.h"
+#include "androidfw/Streams.h"
 #include "google/protobuf/io/coded_stream.h"
 #include "google/protobuf/io/zero_copy_stream.h"
-#include "io/Io.h"
 #include "io/Util.h"
 
 namespace aapt {
@@ -39,7 +39,7 @@
   explicit ContainerWriter(::google::protobuf::io::ZeroCopyOutputStream* out, size_t entry_count);
 
   bool AddResTableEntry(const pb::ResourceTable& table);
-  bool AddResFileEntry(const pb::internal::CompiledFile& file, io::KnownSizeInputStream* in);
+  bool AddResFileEntry(const pb::internal::CompiledFile& file, android::KnownSizeInputStream* in);
   bool HadError() const;
   std::string GetError() const;
 
@@ -79,7 +79,7 @@
 
 class ContainerReader {
  public:
-  explicit ContainerReader(io::InputStream* in);
+  explicit ContainerReader(android::InputStream* in);
 
   ContainerReaderEntry* Next();
 
@@ -91,7 +91,7 @@
 
   friend class ContainerReaderEntry;
 
-  io::InputStream* in_;
+  android::InputStream* in_;
   io::ZeroCopyInputAdaptor adaptor_;
   ::google::protobuf::io::CodedInputStream coded_in_;
   size_t total_entry_count_;
diff --git a/tools/aapt2/io/Data.h b/tools/aapt2/io/Data.h
index db91a77..29f523a 100644
--- a/tools/aapt2/io/Data.h
+++ b/tools/aapt2/io/Data.h
@@ -20,15 +20,14 @@
 #include <memory>
 
 #include "android-base/macros.h"
+#include "androidfw/Streams.h"
 #include "utils/FileMap.h"
 
-#include "io/Io.h"
-
 namespace aapt {
 namespace io {
 
 // Interface for a block of contiguous memory. An instance of this interface owns the data.
-class IData : public KnownSizeInputStream {
+class IData : public android::KnownSizeInputStream {
  public:
   virtual ~IData() = default;
 
diff --git a/tools/aapt2/io/File.cpp b/tools/aapt2/io/File.cpp
index b4f1ff3..4dfdb5b 100644
--- a/tools/aapt2/io/File.cpp
+++ b/tools/aapt2/io/File.cpp
@@ -39,7 +39,7 @@
   return {};
 }
 
-std::unique_ptr<io::InputStream> FileSegment::OpenInputStream() {
+std::unique_ptr<android::InputStream> FileSegment::OpenInputStream() {
   return OpenAsData();
 }
 
diff --git a/tools/aapt2/io/File.h b/tools/aapt2/io/File.h
index 673d1b7..248756b 100644
--- a/tools/aapt2/io/File.h
+++ b/tools/aapt2/io/File.h
@@ -43,7 +43,7 @@
   // Returns nullptr on failure.
   virtual std::unique_ptr<IData> OpenAsData() = 0;
 
-  virtual std::unique_ptr<io::InputStream> OpenInputStream() = 0;
+  virtual std::unique_ptr<android::InputStream> OpenInputStream() = 0;
 
   // Returns the source of this file. This is for presentation to the user and
   // may not be a valid file system path (for example, it may contain a '@' sign to separate
@@ -78,7 +78,7 @@
       : file_(file), offset_(offset), len_(len) {}
 
   std::unique_ptr<IData> OpenAsData() override;
-  std::unique_ptr<io::InputStream> OpenInputStream() override;
+  std::unique_ptr<android::InputStream> OpenInputStream() override;
 
   const android::Source& GetSource() const override {
     return file_->GetSource();
diff --git a/tools/aapt2/io/FileSystem.cpp b/tools/aapt2/io/FileSystem.cpp
index 6a692e4..03fabcc 100644
--- a/tools/aapt2/io/FileSystem.cpp
+++ b/tools/aapt2/io/FileSystem.cpp
@@ -22,9 +22,9 @@
 #include <sys/stat.h>
 
 #include "android-base/errors.h"
+#include "androidfw/FileStream.h"
 #include "androidfw/Source.h"
 #include "androidfw/StringPiece.h"
-#include "io/FileStream.h"
 #include "util/Files.h"
 #include "util/Util.h"
 #include "utils/FileMap.h"
@@ -49,8 +49,8 @@
   return {};
 }
 
-std::unique_ptr<io::InputStream> RegularFile::OpenInputStream() {
-  return util::make_unique<FileInputStream>(source_.path);
+std::unique_ptr<android::InputStream> RegularFile::OpenInputStream() {
+  return util::make_unique<android::FileInputStream>(source_.path);
 }
 
 const android::Source& RegularFile::GetSource() const {
diff --git a/tools/aapt2/io/FileSystem.h b/tools/aapt2/io/FileSystem.h
index f975196..d6ecfeb 100644
--- a/tools/aapt2/io/FileSystem.h
+++ b/tools/aapt2/io/FileSystem.h
@@ -30,7 +30,7 @@
   explicit RegularFile(const android::Source& source);
 
   std::unique_ptr<IData> OpenAsData() override;
-  std::unique_ptr<io::InputStream> OpenInputStream() override;
+  std::unique_ptr<android::InputStream> OpenInputStream() override;
   const android::Source& GetSource() const override;
   bool GetModificationTime(struct tm* buf) const override;
 
diff --git a/tools/aapt2/io/StringStream.cpp b/tools/aapt2/io/StringStream.cpp
index 9c49788..bb3911b 100644
--- a/tools/aapt2/io/StringStream.cpp
+++ b/tools/aapt2/io/StringStream.cpp
@@ -51,6 +51,23 @@
   return str_.size();
 }
 
+bool StringInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) {
+  if (byte_count == 0) {
+    return true;
+  }
+  if (offset < 0) {
+    return false;
+  }
+  if (offset > std::numeric_limits<off64_t>::max() - byte_count) {
+    return false;
+  }
+  if (offset + byte_count > str_.size()) {
+    return false;
+  }
+  memcpy(data, str_.data() + offset, byte_count);
+  return true;
+}
+
 StringOutputStream::StringOutputStream(std::string* str, size_t buffer_capacity)
     : str_(str),
       buffer_capacity_(buffer_capacity),
diff --git a/tools/aapt2/io/StringStream.h b/tools/aapt2/io/StringStream.h
index f7bdecca..7e1abe5 100644
--- a/tools/aapt2/io/StringStream.h
+++ b/tools/aapt2/io/StringStream.h
@@ -17,17 +17,16 @@
 #ifndef AAPT_IO_STRINGSTREAM_H
 #define AAPT_IO_STRINGSTREAM_H
 
-#include "io/Io.h"
-
 #include <memory>
 
 #include "android-base/macros.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
 
 namespace aapt {
 namespace io {
 
-class StringInputStream : public KnownSizeInputStream {
+class StringInputStream : public android::KnownSizeInputStream {
  public:
   explicit StringInputStream(android::StringPiece str);
 
@@ -47,6 +46,8 @@
 
   size_t TotalSize() const override;
 
+  bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(StringInputStream);
 
@@ -54,7 +55,7 @@
   size_t offset_;
 };
 
-class StringOutputStream : public OutputStream {
+class StringOutputStream : public android::OutputStream {
  public:
   explicit StringOutputStream(std::string* str, size_t buffer_capacity = 4096u);
 
diff --git a/tools/aapt2/io/Util.cpp b/tools/aapt2/io/Util.cpp
index 79d8d52..9616e47 100644
--- a/tools/aapt2/io/Util.cpp
+++ b/tools/aapt2/io/Util.cpp
@@ -26,8 +26,9 @@
 namespace aapt {
 namespace io {
 
-bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path,
-                              uint32_t compression_flags, IArchiveWriter* writer) {
+bool CopyInputStreamToArchive(IAaptContext* context, android::InputStream* in,
+                              std::string_view out_path, uint32_t compression_flags,
+                              IArchiveWriter* writer) {
   TRACE_CALL();
   if (context->IsVerbose()) {
     context->GetDiagnostics()->Note(android::DiagMessage()
@@ -91,7 +92,7 @@
   return false;
 }
 
-bool Copy(OutputStream* out, InputStream* in) {
+bool Copy(android::OutputStream* out, android::InputStream* in) {
   TRACE_CALL();
   const void* in_buffer;
   size_t in_len;
@@ -110,7 +111,7 @@
   return !in->HadError();
 }
 
-bool Copy(OutputStream* out, StringPiece in) {
+bool Copy(android::OutputStream* out, StringPiece in) {
   const char* in_buffer = in.data();
   size_t in_len = in.size();
   while (in_len != 0) {
@@ -129,7 +130,7 @@
   return true;
 }
 
-bool Copy(ZeroCopyOutputStream* out, InputStream* in) {
+bool Copy(ZeroCopyOutputStream* out, android::InputStream* in) {
   OutputStreamAdaptor adaptor(out);
   return Copy(&adaptor, in);
 }
diff --git a/tools/aapt2/io/Util.h b/tools/aapt2/io/Util.h
index 685f522..25aa8f8 100644
--- a/tools/aapt2/io/Util.h
+++ b/tools/aapt2/io/Util.h
@@ -19,18 +19,19 @@
 
 #include <string_view>
 
+#include "androidfw/Streams.h"
 #include "format/Archive.h"
 #include "google/protobuf/io/coded_stream.h"
 #include "google/protobuf/message.h"
 #include "io/File.h"
-#include "io/Io.h"
 #include "process/IResourceTableConsumer.h"
 
 namespace aapt {
 namespace io {
 
-bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path,
-                              uint32_t compression_flags, IArchiveWriter* writer);
+bool CopyInputStreamToArchive(IAaptContext* context, android::InputStream* in,
+                              std::string_view out_path, uint32_t compression_flags,
+                              IArchiveWriter* writer);
 
 bool CopyFileToArchive(IAaptContext* context, IFile* file, std::string_view out_path,
                        uint32_t compression_flags, IArchiveWriter* writer);
@@ -44,11 +45,11 @@
 
 // Copies the data from in to out. Returns false if there was an error.
 // If there was an error, check the individual streams' HadError/GetError methods.
-bool Copy(OutputStream* out, InputStream* in);
-bool Copy(OutputStream* out, android::StringPiece in);
-bool Copy(::google::protobuf::io::ZeroCopyOutputStream* out, InputStream* in);
+bool Copy(android::OutputStream* out, android::InputStream* in);
+bool Copy(android::OutputStream* out, android::StringPiece in);
+bool Copy(::google::protobuf::io::ZeroCopyOutputStream* out, android::InputStream* in);
 
-class OutputStreamAdaptor : public io::OutputStream {
+class OutputStreamAdaptor : public android::OutputStream {
  public:
   explicit OutputStreamAdaptor(::google::protobuf::io::ZeroCopyOutputStream* out) : out_(out) {
   }
@@ -84,7 +85,7 @@
 
 class ZeroCopyInputAdaptor : public ::google::protobuf::io::ZeroCopyInputStream {
  public:
-  explicit ZeroCopyInputAdaptor(io::InputStream* in) : in_(in) {
+  explicit ZeroCopyInputAdaptor(android::InputStream* in) : in_(in) {
   }
 
   bool Next(const void** data, int* size) override {
@@ -119,12 +120,13 @@
  private:
   DISALLOW_COPY_AND_ASSIGN(ZeroCopyInputAdaptor);
 
-  io::InputStream* in_;
+  android::InputStream* in_;
 };
 
 class ProtoInputStreamReader {
  public:
-  explicit ProtoInputStreamReader(io::InputStream* in) : in_(in) { }
+  explicit ProtoInputStreamReader(android::InputStream* in) : in_(in) {
+  }
 
   /** Deserializes a Message proto from the current position in the input stream.*/
   template <typename T> bool ReadMessage(T *message) {
@@ -135,7 +137,7 @@
   }
 
  private:
-  io::InputStream* in_;
+  android::InputStream* in_;
 };
 
 }  // namespace io
diff --git a/tools/aapt2/io/ZipArchive.cpp b/tools/aapt2/io/ZipArchive.cpp
index cb5bbe9..e44d61e 100644
--- a/tools/aapt2/io/ZipArchive.cpp
+++ b/tools/aapt2/io/ZipArchive.cpp
@@ -63,7 +63,7 @@
   }
 }
 
-std::unique_ptr<io::InputStream> ZipFile::OpenInputStream() {
+std::unique_ptr<android::InputStream> ZipFile::OpenInputStream() {
   return OpenAsData();
 }
 
diff --git a/tools/aapt2/io/ZipArchive.h b/tools/aapt2/io/ZipArchive.h
index ac125d0..a53c4a2 100644
--- a/tools/aapt2/io/ZipArchive.h
+++ b/tools/aapt2/io/ZipArchive.h
@@ -35,7 +35,7 @@
   ZipFile(::ZipArchiveHandle handle, const ::ZipEntry& entry, const android::Source& source);
 
   std::unique_ptr<IData> OpenAsData() override;
-  std::unique_ptr<io::InputStream> OpenInputStream() override;
+  std::unique_ptr<android::InputStream> OpenInputStream() override;
   const android::Source& GetSource() const override;
   bool WasCompressed() override;
   bool GetModificationTime(struct tm* buf) const override;
diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp
index 98f3bd2..db7aa35 100644
--- a/tools/aapt2/java/ClassDefinition.cpp
+++ b/tools/aapt2/java/ClassDefinition.cpp
@@ -111,7 +111,7 @@
     " */\n\n";
 
 void ClassDefinition::WriteJavaFile(const ClassDefinition* def, StringPiece package, bool final,
-                                    bool strip_api_annotations, io::OutputStream* out) {
+                                    bool strip_api_annotations, android::OutputStream* out) {
   Printer printer(out);
   printer.Print(sWarningHeader).Print("package ").Print(package).Println(";");
   printer.Println();
diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h
index 63c9982..84e3f33 100644
--- a/tools/aapt2/java/ClassDefinition.h
+++ b/tools/aapt2/java/ClassDefinition.h
@@ -241,7 +241,7 @@
 class ClassDefinition : public ClassMember {
  public:
   static void WriteJavaFile(const ClassDefinition* def, android::StringPiece package, bool final,
-                            bool strip_api_annotations, io::OutputStream* out);
+                            bool strip_api_annotations, android::OutputStream* out);
 
   ClassDefinition(android::StringPiece name, ClassQualifier qualifier, bool createIfEmpty)
       : name_(name), qualifier_(qualifier), create_if_empty_(createIfEmpty) {
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp
index 7665d0e..58f6564 100644
--- a/tools/aapt2/java/JavaClassGenerator.cpp
+++ b/tools/aapt2/java/JavaClassGenerator.cpp
@@ -37,8 +37,8 @@
 #include "java/ClassDefinition.h"
 #include "process/SymbolTable.h"
 
-using ::aapt::io::OutputStream;
 using ::aapt::text::Printer;
+using ::android::OutputStream;
 using ::android::StringPiece;
 using ::android::base::StringPrintf;
 
diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h
index 234df04..9909eec 100644
--- a/tools/aapt2/java/JavaClassGenerator.h
+++ b/tools/aapt2/java/JavaClassGenerator.h
@@ -19,11 +19,10 @@
 
 #include <string>
 
-#include "androidfw/StringPiece.h"
-
 #include "ResourceTable.h"
 #include "ResourceValues.h"
-#include "io/Io.h"
+#include "androidfw/Streams.h"
+#include "androidfw/StringPiece.h"
 #include "process/IResourceTableConsumer.h"
 #include "process/SymbolTable.h"
 #include "text/Printer.h"
@@ -70,12 +69,12 @@
   // All symbols technically belong to a single package, but linked libraries will
   // have their names mangled, denoting that they came from a different package.
   // We need to generate these symbols in a separate file. Returns true on success.
-  bool Generate(android::StringPiece package_name_to_generate, io::OutputStream* out,
-                io::OutputStream* out_r_txt = nullptr);
+  bool Generate(android::StringPiece package_name_to_generate, android::OutputStream* out,
+                android::OutputStream* out_r_txt = nullptr);
 
   bool Generate(android::StringPiece package_name_to_generate,
-                android::StringPiece output_package_name, io::OutputStream* out,
-                io::OutputStream* out_r_txt = nullptr);
+                android::StringPiece output_package_name, android::OutputStream* out,
+                android::OutputStream* out_r_txt = nullptr);
 
   const std::string& GetError() const;
 
diff --git a/tools/aapt2/java/ProguardRules.cpp b/tools/aapt2/java/ProguardRules.cpp
index 80a46d5..aef48fc 100644
--- a/tools/aapt2/java/ProguardRules.cpp
+++ b/tools/aapt2/java/ProguardRules.cpp
@@ -29,8 +29,8 @@
 #include "util/Util.h"
 #include "xml/XmlDom.h"
 
-using ::aapt::io::OutputStream;
 using ::aapt::text::Printer;
+using ::android::OutputStream;
 
 namespace aapt {
 namespace proguard {
diff --git a/tools/aapt2/java/ProguardRules.h b/tools/aapt2/java/ProguardRules.h
index 267f7ed..876ef48 100644
--- a/tools/aapt2/java/ProguardRules.h
+++ b/tools/aapt2/java/ProguardRules.h
@@ -26,8 +26,8 @@
 #include "ResourceTable.h"
 #include "ValueVisitor.h"
 #include "androidfw/Source.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
-#include "io/Io.h"
 #include "process/IResourceTableConsumer.h"
 #include "xml/XmlDom.h"
 
@@ -69,7 +69,7 @@
   }
 
  private:
-  friend void WriteKeepSet(const KeepSet& keep_set, io::OutputStream* out, bool minimal_keep,
+  friend void WriteKeepSet(const KeepSet& keep_set, android::OutputStream* out, bool minimal_keep,
                            bool no_location_reference);
 
   friend bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set,
@@ -89,7 +89,7 @@
 
 bool CollectResourceReferences(IAaptContext* context, ResourceTable* table, KeepSet* keep_set);
 
-void WriteKeepSet(const KeepSet& keep_set, io::OutputStream* out, bool minimal_keep,
+void WriteKeepSet(const KeepSet& keep_set, android::OutputStream* out, bool minimal_keep,
                   bool no_location_reference);
 
 bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set,
diff --git a/tools/aapt2/test/Common.h b/tools/aapt2/test/Common.h
index e48668c..0437980 100644
--- a/tools/aapt2/test/Common.h
+++ b/tools/aapt2/test/Common.h
@@ -90,7 +90,7 @@
     return {};
   }
 
-  std::unique_ptr<io::InputStream> OpenInputStream() override {
+  std::unique_ptr<android::InputStream> OpenInputStream() override {
     return OpenAsData();
   }
 
diff --git a/tools/aapt2/test/Fixture.cpp b/tools/aapt2/test/Fixture.cpp
index 428372f..b91abe5 100644
--- a/tools/aapt2/test/Fixture.cpp
+++ b/tools/aapt2/test/Fixture.cpp
@@ -20,6 +20,7 @@
 #include <android-base/file.h>
 #include <android-base/stringprintf.h>
 #include <android-base/utf8.h>
+#include <androidfw/FileStream.h>
 #include <androidfw/StringPiece.h>
 #include <dirent.h>
 #include <gmock/gmock.h>
@@ -28,7 +29,6 @@
 #include "Diagnostics.h"
 #include "cmd/Compile.h"
 #include "cmd/Link.h"
-#include "io/FileStream.h"
 #include "util/Files.h"
 
 using testing::Eq;
diff --git a/tools/aapt2/text/Printer.cpp b/tools/aapt2/text/Printer.cpp
index 8e491ac..c2fa8cc 100644
--- a/tools/aapt2/text/Printer.cpp
+++ b/tools/aapt2/text/Printer.cpp
@@ -20,7 +20,7 @@
 
 #include "io/Util.h"
 
-using ::aapt::io::OutputStream;
+using ::android::OutputStream;
 using ::android::StringPiece;
 
 namespace aapt {
diff --git a/tools/aapt2/text/Printer.h b/tools/aapt2/text/Printer.h
index f7ad98b..44f0fc5 100644
--- a/tools/aapt2/text/Printer.h
+++ b/tools/aapt2/text/Printer.h
@@ -18,17 +18,16 @@
 #define AAPT_TEXT_PRINTER_H
 
 #include "android-base/macros.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
 
-#include "io/Io.h"
-
 namespace aapt {
 namespace text {
 
 // An indenting Printer that helps write formatted text to the OutputStream.
 class Printer {
  public:
-  explicit Printer(::aapt::io::OutputStream* out) : out_(out) {
+  explicit Printer(android::OutputStream* out) : out_(out) {
   }
 
   Printer& Print(android::StringPiece str);
@@ -41,7 +40,7 @@
  private:
   DISALLOW_COPY_AND_ASSIGN(Printer);
 
-  ::aapt::io::OutputStream* out_;
+  android::OutputStream* out_;
   int indent_level_ = 0;
   bool needs_indent_ = false;
   bool error_ = false;
diff --git a/tools/aapt2/xml/XmlDom.cpp b/tools/aapt2/xml/XmlDom.cpp
index 8dea8ea..49807db 100644
--- a/tools/aapt2/xml/XmlDom.cpp
+++ b/tools/aapt2/xml/XmlDom.cpp
@@ -30,7 +30,7 @@
 #include "XmlPullParser.h"
 #include "util/Util.h"
 
-using ::aapt::io::InputStream;
+using ::android::InputStream;
 using ::android::StringPiece;
 using ::android::StringPiece16;
 
diff --git a/tools/aapt2/xml/XmlDom.h b/tools/aapt2/xml/XmlDom.h
index c253b0a..9668b6a6 100644
--- a/tools/aapt2/xml/XmlDom.h
+++ b/tools/aapt2/xml/XmlDom.h
@@ -24,8 +24,8 @@
 #include "Resource.h"
 #include "ResourceValues.h"
 #include "androidfw/IDiagnostics.h"
+#include "androidfw/Streams.h"
 #include "androidfw/StringPiece.h"
-#include "io/Io.h"
 #include "util/Util.h"
 #include "xml/XmlUtil.h"
 
@@ -152,7 +152,7 @@
 };
 
 // Inflates an XML DOM from an InputStream, logging errors to the logger.
-std::unique_ptr<XmlResource> Inflate(io::InputStream* in, android::IDiagnostics* diag,
+std::unique_ptr<XmlResource> Inflate(android::InputStream* in, android::IDiagnostics* diag,
                                      const android::Source& source);
 
 // Inflates an XML DOM from a binary ResXMLTree.
diff --git a/tools/aapt2/xml/XmlPullParser.cpp b/tools/aapt2/xml/XmlPullParser.cpp
index d79446b..203832d 100644
--- a/tools/aapt2/xml/XmlPullParser.cpp
+++ b/tools/aapt2/xml/XmlPullParser.cpp
@@ -21,7 +21,7 @@
 #include "xml/XmlPullParser.h"
 #include "xml/XmlUtil.h"
 
-using ::aapt::io::InputStream;
+using ::android::InputStream;
 using ::android::StringPiece;
 
 namespace aapt {
diff --git a/tools/aapt2/xml/XmlPullParser.h b/tools/aapt2/xml/XmlPullParser.h
index fe4cd01..655e6dc 100644
--- a/tools/aapt2/xml/XmlPullParser.h
+++ b/tools/aapt2/xml/XmlPullParser.h
@@ -27,11 +27,10 @@
 #include <string>
 #include <vector>
 
-#include "android-base/macros.h"
-#include "androidfw/StringPiece.h"
-
 #include "Resource.h"
-#include "io/Io.h"
+#include "android-base/macros.h"
+#include "androidfw/Streams.h"
+#include "androidfw/StringPiece.h"
 #include "process/IResourceTableConsumer.h"
 #include "xml/XmlUtil.h"
 
@@ -66,7 +65,7 @@
   static bool SkipCurrentElement(XmlPullParser* parser);
   static bool IsGoodEvent(Event event);
 
-  explicit XmlPullParser(io::InputStream* in);
+  explicit XmlPullParser(android::InputStream* in);
   ~XmlPullParser();
 
   /**
@@ -179,7 +178,7 @@
     std::vector<Attribute> attributes;
   };
 
-  io::InputStream* in_;
+  android::InputStream* in_;
   XML_Parser parser_;
   std::queue<EventData> event_queue_;
   std::string error_;