Example usage for java.nio ByteBuffer getFloat

List of usage examples for java.nio ByteBuffer getFloat

Introduction

In this page you can find the example usage for java.nio ByteBuffer getFloat.

Prototype

public abstract float getFloat();

Source Link

Document

Returns the float at the current position and increases the position by 4.

Usage

From source file:net.pms.util.AudioUtils.java

/**
 * Parses the old RealAudio 1.0 and 2.0 formats that's not supported by
 * neither {@link org.jaudiotagger} nor MediaInfo. Returns {@code false} if
 * {@code channel} isn't one of these formats or the parsing fails.
 * <p>/* ww w. ja v a 2s  .com*/
 * Primary references:
 * <ul>
 * <li><a href="https://wiki.multimedia.cx/index.php/RealMedia">RealAudio on
 * MultimediaWiki</a></li>
 * <li><a
 * href="https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/rmdec.c"
 * >FFmpeg rmdec.c</a></li>
 * </ul>
 *
 * @param channel the {@link Channel} containing the input. Size will only
 *            be parsed if {@code channel} is a {@link FileChannel}
 *            instance.
 * @param media the {@link DLNAMediaInfo} instance to write the parsing
 *            results to.
 * @return {@code true} if the {@code channel} input is in RealAudio 1.0 or
 *         2.0 format and the parsing succeeds; false otherwise
 */
