Android examples for java.lang:array
Splits an array of NAL units.
/*//from ww w . j a v a 2 s .co m * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import java.util.ArrayList; import java.util.List; public class Main { private static final byte[] NAL_START_CODE = new byte[] { 0, 0, 0, 1 }; /** * Splits an array of NAL units. * <p> * If the input consists of NAL start code delimited units, then the returned array consists of * the split NAL units, each of which is still prefixed with the NAL start code. For any other * input, null is returned. * * @param data An array of data. * @return The individual NAL units, or null if the input did not consist of NAL start code * delimited units. */ public static byte[][] splitNalUnits(byte[] data) { if (!isNalStartCode(data, 0)) { // data does not consist of NAL start code delimited units. return null; } List<Integer> starts = new ArrayList<>(); int nalUnitIndex = 0; do { starts.add(nalUnitIndex); nalUnitIndex = findNalStartCode(data, nalUnitIndex + NAL_START_CODE.length); } while (nalUnitIndex != -1); byte[][] split = new byte[starts.size()][]; for (int i = 0; i < starts.size(); i++) { int startIndex = starts.get(i); int endIndex = i < starts.size() - 1 ? starts.get(i + 1) : data.length; byte[] nal = new byte[endIndex - startIndex]; System.arraycopy(data, startIndex, nal, 0, nal.length); split[i] = nal; } return split; } /** * Tests whether there exists a NAL start code at a given index. * * @param data The data. * @param index The index to test. * @return Whether there exists a start code that begins at {@code index}. */ private static boolean isNalStartCode(byte[] data, int index) { if (data.length - index <= NAL_START_CODE.length) { return false; } for (int j = 0; j < NAL_START_CODE.length; j++) { if (data[index + j] != NAL_START_CODE[j]) { return false; } } return true; } /** * Finds the next occurrence of the NAL start code from a given index. * * @param data The data in which to search. * @param index The first index to test. * @return The index of the first byte of the found start code, or -1. */ private static int findNalStartCode(byte[] data, int index) { int endIndex = data.length - NAL_START_CODE.length; for (int i = index; i <= endIndex; i++) { if (isNalStartCode(data, i)) { return i; } } return -1; } }