package com.google.android.libraries.motionphotoreader;

import androidx.annotation.Nullable;

import com.adobe.internal.xmp.XMPException;
import com.adobe.internal.xmp.XMPMeta;
import com.adobe.internal.xmp.XMPMetaFactory;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Bytes;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * The XmpParser class is a package-private class intended to help extract the microvideo offset
 * information from the XMP metadata of the given Motion Photo. This class is for internal use only.
 */
class XmpParser {

    private static final byte[] OPEN_ARR = "<x:xmpmeta".getBytes();  /* Start of XMP metadata tag */
    private static final byte[] CLOSE_ARR = "</x:xmpmeta>".getBytes();  /* End of XMP metadata tag */

    /**
     * Returns the metadata of the Motion Photo file.
     */
    @Nullable
    public static XMPMeta getXmpMetadata(String filename) throws IOException, XMPException {
        try (FileInputStream in = new FileInputStream(filename)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteStreams.copy(in, out);

            byte[] fileData = out.toByteArray();

            int openIdx = Bytes.indexOf(fileData, OPEN_ARR);
            if (openIdx >= 0) {
                int closeIdx = Bytes.indexOf(Arrays.copyOfRange(fileData, openIdx, fileData.length), CLOSE_ARR) + openIdx + CLOSE_ARR.length;

                byte[] segArr = Arrays.copyOfRange(fileData, openIdx, closeIdx);
                return XMPMetaFactory.parseFromBuffer(segArr);
            }
        }
        return null;
    }
}
@@ -86,16 +86,62 @@
 ullable;
+%0Aimport androidx.annotation.VisibleForTesting;
 %0A%0Aimport
@@ -1078,16 +1078,299 @@
 ption %7B%0A
+        byte%5B%5D segArr = getXmpByteArray(filename);%0A        return XMPMetaFactory.parseFromBuffer(segArr);%0A    %7D%0A%0A    /**%0A     * Returns the byte array containing the xmp metadata.%0A     */%0A    @VisibleForTesting%0A    static byte%5B%5D getXmpByteArray(String filename) throws IOException %7B%0A
         
@@ -1931,46 +1931,14 @@
 urn 
-XMPMetaFactory.parseFromBuffer(
 segArr
-)
 ;%0A  
@@ -1975,19 +1975,26 @@
 return n
-ull
+ew byte%5B0%5D
 ;%0A    %7D%0A

Refactor to allow for unit testing.