public static boolean parseRealAudio(ReadableByteChannel channel, DLNAMediaInfo media) {
    final byte[] magicBytes = { 0x2E, 0x72, 0x61, (byte) 0xFD };
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.BIG_ENDIAN);
    DLNAMediaAudio audio = new DLNAMediaAudio();
    try {
        int count = channel.read(buffer);
        if (count < 4) {
            LOGGER.trace("Input is too short to be RealAudio");
            return false;
        }
        buffer.flip();
        byte[] signature = new byte[4];
        buffer.get(signature);
        if (!Arrays.equals(magicBytes, signature)) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Input signature ({}) mismatches RealAudio version 1.0 or 2.0",
                        new String(signature, StandardCharsets.US_ASCII));
            }
            return false;
        }
        media.setContainer(FormatConfiguration.RA);
        short version = buffer.getShort();
        int reportedHeaderSize = 0;
        int reportedDataSize = 0;
        if (version == 3) {
            audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
            audio.getAudioProperties().setNumberOfChannels(1);
            audio.getAudioProperties().setSampleFrequency(8000);
            short headerSize = buffer.getShort();

            buffer = ByteBuffer.allocate(headerSize);
            channel.read(buffer);
            buffer.flip();
            buffer.position(8);
            int bytesPerMinute = buffer.getShort() & 0xFFFF;
            reportedDataSize = buffer.getInt();
            byte b = buffer.get();
            if (b != 0) {
                byte[] title = new byte[b & 0xFF];
                buffer.get(title);
                String titleString = new String(title, StandardCharsets.US_ASCII);
                audio.setSongname(titleString);
                audio.setAudioTrackTitleFromMetadata(titleString);
            }
            b = buffer.get();
            if (b != 0) {
                byte[] artist = new byte[b & 0xFF];
                buffer.get(artist);
                audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
            }
            audio.setBitRate(bytesPerMinute * 8 / 60);
            media.setBitrate(bytesPerMinute * 8 / 60);
        } else if (version == 4 || version == 5) {
            buffer = ByteBuffer.allocate(14);
            channel.read(buffer);
            buffer.flip();
            buffer.get(signature);
            if (!".ra4".equals(new String(signature, StandardCharsets.US_ASCII))) {
                LOGGER.debug("Invalid RealAudio 2.0 signature \"{}\"",
                        new String(signature, StandardCharsets.US_ASCII));
                return false;
            }
            reportedDataSize = buffer.getInt();
            buffer.getShort(); //skip version repeated
            reportedHeaderSize = buffer.getInt();

            buffer = ByteBuffer.allocate(reportedHeaderSize);
            channel.read(buffer);
            buffer.flip();
            buffer.getShort(); // skip codec flavor
            buffer.getInt(); // skip coded frame size
            buffer.getInt(); // skip unknown
            long bytesPerMinute = buffer.getInt() & 0xFFFFFFFFL;
            buffer.getInt(); // skip unknown
            buffer.getShort(); // skip sub packet
            buffer.getShort(); // skip frame size
            buffer.getShort(); // skip sub packet size
            buffer.getShort(); // skip unknown
            if (version == 5) {
                buffer.position(buffer.position() + 6); // skip unknown
            }
            short sampleRate = buffer.getShort();
            buffer.getShort(); // skip unknown
            short sampleSize = buffer.getShort();
            short nrChannels = buffer.getShort();
            byte[] fourCC;
            if (version == 4) {
                buffer.position(buffer.get() + buffer.position()); // skip interleaver id
                fourCC = new byte[buffer.get()];
                buffer.get(fourCC);
            } else {
                buffer.getFloat(); // skip deinterlace id
                fourCC = new byte[4];
                buffer.get(fourCC);
            }
            String fourCCString = new String(fourCC, StandardCharsets.US_ASCII).toLowerCase(Locale.ROOT);
            switch (fourCCString) {
            case "lpcJ":
                audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
                break;
            case "28_8":
                audio.setCodecA(FormatConfiguration.REALAUDIO_28_8);
                break;
            case "dnet":
                audio.setCodecA(FormatConfiguration.AC3);
                break;
            case "sipr":
                audio.setCodecA(FormatConfiguration.SIPRO);
                break;
            case "cook":
                audio.setCodecA(FormatConfiguration.COOK);
            case "atrc":
                audio.setCodecA(FormatConfiguration.ATRAC);
            case "ralf":
                audio.setCodecA(FormatConfiguration.RALF);
            case "raac":
                audio.setCodecA(FormatConfiguration.AAC_LC);
            case "racp":
                audio.setCodecA(FormatConfiguration.HE_AAC);
            default:
                LOGGER.debug("Unknown RealMedia codec FourCC \"{}\" - parsing failed", fourCCString);
                return false;
            }

            if (buffer.hasRemaining()) {
                parseRealAudioMetaData(buffer, audio, version);
            }

            audio.setBitRate((int) (bytesPerMinute * 8 / 60));
            media.setBitrate((int) (bytesPerMinute * 8 / 60));
            audio.setBitsperSample(sampleSize);
            audio.getAudioProperties().setNumberOfChannels(nrChannels);
            audio.getAudioProperties().setSampleFrequency(sampleRate);
        } else {
            LOGGER.error("Could not parse RealAudio format - unknown format version {}", version);
            return false;
        }

        media.getAudioTracksList().add(audio);
        long fileSize = 0;
        if (channel instanceof FileChannel) {
            fileSize = ((FileChannel) channel).size();
            media.setSize(fileSize);
        }
        // Duration is estimated based on bitrate and might not be accurate
        if (audio.getBitRate() > 0) {
            int dataSize;
            if (fileSize > 0 && reportedHeaderSize > 0) {
                int fullHeaderSize = reportedHeaderSize + (version == 3 ? 8 : 16);
                if (reportedDataSize > 0) {
                    dataSize = (int) Math.min(reportedDataSize, fileSize - fullHeaderSize);
                } else {
                    dataSize = (int) (fileSize - fullHeaderSize);
                }
            } else {
                dataSize = reportedDataSize;
            }
            media.setDuration((double) dataSize / audio.getBitRate() * 8);
        }

    } catch (IOException e) {
        LOGGER.debug("Error while trying to parse RealAudio version 1 or 2: {}", e.getMessage());
        LOGGER.trace("", e);
        return false;
    }
    if (PMS.getConfiguration() != null
            && !PMS.getConfiguration().getAudioThumbnailMethod().equals(CoverSupplier.NONE)
            && (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())
                    || StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist()))) {
        ID3v1Tag tag = new ID3v1Tag();
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())) {
            tag.setTitle(media.getFirstAudioTrack().getSongname());
        }
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist())) {
            tag.setArtist(media.getFirstAudioTrack().getArtist());
        }
        try {
            media.setThumb(DLNAThumbnail.toThumbnail(CoverUtil.get().getThumbnail(tag), 640, 480, ScaleType.MAX,
                    ImageFormat.SOURCE, false));
        } catch (IOException e) {
            LOGGER.error("An error occurred while generating thumbnail for RealAudio source: [\"{}\", \"{}\"]",
                    tag.getFirstTitle(), tag.getFirstArtist());
        }
    }
    media.setThumbready(true);
    media.setMediaparsed(true);

    return true;
}

