Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * 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.
 */

import java.nio.ByteBuffer;

public class Main {
    private static final int NAL_UNIT_TYPE_SPS = 7;

    /**
     * Discards data from the buffer up to the first SPS, where {@code data.position()} is interpreted
     * as the length of the buffer.
     * <p>
     * When the method returns, {@code data.position()} will contain the new length of the buffer. If
     * the buffer is not empty it is guaranteed to start with an SPS.
     *
     * @param data Buffer containing start code delimited NAL units.
     */
    public static void discardToSps(ByteBuffer data) {
        int length = data.position();
        int consecutiveZeros = 0;
        int offset = 0;
        while (offset + 1 < length) {
            int value = data.get(offset) & 0xFF;
            if (consecutiveZeros == 3) {
                if (value == 1 && (data.get(offset + 1) & 0x1F) == NAL_UNIT_TYPE_SPS) {
                    // Copy from this NAL unit onwards to the start of the buffer.
                    ByteBuffer offsetData = data.duplicate();
                    offsetData.position(offset - 3);
                    offsetData.limit(length);
                    data.position(0);
                    data.put(offsetData);
                    return;
                }
            } else if (value == 0) {
                consecutiveZeros++;
            }
            if (value != 0) {
                consecutiveZeros = 0;
            }
            offset++;
        }
        // Empty the buffer if the SPS NAL unit was not found.
        data.clear();
    }
}