Search in sources :

Example 61 with DoubleBuffer

use of java.nio.DoubleBuffer in project ojAlgo by optimatika.

the class BufferArray method create.

private static BasicArray<Double> create(final File file, final long... structure) {
    final long tmpCount = StructureAnyD.count(structure);
    DoubleBuffer tmpDoubleBuffer = null;
    try {
        final RandomAccessFile tmpRandomAccessFile = new RandomAccessFile(file, "rw");
        final FileChannel tmpFileChannel = tmpRandomAccessFile.getChannel();
        final long tmpSize = DOUBLE_ELEMENT_SIZE * tmpCount;
        if (tmpCount > (1L << 8)) {
            final DenseArray.Factory<Double> tmpFactory = new DenseArray.Factory<Double>() {

                long offset = 0L;

                @Override
                public AggregatorSet<Double> aggregator() {
                    return PrimitiveAggregator.getSet();
                }

                @Override
                public FunctionSet<Double> function() {
                    return PrimitiveFunction.getSet();
                }

                @Override
                public Scalar.Factory<Double> scalar() {
                    return PrimitiveScalar.FACTORY;
                }

                @Override
                long getElementSize() {
                    return DOUBLE_ELEMENT_SIZE;
                }

                @Override
                PlainArray<Double> make(final long size) {
                    final long tmpSize2 = size * DOUBLE_ELEMENT_SIZE;
                    try {
                        final MappedByteBuffer tmpMap = tmpFileChannel.map(MapMode.READ_WRITE, offset, tmpSize2);
                        tmpMap.order(ByteOrder.nativeOrder());
                        return new DoubleBufferArray(tmpMap.asDoubleBuffer(), tmpRandomAccessFile);
                    } catch (final IOException exception) {
                        throw new RuntimeException(exception);
                    } finally {
                        offset += tmpSize2;
                    }
                }
            };
            return tmpFactory.makeSegmented(structure);
        } else {
            final MappedByteBuffer tmpMappedByteBuffer = tmpFileChannel.map(FileChannel.MapMode.READ_WRITE, 0L, tmpSize);
            tmpMappedByteBuffer.order(ByteOrder.nativeOrder());
            tmpDoubleBuffer = tmpMappedByteBuffer.asDoubleBuffer();
            return new DoubleBufferArray(tmpDoubleBuffer, tmpRandomAccessFile);
        }
    } catch (final FileNotFoundException exception) {
        throw new RuntimeException(exception);
    } catch (final IOException exception) {
        throw new RuntimeException(exception);
    }
}
Also used : DoubleBuffer(java.nio.DoubleBuffer) FileChannel(java.nio.channels.FileChannel) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) PrimitiveScalar(org.ojalgo.scalar.PrimitiveScalar) Scalar(org.ojalgo.scalar.Scalar) RandomAccessFile(java.io.RandomAccessFile) MappedByteBuffer(java.nio.MappedByteBuffer)

Example 62 with DoubleBuffer

use of java.nio.DoubleBuffer in project GltfSerializers by opensourceBIM.

the class BinaryGltfSerializer method addNode.

private String addNode(String meshName, IfcProduct ifcProduct) {
    String nodeName = "node_" + ifcProduct.getOid();
    ObjectNode nodeNode = OBJECT_MAPPER.createObjectNode();
    ArrayNode matrixArray = OBJECT_MAPPER.createArrayNode();
    ByteBuffer matrixByteBuffer = ByteBuffer.wrap(ifcProduct.getGeometry().getTransformation());
    matrixByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    DoubleBuffer doubleBuffer = matrixByteBuffer.asDoubleBuffer();
    for (int i = 0; i < 16; i++) {
        matrixArray.add(doubleBuffer.get(i));
    }
    ArrayNode meshes = OBJECT_MAPPER.createArrayNode();
    meshes.add(meshName);
    nodeNode.set("meshes", meshes);
    nodeNode.set("matrix", matrixArray);
    nodes.set(nodeName, nodeNode);
    return nodeName;
}
Also used : DoubleBuffer(java.nio.DoubleBuffer) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ByteBuffer(java.nio.ByteBuffer)

Example 63 with DoubleBuffer

use of java.nio.DoubleBuffer in project GltfSerializers by opensourceBIM.

the class BinaryGltfSerializer2 method addNode.