From source file:au.org.ala.layers.intersect.Grid.java

public float[] getGrid() {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (grid_data != null) {
        return grid_data;
    }/*from   w w  w. ja va2 s  . c o  m*/

    Grid loadedAlready = getLoadedGrid(filename);
    if (loadedAlready != null && loadedAlready.grid_data != null) {
        return loadedAlready.grid_data;
    }

    int length = nrows * ncols;

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[(int) Math.min(afile.length(), maxArrayLength)];

        int i = 0;
        int max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[i] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

public void getClassInfo(Map<Float, float[]> info) {

    long length = ((long) nrows) * ((long) ncols);

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {/* w w  w.  java  2 s.  c  o m*/
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];

        long i = 0;
        long max = 0;
        long len;
        float v;
        float ndv = (float) nodatavalue;

        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v < 0)
                        v += 256;
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getFloat();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = (float) bb.getDouble();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * Increase sampleEveryNthPoint to return a smaller grid.
 *
 * Grid max and min values may be skipped.
 *
 * This does not used previously cached data.
 *
 * @param sampleEveryNthPoint/*from  w w  w . j a  v  a  2s  .c  om*/
 * @return
 */
public float[] getGrid(int sampleEveryNthPoint) {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (subgrids != null) {
        //sample points
        int size = 1000;
        double[][] points = new double[size * size][2];
        int pos = 0;
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                points[pos][0] = xmin + (xmax - xmin) * j / (double) size;
                points[pos][1] = ymax - (ymax - ymin) * i / (double) size;
                pos++;
            }
        }

        return getValues3(points, 64);
    }

    int length = (nrows / sampleEveryNthPoint) * (ncols);

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        int sz = (int) Math.min(afile.length() / sampleEveryNthPoint / sampleEveryNthPoint, maxArrayLength);
        sz += 8 - sz % 8;
        byte[] b = new byte[sz];

        long i = 0;
        long max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.get();
                    if (ret[(int) (i / sampleEveryNthPoint)] < 0) {
                        ret[(int) (i / sampleEveryNthPoint)] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / (long) sampleEveryNthPoint)] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[(int) (i / (long) sampleEveryNthPoint)] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[(int) i] == (float) nodatavalue) {
                ret[(int) i] = Float.NaN;
            } else {
                ret[(int) i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

float[] getGrid(double xmin, double ymin, double xmax, double ymax) {
    //expects largest y at the top
    //expects input ranges inside of grid ranges

    int width = (int) ((xmax - xmin) / xres);
    int height = (int) ((ymax - ymin) / yres);
    int startx = (int) ((xmin - this.xmin) / xres);
    int endx = startx + width;
    int starty = (int) ((ymin - this.ymin) / yres);
    //int endy = starty + height;

    int length = width * height;

    float[] ret = new float[length];
    int pos = 0;/*from  w w  w . jav  a 2  s. c  o m*/

    int i;
    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    int size = 4;
    if (datatype.equals("BYTE") || datatype.equals("UBYTE")) {
        size = 1;
    } else if (datatype.equals("SHORT")) {
        size = 2;
    } else if (datatype.equals("INT")) {
        size = 4;
    } else if (datatype.equals("LONG")) {
        size = 8;
    } else if (datatype.equals("FLOAT")) {
        size = 4;
    } else if (datatype.equals("DOUBLE")) {
        size = 8;
    }

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        //seek to first raster
        afile.seek(((long) this.ncols) * starty * size);

        //read relevant rasters
        int readSize = this.ncols * height * size;
        int readLen = this.ncols * height;
        byte[] b = new byte[readSize];
        afile.read(b);
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        }

        if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos++] = bb.get();
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos] = bb.get();
                    if (ret[pos] < 0) {
                        ret[pos] += 256;
                    }
                    pos++;
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getShort();
                } else {
                    ret[pos++] = bb.getShort();
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getInt();
                } else {
                    ret[pos++] = bb.getInt();
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getLong();
                } else {
                    ret[pos++] = bb.getLong();
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getFloat();
                } else {
                    ret[pos++] = bb.getFloat();
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getDouble();
                } else {
                    ret[pos++] = (float) bb.getDouble();
                }
            }
        } else {
            // / should not happen; catch anyway...
            for (i = 0; i < length; i++) {
                ret[i] = Float.NaN;
            }
        }
        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("GRID: " + e.toString(), e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}