1package com.android.rs.refocus;
2
3import android.graphics.Bitmap;
4import com.android.rs.refocus.DepthTransform;
5import com.android.rs.refocus.image.RangeLinearDepthTransform;
6import java.io.InputStream;
7import java.io.IOException;
8import java.lang.RuntimeException;
9import java.lang.StringBuffer;
10import java.nio.ByteBuffer;
11import java.nio.FloatBuffer;
12import java.nio.ByteOrder;
13
14public class PortableFloatMap {
15
16    private int mWidth;
17    private int mHeight;
18    private float mScale;
19    private boolean mLittleEndian;
20    private ByteOrder mByteOrder;
21
22    private int mBytesPerPixel;
23    private ByteBuffer mData;
24
25    private static String readString(InputStream in)
26            throws IOException {
27        StringBuffer buffer = new StringBuffer();
28        int c;
29        while ((c = in.read()) != -1 && c != 0xa && c != 0x20) {
30            buffer.append((char)c);
31        }
32        return buffer.toString();
33    }
34
35    public PortableFloatMap(InputStream in)
36            throws IOException {
37        String formatLine = readString(in);
38
39        if (formatLine.compareTo("Pf") != 0) {
40            // Currently "PF" (RGB32F) is not supported.
41            // Only "Pf" (Greyscale32F) is supported.
42            throw new RuntimeException("Unexpected format line: " + formatLine);
43        }
44
45        mBytesPerPixel = 4;
46
47        String widthLine = readString(in);
48
49        mWidth = Integer.parseInt(widthLine);
50
51        String heightLine = readString(in);
52
53        mHeight = Integer.parseInt(heightLine);
54
55        final int bytesPerRow = mBytesPerPixel * mWidth;
56
57        mData = ByteBuffer.allocate(bytesPerRow * mHeight);
58
59        String scaleLine = readString(in);
60
61        mScale = Float.parseFloat(scaleLine);
62
63        mData.order(mScale < 0 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
64
65        byte[] row = new byte[mBytesPerPixel * mWidth];
66
67        for (int y = 0; y < mHeight; y++) {
68            int nRead = 0;
69            int offset = 0;
70            while (offset < bytesPerRow) {
71                nRead = in.read(row, offset, bytesPerRow - offset);
72                if (nRead < 0) {
73                    throw new RuntimeException("Unexpected End of File.");
74                }
75                offset += nRead;
76            }
77            mData.put(row);
78        }
79        mData.rewind();
80    }
81
82    final float[] getPixelArray() {
83        FloatBuffer floatBuffer = mData.asFloatBuffer();
84        if (floatBuffer.hasArray()) {
85            return floatBuffer.array();
86        }
87
88        float[] array = new float[mWidth * mHeight];
89        floatBuffer.get(array);
90
91        return array;
92    }
93
94    int getWidth() { return mWidth; }
95
96    int getHeight() { return mHeight; }
97}
98