private int addNode(int meshId, IfcProduct ifcProduct) {
    ObjectNode nodeNode = OBJECT_MAPPER.createObjectNode();
    ArrayNode matrixArray = OBJECT_MAPPER.createArrayNode();
    ByteBuffer matrixByteBuffer = ByteBuffer.wrap(ifcProduct.getGeometry().getTransformation());
    matrixByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    DoubleBuffer doubleBuffer = matrixByteBuffer.asDoubleBuffer();
    double[] buffer = new double[16];
    for (int i = 0; i < 16; i++) {
        double d = doubleBuffer.get(i);
        matrixArray.add(d);
        buffer[i] = d;
    }
    nodeNode.put("mesh", meshId);
    if (!Matrix.isIdentity(buffer)) {
        nodeNode.set("matrix", matrixArray);
    }
    nodes.add(nodeNode);
    return nodes.size() - 1;
}
Also used : DoubleBuffer(java.nio.DoubleBuffer) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ByteBuffer(java.nio.ByteBuffer)

Example 64 with DoubleBuffer

use of java.nio.DoubleBuffer in project GltfSerializers by opensourceBIM.

the class BinaryGltfSerializer2 method generateSceneAndBody.

private void generateSceneAndBody() throws SerializerException {
    int totalBodyByteLength = 0;
    int totalIndicesByteLength = 0;
    int totalVerticesByteLength = 0;
    int totalNormalsByteLength = 0;
    int totalColorsByteLength = 0;
    int maxIndexValues = 16389;
    for (IfcProduct ifcProduct : model.getAllWithSubTypes(IfcProduct.class)) {
        GeometryInfo geometryInfo = ifcProduct.getGeometry();
        if (!ifcProduct.eClass().getName().equals("IfcOpeningElement") && geometryInfo != null && geometryInfo.getData().getVertices().length > 0) {
            GeometryData data = geometryInfo.getData();
            int nrIndicesBytes = data.getIndices().length;
            totalIndicesByteLength += nrIndicesBytes / 2;
            if (nrIndicesBytes > 4 * maxIndexValues) {
                int nrIndices = nrIndicesBytes / 4;
                totalVerticesByteLength += nrIndices * 3 * 4;
                totalNormalsByteLength += nrIndices * 3 * 4;
                if (data.getMaterials() != null) {
                    totalColorsByteLength += nrIndices * 4 * 4;
                }
            } else {
                totalVerticesByteLength += data.getVertices().length;
                totalNormalsByteLength += data.getNormals().length;
                if (data.getMaterials() != null) {
                    totalColorsByteLength += data.getMaterials().length;
                }
            }
        }
    }
    totalBodyByteLength = totalIndicesByteLength + totalVerticesByteLength + totalNormalsByteLength + totalColorsByteLength;
    body = ByteBuffer.allocate(totalBodyByteLength + materialColorFragmentShaderBytes.length + materialColorVertexShaderBytes.length + vertexColorFragmentShaderBytes.length + vertexColorVertexShaderBytes.length);
    body.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuffer newIndicesBuffer = ByteBuffer.allocate(totalIndicesByteLength);
    newIndicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuffer newVerticesBuffer = ByteBuffer.allocate(totalVerticesByteLength);
    newVerticesBuffer.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuffer newNormalsBuffer = ByteBuffer.allocate(totalNormalsByteLength);
    newNormalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuffer newColorsBuffer = ByteBuffer.allocate(totalColorsByteLength);
    newColorsBuffer.order(ByteOrder.LITTLE_ENDIAN);
    int indicesBufferView = createBufferView(totalIndicesByteLength, 0, ELEMENT_ARRAY_BUFFER, -1);
    int verticesBufferView = createBufferView(totalVerticesByteLength, totalIndicesByteLength, ARRAY_BUFFER, 12);
    int normalsBufferView = createBufferView(totalNormalsByteLength, totalIndicesByteLength + totalVerticesByteLength, ARRAY_BUFFER, 12);
    int colorsBufferView = -1;
    scenesNode.add(createDefaultScene());
    gltfNode.put("scene", 0);
    createModelNode();
    for (IfcProduct ifcProduct : model.getAllWithSubTypes(IfcProduct.class)) {
        GeometryInfo geometryInfo = ifcProduct.getGeometry();
        if (!ifcProduct.eClass().getName().equals("IfcOpeningElement") && geometryInfo != null) {
            ByteBuffer matrixByteBuffer = ByteBuffer.wrap(ifcProduct.getGeometry().getTransformation());
            matrixByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            DoubleBuffer doubleBuffer = matrixByteBuffer.asDoubleBuffer();
            float[] matrix = new float[16];
            for (int i = 0; i < doubleBuffer.capacity(); i++) {
                matrix[i] = (float) doubleBuffer.get();
            }
            updateExtends(geometryInfo, matrix);
        }
    }
    float[] offsets = getOffsets();
    // This will "normalize" the model by moving it's axis-aligned bounding box center to the 0-point. This will always be the wrong position, but at least the building will be close to the 0-point
    modelTranslation.add(-offsets[0]);
    modelTranslation.add(-offsets[1]);
    modelTranslation.add(-offsets[2]);
    for (IfcProduct ifcProduct : model.getAllWithSubTypes(IfcProduct.class)) {
        GeometryInfo geometryInfo = ifcProduct.getGeometry();
        if (!ifcProduct.eClass().getName().equals("IfcOpeningElement") && geometryInfo != null && geometryInfo.getData().getVertices().length > 0) {
            int startPositionIndices = newIndicesBuffer.position();
            int startPositionVertices = newVerticesBuffer.position();
            int startPositionNormals = newNormalsBuffer.position();
            int startPositionColors = newColorsBuffer.position();
            GeometryData data = geometryInfo.getData();
            ByteBuffer indicesBuffer = ByteBuffer.wrap(data.getIndices());
            indicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
            IntBuffer indicesIntBuffer = indicesBuffer.asIntBuffer();
            ByteBuffer verticesBuffer = ByteBuffer.wrap(data.getVertices());
            verticesBuffer.order(ByteOrder.LITTLE_ENDIAN);
            FloatBuffer verticesFloatBuffer = verticesBuffer.asFloatBuffer();
            ByteBuffer normalsBuffer = ByteBuffer.wrap(data.getNormals());
            normalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
            FloatBuffer normalsFloatBuffer = normalsBuffer.asFloatBuffer();
            FloatBuffer materialsFloatBuffer = null;
            if (data.getMaterials() != null) {
                ByteBuffer materialsBuffer = ByteBuffer.wrap(data.getMaterials());
                materialsBuffer.order(ByteOrder.LITTLE_ENDIAN);
                materialsFloatBuffer = materialsBuffer.asFloatBuffer();
            }
            if (data.getIndices().length > 4 * maxIndexValues) {
                int totalNrIndices = indicesIntBuffer.capacity();
                int nrParts = (totalNrIndices + maxIndexValues - 1) / maxIndexValues;
                ArrayNode primitivesNode = OBJECT_MAPPER.createArrayNode();
                for (int part = 0; part < nrParts; part++) {
                    startPositionIndices = newIndicesBuffer.position();
                    startPositionVertices = newVerticesBuffer.position();
                    startPositionNormals = newNormalsBuffer.position();
                    startPositionColors = newColorsBuffer.position();
                    short indexCounter = 0;
                    int upto = Math.min((part + 1) * maxIndexValues, totalNrIndices);
                    for (int i = part * maxIndexValues; i < upto; i++) {
                        newIndicesBuffer.putShort(indexCounter++);
                    }
                    int[] min = new int[] { 0 };
                    int[] max = new int[] { upto };
                    int nrVertices = upto - part * maxIndexValues;
                    for (int i = part * maxIndexValues; i < upto; i += 3) {
                        int oldIndex1 = indicesIntBuffer.get(i);
                        int oldIndex2 = indicesIntBuffer.get(i + 1);
                        int oldIndex3 = indicesIntBuffer.get(i + 2);
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex1 * 3));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex1 * 3 + 1));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex1 * 3 + 2));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex2 * 3));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex2 * 3 + 1));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex2 * 3 + 2));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex3 * 3));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex3 * 3 + 1));
                        newVerticesBuffer.putFloat(verticesFloatBuffer.get(oldIndex3 * 3 + 2));
                    }
                    for (int i = part * maxIndexValues; i < upto; i += 3) {
                        int oldIndex1 = indicesIntBuffer.get(i);
                        int oldIndex2 = indicesIntBuffer.get(i + 1);
                        int oldIndex3 = indicesIntBuffer.get(i + 2);
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex1 * 3));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex1 * 3 + 1));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex1 * 3 + 2));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex2 * 3));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex2 * 3 + 1));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex2 * 3 + 2));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex3 * 3));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex3 * 3 + 1));
                        newNormalsBuffer.putFloat(normalsFloatBuffer.get(oldIndex3 * 3 + 2));
                    }
                    if (materialsFloatBuffer != null) {
                        for (int i = part * maxIndexValues; i < upto; i += 3) {
                            int oldIndex1 = indicesIntBuffer.get(i);
                            int oldIndex2 = indicesIntBuffer.get(i + 1);
                            int oldIndex3 = indicesIntBuffer.get(i + 2);
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex1 * 4));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex1 * 4 + 1));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex1 * 4 + 2));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex1 * 4 + 3));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex2 * 4));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex2 * 4 + 1));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex2 * 4 + 2));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex2 * 4 + 3));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex3 * 4));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex3 * 4 + 1));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex3 * 4 + 2));
                            newColorsBuffer.putFloat(materialsFloatBuffer.get(oldIndex3 * 4 + 3));
                        }
                    }
                    ObjectNode primitiveNode = OBJECT_MAPPER.createObjectNode();
                    int indicesAccessor = addIndicesAccessor(ifcProduct, indicesBufferView, startPositionIndices, nrVertices / 3, min, max);
                    int verticesAccessor = addVerticesAccessor(ifcProduct, verticesBufferView, startPositionVertices, nrVertices);
                    int normalsAccessor = addNormalsAccessor(ifcProduct, normalsBufferView, startPositionNormals, nrVertices);
                    int colorAccessor = -1;
                    if (data.getMaterials() != null) {
                        if (colorsBufferView == -1) {
                            colorsBufferView = createBufferView(totalColorsByteLength, totalIndicesByteLength + totalVerticesByteLength + totalNormalsByteLength, ARRAY_BUFFER, 16);
                        }
                        colorAccessor = addColorsAccessor(ifcProduct, colorsBufferView, startPositionColors, 16);
                    }
                    primitivesNode.add(primitiveNode);
                    primitiveNode.put("indices", indicesAccessor);
                    primitiveNode.put("mode", TRIANGLES);
                    ObjectNode attributesNode = OBJECT_MAPPER.createObjectNode();
                    primitiveNode.set("attributes", attributesNode);
                    attributesNode.put("NORMAL", normalsAccessor);
                    attributesNode.put("POSITION", verticesAccessor);
                    if (colorAccessor != -1) {
                        // attributesNode.put("COLOR_0", colorAccessor);
                        primitiveNode.put("material", vertexColorIndex);
                    } else {
                        primitiveNode.put("material", createOrGetMaterial(ifcProduct.eClass().getName(), IfcColors.getDefaultColor(ifcProduct.eClass().getName())));
                    }
                }
                int meshId = addMesh(ifcProduct, primitivesNode);
                int nodeId = addNode(meshId, ifcProduct);
                translationChildrenNode.add(nodeId);
            } else {
                int maxVal = 0;
                for (int i = 0; i < indicesIntBuffer.capacity(); i++) {
                    int index = indicesIntBuffer.get(i);
                    if (index > Short.MAX_VALUE) {
                        throw new SerializerException("Index too large to store as short " + index);
                    }
                    newIndicesBuffer.putShort((short) (index));
                    if (index > maxVal) {
                        maxVal = index;
                    }
                }
                int[] min = new int[] { 0 };
                int[] max = new int[] { maxVal };
                newVerticesBuffer.put(data.getVertices());
                newNormalsBuffer.put(data.getNormals());
                if (data.getMaterials() != null) {
                    newColorsBuffer.put(data.getMaterials());
                }
                int totalNrIndices = indicesIntBuffer.capacity();
                ArrayNode primitivesNode = OBJECT_MAPPER.createArrayNode();
                ObjectNode primitiveNode = OBJECT_MAPPER.createObjectNode();
                int indicesAccessor = addIndicesAccessor(ifcProduct, indicesBufferView, startPositionIndices, totalNrIndices, min, max);
                int verticesAccessor = addVerticesAccessor(ifcProduct, verticesBufferView, startPositionVertices, data.getVertices().length / 12);
                int normalsAccessor = addNormalsAccessor(ifcProduct, normalsBufferView, startPositionNormals, data.getNormals().length / 12);
                int colorAccessor = -1;
                if (data.getMaterials() != null) {
                    if (colorsBufferView == -1) {
                        colorsBufferView = createBufferView(totalColorsByteLength, totalIndicesByteLength + totalVerticesByteLength + totalNormalsByteLength, ARRAY_BUFFER, 16);
                    }
                    colorAccessor = addColorsAccessor(ifcProduct, colorsBufferView, startPositionColors, data.getVertices().length / 12);
                }
                primitivesNode.add(primitiveNode);
                primitiveNode.put("indices", indicesAccessor);
                primitiveNode.put("mode", TRIANGLES);
                ObjectNode attributesNode = OBJECT_MAPPER.createObjectNode();
                primitiveNode.set("attributes", attributesNode);
                attributesNode.put("NORMAL", normalsAccessor);
                attributesNode.put("POSITION", verticesAccessor);
                if (colorAccessor != -1) {
                    attributesNode.put("COLOR_0", colorAccessor);
                    primitiveNode.put("material", vertexColorIndex);
                } else {
                    primitiveNode.put("material", createOrGetMaterial(ifcProduct.eClass().getName(), IfcColors.getDefaultColor(ifcProduct.eClass().getName())));
                }
                int meshId = addMesh(ifcProduct, primitivesNode);
                int nodeId = addNode(meshId, ifcProduct);
                translationChildrenNode.add(nodeId);
            }
        }
    }
    if (newIndicesBuffer.position() != newIndicesBuffer.capacity()) {
        throw new SerializerException("Not all space used");
    }
    if (newVerticesBuffer.position() != newVerticesBuffer.capacity()) {
        throw new SerializerException("Not all space used");
    }
    if (newNormalsBuffer.position() != newNormalsBuffer.capacity()) {
        throw new SerializerException("Not all space used");
    }
    if (newColorsBuffer.position() != newColorsBuffer.capacity()) {
        throw new SerializerException("Not all space used");
    }
    newIndicesBuffer.position(0);
    newVerticesBuffer.position(0);
    newNormalsBuffer.position(0);
    newColorsBuffer.position(0);
    body.put(newIndicesBuffer);
    body.put(newVerticesBuffer);
    body.put(newNormalsBuffer);
    body.put(newColorsBuffer);
    int vertexColorFragmentShaderBufferViewName = createBufferView(vertexColorFragmentShaderBytes.length, body.position(), -1, -1);
    body.put(vertexColorFragmentShaderBytes);
    int vertexColorVertexShaderBufferViewName = createBufferView(vertexColorVertexShaderBytes.length, body.position(), -1, -1);
    body.put(vertexColorVertexShaderBytes);
    int materialColorFragmentShaderBufferViewName = createBufferView(materialColorFragmentShaderBytes.length, body.position(), -1, -1);
    body.put(materialColorFragmentShaderBytes);
    int materialColorVertexShaderBufferViewName = createBufferView(materialColorVertexShaderBytes.length, body.position(), -1, -1);
    body.put(materialColorVertexShaderBytes);
    // gltfNode.set("animations", createAnimations());
    gltfNode.set("asset", createAsset());
    // gltfNode.set("programs", createPrograms());
    gltfNode.put("scene", 0);
    // gltfNode.set("skins", createSkins());
    // gltfNode.set("techniques", createTechniques());
    // createVertexColorShaders(vertexColorFragmentShaderBufferViewName, vertexColorVertexShaderBufferViewName);
    // createMaterialColorShaders(materialColorFragmentShaderBufferViewName, materialColorVertexShaderBufferViewName);
    addBuffer(body.capacity());
// ArrayNode extensions = OBJECT_MAPPER.createArrayNode();
// extensions.add("KHR_binary_glTF");
// gltfNode.set("extensionsUsed", extensions);
}
Also used : DoubleBuffer(java.nio.DoubleBuffer) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) GeometryData(org.bimserver.models.geometry.GeometryData) FloatBuffer(java.nio.FloatBuffer) ByteBuffer(java.nio.ByteBuffer) SerializerException(org.bimserver.plugins.serializers.SerializerException) IntBuffer(java.nio.IntBuffer) GeometryInfo(org.bimserver.models.geometry.GeometryInfo) IfcProduct(org.bimserver.models.ifc2x3tc1.IfcProduct) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 65 with DoubleBuffer

use of java.nio.DoubleBuffer in project javacv by bytedeco.

the class FFmpegFrameRecorder method recordSamples.

public boolean recordSamples(int sampleRate, int audioChannels, Buffer... samples) throws Exception {
    if (audio_st == null) {
        throw new Exception("No audio output stream (Is audioChannels > 0 and has start() been called?)");
    }
    if (samples == null && samples_out[0].position() > 0) {
        // Typically samples_out[0].limit() is double the audio_input_frame_size --> sampleDivisor = 2
        double sampleDivisor = Math.floor((int) Math.min(samples_out[0].limit(), Integer.MAX_VALUE) / audio_input_frame_size);
        writeSamples((int) Math.floor((int) samples_out[0].position() / sampleDivisor));
        return record((AVFrame) null);
    }
    int ret;
    if (sampleRate <= 0) {
        sampleRate = audio_c.sample_rate();
    }
    if (audioChannels <= 0) {
        audioChannels = audio_c.channels();
    }
    int inputSize = samples != null ? samples[0].limit() - samples[0].position() : 0;
    int inputFormat = samples_format;
    int inputChannels = samples != null && samples.length > 1 ? 1 : audioChannels;
    int inputDepth = 0;
    int outputFormat = audio_c.sample_fmt();
    int outputChannels = samples_out.length > 1 ? 1 : audio_c.channels();
    int outputDepth = av_get_bytes_per_sample(outputFormat);
    if (samples != null && samples[0] instanceof ByteBuffer) {
        inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_U8P : AV_SAMPLE_FMT_U8;
        inputDepth = 1;
        for (int i = 0; i < samples.length; i++) {
            ByteBuffer b = (ByteBuffer) samples[i];
            if (samples_in[i] instanceof BytePointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                ((BytePointer) samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
            } else {
                samples_in[i] = new BytePointer(b);
            }
        }
    } else if (samples != null && samples[0] instanceof ShortBuffer) {
        inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_S16P : AV_SAMPLE_FMT_S16;
        inputDepth = 2;
        for (int i = 0; i < samples.length; i++) {
            ShortBuffer b = (ShortBuffer) samples[i];
            if (samples_in[i] instanceof ShortPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                ((ShortPointer) samples_in[i]).position(0).put(b.array(), samples[i].position(), inputSize);
            } else {
                samples_in[i] = new ShortPointer(b);
            }
        }
    } else if (samples != null && samples[0] instanceof IntBuffer) {
        inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_S32P : AV_SAMPLE_FMT_S32;
        inputDepth = 4;
        for (int i = 0; i < samples.length; i++) {
            IntBuffer b = (IntBuffer) samples[i];
            if (samples_in[i] instanceof IntPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                ((IntPointer) samples_in[i]).position(0).put(b.array(), samples[i].position(), inputSize);
            } else {
                samples_in[i] = new IntPointer(b);
            }
        }
    } else if (samples != null && samples[0] instanceof FloatBuffer) {
        inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_FLTP : AV_SAMPLE_FMT_FLT;
        inputDepth = 4;
        for (int i = 0; i < samples.length; i++) {
            FloatBuffer b = (FloatBuffer) samples[i];
            if (samples_in[i] instanceof FloatPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                ((FloatPointer) samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
            } else {
                samples_in[i] = new FloatPointer(b);
            }
        }
    } else if (samples != null && samples[0] instanceof DoubleBuffer) {
        inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_DBLP : AV_SAMPLE_FMT_DBL;
        inputDepth = 8;
        for (int i = 0; i < samples.length; i++) {
            DoubleBuffer b = (DoubleBuffer) samples[i];
            if (samples_in[i] instanceof DoublePointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                ((DoublePointer) samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
            } else {
                samples_in[i] = new DoublePointer(b);
            }
        }
    } else if (samples != null) {
        throw new Exception("Audio samples Buffer has unsupported type: " + samples);
    }
    if (samples_convert_ctx == null || samples_channels != audioChannels || samples_format != inputFormat || samples_rate != sampleRate) {
        samples_convert_ctx = swr_alloc_set_opts(samples_convert_ctx, audio_c.channel_layout(), outputFormat, audio_c.sample_rate(), av_get_default_channel_layout(audioChannels), inputFormat, sampleRate, 0, null);
        if (samples_convert_ctx == null) {
            throw new Exception("swr_alloc_set_opts() error: Cannot allocate the conversion context.");
        } else if ((ret = swr_init(samples_convert_ctx)) < 0) {
            throw new Exception("swr_init() error " + ret + ": Cannot initialize the conversion context.");
        }
        samples_channels = audioChannels;
        samples_format = inputFormat;
        samples_rate = sampleRate;
    }
    for (int i = 0; samples != null && i < samples.length; i++) {
        samples_in[i].position(samples_in[i].position() * inputDepth).limit((samples_in[i].position() + inputSize) * inputDepth);
    }
    while (true) {
        int inputCount = (int) Math.min(samples != null ? (samples_in[0].limit() - samples_in[0].position()) / (inputChannels * inputDepth) : 0, Integer.MAX_VALUE);
        int outputCount = (int) Math.min((samples_out[0].limit() - samples_out[0].position()) / (outputChannels * outputDepth), Integer.MAX_VALUE);
        inputCount = Math.min(inputCount, (outputCount * sampleRate + audio_c.sample_rate() - 1) / audio_c.sample_rate());
        for (int i = 0; samples != null && i < samples.length; i++) {
            samples_in_ptr.put(i, samples_in[i]);
        }
        for (int i = 0; i < samples_out.length; i++) {
            samples_out_ptr.put(i, samples_out[i]);
        }
        if ((ret = swr_convert(samples_convert_ctx, samples_out_ptr, outputCount, samples_in_ptr, inputCount)) < 0) {
            throw new Exception("swr_convert() error " + ret + ": Cannot convert audio samples.");
        } else if (ret == 0) {
            break;
        }
        for (int i = 0; samples != null && i < samples.length; i++) {
            samples_in[i].position(samples_in[i].position() + inputCount * inputChannels * inputDepth);
        }
        for (int i = 0; i < samples_out.length; i++) {
            samples_out[i].position(samples_out[i].position() + ret * outputChannels * outputDepth);
        }
        if (samples == null || samples_out[0].position() >= samples_out[0].limit()) {
            writeSamples(audio_input_frame_size);
        }
    }
    return samples != null ? frame.key_frame() != 0 : record((AVFrame) null);
}
Also used : DoubleBuffer(java.nio.DoubleBuffer) BytePointer(org.bytedeco.javacpp.BytePointer) DoublePointer(org.bytedeco.javacpp.DoublePointer) FloatBuffer(java.nio.FloatBuffer) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) ShortPointer(org.bytedeco.javacpp.ShortPointer) FloatPointer(org.bytedeco.javacpp.FloatPointer) IntBuffer(java.nio.IntBuffer) IntPointer(org.bytedeco.javacpp.IntPointer) ShortBuffer(java.nio.ShortBuffer)

Aggregations

DoubleBuffer (java.nio.DoubleBuffer)162 ByteBuffer (java.nio.ByteBuffer)39 FloatBuffer (java.nio.FloatBuffer)26 IntBuffer (java.nio.IntBuffer)25 ShortBuffer (java.nio.ShortBuffer)22 LongBuffer (java.nio.LongBuffer)14 CharBuffer (java.nio.CharBuffer)11 BufferOverflowException (java.nio.BufferOverflowException)8 IOException (java.io.IOException)5 BufferUnderflowException (java.nio.BufferUnderflowException)5 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 ServerDenseDoubleRow (com.tencent.angel.ps.impl.matrix.ServerDenseDoubleRow)4 Test (org.junit.Test)4 InvalidMarkException (java.nio.InvalidMarkException)3 Random (java.util.Random)3 BytePointer (org.bytedeco.javacpp.BytePointer)3 DoublePointer (org.bytedeco.javacpp.DoublePointer)3 FloatPointer (org.bytedeco.javacpp.FloatPointer)3 IntPointer (org.bytedeco.javacpp.IntPointer)3