mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-19 14:52:40 +08:00
Remove some format rule (#10919)
* remove some rules * format all codes with new format rule
This commit is contained in:
@@ -4,8 +4,6 @@ BasedOnStyle: Google
|
||||
|
||||
AccessModifierOffset: -4
|
||||
AlignConsecutiveMacros: true
|
||||
AlignConsecutiveAssignments: true
|
||||
AlignConsecutiveDeclarations: true
|
||||
AllowShortCaseLabelsOnASingleLine: true
|
||||
ColumnLimit: 0
|
||||
ConstructorInitializerIndentWidth: 0
|
||||
@@ -19,6 +17,4 @@ ObjCSpaceAfterProperty: true
|
||||
|
||||
---
|
||||
Language: Cpp
|
||||
# Force pointers to the type for C++.
|
||||
DerivePointerAlignment: false
|
||||
PointerAlignment: Right
|
||||
DerivePointerAlignment: true
|
||||
@@ -56,7 +56,7 @@ uint32_t getComponentByteLength(gfx::Format format) {
|
||||
using DataReaderCallback = std::function<TypedArrayElementType(uint32_t)>;
|
||||
|
||||
DataReaderCallback getReader(const DataView &dataView, gfx::Format format) {
|
||||
const auto & info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const uint32_t stride = info.size / info.count;
|
||||
|
||||
switch (info.type) {
|
||||
@@ -113,7 +113,7 @@ DataReaderCallback getReader(const DataView &dataView, gfx::Format format) {
|
||||
using DataWritterCallback = std::function<void(uint32_t, TypedArrayElementType)>;
|
||||
|
||||
DataWritterCallback getWriter(DataView &dataView, gfx::Format format) {
|
||||
const auto & info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const uint32_t stride = info.size / info.count;
|
||||
|
||||
switch (info.type) {
|
||||
@@ -225,7 +225,7 @@ void Mesh::initialize() {
|
||||
_initialized = true;
|
||||
|
||||
if (_struct.dynamic.has_value()) {
|
||||
auto * device = gfx::Device::getInstance();
|
||||
auto *device = gfx::Device::getInstance();
|
||||
gfx::BufferList vertexBuffers;
|
||||
|
||||
for (const auto &vertexBundle : _struct.vertexBundles) {
|
||||
@@ -237,8 +237,8 @@ void Mesh::initialize() {
|
||||
}
|
||||
|
||||
for (auto i = 0U; i < _struct.primitives.size(); i++) {
|
||||
const auto & primitive = _struct.primitives[i];
|
||||
const auto & indexView = primitive.indexView;
|
||||
const auto &primitive = _struct.primitives[i];
|
||||
const auto &indexView = primitive.indexView;
|
||||
gfx::Buffer *indexBuffer = nullptr;
|
||||
|
||||
if (indexView.has_value()) {
|
||||
@@ -274,10 +274,10 @@ void Mesh::initialize() {
|
||||
return;
|
||||
}
|
||||
|
||||
auto & buffer = _data;
|
||||
gfx::Device * gfxDevice = gfx::Device::getInstance();
|
||||
auto vertexBuffers = createVertexBuffers(gfxDevice, buffer.buffer());
|
||||
gfx::BufferList indexBuffers;
|
||||
auto &buffer = _data;
|
||||
gfx::Device *gfxDevice = gfx::Device::getInstance();
|
||||
auto vertexBuffers = createVertexBuffers(gfxDevice, buffer.buffer());
|
||||
gfx::BufferList indexBuffers;
|
||||
ccstd::vector<IntrusivePtr<RenderingSubMesh>> subMeshes;
|
||||
|
||||
for (size_t i = 0; i < _struct.primitives.size(); i++) {
|
||||
@@ -291,7 +291,7 @@ void Mesh::initialize() {
|
||||
const auto &idxView = prim.indexView.value();
|
||||
|
||||
uint32_t dstStride = idxView.stride;
|
||||
uint32_t dstSize = idxView.length;
|
||||
uint32_t dstSize = idxView.length;
|
||||
if (dstStride == 4 && !gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
|
||||
uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
|
||||
if (vertexCount >= 65536) {
|
||||
@@ -328,9 +328,9 @@ void Mesh::initialize() {
|
||||
|
||||
gfx::AttributeList gfxAttributes;
|
||||
if (!prim.vertexBundelIndices.empty()) {
|
||||
uint32_t idx = prim.vertexBundelIndices[0];
|
||||
const IVertexBundle & vertexBundle = _struct.vertexBundles[idx];
|
||||
const gfx::AttributeList &attrs = vertexBundle.attributes;
|
||||
uint32_t idx = prim.vertexBundelIndices[0];
|
||||
const IVertexBundle &vertexBundle = _struct.vertexBundles[idx];
|
||||
const gfx::AttributeList &attrs = vertexBundle.attributes;
|
||||
gfxAttributes.resize(attrs.size());
|
||||
for (size_t j = 0; j < attrs.size(); ++j) {
|
||||
const auto &attr = attrs[j];
|
||||
@@ -370,8 +370,8 @@ void Mesh::assign(const IStruct &structInfo, const Uint8Array &data) {
|
||||
void Mesh::reset(ICreateInfo &&info) {
|
||||
destroyRenderingMesh();
|
||||
_struct = std::move(info.structInfo);
|
||||
_data = std::move(info.data);
|
||||
_hash = 0;
|
||||
_data = std::move(info.data);
|
||||
_hash = 0;
|
||||
}
|
||||
|
||||
Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) {
|
||||
@@ -379,10 +379,10 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) {
|
||||
if (iter != _boneSpaceBounds.end()) {
|
||||
return iter->second;
|
||||
}
|
||||
Vec3 v32;
|
||||
BoneSpaceBounds & bounds = _boneSpaceBounds[skeleton->getHash()];
|
||||
Vec3 v32;
|
||||
BoneSpaceBounds &bounds = _boneSpaceBounds[skeleton->getHash()];
|
||||
ccstd::vector<bool> valid;
|
||||
const auto & bindposes = skeleton->getBindposes();
|
||||
const auto &bindposes = skeleton->getBindposes();
|
||||
valid.reserve(bindposes.size());
|
||||
for (size_t i = 0; i < bindposes.size(); i++) {
|
||||
bounds.emplace_back(ccnew geometry::AABB{
|
||||
@@ -392,8 +392,8 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) {
|
||||
}
|
||||
const auto &primitives = _struct.primitives;
|
||||
for (index_t p = 0; p < primitives.size(); p++) {
|
||||
const auto joints = readAttribute(p, gfx::ATTR_NAME_JOINTS);
|
||||
const auto weights = readAttribute(p, gfx::ATTR_NAME_WEIGHTS);
|
||||
const auto joints = readAttribute(p, gfx::ATTR_NAME_JOINTS);
|
||||
const auto weights = readAttribute(p, gfx::ATTR_NAME_WEIGHTS);
|
||||
const auto positions = readAttribute(p, gfx::ATTR_NAME_POSITION);
|
||||
if (joints.index() == 0 || weights.index() == 0 || positions.index() == 0) {
|
||||
continue;
|
||||
@@ -409,8 +409,8 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) {
|
||||
getTypedArrayValue<float>(positions, 3 * i + 2)};
|
||||
|
||||
for (uint32_t j = 0; j < 4; ++j) {
|
||||
const uint32_t idx = 4 * i + j;
|
||||
const auto joint = getTypedArrayValue<int32_t>(joints, idx);
|
||||
const uint32_t idx = 4 * i + j;
|
||||
const auto joint = getTypedArrayValue<int32_t>(joints, idx);
|
||||
|
||||
if (std::fabs(getTypedArrayValue<float>(weights, idx)) < FLT_EPSILON || joint >= bindposes.size()) {
|
||||
continue;
|
||||
@@ -418,7 +418,7 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) {
|
||||
|
||||
Vec3::transformMat4(v31, bindposes[joint], &v32);
|
||||
valid[joint] = true;
|
||||
auto &b = bounds[joint];
|
||||
auto &b = bounds[joint];
|
||||
Vec3::min(b->center, v32, &b->center);
|
||||
Vec3::max(b->halfExtents, v32, &b->halfExtents);
|
||||
}
|
||||
@@ -442,14 +442,14 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
}
|
||||
}
|
||||
|
||||
Vec3 vec3Temp;
|
||||
Quaternion rotate;
|
||||
Vec3 vec3Temp;
|
||||
Quaternion rotate;
|
||||
geometry::AABB boundingBox;
|
||||
if (worldMatrix != nullptr) {
|
||||
worldMatrix->getRotation(&rotate);
|
||||
}
|
||||
if (!_initialized) {
|
||||
auto structInfo = mesh->_struct; //NOTE: Need copy struct, so don't use referece
|
||||
auto structInfo = mesh->_struct; //NOTE: Need copy struct, so don't use referece
|
||||
Uint8Array data{mesh->_data.slice()};
|
||||
if (worldMatrix != nullptr) {
|
||||
if (structInfo.maxPosition.has_value() && structInfo.minPosition.has_value()) {
|
||||
@@ -481,7 +481,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
|
||||
const uint32_t vertexCount = vtxBdl.view.count;
|
||||
|
||||
const uint32_t vertexStride = vtxBdl.view.stride;
|
||||
const uint32_t vertexStride = vtxBdl.view.stride;
|
||||
const uint32_t attrComponentByteLength = getComponentByteLength(format);
|
||||
for (uint32_t vtxIdx = 0; vtxIdx < vertexCount; vtxIdx++) {
|
||||
const uint32_t xOffset = vtxIdx * vertexStride;
|
||||
@@ -516,15 +516,15 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
BufferBlob bufferBlob;
|
||||
|
||||
// merge vertex buffer
|
||||
uint32_t vertCount = 0;
|
||||
uint32_t vertCount = 0;
|
||||
uint32_t vertStride = 0;
|
||||
uint32_t srcOffset = 0;
|
||||
uint32_t dstOffset = 0;
|
||||
uint32_t srcOffset = 0;
|
||||
uint32_t dstOffset = 0;
|
||||
|
||||
uint32_t srcAttrOffset = 0;
|
||||
uint32_t srcVBOffset = 0;
|
||||
uint32_t dstVBOffset = 0;
|
||||
uint32_t attrSize = 0;
|
||||
uint32_t srcVBOffset = 0;
|
||||
uint32_t dstVBOffset = 0;
|
||||
uint32_t attrSize = 0;
|
||||
|
||||
bool hasAttr = false;
|
||||
|
||||
@@ -534,15 +534,15 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
for (size_t i = 0; i < _struct.vertexBundles.size(); ++i) {
|
||||
Uint8Array dstAttrView;
|
||||
|
||||
const auto &bundle = _struct.vertexBundles[i];
|
||||
auto & dstBundle = mesh->_struct.vertexBundles[i];
|
||||
const auto &bundle = _struct.vertexBundles[i];
|
||||
auto &dstBundle = mesh->_struct.vertexBundles[i];
|
||||
|
||||
srcOffset = bundle.view.offset;
|
||||
dstOffset = dstBundle.view.offset;
|
||||
srcOffset = bundle.view.offset;
|
||||
dstOffset = dstBundle.view.offset;
|
||||
vertStride = bundle.view.stride;
|
||||
vertCount = bundle.view.count + dstBundle.view.count;
|
||||
vertCount = bundle.view.count + dstBundle.view.count;
|
||||
|
||||
auto * vb = ccnew ArrayBuffer(vertCount * vertStride);
|
||||
auto *vb = ccnew ArrayBuffer(vertCount * vertStride);
|
||||
Uint8Array vbView(vb);
|
||||
|
||||
Uint8Array srcVBView = _data.subarray(srcOffset, srcOffset + bundle.view.length);
|
||||
@@ -555,7 +555,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
srcAttrOffset = 0;
|
||||
for (const auto &attr : bundle.attributes) {
|
||||
dstVBOffset = 0;
|
||||
hasAttr = false;
|
||||
hasAttr = false;
|
||||
for (const auto &dstAttr : dstBundle.attributes) {
|
||||
if (attr.name == dstAttr.name && attr.format == dstAttr.format) {
|
||||
hasAttr = true;
|
||||
@@ -564,7 +564,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
dstVBOffset += gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(dstAttr.format)].size;
|
||||
}
|
||||
if (hasAttr) {
|
||||
attrSize = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr.format)].size;
|
||||
attrSize = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr.format)].size;
|
||||
srcVBOffset = bundle.view.length + srcAttrOffset;
|
||||
for (uint32_t v = 0; v < dstBundle.view.count; ++v) {
|
||||
dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize);
|
||||
@@ -589,29 +589,29 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
srcAttrOffset += gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr.format)].size;
|
||||
}
|
||||
|
||||
auto &vertexBundle = vertexBundles[i];
|
||||
vertexBundle.attributes = bundle.attributes,
|
||||
auto &vertexBundle = vertexBundles[i];
|
||||
vertexBundle.attributes = bundle.attributes,
|
||||
vertexBundle.view.offset = bufferBlob.getLength();
|
||||
vertexBundle.view.length = vb->byteLength();
|
||||
vertexBundle.view.count = vertCount;
|
||||
vertexBundle.view.count = vertCount;
|
||||
vertexBundle.view.stride = vertStride;
|
||||
|
||||
bufferBlob.addBuffer(vb);
|
||||
}
|
||||
|
||||
// merge index buffer
|
||||
uint32_t idxCount = 0;
|
||||
uint32_t idxStride = 2;
|
||||
uint32_t idxCount = 0;
|
||||
uint32_t idxStride = 2;
|
||||
uint32_t vertBatchCount = 0;
|
||||
|
||||
ccstd::vector<Mesh::ISubMesh> primitives;
|
||||
primitives.resize(_struct.primitives.size());
|
||||
|
||||
for (size_t i = 0; i < _struct.primitives.size(); ++i) {
|
||||
const auto &prim = _struct.primitives[i];
|
||||
auto & dstPrim = mesh->_struct.primitives[i];
|
||||
const auto &prim = _struct.primitives[i];
|
||||
auto &dstPrim = mesh->_struct.primitives[i];
|
||||
|
||||
primitives[i].primitiveMode = prim.primitiveMode;
|
||||
primitives[i].primitiveMode = prim.primitiveMode;
|
||||
primitives[i].vertexBundelIndices = prim.vertexBundelIndices;
|
||||
|
||||
for (const uint32_t bundleIdx : prim.vertexBundelIndices) {
|
||||
@@ -705,10 +705,10 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
dstOffset += dstPrim.indexView.value().length;
|
||||
|
||||
IBufferView indexView;
|
||||
indexView.offset = bufferBlob.getLength();
|
||||
indexView.length = ib->byteLength();
|
||||
indexView.count = idxCount;
|
||||
indexView.stride = idxStride;
|
||||
indexView.offset = bufferBlob.getLength();
|
||||
indexView.length = ib->byteLength();
|
||||
indexView.count = idxCount;
|
||||
indexView.stride = idxStride;
|
||||
primitives[i].indexView = indexView;
|
||||
|
||||
bufferBlob.setNextAlignment(idxStride);
|
||||
@@ -719,9 +719,9 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid
|
||||
// Create mesh struct.
|
||||
Mesh::IStruct meshStruct;
|
||||
meshStruct.vertexBundles = vertexBundles;
|
||||
meshStruct.primitives = primitives;
|
||||
meshStruct.minPosition = _struct.minPosition;
|
||||
meshStruct.maxPosition = _struct.maxPosition;
|
||||
meshStruct.primitives = primitives;
|
||||
meshStruct.minPosition = _struct.minPosition;
|
||||
meshStruct.maxPosition = _struct.maxPosition;
|
||||
|
||||
if (meshStruct.minPosition && mesh->_struct.minPosition && meshStruct.maxPosition && mesh->_struct.maxPosition) {
|
||||
if (worldMatrix != nullptr) {
|
||||
@@ -764,8 +764,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) {
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < _struct.vertexBundles.size(); ++i) {
|
||||
const auto &bundle = _struct.vertexBundles[i];
|
||||
auto & dstBundle = mesh->_struct.vertexBundles[i];
|
||||
const auto &bundle = _struct.vertexBundles[i];
|
||||
auto &dstBundle = mesh->_struct.vertexBundles[i];
|
||||
|
||||
if (bundle.attributes.size() != dstBundle.attributes.size()) {
|
||||
return false;
|
||||
@@ -782,8 +782,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < _struct.primitives.size(); ++i) {
|
||||
const auto &prim = _struct.primitives[i];
|
||||
auto & dstPrim = mesh->_struct.primitives[i];
|
||||
const auto &prim = _struct.primitives[i];
|
||||
auto &dstPrim = mesh->_struct.primitives[i];
|
||||
if (prim.vertexBundelIndices.size() != dstPrim.vertexBundelIndices.size()) {
|
||||
return false;
|
||||
}
|
||||
@@ -811,8 +811,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) {
|
||||
TypedArray Mesh::readAttribute(index_t primitiveIndex, const char *attributeName) {
|
||||
TypedArray result;
|
||||
accessAttribute(primitiveIndex, attributeName, [&](const IVertexBundle &vertexBundle, uint32_t iAttribute) {
|
||||
const uint32_t vertexCount = vertexBundle.view.count;
|
||||
const gfx::Format format = vertexBundle.attributes[iAttribute].format;
|
||||
const uint32_t vertexCount = vertexBundle.view.count;
|
||||
const gfx::Format format = vertexBundle.attributes[iAttribute].format;
|
||||
if (vertexCount == 0) {
|
||||
return;
|
||||
}
|
||||
@@ -827,8 +827,8 @@ TypedArray Mesh::readAttribute(index_t primitiveIndex, const char *attributeName
|
||||
}
|
||||
|
||||
const uint32_t componentCount = formatInfo.count;
|
||||
result = createTypedArrayWithGFXFormat(format, vertexCount * componentCount);
|
||||
const uint32_t inputStride = vertexBundle.view.stride;
|
||||
result = createTypedArrayWithGFXFormat(format, vertexCount * componentCount);
|
||||
const uint32_t inputStride = vertexBundle.view.stride;
|
||||
for (uint32_t iVertex = 0; iVertex < vertexCount; ++iVertex) {
|
||||
for (uint32_t iComponent = 0; iComponent < componentCount; ++iComponent) {
|
||||
TypedArrayElementType element = reader(inputStride * iVertex + getTypedArrayBytesPerElement(result) * iComponent);
|
||||
@@ -867,13 +867,13 @@ bool Mesh::copyAttribute(index_t primitiveIndex, const char *attributeName, Arra
|
||||
|
||||
const uint32_t componentCount = formatInfo.count;
|
||||
|
||||
const uint32_t inputStride = vertexBundle.view.stride;
|
||||
const uint32_t inputComponentByteLength = getComponentByteLength(format);
|
||||
const uint32_t outputStride = stride;
|
||||
const uint32_t inputStride = vertexBundle.view.stride;
|
||||
const uint32_t inputComponentByteLength = getComponentByteLength(format);
|
||||
const uint32_t outputStride = stride;
|
||||
const uint32_t outputComponentByteLength = inputComponentByteLength;
|
||||
for (uint32_t iVertex = 0; iVertex < vertexCount; ++iVertex) {
|
||||
for (uint32_t iComponent = 0; iComponent < componentCount; ++iComponent) {
|
||||
const uint32_t inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent;
|
||||
const uint32_t inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent;
|
||||
const uint32_t outputOffset = outputStride * iVertex + outputComponentByteLength * iComponent;
|
||||
writer(outputOffset, reader(inputOffset));
|
||||
}
|
||||
@@ -891,10 +891,10 @@ IBArray Mesh::readIndices(index_t primitiveIndex) {
|
||||
if (!primitive.indexView.has_value()) {
|
||||
return {};
|
||||
}
|
||||
const uint32_t stride = primitive.indexView.value().stride;
|
||||
const uint32_t count = primitive.indexView.value().count;
|
||||
const uint32_t stride = primitive.indexView.value().stride;
|
||||
const uint32_t count = primitive.indexView.value().count;
|
||||
const uint32_t byteOffset = primitive.indexView.value().offset;
|
||||
IBArray ret;
|
||||
IBArray ret;
|
||||
if (stride == 1) {
|
||||
ret = Uint8Array(_data.buffer(), byteOffset, count);
|
||||
} else if (stride == 2) {
|
||||
@@ -915,12 +915,12 @@ bool Mesh::copyIndices(index_t primitiveIndex, TypedArray &outputArray) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint32_t indexCount = primitive.indexView.value().count;
|
||||
const uint32_t indexCount = primitive.indexView.value().count;
|
||||
const gfx::Format indexFormat = primitive.indexView.value().stride == 1 ? gfx::Format::R8UI
|
||||
: (primitive.indexView.value().stride == 2 ? gfx::Format::R16UI
|
||||
: gfx::Format::R32UI);
|
||||
DataView view(_data.buffer());
|
||||
auto reader = getReader(view, indexFormat);
|
||||
DataView view(_data.buffer());
|
||||
auto reader = getReader(view, indexFormat);
|
||||
for (uint32_t i = 0; i < indexCount; ++i) {
|
||||
TypedArrayElementType element = reader(primitive.indexView.value().offset + gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(indexFormat)].size * i);
|
||||
setTypedArrayValue(outputArray, i, element);
|
||||
@@ -964,22 +964,22 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr
|
||||
}
|
||||
}
|
||||
|
||||
auto &dynamic = _struct.dynamic.value();
|
||||
auto &info = dynamic.info;
|
||||
auto &dynamic = _struct.dynamic.value();
|
||||
auto &info = dynamic.info;
|
||||
auto &primitive = _struct.primitives[primitiveIndex];
|
||||
auto &subMesh = _renderingSubMeshes[primitiveIndex];
|
||||
auto &drawInfo = subMesh->getDrawInfo().value();
|
||||
auto &subMesh = _renderingSubMeshes[primitiveIndex];
|
||||
auto &drawInfo = subMesh->getDrawInfo().value();
|
||||
|
||||
// update _data & buffer
|
||||
for (auto index = 0U; index < buffers.size(); index++) {
|
||||
const auto &vertices = *buffers[index];
|
||||
auto & bundle = _struct.vertexBundles[primitive.vertexBundelIndices[index]];
|
||||
const auto stride = bundle.view.stride;
|
||||
const auto vertexCount = vertices.byteLength() / stride;
|
||||
const auto updateSize = vertices.byteLength();
|
||||
auto * dstBuffer = _data.buffer()->getData() + bundle.view.offset;
|
||||
const auto *srcBuffer = vertices.buffer()->getData() + vertices.byteOffset();
|
||||
auto * vertexBuffer = subMesh->getVertexBuffers()[index];
|
||||
const auto &vertices = *buffers[index];
|
||||
auto &bundle = _struct.vertexBundles[primitive.vertexBundelIndices[index]];
|
||||
const auto stride = bundle.view.stride;
|
||||
const auto vertexCount = vertices.byteLength() / stride;
|
||||
const auto updateSize = vertices.byteLength();
|
||||
auto *dstBuffer = _data.buffer()->getData() + bundle.view.offset;
|
||||
const auto *srcBuffer = vertices.buffer()->getData() + vertices.byteOffset();
|
||||
auto *vertexBuffer = subMesh->getVertexBuffers()[index];
|
||||
CC_ASSERT(vertexCount <= info.maxSubMeshVertices);
|
||||
|
||||
if (updateSize > 0U) {
|
||||
@@ -987,19 +987,19 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr
|
||||
vertexBuffer->update(srcBuffer, updateSize);
|
||||
}
|
||||
|
||||
bundle.view.count = vertexCount;
|
||||
bundle.view.count = vertexCount;
|
||||
drawInfo.vertexCount = vertexCount;
|
||||
}
|
||||
|
||||
if (primitive.indexView.has_value()) {
|
||||
auto & indexView = primitive.indexView.value();
|
||||
const auto &stride = indexView.stride;
|
||||
const auto indexCount = (stride == sizeof(uint16_t)) ? geometry.indices16.value().length() : geometry.indices32.value().length();
|
||||
const auto updateSize = indexCount * stride;
|
||||
auto * dstBuffer = _data.buffer()->getData() + indexView.offset;
|
||||
const auto *srcBuffer = (stride == sizeof(uint16_t)) ? geometry.indices16.value().buffer()->getData() + geometry.indices16.value().byteOffset()
|
||||
: geometry.indices32.value().buffer()->getData() + geometry.indices32.value().byteOffset();
|
||||
auto * indexBuffer = subMesh->getIndexBuffer();
|
||||
auto &indexView = primitive.indexView.value();
|
||||
const auto &stride = indexView.stride;
|
||||
const auto indexCount = (stride == sizeof(uint16_t)) ? geometry.indices16.value().length() : geometry.indices32.value().length();
|
||||
const auto updateSize = indexCount * stride;
|
||||
auto *dstBuffer = _data.buffer()->getData() + indexView.offset;
|
||||
const auto *srcBuffer = (stride == sizeof(uint16_t)) ? geometry.indices16.value().buffer()->getData() + geometry.indices16.value().byteOffset()
|
||||
: geometry.indices32.value().buffer()->getData() + geometry.indices32.value().byteOffset();
|
||||
auto *indexBuffer = subMesh->getIndexBuffer();
|
||||
CC_ASSERT(indexCount <= info.maxSubMeshIndices);
|
||||
|
||||
if (updateSize > 0U) {
|
||||
@@ -1007,7 +1007,7 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr
|
||||
indexBuffer->update(srcBuffer, updateSize);
|
||||
}
|
||||
|
||||
indexView.count = indexCount;
|
||||
indexView.count = indexCount;
|
||||
drawInfo.indexCount = indexCount;
|
||||
}
|
||||
|
||||
@@ -1045,7 +1045,7 @@ void Mesh::accessAttribute(index_t primitiveIndex, const char *attributeName, co
|
||||
auto &primitive = _struct.primitives[primitiveIndex];
|
||||
for (const auto &vertexBundleIndex : primitive.vertexBundelIndices) {
|
||||
const auto &vertexBundle = _struct.vertexBundles[vertexBundleIndex];
|
||||
auto iter = std::find_if(vertexBundle.attributes.begin(), vertexBundle.attributes.end(), [&](const auto &a) -> bool { return a.name == attributeName; });
|
||||
auto iter = std::find_if(vertexBundle.attributes.begin(), vertexBundle.attributes.end(), [&](const auto &a) -> bool { return a.name == attributeName; });
|
||||
if (iter == vertexBundle.attributes.end()) {
|
||||
continue;
|
||||
}
|
||||
@@ -1079,7 +1079,7 @@ bool Mesh::validate() const {
|
||||
}
|
||||
|
||||
TypedArray Mesh::createTypedArrayWithGFXFormat(gfx::Format format, uint32_t count) {
|
||||
const auto & info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
const uint32_t stride = info.size / info.count;
|
||||
|
||||
switch (info.type) {
|
||||
|
||||
@@ -205,7 +205,7 @@ public:
|
||||
~Mesh() override;
|
||||
|
||||
cc::any getNativeAsset() const override;
|
||||
void setNativeAsset(const cc::any &obj) override;
|
||||
void setNativeAsset(const cc::any &obj) override;
|
||||
|
||||
void setAssetData(cc::ArrayBuffer *data) {
|
||||
_data = Uint8Array(data);
|
||||
@@ -431,8 +431,8 @@ public:
|
||||
IntrusivePtr<MorphRendering> morphRendering;
|
||||
|
||||
private:
|
||||
IStruct _struct;
|
||||
uint64_t _hash{0};
|
||||
IStruct _struct;
|
||||
uint64_t _hash{0};
|
||||
Uint8Array _data;
|
||||
|
||||
bool _initialized{false};
|
||||
|
||||
@@ -48,7 +48,7 @@ MorphRendering *createMorphRendering(Mesh *mesh, gfx::Device *gfxDevice);
|
||||
*/
|
||||
class MorphRendering : public RefCounted {
|
||||
public:
|
||||
~MorphRendering() override = default;
|
||||
~MorphRendering() override = default;
|
||||
virtual MorphRenderingInstance *createInstance() = 0;
|
||||
};
|
||||
|
||||
|
||||
@@ -132,9 +132,9 @@ public:
|
||||
|
||||
void initialize(gfx::Device *gfxDevice, uint32_t width, uint32_t height, uint32_t pixelBytes, bool /*useFloat32Array*/, PixelFormat pixelFormat) {
|
||||
_arrayBuffer = ccnew ArrayBuffer(width * height * pixelBytes);
|
||||
_valueView = Float32Array(_arrayBuffer);
|
||||
_valueView = Float32Array(_arrayBuffer);
|
||||
|
||||
auto * imageAsset = ccnew ImageAsset();
|
||||
auto *imageAsset = ccnew ImageAsset();
|
||||
IMemoryImageSource source{_arrayBuffer, false, width, height, pixelFormat};
|
||||
imageAsset->setNativeAsset(source);
|
||||
|
||||
@@ -152,15 +152,15 @@ public:
|
||||
|
||||
private:
|
||||
IntrusivePtr<Texture2D> _textureAsset;
|
||||
gfx::Sampler * _sampler{nullptr};
|
||||
ArrayBuffer::Ptr _arrayBuffer;
|
||||
Float32Array _valueView;
|
||||
gfx::Sampler *_sampler{nullptr};
|
||||
ArrayBuffer::Ptr _arrayBuffer;
|
||||
Float32Array _valueView;
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(MorphTexture);
|
||||
};
|
||||
|
||||
struct GpuMorphAttribute {
|
||||
ccstd::string attributeName;
|
||||
ccstd::string attributeName;
|
||||
IntrusivePtr<MorphTexture> morphTexture;
|
||||
};
|
||||
|
||||
@@ -171,13 +171,13 @@ struct CpuMorphAttributeTarget {
|
||||
using CpuMorphAttributeTargetList = ccstd::vector<CpuMorphAttributeTarget>;
|
||||
|
||||
struct CpuMorphAttribute {
|
||||
ccstd::string name;
|
||||
ccstd::string name;
|
||||
CpuMorphAttributeTargetList targets;
|
||||
};
|
||||
|
||||
struct Vec4TextureFactory {
|
||||
uint32_t width{0};
|
||||
uint32_t height{0};
|
||||
uint32_t width{0};
|
||||
uint32_t height{0};
|
||||
std::function<MorphTexture *()> create{nullptr};
|
||||
};
|
||||
|
||||
@@ -205,11 +205,11 @@ bool bestSizeToHavePixels(uint32_t nPixels, uint32_t *pWidth, uint32_t *pHeight)
|
||||
nPixels = 5;
|
||||
}
|
||||
const uint32_t aligned = pipeline::nextPow2(nPixels);
|
||||
const auto epxSum = static_cast<uint32_t>(std::log2(aligned));
|
||||
const uint32_t h = epxSum >> 1;
|
||||
const uint32_t w = (epxSum & 1) ? (h + 1) : h;
|
||||
const auto epxSum = static_cast<uint32_t>(std::log2(aligned));
|
||||
const uint32_t h = epxSum >> 1;
|
||||
const uint32_t w = (epxSum & 1) ? (h + 1) : h;
|
||||
|
||||
*pWidth = 1 << w;
|
||||
*pWidth = 1 << w;
|
||||
*pHeight = 1 << h;
|
||||
|
||||
return true;
|
||||
@@ -235,29 +235,29 @@ void enableVertexId(Mesh *mesh, uint32_t subMeshIndex, gfx::Device *gfxDevice) {
|
||||
Vec4TextureFactory createVec4TextureFactory(gfx::Device *gfxDevice, uint32_t vec4Capacity) {
|
||||
bool hasFeatureFloatTexture = static_cast<uint32_t>(gfxDevice->getFormatFeatures(gfx::Format::RGBA32F) & gfx::FormatFeature::SAMPLED_TEXTURE) != 0;
|
||||
|
||||
uint32_t pixelRequired = 0;
|
||||
PixelFormat pixelFormat = PixelFormat::RGBA8888;
|
||||
uint32_t pixelBytes = 4;
|
||||
bool useFloat32Array = false;
|
||||
uint32_t pixelRequired = 0;
|
||||
PixelFormat pixelFormat = PixelFormat::RGBA8888;
|
||||
uint32_t pixelBytes = 4;
|
||||
bool useFloat32Array = false;
|
||||
if (hasFeatureFloatTexture) {
|
||||
pixelRequired = vec4Capacity;
|
||||
pixelBytes = 16;
|
||||
pixelFormat = Texture2D::PixelFormat::RGBA32F;
|
||||
pixelRequired = vec4Capacity;
|
||||
pixelBytes = 16;
|
||||
pixelFormat = Texture2D::PixelFormat::RGBA32F;
|
||||
useFloat32Array = true;
|
||||
} else {
|
||||
pixelRequired = 4 * vec4Capacity;
|
||||
pixelBytes = 4;
|
||||
pixelFormat = Texture2D::PixelFormat::RGBA8888;
|
||||
pixelRequired = 4 * vec4Capacity;
|
||||
pixelBytes = 4;
|
||||
pixelFormat = Texture2D::PixelFormat::RGBA8888;
|
||||
useFloat32Array = false;
|
||||
}
|
||||
|
||||
uint32_t width = 0;
|
||||
uint32_t width = 0;
|
||||
uint32_t height = 0;
|
||||
bestSizeToHavePixels(pixelRequired, &width, &height);
|
||||
CC_ASSERT(width * height >= pixelRequired);
|
||||
|
||||
Vec4TextureFactory ret;
|
||||
ret.width = width;
|
||||
ret.width = width;
|
||||
ret.height = height;
|
||||
ret.create = [=]() -> MorphTexture * {
|
||||
auto *texture = ccnew MorphTexture(); // texture will be held by IntrusivePtr in GpuMorphAttribute
|
||||
@@ -319,8 +319,8 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t _targetCount{0};
|
||||
DataView * _localBuffer{nullptr};
|
||||
uint32_t _targetCount{0};
|
||||
DataView *_localBuffer{nullptr};
|
||||
IntrusivePtr<gfx::Buffer> _remoteBuffer;
|
||||
};
|
||||
|
||||
@@ -328,12 +328,12 @@ class CpuComputing final : public SubMeshMorphRendering {
|
||||
public:
|
||||
explicit CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice);
|
||||
|
||||
SubMeshMorphRenderingInstance * createInstance() override;
|
||||
SubMeshMorphRenderingInstance *createInstance() override;
|
||||
const ccstd::vector<CpuMorphAttribute> &getData() const;
|
||||
|
||||
private:
|
||||
ccstd::vector<CpuMorphAttribute> _attributes;
|
||||
gfx::Device * _gfxDevice{nullptr};
|
||||
gfx::Device *_gfxDevice{nullptr};
|
||||
};
|
||||
|
||||
class GpuComputing final : public SubMeshMorphRendering {
|
||||
@@ -344,12 +344,12 @@ public:
|
||||
void destroy();
|
||||
|
||||
private:
|
||||
gfx::Device * _gfxDevice{nullptr};
|
||||
const SubMeshMorph * _subMeshMorph{nullptr};
|
||||
uint32_t _textureWidth{0};
|
||||
uint32_t _textureHeight{0};
|
||||
gfx::Device *_gfxDevice{nullptr};
|
||||
const SubMeshMorph *_subMeshMorph{nullptr};
|
||||
uint32_t _textureWidth{0};
|
||||
uint32_t _textureHeight{0};
|
||||
ccstd::vector<GpuMorphAttribute> _attributes;
|
||||
uint32_t _verticesCount{0};
|
||||
uint32_t _verticesCount{0};
|
||||
|
||||
friend class GpuComputingRenderingInstance;
|
||||
};
|
||||
@@ -357,7 +357,7 @@ private:
|
||||
class CpuComputingRenderingInstance final : public SubMeshMorphRenderingInstance {
|
||||
public:
|
||||
explicit CpuComputingRenderingInstance(CpuComputing *owner, uint32_t nVertices, gfx::Device *gfxDevice) {
|
||||
_owner = owner; //NOTE: release by mesh`s destroy, it`ll call current instance`s destroy method
|
||||
_owner = owner; //NOTE: release by mesh`s destroy, it`ll call current instance`s destroy method
|
||||
_morphUniforms = ccnew MorphUniforms(gfxDevice, 0 /* TODO? */);
|
||||
|
||||
auto vec4TextureFactory = createVec4TextureFactory(gfxDevice, nVertices);
|
||||
@@ -371,14 +371,14 @@ public:
|
||||
|
||||
void setWeights(const ccstd::vector<float> &weights) override {
|
||||
for (size_t iAttribute = 0; iAttribute < _attributes.size(); ++iAttribute) {
|
||||
const auto & myAttribute = _attributes[iAttribute];
|
||||
Float32Array &valueView = myAttribute.morphTexture->getValueView();
|
||||
const auto & attributeMorph = _owner->getData()[iAttribute];
|
||||
const auto &myAttribute = _attributes[iAttribute];
|
||||
Float32Array &valueView = myAttribute.morphTexture->getValueView();
|
||||
const auto &attributeMorph = _owner->getData()[iAttribute];
|
||||
CC_ASSERT(weights.size() == attributeMorph.targets.size());
|
||||
for (size_t iTarget = 0; iTarget < attributeMorph.targets.size(); ++iTarget) {
|
||||
const auto & targetDisplacements = attributeMorph.targets[iTarget].displacements;
|
||||
const float weight = weights[iTarget];
|
||||
const uint32_t nVertices = targetDisplacements.length() / 3;
|
||||
const auto &targetDisplacements = attributeMorph.targets[iTarget].displacements;
|
||||
const float weight = weights[iTarget];
|
||||
const uint32_t nVertices = targetDisplacements.length() / 3;
|
||||
if (iTarget == 0) {
|
||||
for (uint32_t iVertex = 0; iVertex < nVertices; ++iVertex) {
|
||||
valueView[4 * iVertex + 0] = targetDisplacements[3 * iVertex + 0] * weight;
|
||||
@@ -407,7 +407,7 @@ public:
|
||||
|
||||
void adaptPipelineState(gfx::DescriptorSet *descriptorSet) override {
|
||||
for (const auto &attribute : _attributes) {
|
||||
const auto & attributeName = attribute.attributeName;
|
||||
const auto &attributeName = attribute.attributeName;
|
||||
cc::optional<uint32_t> binding;
|
||||
if (attributeName == gfx::ATTR_NAME_POSITION) {
|
||||
binding = uint32_t{pipeline::POSITIONMORPH::BINDING};
|
||||
@@ -437,14 +437,14 @@ public:
|
||||
|
||||
private:
|
||||
ccstd::vector<GpuMorphAttribute> _attributes;
|
||||
IntrusivePtr<CpuComputing> _owner;
|
||||
IntrusivePtr<MorphUniforms> _morphUniforms;
|
||||
IntrusivePtr<CpuComputing> _owner;
|
||||
IntrusivePtr<MorphUniforms> _morphUniforms;
|
||||
};
|
||||
|
||||
class GpuComputingRenderingInstance final : public SubMeshMorphRenderingInstance {
|
||||
public:
|
||||
explicit GpuComputingRenderingInstance(GpuComputing *owner, gfx::Device *gfxDevice) {
|
||||
_owner = owner;
|
||||
_owner = owner;
|
||||
_morphUniforms = ccnew MorphUniforms(gfxDevice, static_cast<uint32_t>(_owner->_subMeshMorph->targets.size()));
|
||||
_morphUniforms->setMorphTextureInfo(static_cast<float>(_owner->_textureWidth), static_cast<float>(_owner->_textureHeight));
|
||||
_morphUniforms->setVerticesCount(_owner->_verticesCount);
|
||||
@@ -465,7 +465,7 @@ public:
|
||||
|
||||
void adaptPipelineState(gfx::DescriptorSet *descriptorSet) override {
|
||||
for (const auto &attribute : *_attributes) {
|
||||
const auto & attributeName = attribute.attributeName;
|
||||
const auto &attributeName = attribute.attributeName;
|
||||
cc::optional<uint32_t> binding;
|
||||
if (attributeName == gfx::ATTR_NAME_POSITION) {
|
||||
binding = uint32_t{pipeline::POSITIONMORPH::BINDING};
|
||||
@@ -491,12 +491,12 @@ public:
|
||||
|
||||
private:
|
||||
ccstd::vector<GpuMorphAttribute> *_attributes{nullptr};
|
||||
IntrusivePtr<GpuComputing> _owner;
|
||||
IntrusivePtr<MorphUniforms> _morphUniforms;
|
||||
IntrusivePtr<GpuComputing> _owner;
|
||||
IntrusivePtr<MorphUniforms> _morphUniforms;
|
||||
};
|
||||
|
||||
CpuComputing::CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice) {
|
||||
_gfxDevice = gfxDevice;
|
||||
_gfxDevice = gfxDevice;
|
||||
const auto &subMeshMorph = morph->subMeshMorphs[subMeshIndex].value();
|
||||
enableVertexId(mesh, subMeshIndex, gfxDevice);
|
||||
|
||||
@@ -510,7 +510,7 @@ CpuComputing::CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph
|
||||
uint32_t i = 0;
|
||||
for (const auto &attributeDisplacement : subMeshMorph.targets) {
|
||||
const Mesh::IBufferView &displacementsView = attributeDisplacement.displacements[attributeIndex];
|
||||
attr.targets[i].displacements = Float32Array(mesh->getData().buffer(),
|
||||
attr.targets[i].displacements = Float32Array(mesh->getData().buffer(),
|
||||
mesh->getData().byteOffset() + displacementsView.offset,
|
||||
attributeDisplacement.displacements[attributeIndex].count);
|
||||
|
||||
@@ -533,7 +533,7 @@ const ccstd::vector<CpuMorphAttribute> &CpuComputing::getData() const {
|
||||
}
|
||||
|
||||
GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice) {
|
||||
_gfxDevice = gfxDevice;
|
||||
_gfxDevice = gfxDevice;
|
||||
const auto &subMeshMorph = morph->subMeshMorphs[subMeshIndex].value();
|
||||
|
||||
_subMeshMorph = &subMeshMorph;
|
||||
@@ -541,20 +541,20 @@ GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph
|
||||
|
||||
enableVertexId(mesh, subMeshIndex, gfxDevice);
|
||||
|
||||
uint32_t nVertices = mesh->getStruct().vertexBundles[mesh->getStruct().primitives[subMeshIndex].vertexBundelIndices[0]].view.count;
|
||||
_verticesCount = nVertices;
|
||||
auto nTargets = static_cast<uint32_t>(subMeshMorph.targets.size());
|
||||
uint32_t nVertices = mesh->getStruct().vertexBundles[mesh->getStruct().primitives[subMeshIndex].vertexBundelIndices[0]].view.count;
|
||||
_verticesCount = nVertices;
|
||||
auto nTargets = static_cast<uint32_t>(subMeshMorph.targets.size());
|
||||
uint32_t vec4Required = nVertices * nTargets;
|
||||
|
||||
auto vec4TextureFactory = createVec4TextureFactory(gfxDevice, vec4Required);
|
||||
_textureWidth = vec4TextureFactory.width;
|
||||
_textureHeight = vec4TextureFactory.height;
|
||||
_textureWidth = vec4TextureFactory.width;
|
||||
_textureHeight = vec4TextureFactory.height;
|
||||
|
||||
// Creates texture for each attribute.
|
||||
uint32_t attributeIndex = 0;
|
||||
_attributes.reserve(subMeshMorph.attributes.size());
|
||||
for (const auto &attributeName : subMeshMorph.attributes) {
|
||||
auto * vec4Tex = vec4TextureFactory.create();
|
||||
auto *vec4Tex = vec4TextureFactory.create();
|
||||
Float32Array &valueView = vec4Tex->getValueView();
|
||||
// if (DEV) { // Make it easy to view texture in profilers...
|
||||
// for (let i = 0; i < valueView.length / 4; ++i) {
|
||||
@@ -564,8 +564,8 @@ GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph
|
||||
|
||||
uint32_t morphTargetIndex = 0;
|
||||
for (const auto &morphTarget : subMeshMorph.targets) {
|
||||
const auto & displacementsView = morphTarget.displacements[attributeIndex];
|
||||
Float32Array displacements(mesh->getData().buffer(),
|
||||
const auto &displacementsView = morphTarget.displacements[attributeIndex];
|
||||
Float32Array displacements(mesh->getData().buffer(),
|
||||
mesh->getData().byteOffset() + displacementsView.offset,
|
||||
displacementsView.count);
|
||||
const uint32_t displacementsOffset = (nVertices * morphTargetIndex) * 4;
|
||||
@@ -601,7 +601,7 @@ void GpuComputing::destroy() {
|
||||
class StdMorphRenderingInstance : public MorphRenderingInstance {
|
||||
public:
|
||||
explicit StdMorphRenderingInstance(StdMorphRendering *owner) {
|
||||
_owner = owner;
|
||||
_owner = owner;
|
||||
size_t nSubMeshes = _owner->_mesh->getStruct().primitives.size();
|
||||
_subMeshInstances.resize(nSubMeshes, nullptr);
|
||||
|
||||
@@ -628,8 +628,8 @@ public:
|
||||
|
||||
ccstd::vector<scene::IMacroPatch> requiredPatches(index_t subMeshIndex) override {
|
||||
CC_ASSERT(_owner->_mesh->getStruct().morph.has_value());
|
||||
const auto &subMeshMorphOpt = _owner->_mesh->getStruct().morph.value().subMeshMorphs[subMeshIndex];
|
||||
auto * subMeshRenderingInstance = _subMeshInstances[subMeshIndex].get();
|
||||
const auto &subMeshMorphOpt = _owner->_mesh->getStruct().morph.value().subMeshMorphs[subMeshIndex];
|
||||
auto *subMeshRenderingInstance = _subMeshInstances[subMeshIndex].get();
|
||||
if (subMeshRenderingInstance == nullptr || !subMeshMorphOpt.has_value()) {
|
||||
return {};
|
||||
}
|
||||
@@ -680,12 +680,12 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
IntrusivePtr<StdMorphRendering> _owner;
|
||||
IntrusivePtr<StdMorphRendering> _owner;
|
||||
ccstd::vector<IntrusivePtr<SubMeshMorphRenderingInstance>> _subMeshInstances;
|
||||
};
|
||||
|
||||
StdMorphRendering::StdMorphRendering(Mesh *mesh, gfx::Device *gfxDevice) {
|
||||
_mesh = mesh;
|
||||
_mesh = mesh;
|
||||
const auto &structInfo = _mesh->getStruct();
|
||||
if (!structInfo.morph.has_value()) {
|
||||
return;
|
||||
|
||||
@@ -44,7 +44,7 @@ public:
|
||||
MorphRenderingInstance *createInstance() override;
|
||||
|
||||
private:
|
||||
Mesh * _mesh{nullptr};
|
||||
Mesh *_mesh{nullptr};
|
||||
ccstd::vector<IntrusivePtr<SubMeshMorphRendering>> _subMeshRenderings;
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(StdMorphRendering);
|
||||
|
||||
@@ -54,7 +54,7 @@ uint64_t Skeleton::getHash() {
|
||||
<< ibm.m[12] << " " << ibm.m[13] << " " << ibm.m[14] << " " << ibm.m[15] << "\n";
|
||||
}
|
||||
ccstd::string str{sstr.str()};
|
||||
std::size_t seed = 666;
|
||||
std::size_t seed = 666;
|
||||
boost::hash_range(seed, str.begin(), str.end());
|
||||
_hash = static_cast<uint32_t>(seed);
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ namespace cc {
|
||||
*/
|
||||
class Skeleton final : public Asset {
|
||||
public:
|
||||
using Super = Asset;
|
||||
Skeleton() = default;
|
||||
using Super = Asset;
|
||||
Skeleton() = default;
|
||||
~Skeleton() override = default;
|
||||
/**
|
||||
* @en The path of all bones, the length always equals the length of [[bindposes]]
|
||||
@@ -73,7 +73,7 @@ public:
|
||||
* @zh 获取骨骼资源的哈希值
|
||||
*/
|
||||
uint64_t getHash();
|
||||
void setHash(uint64_t hash) { _hash = hash; }
|
||||
void setHash(uint64_t hash) { _hash = hash; }
|
||||
|
||||
inline double getHashForJS() {
|
||||
return static_cast<double>(getHash());
|
||||
@@ -83,10 +83,10 @@ public:
|
||||
bool validate() const override;
|
||||
|
||||
private:
|
||||
ccstd::vector<ccstd::string> _joints;
|
||||
ccstd::vector<Mat4> _bindposes;
|
||||
ccstd::vector<ccstd::string> _joints;
|
||||
ccstd::vector<Mat4> _bindposes;
|
||||
cc::optional<ccstd::vector<Mat4>> _invBindposes;
|
||||
uint64_t _hash{0};
|
||||
uint64_t _hash{0};
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -40,7 +40,7 @@ Record<gfx::FormatType, ccstd::string> typeMap{
|
||||
|
||||
ccstd::string getDataViewType(const gfx::FormatInfo &info) {
|
||||
ccstd::string type;
|
||||
auto iter = typeMap.find(info.type);
|
||||
auto iter = typeMap.find(info.type);
|
||||
if (iter != typeMap.end()) {
|
||||
type = iter->second;
|
||||
} else {
|
||||
@@ -53,20 +53,20 @@ ccstd::string getDataViewType(const gfx::FormatInfo &info) {
|
||||
|
||||
} // namespace
|
||||
|
||||
using DataVariant = cc::variant<int32_t, float>;
|
||||
using DataVariant = cc::variant<int32_t, float>;
|
||||
using MapBufferCallback = std::function<DataVariant(const DataVariant &cur, uint32_t idx, const DataView &view)>;
|
||||
|
||||
DataView mapBuffer(DataView & target,
|
||||
const MapBufferCallback & callback,
|
||||
DataView mapBuffer(DataView &target,
|
||||
const MapBufferCallback &callback,
|
||||
cc::optional<gfx::Format> aFormat,
|
||||
cc::optional<uint32_t> aOffset,
|
||||
cc::optional<uint32_t> aLength,
|
||||
cc::optional<uint32_t> aStride,
|
||||
DataView * out) {
|
||||
cc::optional<uint32_t> aOffset,
|
||||
cc::optional<uint32_t> aLength,
|
||||
cc::optional<uint32_t> aStride,
|
||||
DataView *out) {
|
||||
gfx::Format format = aFormat.has_value() ? aFormat.value() : gfx::Format::R32F;
|
||||
uint32_t offset = aOffset.has_value() ? aOffset.value() : 0;
|
||||
uint32_t length = aLength.has_value() ? aLength.value() : target.byteLength() - offset;
|
||||
uint32_t stride = aStride.has_value() ? aStride.value() : 0;
|
||||
uint32_t offset = aOffset.has_value() ? aOffset.value() : 0;
|
||||
uint32_t length = aLength.has_value() ? aLength.value() : target.byteLength() - offset;
|
||||
uint32_t stride = aStride.has_value() ? aStride.value() : 0;
|
||||
|
||||
DataView dataView;
|
||||
if (out == nullptr) {
|
||||
@@ -82,7 +82,7 @@ DataView mapBuffer(DataView & target,
|
||||
static const ccstd::string SET_PREFIX{"set"};
|
||||
static const ccstd::string GET_PREFIX{"get"};
|
||||
|
||||
bool isFloat = info.type == gfx::FormatType::FLOAT || info.type == gfx::FormatType::UFLOAT;
|
||||
bool isFloat = info.type == gfx::FormatType::FLOAT || info.type == gfx::FormatType::UFLOAT;
|
||||
DataView::IntWritter intWritter = nullptr;
|
||||
if (!isFloat) {
|
||||
intWritter = DataView::intWritterMap[SET_PREFIX + getDataViewType(info)];
|
||||
@@ -94,7 +94,7 @@ DataView mapBuffer(DataView & target,
|
||||
}
|
||||
|
||||
const uint32_t componentBytesLength = info.size / info.count;
|
||||
const uint32_t nSeg = floor(length / stride);
|
||||
const uint32_t nSeg = floor(length / stride);
|
||||
|
||||
for (uint32_t iSeg = 0; iSeg < nSeg; ++iSeg) {
|
||||
const uint32_t x = offset + stride * iSeg;
|
||||
|
||||
@@ -33,17 +33,17 @@ namespace cc {
|
||||
|
||||
// default params behaviors just like on an plain, compact Float32Array
|
||||
template <typename T>
|
||||
void writeBuffer(DataView & target,
|
||||
void writeBuffer(DataView &target,
|
||||
const ccstd::vector<T> &data,
|
||||
const gfx::Format & format = gfx::Format::R32F,
|
||||
uint32_t offset = 0,
|
||||
uint32_t stride = 0) {
|
||||
const gfx::Format &format = gfx::Format::R32F,
|
||||
uint32_t offset = 0,
|
||||
uint32_t stride = 0) {
|
||||
const gfx::FormatInfo &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)];
|
||||
if (stride == 0) {
|
||||
stride = info.size;
|
||||
}
|
||||
const uint32_t componentBytesLength = info.size / info.count;
|
||||
const auto nSeg = static_cast<uint32_t>(floor(data.size() / info.count));
|
||||
const auto nSeg = static_cast<uint32_t>(floor(data.size() / info.count));
|
||||
|
||||
const uint32_t bytes = info.size / info.count * 8;
|
||||
|
||||
@@ -112,15 +112,15 @@ void writeBuffer(DataView & target,
|
||||
}
|
||||
}
|
||||
|
||||
using DataVariant = cc::variant<int32_t, float>;
|
||||
using DataVariant = cc::variant<int32_t, float>;
|
||||
using MapBufferCallback = std::function<DataVariant(const DataVariant &cur, uint32_t idx, const DataView &view)>;
|
||||
|
||||
DataView mapBuffer(DataView & target,
|
||||
const MapBufferCallback & callback,
|
||||
DataView mapBuffer(DataView &target,
|
||||
const MapBufferCallback &callback,
|
||||
cc::optional<gfx::Format> aFormat,
|
||||
cc::optional<uint32_t> aOffset,
|
||||
cc::optional<uint32_t> aLength,
|
||||
cc::optional<uint32_t> aStride,
|
||||
DataView * out);
|
||||
cc::optional<uint32_t> aOffset,
|
||||
cc::optional<uint32_t> aLength,
|
||||
cc::optional<uint32_t> aStride,
|
||||
DataView *out);
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -47,7 +47,7 @@ uint32_t BufferBlob::addBuffer(ArrayBuffer *arrayBuffer) {
|
||||
|
||||
ArrayBuffer::Ptr BufferBlob::getCombined() {
|
||||
Int8Array result(_length);
|
||||
uint32_t counter = 0;
|
||||
uint32_t counter = 0;
|
||||
|
||||
for (const auto &arrayBufferOrPadding : _arrayBufferOrPaddings) {
|
||||
if (const auto *p = cc::get_if<uint32_t>(&arrayBufferOrPadding)) {
|
||||
|
||||
@@ -42,7 +42,7 @@ public:
|
||||
|
||||
private:
|
||||
ccstd::vector<cc::variant<ArrayBuffer::Ptr, uint32_t>> _arrayBufferOrPaddings;
|
||||
uint32_t _length{0};
|
||||
uint32_t _length{0};
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -30,14 +30,14 @@ Mesh *MeshUtils::createMesh(const IGeometry &geometry, Mesh *out /*= nullptr*/,
|
||||
Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICreateMeshOptions &options /* = {}*/) {
|
||||
// Collect attributes and calculate length of result vertex buffer.
|
||||
gfx::AttributeList attributes;
|
||||
uint32_t stride = 0;
|
||||
uint32_t stride = 0;
|
||||
struct Channel {
|
||||
uint32_t offset{0};
|
||||
uint32_t offset{0};
|
||||
ccstd::vector<float> data; // float?
|
||||
gfx::Attribute attribute;
|
||||
gfx::Attribute attribute;
|
||||
};
|
||||
ccstd::vector<Channel> channels;
|
||||
uint32_t vertCount = 0;
|
||||
uint32_t vertCount = 0;
|
||||
|
||||
const gfx::Attribute *attr = nullptr;
|
||||
|
||||
@@ -60,7 +60,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
attributes.emplace_back(*attr);
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(positions.size() / info.count)));
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(positions.size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, positions, *attr});
|
||||
stride += info.size;
|
||||
}
|
||||
@@ -82,7 +82,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
attributes.emplace_back(*attr);
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.normals->size() / info.count)));
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.normals->size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, geometry.normals.value(), *attr});
|
||||
stride += info.size;
|
||||
}
|
||||
@@ -104,7 +104,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
attributes.emplace_back(*attr);
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.uvs->size() / info.count)));
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.uvs->size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, geometry.uvs.value(), *attr});
|
||||
stride += info.size;
|
||||
}
|
||||
@@ -126,7 +126,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
attributes.emplace_back(*attr);
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.tangents->size() / info.count)));
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.tangents->size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, geometry.tangents.value(), *attr});
|
||||
stride += info.size;
|
||||
}
|
||||
@@ -148,7 +148,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
attributes.emplace_back(*attr);
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.colors->size() / info.count)));
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(geometry.colors->size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, geometry.colors.value(), *attr});
|
||||
stride += info.size;
|
||||
}
|
||||
@@ -167,32 +167,32 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
BufferBlob bufferBlob;
|
||||
|
||||
// Fill vertex buffer.
|
||||
auto * vertexBuffer = ccnew ArrayBuffer(vertCount * stride);
|
||||
auto *vertexBuffer = ccnew ArrayBuffer(vertCount * stride);
|
||||
DataView vertexBufferView(vertexBuffer);
|
||||
for (const auto &channel : channels) {
|
||||
writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
|
||||
}
|
||||
bufferBlob.setNextAlignment(0);
|
||||
Mesh::IVertexBundle vertexBundle;
|
||||
Mesh::IBufferView buffferView;
|
||||
Mesh::IBufferView buffferView;
|
||||
|
||||
buffferView.offset = bufferBlob.getLength();
|
||||
buffferView.length = static_cast<uint32_t>(vertexBuffer->byteLength());
|
||||
buffferView.count = vertCount;
|
||||
buffferView.stride = stride;
|
||||
buffferView.offset = bufferBlob.getLength();
|
||||
buffferView.length = static_cast<uint32_t>(vertexBuffer->byteLength());
|
||||
buffferView.count = vertCount;
|
||||
buffferView.stride = stride;
|
||||
vertexBundle.attributes = attributes;
|
||||
vertexBundle.view = buffferView;
|
||||
vertexBundle.view = buffferView;
|
||||
|
||||
bufferBlob.addBuffer(vertexBuffer);
|
||||
|
||||
// Fill index buffer.
|
||||
ArrayBuffer::Ptr indexBuffer;
|
||||
uint32_t idxCount = 0;
|
||||
const uint32_t idxStride = 2;
|
||||
uint32_t idxCount = 0;
|
||||
const uint32_t idxStride = 2;
|
||||
if (geometry.indices.has_value()) {
|
||||
const ccstd::vector<uint32_t> &indices = geometry.indices.value();
|
||||
idxCount = static_cast<uint32_t>(indices.size());
|
||||
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
|
||||
idxCount = static_cast<uint32_t>(indices.size());
|
||||
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
|
||||
DataView indexBufferView(indexBuffer);
|
||||
writeBuffer(indexBufferView, indices, gfx::Format::R16UI);
|
||||
}
|
||||
@@ -200,15 +200,15 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
// Create primitive.
|
||||
Mesh::ISubMesh primitive;
|
||||
primitive.vertexBundelIndices = {0};
|
||||
primitive.primitiveMode = geometry.primitiveMode.has_value() ? geometry.primitiveMode.value() : gfx::PrimitiveMode::TRIANGLE_LIST;
|
||||
primitive.primitiveMode = geometry.primitiveMode.has_value() ? geometry.primitiveMode.value() : gfx::PrimitiveMode::TRIANGLE_LIST;
|
||||
|
||||
if (indexBuffer) {
|
||||
bufferBlob.setNextAlignment(idxStride);
|
||||
Mesh::IBufferView bufferView;
|
||||
bufferView.offset = bufferBlob.getLength();
|
||||
bufferView.length = indexBuffer->byteLength();
|
||||
bufferView.count = idxCount;
|
||||
bufferView.stride = idxStride;
|
||||
bufferView.offset = bufferBlob.getLength();
|
||||
bufferView.length = indexBuffer->byteLength();
|
||||
bufferView.count = idxCount;
|
||||
bufferView.stride = idxStride;
|
||||
primitive.indexView = bufferView;
|
||||
bufferBlob.addBuffer(indexBuffer);
|
||||
}
|
||||
@@ -232,7 +232,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
// Create mesh struct
|
||||
Mesh::IStruct meshStruct;
|
||||
meshStruct.vertexBundles = {vertexBundle};
|
||||
meshStruct.primitives = {primitive};
|
||||
meshStruct.primitives = {primitive};
|
||||
|
||||
if (minPosition.has_value()) {
|
||||
meshStruct.minPosition = minPosition.value();
|
||||
@@ -243,7 +243,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr
|
||||
|
||||
Mesh::ICreateInfo createInfo;
|
||||
createInfo.structInfo = std::move(meshStruct);
|
||||
createInfo.data = Uint8Array(bufferBlob.getCombined());
|
||||
createInfo.data = Uint8Array(bufferBlob.getCombined());
|
||||
return createInfo;
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ Mesh *MeshUtils::createDynamicMesh(index_t primitiveIndex, const IDynamicGeometr
|
||||
|
||||
Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geometry, const ICreateDynamicMeshOptions &options /* = {}*/) {
|
||||
gfx::AttributeList attributes;
|
||||
uint32_t stream = 0U;
|
||||
uint32_t stream = 0U;
|
||||
|
||||
if (!geometry.positions.empty()) {
|
||||
attributes.push_back({gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F, false, stream++, false, 0U});
|
||||
@@ -297,15 +297,15 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
|
||||
|
||||
if (geometry.customAttributes.has_value()) {
|
||||
for (const auto &ca : geometry.customAttributes.value()) {
|
||||
auto attr = ca.attr;
|
||||
auto attr = ca.attr;
|
||||
attr.stream = stream++;
|
||||
attributes.emplace_back(attr);
|
||||
}
|
||||
}
|
||||
|
||||
ccstd::vector<Mesh::IVertexBundle> vertexBundles;
|
||||
ccstd::vector<Mesh::ISubMesh> primitives;
|
||||
uint32_t dataSize = 0U;
|
||||
ccstd::vector<Mesh::ISubMesh> primitives;
|
||||
uint32_t dataSize = 0U;
|
||||
|
||||
for (auto i = 0U; i < options.maxSubMeshes; i++) {
|
||||
Mesh::ISubMesh primitive;
|
||||
@@ -313,8 +313,8 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
|
||||
|
||||
// add vertex buffers
|
||||
for (const auto &attr : attributes) {
|
||||
const auto &formatInfo = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr.format)];
|
||||
uint32_t vertexBufferSize = options.maxSubMeshVertices * formatInfo.size;
|
||||
const auto &formatInfo = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr.format)];
|
||||
uint32_t vertexBufferSize = options.maxSubMeshVertices * formatInfo.size;
|
||||
|
||||
Mesh::IBufferView vertexView = {
|
||||
dataSize,
|
||||
@@ -371,12 +371,12 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
|
||||
|
||||
Mesh::IStruct meshStruct;
|
||||
meshStruct.vertexBundles = vertexBundles;
|
||||
meshStruct.primitives = primitives;
|
||||
meshStruct.dynamic = std::move(dynamicStruct);
|
||||
meshStruct.primitives = primitives;
|
||||
meshStruct.dynamic = std::move(dynamicStruct);
|
||||
|
||||
Mesh::ICreateInfo createInfo;
|
||||
createInfo.structInfo = std::move(meshStruct);
|
||||
createInfo.data = Uint8Array(dataSize);
|
||||
createInfo.data = Uint8Array(dataSize);
|
||||
return createInfo;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ void BakedSkinningModel::destroy() {
|
||||
|
||||
void BakedSkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh) {
|
||||
_skeleton = skeleton;
|
||||
_mesh = mesh;
|
||||
_mesh = mesh;
|
||||
if (skeleton == nullptr || skinningRoot == nullptr || mesh == nullptr) return;
|
||||
setTransform(skinningRoot);
|
||||
|
||||
@@ -94,9 +94,9 @@ void BakedSkinningModel::updateTransform(uint32_t stamp) {
|
||||
if (!_isUploadedAnim) {
|
||||
return;
|
||||
}
|
||||
IAnimInfo & animInfo = _jointMedium.animInfo;
|
||||
IAnimInfo &animInfo = _jointMedium.animInfo;
|
||||
geometry::AABB *skelBound = nullptr;
|
||||
const float * curFrame = animInfo.curFrame;
|
||||
const float *curFrame = animInfo.curFrame;
|
||||
// float curFrame = info.data[0];
|
||||
auto index = static_cast<index_t>(std::roundf(*curFrame));
|
||||
if (!_jointMedium.boundsInfo.empty() && index < _jointMedium.boundsInfo.size()) {
|
||||
@@ -112,10 +112,10 @@ void BakedSkinningModel::updateTransform(uint32_t stamp) {
|
||||
void BakedSkinningModel::updateUBOs(uint32_t stamp) {
|
||||
Super::updateUBOs(stamp);
|
||||
|
||||
IAnimInfo & info = _jointMedium.animInfo;
|
||||
int idx = _instAnimInfoIdx;
|
||||
const float *curFrame = info.curFrame;
|
||||
uint32_t frameDataBytes = info.frameDataBytes;
|
||||
IAnimInfo &info = _jointMedium.animInfo;
|
||||
int idx = _instAnimInfoIdx;
|
||||
const float *curFrame = info.curFrame;
|
||||
uint32_t frameDataBytes = info.frameDataBytes;
|
||||
// float curFrame = info.data[0];
|
||||
// uint32_t curFrameDataBytes = info.data.byteLength();
|
||||
if (idx >= 0) {
|
||||
@@ -136,13 +136,13 @@ void BakedSkinningModel::applyJointTexture(const cc::optional<IJointTextureHandl
|
||||
if (!texture.has_value()) {
|
||||
return;
|
||||
}
|
||||
auto *textureHandle = texture.value();
|
||||
auto *buffer = _jointMedium.buffer.get();
|
||||
auto *textureHandle = texture.value();
|
||||
auto *buffer = _jointMedium.buffer.get();
|
||||
auto &jointTextureInfo = _jointMedium.jointTextureInfo;
|
||||
jointTextureInfo[0] = static_cast<float>(textureHandle->handle.texture->getWidth());
|
||||
jointTextureInfo[1] = static_cast<float>(_skeleton->getJoints().size());
|
||||
jointTextureInfo[2] = static_cast<float>(textureHandle->pixelOffset) + 0.1F; // guard against floor() underflow
|
||||
jointTextureInfo[3] = 1 / jointTextureInfo[0];
|
||||
jointTextureInfo[0] = static_cast<float>(textureHandle->handle.texture->getWidth());
|
||||
jointTextureInfo[1] = static_cast<float>(_skeleton->getJoints().size());
|
||||
jointTextureInfo[2] = static_cast<float>(textureHandle->pixelOffset) + 0.1F; // guard against floor() underflow
|
||||
jointTextureInfo[3] = 1 / jointTextureInfo[0];
|
||||
updateInstancedJointTextureInfo();
|
||||
if (buffer != nullptr) {
|
||||
buffer->update(&jointTextureInfo[0], jointTextureInfo.byteLength());
|
||||
@@ -164,8 +164,8 @@ ccstd::vector<scene::IMacroPatch> BakedSkinningModel::getMacroPatches(index_t su
|
||||
|
||||
void BakedSkinningModel::updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) {
|
||||
Super::updateLocalDescriptors(subModelIndex, descriptorSet);
|
||||
gfx::Buffer * buffer = _jointMedium.buffer;
|
||||
auto & texture = _jointMedium.texture;
|
||||
gfx::Buffer *buffer = _jointMedium.buffer;
|
||||
auto &texture = _jointMedium.texture;
|
||||
const IAnimInfo &animInfo = _jointMedium.animInfo;
|
||||
descriptorSet->bindBuffer(pipeline::UBOSkinningTexture::BINDING, buffer);
|
||||
descriptorSet->bindBuffer(pipeline::UBOSkinningAnimation::BINDING, animInfo.buffer);
|
||||
@@ -183,9 +183,9 @@ void BakedSkinningModel::updateInstancedAttributes(const ccstd::vector<gfx::Attr
|
||||
}
|
||||
|
||||
void BakedSkinningModel::updateInstancedJointTextureInfo() {
|
||||
const auto & jointTextureInfo = _jointMedium.jointTextureInfo;
|
||||
const IAnimInfo &animInfo = _jointMedium.animInfo;
|
||||
index_t idx = _instAnimInfoIdx;
|
||||
const auto &jointTextureInfo = _jointMedium.jointTextureInfo;
|
||||
const IAnimInfo &animInfo = _jointMedium.animInfo;
|
||||
index_t idx = _instAnimInfoIdx;
|
||||
if (idx >= 0) {
|
||||
auto &view = getInstancedAttributeBlock()->views[idx];
|
||||
setTypedArrayValue(view, 0, *animInfo.curFrame); //NOTE: curFrame is only used in JSB.
|
||||
@@ -195,20 +195,20 @@ void BakedSkinningModel::updateInstancedJointTextureInfo() {
|
||||
}
|
||||
|
||||
void BakedSkinningModel::syncAnimInfoForJS(gfx::Buffer *buffer, const Float32Array &data, Uint8Array &dirty) {
|
||||
_jointMedium.animInfo.buffer = buffer;
|
||||
_jointMedium.animInfo.curFrame = &data[0];
|
||||
_jointMedium.animInfo.buffer = buffer;
|
||||
_jointMedium.animInfo.curFrame = &data[0];
|
||||
_jointMedium.animInfo.frameDataBytes = data.byteLength();
|
||||
_jointMedium.animInfo.dirtyForJSB = &dirty[0];
|
||||
_jointMedium.animInfo.dirtyForJSB = &dirty[0];
|
||||
}
|
||||
|
||||
void BakedSkinningModel::syncDataForJS(const ccstd::vector<cc::optional<geometry::AABB>> &boundsInfo,
|
||||
const cc::optional<geometry::AABB> & modelBound,
|
||||
float jointTextureInfo0,
|
||||
float jointTextureInfo1,
|
||||
float jointTextureInfo2,
|
||||
float jointTextureInfo3,
|
||||
gfx::Texture * tex,
|
||||
const Float32Array & animInfoData) {
|
||||
const cc::optional<geometry::AABB> &modelBound,
|
||||
float jointTextureInfo0,
|
||||
float jointTextureInfo1,
|
||||
float jointTextureInfo2,
|
||||
float jointTextureInfo3,
|
||||
gfx::Texture *tex,
|
||||
const Float32Array &animInfoData) {
|
||||
_jointMedium.boundsInfo = boundsInfo;
|
||||
|
||||
if (modelBound.has_value()) {
|
||||
@@ -223,11 +223,11 @@ void BakedSkinningModel::syncDataForJS(const ccstd::vector<cc::optional<geometry
|
||||
_jointMedium.jointTextureInfo[2] = jointTextureInfo2;
|
||||
_jointMedium.jointTextureInfo[3] = jointTextureInfo3;
|
||||
|
||||
_jointMedium.animInfo.curFrame = &animInfoData[0];
|
||||
_jointMedium.animInfo.curFrame = &animInfoData[0];
|
||||
_jointMedium.animInfo.frameDataBytes = animInfoData.byteLength();
|
||||
IJointTextureHandle *textureInfo = IJointTextureHandle::createJoinTextureHandle();
|
||||
textureInfo->handle.texture = tex;
|
||||
_jointMedium.texture = textureInfo;
|
||||
IJointTextureHandle *textureInfo = IJointTextureHandle::createJoinTextureHandle();
|
||||
textureInfo->handle.texture = tex;
|
||||
_jointMedium.texture = textureInfo;
|
||||
|
||||
updateInstancedJointTextureInfo();
|
||||
|
||||
|
||||
@@ -41,10 +41,10 @@ class Texture;
|
||||
class DataPoolManager;
|
||||
|
||||
struct BakedJointInfo {
|
||||
IntrusivePtr<gfx::Buffer> buffer;
|
||||
Float32Array jointTextureInfo;
|
||||
cc::optional<IJointTextureHandle *> texture;
|
||||
IAnimInfo animInfo;
|
||||
IntrusivePtr<gfx::Buffer> buffer;
|
||||
Float32Array jointTextureInfo;
|
||||
cc::optional<IJointTextureHandle *> texture;
|
||||
IAnimInfo animInfo;
|
||||
ccstd::vector<cc::optional<geometry::AABB>> boundsInfo;
|
||||
};
|
||||
|
||||
@@ -56,12 +56,12 @@ public:
|
||||
|
||||
void destroy() override;
|
||||
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) override;
|
||||
void updateTransform(uint32_t stamp) override;
|
||||
void updateUBOs(uint32_t stamp) override;
|
||||
void updateInstancedAttributes(const ccstd::vector<gfx::Attribute> &attributes, scene::Pass *pass) override;
|
||||
void updateInstancedJointTextureInfo();
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) override;
|
||||
void updateTransform(uint32_t stamp) override;
|
||||
void updateUBOs(uint32_t stamp) override;
|
||||
void updateInstancedAttributes(const ccstd::vector<gfx::Attribute> &attributes, scene::Pass *pass) override;
|
||||
void updateInstancedJointTextureInfo();
|
||||
// void uploadAnimation(AnimationClip *anim); // TODO(xwx): AnimationClip not define
|
||||
|
||||
void bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh);
|
||||
@@ -76,13 +76,13 @@ public:
|
||||
|
||||
void syncAnimInfoForJS(gfx::Buffer *buffer, const Float32Array &data, Uint8Array &dirty);
|
||||
void syncDataForJS(const ccstd::vector<cc::optional<geometry::AABB>> &boundsInfo,
|
||||
const cc::optional<geometry::AABB> & modelBound,
|
||||
float jointTextureInfo0,
|
||||
float jointTextureInfo1,
|
||||
float jointTextureInfo2,
|
||||
float jointTextureInfo3,
|
||||
gfx::Texture * tex,
|
||||
const Float32Array & animInfoData);
|
||||
const cc::optional<geometry::AABB> &modelBound,
|
||||
float jointTextureInfo0,
|
||||
float jointTextureInfo1,
|
||||
float jointTextureInfo2,
|
||||
float jointTextureInfo3,
|
||||
gfx::Texture *tex,
|
||||
const Float32Array &animInfoData);
|
||||
|
||||
void setUploadedAnimForJS(bool value) { _isUploadedAnim = value; }
|
||||
|
||||
@@ -91,10 +91,10 @@ protected:
|
||||
|
||||
private:
|
||||
BakedJointInfo _jointMedium;
|
||||
index_t _instAnimInfoIdx{CC_INVALID_INDEX};
|
||||
index_t _instAnimInfoIdx{CC_INVALID_INDEX};
|
||||
// IntrusivePtr<DataPoolManager> _dataPoolManager;
|
||||
IntrusivePtr<Skeleton> _skeleton;
|
||||
IntrusivePtr<Mesh> _mesh;
|
||||
IntrusivePtr<Mesh> _mesh;
|
||||
// AnimationClip* uploadedAnim;
|
||||
bool _isUploadedAnim{false};
|
||||
|
||||
|
||||
@@ -35,14 +35,14 @@ class MorphModel : public scene::Model {
|
||||
public:
|
||||
using Super = scene::Model;
|
||||
|
||||
MorphModel() = default;
|
||||
MorphModel() = default;
|
||||
~MorphModel() override = default;
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(MorphModel);
|
||||
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override;
|
||||
void destroy() override;
|
||||
void setSubModelMaterial(index_t idx, Material *mat) override;
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override;
|
||||
void destroy() override;
|
||||
void setSubModelMaterial(index_t idx, Material *mat) override;
|
||||
|
||||
inline void setMorphRendering(MorphRenderingInstance *morphRendering) { _morphRenderingInstance = morphRendering; }
|
||||
|
||||
|
||||
@@ -85,18 +85,18 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
|
||||
if (!skeleton || !skinningRoot || !mesh) return;
|
||||
setTransform(skinningRoot);
|
||||
auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton);
|
||||
const auto &jointMaps = mesh->getStruct().jointMaps;
|
||||
auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton);
|
||||
const auto &jointMaps = mesh->getStruct().jointMaps;
|
||||
ensureEnoughBuffers((jointMaps.has_value() && !jointMaps->empty()) ? static_cast<int32_t>(jointMaps->size()) : 1);
|
||||
_bufferIndices = mesh->getJointBufferIndices();
|
||||
|
||||
for (index_t index = 0; index < skeleton->getJoints().size(); ++index) {
|
||||
geometry::AABB *bound = boneSpaceBounds[index];
|
||||
auto * target = skinningRoot->getChildByPath(skeleton->getJoints()[index]);
|
||||
geometry::AABB *bound = boneSpaceBounds[index];
|
||||
auto *target = skinningRoot->getChildByPath(skeleton->getJoints()[index]);
|
||||
if (!bound || !target) continue;
|
||||
|
||||
auto * transform = cc::getTransform(target, skinningRoot);
|
||||
const Mat4 & bindPose = skeleton->getBindposes()[index];
|
||||
auto *transform = cc::getTransform(target, skinningRoot);
|
||||
const Mat4 &bindPose = skeleton->getBindposes()[index];
|
||||
ccstd::vector<index_t> indices;
|
||||
ccstd::vector<index_t> buffers;
|
||||
if (!jointMaps.has_value()) {
|
||||
@@ -107,12 +107,12 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
}
|
||||
|
||||
JointInfo jointInfo;
|
||||
jointInfo.bound = bound;
|
||||
jointInfo.target = target;
|
||||
jointInfo.bindpose = bindPose;
|
||||
jointInfo.bound = bound;
|
||||
jointInfo.target = target;
|
||||
jointInfo.bindpose = bindPose;
|
||||
jointInfo.transform = transform;
|
||||
jointInfo.buffers = std::move(buffers);
|
||||
jointInfo.indices = std::move(indices);
|
||||
jointInfo.buffers = std::move(buffers);
|
||||
jointInfo.indices = std::move(indices);
|
||||
_joints.emplace_back(std::move(jointInfo));
|
||||
}
|
||||
}
|
||||
@@ -123,15 +123,15 @@ void SkinningModel::updateTransform(uint32_t stamp) {
|
||||
root->updateWorldTransform();
|
||||
_localDataUpdated = true;
|
||||
}
|
||||
Vec3 v3Min{INFINITY, INFINITY, INFINITY};
|
||||
Vec3 v3Max{-INFINITY, -INFINITY, -INFINITY};
|
||||
Vec3 v3Min{INFINITY, INFINITY, INFINITY};
|
||||
Vec3 v3Max{-INFINITY, -INFINITY, -INFINITY};
|
||||
geometry::AABB ab1;
|
||||
Vec3 v31;
|
||||
Vec3 v32;
|
||||
Vec3 v31;
|
||||
Vec3 v32;
|
||||
for (JointInfo &jointInfo : _joints) {
|
||||
const auto *bound = jointInfo.bound;
|
||||
auto * transform = jointInfo.transform;
|
||||
Mat4 worldMatrix = cc::getWorldMatrix(transform, static_cast<int32_t>(stamp));
|
||||
const auto *bound = jointInfo.bound;
|
||||
auto *transform = jointInfo.transform;
|
||||
Mat4 worldMatrix = cc::getWorldMatrix(transform, static_cast<int32_t>(stamp));
|
||||
jointInfo.bound->transform(worldMatrix, &ab1);
|
||||
ab1.getBoundary(&v31, &v32);
|
||||
Vec3::min(v3Min, v31, &v3Min);
|
||||
@@ -146,7 +146,7 @@ void SkinningModel::updateTransform(uint32_t stamp) {
|
||||
void SkinningModel::updateUBOs(uint32_t stamp) {
|
||||
Super::updateUBOs(stamp);
|
||||
uint32_t bIdx = 0;
|
||||
Mat4 mat4;
|
||||
Mat4 mat4;
|
||||
for (const JointInfo &jointInfo : _joints) {
|
||||
Mat4::multiply(jointInfo.transform->world, jointInfo.bindpose, &mat4);
|
||||
for (uint32_t buffer : jointInfo.buffers) {
|
||||
@@ -164,7 +164,7 @@ void SkinningModel::updateUBOs(uint32_t stamp) {
|
||||
|
||||
void SkinningModel::initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) {
|
||||
const auto &original = subMeshData->getVertexBuffers();
|
||||
auto & iaInfo = subMeshData->getIaInfo();
|
||||
auto &iaInfo = subMeshData->getIaInfo();
|
||||
iaInfo.vertexBuffers = subMeshData->getJointMappedBuffers();
|
||||
Super::initSubModel(idx, subMeshData, mat);
|
||||
iaInfo.vertexBuffers = original;
|
||||
@@ -177,14 +177,14 @@ ccstd::vector<scene::IMacroPatch> SkinningModel::getMacroPatches(index_t subMode
|
||||
patches.insert(std::begin(patches), std::begin(myPatches), std::end(myPatches));
|
||||
return patches;
|
||||
}
|
||||
|
||||
|
||||
return myPatches;
|
||||
}
|
||||
|
||||
void SkinningModel::uploadJointData(uint32_t base, const Mat4 &mat, float *dst) {
|
||||
memcpy(reinterpret_cast<void *>(dst + base), mat.m, sizeof(float) * 12);
|
||||
dst[base + 3] = mat.m[12];
|
||||
dst[base + 7] = mat.m[13];
|
||||
dst[base + 3] = mat.m[12];
|
||||
dst[base + 7] = mat.m[13];
|
||||
dst[base + 11] = mat.m[14];
|
||||
}
|
||||
|
||||
|
||||
@@ -40,10 +40,10 @@ class AABB;
|
||||
}
|
||||
|
||||
struct JointInfo {
|
||||
geometry::AABB * bound{nullptr};
|
||||
Node * target{nullptr};
|
||||
Mat4 bindpose;
|
||||
IJointTransform * transform{nullptr};
|
||||
geometry::AABB *bound{nullptr};
|
||||
Node *target{nullptr};
|
||||
Mat4 bindpose;
|
||||
IJointTransform *transform{nullptr};
|
||||
ccstd::vector<index_t> buffers;
|
||||
ccstd::vector<index_t> indices;
|
||||
};
|
||||
@@ -59,19 +59,19 @@ public:
|
||||
void updateUBOs(uint32_t stamp) override;
|
||||
void destroy() override;
|
||||
|
||||
void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override;
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void updateInstancedAttributes(const ccstd::vector<gfx::Attribute> &attributes, scene::Pass *pass) override;
|
||||
void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override;
|
||||
ccstd::vector<scene::IMacroPatch> getMacroPatches(index_t subModelIndex) override;
|
||||
void updateInstancedAttributes(const ccstd::vector<gfx::Attribute> &attributes, scene::Pass *pass) override;
|
||||
|
||||
void bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh);
|
||||
|
||||
private:
|
||||
static void uploadJointData(uint32_t base, const Mat4 &mat, float *dst);
|
||||
void ensureEnoughBuffers(index_t count);
|
||||
void ensureEnoughBuffers(index_t count);
|
||||
|
||||
ccstd::vector<index_t> _bufferIndices;
|
||||
ccstd::vector<IntrusivePtr<gfx::Buffer>> _buffers;
|
||||
ccstd::vector<JointInfo> _joints;
|
||||
ccstd::vector<index_t> _bufferIndices;
|
||||
ccstd::vector<IntrusivePtr<gfx::Buffer>> _buffers;
|
||||
ccstd::vector<JointInfo> _joints;
|
||||
ccstd::vector<ccstd::array<float, pipeline::UBOSkinning::COUNT> *> _dataArray;
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(SkinningModel);
|
||||
|
||||
@@ -40,25 +40,25 @@ cc::gfx::Format selectJointsMediumFormat(cc::gfx::Device *device) {
|
||||
|
||||
// Linear Blending Skinning
|
||||
void uploadJointDataLBS(cc::Float32Array out, uint32_t base, const cc::Mat4 &mat, bool /*firstBone*/) {
|
||||
out[base + 0] = mat.m[0];
|
||||
out[base + 1] = mat.m[1];
|
||||
out[base + 2] = mat.m[2];
|
||||
out[base + 3] = mat.m[12];
|
||||
out[base + 4] = mat.m[4];
|
||||
out[base + 5] = mat.m[5];
|
||||
out[base + 6] = mat.m[6];
|
||||
out[base + 7] = mat.m[13];
|
||||
out[base + 8] = mat.m[8];
|
||||
out[base + 9] = mat.m[9];
|
||||
out[base + 0] = mat.m[0];
|
||||
out[base + 1] = mat.m[1];
|
||||
out[base + 2] = mat.m[2];
|
||||
out[base + 3] = mat.m[12];
|
||||
out[base + 4] = mat.m[4];
|
||||
out[base + 5] = mat.m[5];
|
||||
out[base + 6] = mat.m[6];
|
||||
out[base + 7] = mat.m[13];
|
||||
out[base + 8] = mat.m[8];
|
||||
out[base + 9] = mat.m[9];
|
||||
out[base + 10] = mat.m[10];
|
||||
out[base + 11] = mat.m[14];
|
||||
}
|
||||
|
||||
cc::Quaternion dq0;
|
||||
cc::Quaternion dq1;
|
||||
cc::Vec3 v31;
|
||||
cc::Vec3 v31;
|
||||
cc::Quaternion qt1;
|
||||
cc::Vec3 v32;
|
||||
cc::Vec3 v32;
|
||||
|
||||
float dot(const cc::Quaternion &a, const cc::Quaternion &b) {
|
||||
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
|
||||
@@ -87,16 +87,16 @@ void uploadJointDataDQS(cc::Float32Array out, uint32_t base, cc::Mat4 &mat, bool
|
||||
dq1.w = 0;
|
||||
multiplyScalar(dq1 * qt1, 0.5, &dq1);
|
||||
// upload
|
||||
out[base + 0] = qt1.x;
|
||||
out[base + 1] = qt1.y;
|
||||
out[base + 2] = qt1.z;
|
||||
out[base + 3] = qt1.w;
|
||||
out[base + 4] = dq1.x;
|
||||
out[base + 5] = dq1.y;
|
||||
out[base + 6] = dq1.z;
|
||||
out[base + 7] = dq1.w;
|
||||
out[base + 8] = v32.x;
|
||||
out[base + 9] = v32.y;
|
||||
out[base + 0] = qt1.x;
|
||||
out[base + 1] = qt1.y;
|
||||
out[base + 2] = qt1.z;
|
||||
out[base + 3] = qt1.w;
|
||||
out[base + 4] = dq1.x;
|
||||
out[base + 5] = dq1.y;
|
||||
out[base + 6] = dq1.z;
|
||||
out[base + 7] = dq1.w;
|
||||
out[base + 8] = v32.x;
|
||||
out[base + 9] = v32.y;
|
||||
out[base + 10] = v32.z;
|
||||
}
|
||||
|
||||
@@ -136,18 +136,18 @@ cc::Mat4 *getWorldTransformUntilRoot(cc::Node *target, cc::Node *root, cc::Mat4
|
||||
} // namespace
|
||||
namespace cc {
|
||||
JointTexturePool::JointTexturePool(gfx::Device *device) {
|
||||
_device = device;
|
||||
_device = device;
|
||||
const auto &format = selectJointsMediumFormat(_device);
|
||||
_formatSize = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)].size;
|
||||
_pixelsPerJoint = 48 / _formatSize;
|
||||
_pool = ccnew TextureBufferPool(device);
|
||||
_formatSize = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(format)].size;
|
||||
_pixelsPerJoint = 48 / _formatSize;
|
||||
_pool = ccnew TextureBufferPool(device);
|
||||
ITextureBufferPoolInfo poolInfo;
|
||||
poolInfo.format = format;
|
||||
poolInfo.format = format;
|
||||
poolInfo.roundUpFn = roundUpType{roundUpTextureSize};
|
||||
_pool->initialize(poolInfo);
|
||||
_customPool = ccnew TextureBufferPool(device);
|
||||
ITextureBufferPoolInfo customPoolInfo;
|
||||
customPoolInfo.format = format;
|
||||
customPoolInfo.format = format;
|
||||
customPoolInfo.roundUpFn = roundUpType{roundUpTextureSize};
|
||||
_customPool->initialize(customPoolInfo);
|
||||
}
|
||||
@@ -161,7 +161,7 @@ void JointTexturePool::registerCustomTextureLayouts(const ccstd::vector<ICustomJ
|
||||
for (const auto &layout : layouts) {
|
||||
auto chunkIdx = static_cast<index_t>(_customPool->createChunk(layout.textureLength));
|
||||
for (const auto &content : layout.contents) {
|
||||
auto skeleton = content.skeleton;
|
||||
auto skeleton = content.skeleton;
|
||||
_chunkIdxMap[skeleton] = chunkIdx; // include default pose too
|
||||
for (const auto &clip : content.clips) {
|
||||
_chunkIdxMap[skeleton ^ clip] = chunkIdx;
|
||||
@@ -171,19 +171,19 @@ void JointTexturePool::registerCustomTextureLayouts(const ccstd::vector<ICustomJ
|
||||
}
|
||||
|
||||
cc::optional<IJointTextureHandle *> JointTexturePool::getDefaultPoseTexture(Skeleton *skeleton, Mesh *mesh, Node *skinningRoot) {
|
||||
uint64_t hash = skeleton->getHash() ^ 0; // may not equal to skeleton.hash
|
||||
uint64_t hash = skeleton->getHash() ^ 0; // may not equal to skeleton.hash
|
||||
cc::optional<IJointTextureHandle *> texture;
|
||||
if (_textureBuffers.find(hash) != _textureBuffers.end()) {
|
||||
texture = _textureBuffers[hash];
|
||||
}
|
||||
|
||||
const ccstd::vector<ccstd::string> &joints = skeleton->getJoints();
|
||||
const ccstd::vector<Mat4> & bindPoses = skeleton->getBindposes();
|
||||
Float32Array textureBuffer;
|
||||
bool buildTexture = false;
|
||||
auto jointCount = static_cast<uint32_t>(joints.size());
|
||||
const ccstd::vector<ccstd::string> &joints = skeleton->getJoints();
|
||||
const ccstd::vector<Mat4> &bindPoses = skeleton->getBindposes();
|
||||
Float32Array textureBuffer;
|
||||
bool buildTexture = false;
|
||||
auto jointCount = static_cast<uint32_t>(joints.size());
|
||||
if (!texture.has_value()) {
|
||||
uint32_t bufSize = jointCount * 12;
|
||||
uint32_t bufSize = jointCount * 12;
|
||||
ITextureBufferHandle handle;
|
||||
if (_chunkIdxMap.find(hash) != _chunkIdxMap.end()) {
|
||||
handle = _customPool->alloc(bufSize * Float32Array::BYTES_PER_ELEMENT, _chunkIdxMap[hash]);
|
||||
@@ -192,29 +192,29 @@ cc::optional<IJointTextureHandle *> JointTexturePool::getDefaultPoseTexture(Skel
|
||||
return texture;
|
||||
}
|
||||
IJointTextureHandle *textureHandle = IJointTextureHandle::createJoinTextureHandle();
|
||||
textureHandle->pixelOffset = handle.start / _formatSize;
|
||||
textureHandle->refCount = 1;
|
||||
textureHandle->clipHash = 0;
|
||||
textureHandle->skeletonHash = skeleton->getHash();
|
||||
textureHandle->readyToBeDeleted = false;
|
||||
textureHandle->handle = handle;
|
||||
texture = textureHandle;
|
||||
textureBuffer = Float32Array(bufSize);
|
||||
buildTexture = true;
|
||||
textureHandle->pixelOffset = handle.start / _formatSize;
|
||||
textureHandle->refCount = 1;
|
||||
textureHandle->clipHash = 0;
|
||||
textureHandle->skeletonHash = skeleton->getHash();
|
||||
textureHandle->readyToBeDeleted = false;
|
||||
textureHandle->handle = handle;
|
||||
texture = textureHandle;
|
||||
textureBuffer = Float32Array(bufSize);
|
||||
buildTexture = true;
|
||||
} else {
|
||||
texture.value()->refCount++;
|
||||
}
|
||||
|
||||
geometry::AABB ab1;
|
||||
Mat4 mat4;
|
||||
Vec3 v34;
|
||||
Vec3 v33;
|
||||
Vec3 v3Min(-INF, -INF, -INF);
|
||||
Vec3 v3Max(-INF, -INF, -INF);
|
||||
auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton);
|
||||
Mat4 mat4;
|
||||
Vec3 v34;
|
||||
Vec3 v33;
|
||||
Vec3 v3Min(-INF, -INF, -INF);
|
||||
Vec3 v3Max(-INF, -INF, -INF);
|
||||
auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton);
|
||||
for (uint32_t j = 0, offset = 0; j < jointCount; ++j, offset += 12) {
|
||||
auto *node = skinningRoot->getChildByPath(joints[j]);
|
||||
Mat4 mat = node ? *getWorldTransformUntilRoot(node, skinningRoot, &mat4) : skeleton->getInverseBindposes()[j];
|
||||
Mat4 mat = node ? *getWorldTransformUntilRoot(node, skinningRoot, &mat4) : skeleton->getInverseBindposes()[j];
|
||||
if (j < boneSpaceBounds.size()) {
|
||||
auto *bound = boneSpaceBounds[j].get();
|
||||
bound->transform(mat, &ab1);
|
||||
@@ -474,9 +474,9 @@ IAnimInfo JointAnimationInfo::getData(const ccstd::string &nodeID) {
|
||||
Float32Array data;
|
||||
buffer->update(data.buffer()->getData());
|
||||
IAnimInfo info;
|
||||
info.buffer = buffer;
|
||||
info.data = data;
|
||||
info.dirty = false;
|
||||
info.buffer = buffer;
|
||||
info.data = data;
|
||||
info.dirty = false;
|
||||
_pool[nodeID] = info;
|
||||
|
||||
return info;
|
||||
|
||||
@@ -42,32 +42,32 @@ class Mesh;
|
||||
|
||||
// _chunkIdxMap[key] = skeleton ^ clips[i]
|
||||
struct IChunkContent {
|
||||
uint64_t skeleton{0};
|
||||
uint64_t skeleton{0};
|
||||
ccstd::vector<uint64_t> clips;
|
||||
};
|
||||
|
||||
struct ICustomJointTextureLayout {
|
||||
uint32_t textureLength{0};
|
||||
uint32_t textureLength{0};
|
||||
ccstd::vector<IChunkContent> contents;
|
||||
};
|
||||
|
||||
struct IInternalJointAnimInfo {
|
||||
cc::optional<Mat4> downstream; // downstream default pose, if present
|
||||
cc::optional<ccstd::vector<Mat4>> curveData; // the nearest animation curve, if present
|
||||
index_t bindposeIdx{0}; // index of the actual bindpose to use
|
||||
cc::optional<Mat4> bindposeCorrection; // correction factor from the original bindpose
|
||||
cc::optional<Mat4> downstream; // downstream default pose, if present
|
||||
cc::optional<ccstd::vector<Mat4>> curveData; // the nearest animation curve, if present
|
||||
index_t bindposeIdx{0}; // index of the actual bindpose to use
|
||||
cc::optional<Mat4> bindposeCorrection; // correction factor from the original bindpose
|
||||
};
|
||||
|
||||
class IJointTextureHandle {
|
||||
public:
|
||||
uint32_t pixelOffset{0};
|
||||
uint32_t refCount{0};
|
||||
uint64_t clipHash{0};
|
||||
uint64_t skeletonHash{0};
|
||||
bool readyToBeDeleted{false};
|
||||
ITextureBufferHandle handle;
|
||||
uint32_t pixelOffset{0};
|
||||
uint32_t refCount{0};
|
||||
uint64_t clipHash{0};
|
||||
uint64_t skeletonHash{0};
|
||||
bool readyToBeDeleted{false};
|
||||
ITextureBufferHandle handle;
|
||||
ccstd::unordered_map<uint32_t, ccstd::vector<geometry::AABB>> bounds;
|
||||
cc::optional<ccstd::vector<IInternalJointAnimInfo>> animInfos;
|
||||
cc::optional<ccstd::vector<IInternalJointAnimInfo>> animInfos;
|
||||
|
||||
static IJointTextureHandle *createJoinTextureHandle() {
|
||||
return ccnew IJointTextureHandle();
|
||||
@@ -114,13 +114,13 @@ public:
|
||||
private:
|
||||
// const IInternalJointAnimInfo &createAnimInfos(Skeleton *skeleton, AnimationClip *clip, Node *skinningRoot); // TODO(xwx): AnimationClip not define
|
||||
|
||||
gfx::Device * _device{nullptr};
|
||||
IntrusivePtr<TextureBufferPool> _pool;
|
||||
gfx::Device *_device{nullptr};
|
||||
IntrusivePtr<TextureBufferPool> _pool;
|
||||
ccstd::unordered_map<uint64_t, IJointTextureHandle *> _textureBuffers;
|
||||
uint32_t _formatSize{0};
|
||||
uint32_t _pixelsPerJoint{0};
|
||||
IntrusivePtr<TextureBufferPool> _customPool;
|
||||
ccstd::unordered_map<uint64_t, index_t> _chunkIdxMap; // hash -> chunkIdx
|
||||
uint32_t _formatSize{0};
|
||||
uint32_t _pixelsPerJoint{0};
|
||||
IntrusivePtr<TextureBufferPool> _customPool;
|
||||
ccstd::unordered_map<uint64_t, index_t> _chunkIdxMap; // hash -> chunkIdx
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(JointTexturePool);
|
||||
};
|
||||
@@ -128,10 +128,10 @@ private:
|
||||
struct IAnimInfo {
|
||||
gfx::Buffer *buffer{nullptr};
|
||||
Float32Array data;
|
||||
const float *curFrame{nullptr}; // Only used in JSB
|
||||
uint32_t frameDataBytes{0}; // Only used in JSB
|
||||
uint8_t * dirtyForJSB{nullptr}; // Only used in JSB
|
||||
bool dirty{false};
|
||||
const float *curFrame{nullptr}; // Only used in JSB
|
||||
uint32_t frameDataBytes{0}; // Only used in JSB
|
||||
uint8_t *dirtyForJSB{nullptr}; // Only used in JSB
|
||||
bool dirty{false};
|
||||
};
|
||||
|
||||
class JointAnimationInfo : public RefCounted {
|
||||
@@ -140,14 +140,14 @@ public:
|
||||
explicit JointAnimationInfo(gfx::Device *device);
|
||||
~JointAnimationInfo() override = default;
|
||||
|
||||
IAnimInfo getData(const ccstd::string &nodeID = "-1");
|
||||
void destroy(const ccstd::string &nodeID);
|
||||
IAnimInfo getData(const ccstd::string &nodeID = "-1");
|
||||
void destroy(const ccstd::string &nodeID);
|
||||
static const IAnimInfo &switchClip(IAnimInfo &info /*, AnimationClip *clip */);
|
||||
void clear();
|
||||
void clear();
|
||||
|
||||
private:
|
||||
ccstd::unordered_map<ccstd::string, IAnimInfo> _pool; // pre node
|
||||
gfx::Device * _device{nullptr};
|
||||
gfx::Device *_device{nullptr};
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(JointAnimationInfo);
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
namespace cc {
|
||||
class CC_DLL ApplicationManager {
|
||||
public:
|
||||
static ApplicationManager *getInstance();
|
||||
static ApplicationManager* getInstance();
|
||||
|
||||
using ApplicationPtr = std::shared_ptr<BaseApplication>;
|
||||
|
||||
@@ -64,7 +64,7 @@ public:
|
||||
|
||||
private:
|
||||
std::weak_ptr<BaseApplication> _currentApp;
|
||||
ccstd::vector<ApplicationPtr> _apps;
|
||||
ccstd::vector<ApplicationPtr> _apps;
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public:
|
||||
/**
|
||||
* @brief Application main business logic.
|
||||
*/
|
||||
virtual int32_t run(int argc,
|
||||
virtual int32_t run(int argc,
|
||||
const char **argv) = 0;
|
||||
/**
|
||||
* @brief Pause the application.
|
||||
|
||||
@@ -30,18 +30,18 @@ namespace cc {
|
||||
class BaseGame : public CocosApplication {
|
||||
public:
|
||||
struct DebuggerInfo {
|
||||
bool enabled{true};
|
||||
int32_t port{6086};
|
||||
bool enabled{true};
|
||||
int32_t port{6086};
|
||||
std::string address{"0.0.0.0"};
|
||||
bool pauseOnStart{false};
|
||||
bool pauseOnStart{false};
|
||||
};
|
||||
struct WindowInfo {
|
||||
std::string title;
|
||||
int32_t x{-1};
|
||||
int32_t y{-1};
|
||||
int32_t width{-1};
|
||||
int32_t height{-1};
|
||||
int32_t flags{-1};
|
||||
int32_t x{-1};
|
||||
int32_t y{-1};
|
||||
int32_t width{-1};
|
||||
int32_t height{-1};
|
||||
int32_t flags{-1};
|
||||
};
|
||||
|
||||
BaseGame() = default;
|
||||
@@ -51,9 +51,9 @@ public:
|
||||
// override default value
|
||||
//_windowInfo.x = _windowInfo.x == -1 ? 0 : _windowInfo.x;
|
||||
//_windowInfo.y = _windowInfo.y == -1 ? 0 : _windowInfo.y;
|
||||
_windowInfo.width = _windowInfo.width == -1 ? 800 : _windowInfo.width;
|
||||
_windowInfo.width = _windowInfo.width == -1 ? 800 : _windowInfo.width;
|
||||
_windowInfo.height = _windowInfo.height == -1 ? 600 : _windowInfo.height;
|
||||
_windowInfo.flags = _windowInfo.flags == -1 ? cc::ISystemWindow::CC_WINDOW_SHOWN |
|
||||
_windowInfo.flags = _windowInfo.flags == -1 ? cc::ISystemWindow::CC_WINDOW_SHOWN |
|
||||
cc::ISystemWindow::CC_WINDOW_RESIZABLE |
|
||||
cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS
|
||||
: _windowInfo.flags;
|
||||
@@ -82,8 +82,8 @@ public:
|
||||
}
|
||||
|
||||
protected:
|
||||
std::string _xxteaKey;
|
||||
std::string _xxteaKey;
|
||||
DebuggerInfo _debuggerInfo;
|
||||
WindowInfo _windowInfo;
|
||||
WindowInfo _windowInfo;
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
namespace cc {
|
||||
|
||||
CocosApplication::CocosApplication() {
|
||||
_engine = BaseEngine::createEngine();
|
||||
_engine = BaseEngine::createEngine();
|
||||
_systemWidow = _engine->getInterface<ISystemWindow>();
|
||||
CC_ASSERT(_systemWidow != nullptr);
|
||||
}
|
||||
@@ -78,9 +78,9 @@ int CocosApplication::init() {
|
||||
se->start();
|
||||
|
||||
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS)
|
||||
auto logicSize = _systemWidow->getViewSize();
|
||||
IScreen *screen = _engine->getInterface<IScreen>();
|
||||
float pixelRatio = screen->getDevicePixelRatio();
|
||||
auto logicSize = _systemWidow->getViewSize();
|
||||
IScreen *screen = _engine->getInterface<IScreen>();
|
||||
float pixelRatio = screen->getDevicePixelRatio();
|
||||
cc::EventDispatcher::dispatchResizeEvent(logicSize.x * pixelRatio, logicSize.y * pixelRatio);
|
||||
#endif
|
||||
return 0;
|
||||
|
||||
@@ -98,7 +98,7 @@ public:
|
||||
* @param h: Window height
|
||||
* @param flags: Window flag
|
||||
*/
|
||||
virtual void createWindow(const char* title, int32_t w,
|
||||
virtual void createWindow(const char *title, int32_t w,
|
||||
int32_t h, int32_t flags);
|
||||
#endif
|
||||
/**
|
||||
@@ -107,12 +107,12 @@ public:
|
||||
* @param port:Server port.
|
||||
* @param isWaitForConnect:Is Wait for connect.
|
||||
*/
|
||||
virtual void setDebugIpAndPort(const ccstd::string& serverAddr, uint32_t port, bool isWaitForConnect);
|
||||
virtual void setDebugIpAndPort(const ccstd::string &serverAddr, uint32_t port, bool isWaitForConnect);
|
||||
/**
|
||||
* @brief Run the script file
|
||||
* @param filePath:script path.
|
||||
*/
|
||||
virtual void runScript(const ccstd::string& filePath);
|
||||
virtual void runScript(const ccstd::string &filePath);
|
||||
/**
|
||||
* @brief Script exception handling
|
||||
* @param location,Exception location
|
||||
@@ -123,7 +123,7 @@ public:
|
||||
virtual void setXXTeaKey(const ccstd::string &key);
|
||||
|
||||
private:
|
||||
ISystemWindow* _systemWidow{nullptr};
|
||||
ISystemWindow *_systemWidow{nullptr};
|
||||
BaseEngine::Ptr _engine{nullptr};
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
@@ -56,25 +56,25 @@
|
||||
|
||||
using namespace cc; //NOLINT
|
||||
|
||||
const int AudioEngine::INVALID_AUDIO_ID = -1;
|
||||
const float AudioEngine::TIME_UNKNOWN = -1.0F;
|
||||
const int AudioEngine::INVALID_AUDIO_ID = -1;
|
||||
const float AudioEngine::TIME_UNKNOWN = -1.0F;
|
||||
|
||||
//audio file path,audio IDs
|
||||
ccstd::unordered_map<ccstd::string, ccstd::list<int>> AudioEngine::sAudioPathIDMap;
|
||||
//profileName,ProfileHelper
|
||||
ccstd::unordered_map<ccstd::string, AudioEngine::ProfileHelper> AudioEngine::sAudioPathProfileHelperMap;
|
||||
unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES;
|
||||
AudioEngine::ProfileHelper * AudioEngine::sDefaultProfileHelper = nullptr;
|
||||
ccstd::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::sAudioIDInfoMap;
|
||||
AudioEngineImpl * AudioEngine::sAudioEngineImpl = nullptr;
|
||||
unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES;
|
||||
AudioEngine::ProfileHelper *AudioEngine::sDefaultProfileHelper = nullptr;
|
||||
ccstd::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::sAudioIDInfoMap;
|
||||
AudioEngineImpl *AudioEngine::sAudioEngineImpl = nullptr;
|
||||
|
||||
float AudioEngine::sVolumeFactor = 1.0F;
|
||||
uint32_t AudioEngine::sOnPauseListenerID = 0;
|
||||
uint32_t AudioEngine::sOnResumeListenerID = 0;
|
||||
float AudioEngine::sVolumeFactor = 1.0F;
|
||||
uint32_t AudioEngine::sOnPauseListenerID = 0;
|
||||
uint32_t AudioEngine::sOnResumeListenerID = 0;
|
||||
ccstd::vector<int> AudioEngine::sBreakAudioID;
|
||||
|
||||
AudioEngine::AudioEngineThreadPool *AudioEngine::sThreadPool = nullptr;
|
||||
bool AudioEngine::sIsEnabled = true;
|
||||
bool AudioEngine::sIsEnabled = true;
|
||||
|
||||
AudioEngine::AudioInfo::AudioInfo()
|
||||
: filePath(nullptr),
|
||||
@@ -135,12 +135,12 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
ccstd::vector<std::thread> _workers;
|
||||
ccstd::vector<std::thread> _workers;
|
||||
ccstd::queue<std::function<void()>> _taskQueue;
|
||||
|
||||
std::mutex _queueMutex;
|
||||
std::mutex _queueMutex;
|
||||
std::condition_variable _taskCondition;
|
||||
bool _stop{};
|
||||
bool _stop{};
|
||||
};
|
||||
|
||||
void AudioEngine::end() {
|
||||
@@ -176,7 +176,7 @@ bool AudioEngine::lazyInit() {
|
||||
sAudioEngineImpl = nullptr;
|
||||
return false;
|
||||
}
|
||||
sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground);
|
||||
sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground);
|
||||
sOnResumeListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_FOREGROUND, AudioEngine::onEnterForeground);
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume,
|
||||
auto *profileHelper = sDefaultProfileHelper;
|
||||
if (profile && profile != &profileHelper->profile) {
|
||||
CC_ASSERT(!profile->name.empty());
|
||||
profileHelper = &sAudioPathProfileHelperMap[profile->name];
|
||||
profileHelper = &sAudioPathProfileHelperMap[profile->name];
|
||||
profileHelper->profile = *profile;
|
||||
}
|
||||
|
||||
@@ -223,7 +223,7 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume,
|
||||
}
|
||||
if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) {
|
||||
auto currTime = std::chrono::high_resolution_clock::now();
|
||||
auto delay = static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>(currTime - profileHelper->lastPlayTime).count()) / 1000000.0;
|
||||
auto delay = static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>(currTime - profileHelper->lastPlayTime).count()) / 1000000.0;
|
||||
if (profileHelper->lastPlayTime.time_since_epoch().count() != 0 && delay <= profileHelper->profile.minDelay) {
|
||||
CC_LOG_INFO("Fail to play %s cause by limited minimum delay", filePath.c_str());
|
||||
break;
|
||||
@@ -242,9 +242,9 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume,
|
||||
sAudioPathIDMap[filePath].push_back(ret);
|
||||
auto it = sAudioPathIDMap.find(filePath);
|
||||
|
||||
auto &audioRef = sAudioIDInfoMap[ret];
|
||||
audioRef.volume = volume;
|
||||
audioRef.loop = loop;
|
||||
auto &audioRef = sAudioIDInfoMap[ret];
|
||||
audioRef.volume = volume;
|
||||
audioRef.loop = loop;
|
||||
audioRef.filePath = &it->first;
|
||||
|
||||
if (profileHelper) {
|
||||
|
||||
@@ -34,8 +34,8 @@ THE SOFTWARE.
|
||||
namespace cc {
|
||||
|
||||
size_t AudioDecoder::fileRead(void *ptr, size_t size, size_t nmemb, void *datasource) {
|
||||
AudioDecoder *thiz = (AudioDecoder *)datasource;
|
||||
ssize_t toReadBytes = std::min((ssize_t)(thiz->_fileData.getSize() - thiz->_fileCurrPos), (ssize_t)(nmemb * size));
|
||||
AudioDecoder *thiz = (AudioDecoder *)datasource;
|
||||
ssize_t toReadBytes = std::min((ssize_t)(thiz->_fileData.getSize() - thiz->_fileCurrPos), (ssize_t)(nmemb * size));
|
||||
if (toReadBytes > 0) {
|
||||
memcpy(ptr, (unsigned char *)thiz->_fileData.getBytes() + thiz->_fileCurrPos, toReadBytes);
|
||||
thiz->_fileCurrPos += toReadBytes;
|
||||
@@ -76,7 +76,7 @@ AudioDecoder::~AudioDecoder() {
|
||||
}
|
||||
|
||||
bool AudioDecoder::init(const ccstd::string &url, int sampleRate) {
|
||||
_url = url;
|
||||
_url = url;
|
||||
_sampleRate = sampleRate;
|
||||
return true;
|
||||
}
|
||||
@@ -130,16 +130,16 @@ bool AudioDecoder::resample() {
|
||||
|
||||
ALOGV("Resample: %d --> %d", _result.sampleRate, _sampleRate);
|
||||
|
||||
auto r = _result;
|
||||
auto r = _result;
|
||||
PcmBufferProvider provider;
|
||||
provider.init(r.pcmBuffer->data(), r.numFrames, r.pcmBuffer->size() / r.numFrames);
|
||||
|
||||
const int outFrameRate = _sampleRate;
|
||||
int outputChannels = 2;
|
||||
size_t outputFrameSize = outputChannels * sizeof(int32_t);
|
||||
auto outputFrames = static_cast<size_t>(((int64_t)r.numFrames * outFrameRate) / r.sampleRate);
|
||||
size_t outputSize = outputFrames * outputFrameSize;
|
||||
void * outputVAddr = malloc(outputSize);
|
||||
const int outFrameRate = _sampleRate;
|
||||
int outputChannels = 2;
|
||||
size_t outputFrameSize = outputChannels * sizeof(int32_t);
|
||||
auto outputFrames = static_cast<size_t>(((int64_t)r.numFrames * outFrameRate) / r.sampleRate);
|
||||
size_t outputSize = outputFrames * outputFrameSize;
|
||||
void *outputVAddr = malloc(outputSize);
|
||||
|
||||
auto resampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT, r.numChannels, outFrameRate,
|
||||
AudioResampler::MED_QUALITY);
|
||||
@@ -181,9 +181,9 @@ bool AudioDecoder::resample() {
|
||||
// mono takes left channel only (out of stereo output pair)
|
||||
// stereo and multichannel preserve all channels.
|
||||
|
||||
int channels = r.numChannels;
|
||||
int32_t *out = (int32_t *)outputVAddr;
|
||||
int16_t *convert = (int16_t *)malloc(outputFrames * channels * sizeof(int16_t));
|
||||
int channels = r.numChannels;
|
||||
int32_t *out = (int32_t *)outputVAddr;
|
||||
int16_t *convert = (int16_t *)malloc(outputFrames * channels * sizeof(int16_t));
|
||||
|
||||
const int volumeShift = 12; // shift requirement for Q4.27 to Q.15
|
||||
// round to half towards zero and saturate at int16 (non-dithered)
|
||||
@@ -208,7 +208,7 @@ bool AudioDecoder::resample() {
|
||||
}
|
||||
|
||||
// Reset result
|
||||
_result.numFrames = static_cast<int>(outputFrames);
|
||||
_result.numFrames = static_cast<int>(outputFrames);
|
||||
_result.sampleRate = outFrameRate;
|
||||
|
||||
auto buffer = std::make_shared<ccstd::vector<char>>();
|
||||
@@ -232,7 +232,7 @@ bool AudioDecoder::interleave() {
|
||||
} else if (_result.numChannels == 1) {
|
||||
// If it's a mono audio, try to compose a fake stereo buffer
|
||||
size_t newBufferSize = _result.pcmBuffer->size() * 2;
|
||||
auto newBuffer = std::make_shared<ccstd::vector<char>>();
|
||||
auto newBuffer = std::make_shared<ccstd::vector<char>>();
|
||||
newBuffer->reserve(newBufferSize);
|
||||
size_t totalFrameSizeInBytes = (size_t)(_result.numFrames * _result.bitsPerSample / 8);
|
||||
|
||||
@@ -249,7 +249,7 @@ bool AudioDecoder::interleave() {
|
||||
}
|
||||
_result.numChannels = 2;
|
||||
_result.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
|
||||
_result.pcmBuffer = newBuffer;
|
||||
_result.pcmBuffer = newBuffer;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,19 +43,19 @@ public:
|
||||
|
||||
protected:
|
||||
virtual bool decodeToPcm() = 0;
|
||||
bool resample();
|
||||
bool interleave();
|
||||
bool resample();
|
||||
bool interleave();
|
||||
|
||||
static size_t fileRead(void *ptr, size_t size, size_t nmemb, void *datasource);
|
||||
static int fileSeek(void *datasource, int64_t offset, int whence);
|
||||
static int fileClose(void *datasource);
|
||||
static long fileTell(void *datasource);
|
||||
static int fileSeek(void *datasource, int64_t offset, int whence);
|
||||
static int fileClose(void *datasource);
|
||||
static long fileTell(void *datasource);
|
||||
|
||||
ccstd::string _url;
|
||||
PcmData _result;
|
||||
int _sampleRate;
|
||||
Data _fileData;
|
||||
size_t _fileCurrPos;
|
||||
PcmData _result;
|
||||
int _sampleRate;
|
||||
Data _fileData;
|
||||
size_t _fileCurrPos;
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -44,24 +44,24 @@ bool AudioDecoderMp3::decodeToPcm() {
|
||||
}
|
||||
|
||||
mp3_callbacks callbacks;
|
||||
callbacks.read = AudioDecoder::fileRead;
|
||||
callbacks.seek = AudioDecoder::fileSeek;
|
||||
callbacks.read = AudioDecoder::fileRead;
|
||||
callbacks.seek = AudioDecoder::fileSeek;
|
||||
callbacks.close = AudioDecoder::fileClose;
|
||||
callbacks.tell = AudioDecoder::fileTell;
|
||||
callbacks.tell = AudioDecoder::fileTell;
|
||||
|
||||
int numChannels = 0;
|
||||
int sampleRate = 0;
|
||||
int numFrames = 0;
|
||||
int sampleRate = 0;
|
||||
int numFrames = 0;
|
||||
|
||||
if (EXIT_SUCCESS == decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames) && numChannels > 0 && sampleRate > 0 && numFrames > 0) {
|
||||
_result.numChannels = numChannels;
|
||||
_result.sampleRate = sampleRate;
|
||||
_result.numChannels = numChannels;
|
||||
_result.sampleRate = sampleRate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = numFrames;
|
||||
_result.duration = 1.0f * numFrames / sampleRate;
|
||||
_result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = numFrames;
|
||||
_result.duration = 1.0f * numFrames / sampleRate;
|
||||
|
||||
ccstd::string info = _result.toString();
|
||||
ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size());
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
namespace cc {
|
||||
|
||||
AudioDecoder *AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) {
|
||||
AudioDecoder *decoder = nullptr;
|
||||
AudioDecoder *decoder = nullptr;
|
||||
ccstd::string extension = FileUtils::getInstance()->getFileExtension(url);
|
||||
ALOGV("url:%s, extension:%s", url.c_str(), extension.c_str());
|
||||
if (extension == ".ogg") {
|
||||
|
||||
@@ -34,7 +34,7 @@ class AudioDecoder;
|
||||
class AudioDecoderProvider {
|
||||
public:
|
||||
static AudioDecoder *createAudioDecoder(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback);
|
||||
static void destroyAudioDecoder(AudioDecoder **decoder);
|
||||
static void destroyAudioDecoder(AudioDecoder **decoder);
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
@@ -111,12 +111,12 @@ AudioDecoderSLES::~AudioDecoderSLES() {
|
||||
|
||||
bool AudioDecoderSLES::init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) {
|
||||
if (AudioDecoder::init(url, sampleRate)) {
|
||||
_engineItf = engineItf;
|
||||
_engineItf = engineItf;
|
||||
_bufferSizeInFrames = bufferSizeInFrames;
|
||||
_fdGetterCallback = fdGetterCallback;
|
||||
_fdGetterCallback = fdGetterCallback;
|
||||
|
||||
BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2);
|
||||
_pcmData = (char *)malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES);
|
||||
_pcmData = (char *)malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES);
|
||||
memset(_pcmData, 0x00, NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES);
|
||||
return true;
|
||||
}
|
||||
@@ -132,23 +132,23 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
|
||||
/* Interfaces for the audio player */
|
||||
SLAndroidSimpleBufferQueueItf decBuffQueueItf;
|
||||
SLPrefetchStatusItf prefetchItf;
|
||||
SLPlayItf playItf;
|
||||
SLMetadataExtractionItf mdExtrItf;
|
||||
SLPrefetchStatusItf prefetchItf;
|
||||
SLPlayItf playItf;
|
||||
SLMetadataExtractionItf mdExtrItf;
|
||||
|
||||
/* Source of audio data for the decoding */
|
||||
SLDataSource decSource;
|
||||
|
||||
// decUri & locFd should be defined here
|
||||
SLDataLocator_URI decUri;
|
||||
SLDataLocator_URI decUri;
|
||||
SLDataLocator_AndroidFD locFd;
|
||||
|
||||
/* Data sink for decoded audio */
|
||||
SLDataSink decDest;
|
||||
SLDataSink decDest;
|
||||
SLDataLocator_AndroidSimpleBufferQueue decBuffQueue;
|
||||
SLDataFormat_PCM pcm;
|
||||
SLDataFormat_PCM pcm;
|
||||
|
||||
SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER];
|
||||
SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER];
|
||||
SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_PLAYER];
|
||||
|
||||
/* Initialize arrays required[] and iidArray[] */
|
||||
@@ -171,12 +171,12 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
iidArray[2] = SL_IID_METADATAEXTRACTION;
|
||||
|
||||
SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED};
|
||||
decSource.pFormat = &formatMime;
|
||||
decSource.pFormat = &formatMime;
|
||||
|
||||
if (_url[0] != '/') {
|
||||
off_t start = 0, length = 0;
|
||||
off_t start = 0, length = 0;
|
||||
ccstd::string relativePath;
|
||||
size_t position = _url.find("@assets/");
|
||||
size_t position = _url.find("@assets/");
|
||||
|
||||
if (0 == position) {
|
||||
// "@assets/" is at the beginning of the path and we don't want it
|
||||
@@ -197,25 +197,25 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
|
||||
decSource.pLocator = &locFd;
|
||||
} else {
|
||||
decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()};
|
||||
decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()};
|
||||
decSource.pLocator = &decUri;
|
||||
}
|
||||
|
||||
/* Setup the data sink */
|
||||
decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
|
||||
decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE;
|
||||
decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE;
|
||||
/* set up the format of the data in the buffer queue */
|
||||
pcm.formatType = SL_DATAFORMAT_PCM;
|
||||
// IDEA: valid value required but currently ignored
|
||||
pcm.numChannels = 2;
|
||||
pcm.numChannels = 2;
|
||||
pcm.samplesPerSec = SL_SAMPLINGRATE_44_1;
|
||||
pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
|
||||
pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
|
||||
pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
|
||||
decDest.pLocator = (void *)&decBuffQueue;
|
||||
decDest.pFormat = (void *)&pcm;
|
||||
decDest.pFormat = (void *)&pcm;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(__SLPlayerMutex);
|
||||
@@ -264,11 +264,11 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
|
||||
/* ------------------------------------------------------ */
|
||||
/* Initialize the callback and its context for the decoding buffer queue */
|
||||
_decContext.playItf = playItf;
|
||||
_decContext.metaItf = mdExtrItf;
|
||||
_decContext.playItf = playItf;
|
||||
_decContext.metaItf = mdExtrItf;
|
||||
_decContext.pDataBase = (int8_t *)_pcmData;
|
||||
_decContext.pData = _decContext.pDataBase;
|
||||
_decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES;
|
||||
_decContext.pData = _decContext.pDataBase;
|
||||
_decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES;
|
||||
|
||||
result = (*decBuffQueueItf)->RegisterCallback(decBuffQueueItf, SLAudioDecoderCallbackProxy::decPlayCallback, this);
|
||||
SL_RETURN_VAL_IF_FAILED(result, false, "decBuffQueueItf RegisterCallback failed");
|
||||
@@ -299,7 +299,7 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
|
||||
/* 2/ block until data has been prefetched */
|
||||
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
|
||||
SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s
|
||||
SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s
|
||||
while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
|
||||
!_prefetchError) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
@@ -315,7 +315,7 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
/* ------------------------------------------------------ */
|
||||
/* Display duration */
|
||||
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
|
||||
result = (*playItf)->GetDuration(playItf, &durationInMsec);
|
||||
result = (*playItf)->GetDuration(playItf, &durationInMsec);
|
||||
SL_RETURN_VAL_IF_FAILED(result, false, "GetDuration failed");
|
||||
|
||||
if (durationInMsec == SL_TIME_UNKNOWN) {
|
||||
@@ -331,14 +331,14 @@ bool AudioDecoderSLES::decodeToPcm() {
|
||||
// can make assumptions about the size of the keys and their matching values (all SLuint32)
|
||||
SLuint32 itemCount;
|
||||
result = (*mdExtrItf)->GetItemCount(mdExtrItf, &itemCount);
|
||||
SLuint32 i, keySize, valueSize;
|
||||
SLuint32 i, keySize, valueSize;
|
||||
SLMetadataInfo *keyInfo, *value;
|
||||
for (i = 0; i < itemCount; i++) {
|
||||
keyInfo = nullptr;
|
||||
keySize = 0;
|
||||
value = nullptr;
|
||||
keyInfo = nullptr;
|
||||
keySize = 0;
|
||||
value = nullptr;
|
||||
valueSize = 0;
|
||||
result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize);
|
||||
result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize);
|
||||
SL_RETURN_VAL_IF_FAILED(result, false, "GetKeySize(%d) failed", (int)i);
|
||||
|
||||
result = (*mdExtrItf)->GetValueSize(mdExtrItf, i, &valueSize);
|
||||
@@ -433,7 +433,7 @@ void AudioDecoderSLES::queryAudioInfo() {
|
||||
SLresult result;
|
||||
/* Get duration in callback where we use the callback context for the SLPlayItf*/
|
||||
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
|
||||
result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec);
|
||||
result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec);
|
||||
SL_RETURN_IF_FAILED(result, "decodeProgressCallback,GetDuration failed");
|
||||
|
||||
if (durationInMsec == SL_TIME_UNKNOWN) {
|
||||
@@ -455,7 +455,7 @@ void AudioDecoderSLES::queryAudioInfo() {
|
||||
// but the call was successful for the PCM format keys, so those conditions are implied
|
||||
|
||||
_result.sampleRate = *((SLuint32 *)pcmMetaData.data);
|
||||
result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData);
|
||||
result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData);
|
||||
SL_RETURN_IF_FAILED(result, "%s GetValue _numChannelsKeyIndex failed", __FUNCTION__);
|
||||
|
||||
_result.numChannels = *((SLuint32 *)pcmMetaData.data);
|
||||
@@ -481,7 +481,7 @@ void AudioDecoderSLES::queryAudioInfo() {
|
||||
|
||||
void AudioDecoderSLES::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event) {
|
||||
SLpermille level = 0;
|
||||
SLresult result;
|
||||
SLresult result;
|
||||
result = (*caller)->GetFillLevel(caller, &level);
|
||||
SL_RETURN_IF_FAILED(result, "GetFillLevel failed");
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ protected:
|
||||
AudioDecoderSLES();
|
||||
virtual ~AudioDecoderSLES();
|
||||
|
||||
bool init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback);
|
||||
bool init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback);
|
||||
virtual bool decodeToPcm() override;
|
||||
|
||||
private:
|
||||
@@ -69,24 +69,24 @@ private:
|
||||
int _endiannessKeyIndex;
|
||||
|
||||
/* to signal to the test app the end of the stream to decode has been reached */
|
||||
bool _eos;
|
||||
std::mutex _eosLock;
|
||||
bool _eos;
|
||||
std::mutex _eosLock;
|
||||
std::condition_variable _eosCondition;
|
||||
|
||||
/* Structure for passing information to callback function */
|
||||
typedef struct CallbackCntxt_ {
|
||||
SLPlayItf playItf;
|
||||
SLPlayItf playItf;
|
||||
SLMetadataExtractionItf metaItf;
|
||||
SLuint32 size;
|
||||
SLint8 * pDataBase; // Base address of local audio data storage
|
||||
SLint8 * pData; // Current address of local audio data storage
|
||||
SLuint32 size;
|
||||
SLint8 *pDataBase; // Base address of local audio data storage
|
||||
SLint8 *pData; // Current address of local audio data storage
|
||||
} CallbackCntxt;
|
||||
|
||||
CallbackCntxt _decContext;
|
||||
int _bufferSizeInFrames;
|
||||
int _assetFd;
|
||||
CallbackCntxt _decContext;
|
||||
int _bufferSizeInFrames;
|
||||
int _assetFd;
|
||||
FdGetterCallback _fdGetterCallback;
|
||||
bool _isDecodingCallbackInvoked;
|
||||
bool _isDecodingCallbackInvoked;
|
||||
|
||||
friend class SLAudioDecoderCallbackProxy;
|
||||
friend class AudioDecoderProvider;
|
||||
|
||||
@@ -58,14 +58,14 @@ bool AudioDecoderWav::decodeToPcm() {
|
||||
SF_INFO info;
|
||||
|
||||
snd_callbacks cb;
|
||||
cb.open = onWavOpen;
|
||||
cb.read = AudioDecoder::fileRead;
|
||||
cb.seek = onWavSeek;
|
||||
cb.open = onWavOpen;
|
||||
cb.read = AudioDecoder::fileRead;
|
||||
cb.seek = onWavSeek;
|
||||
cb.close = onWavClose;
|
||||
cb.tell = AudioDecoder::fileTell;
|
||||
cb.tell = AudioDecoder::fileTell;
|
||||
|
||||
SNDFILE *handle = nullptr;
|
||||
bool ret = false;
|
||||
bool ret = false;
|
||||
do {
|
||||
handle = sf_open_read(_url.c_str(), &info, &cb, this);
|
||||
if (handle == nullptr) {
|
||||
@@ -77,20 +77,20 @@ bool AudioDecoderWav::decodeToPcm() {
|
||||
}
|
||||
|
||||
ALOGD("wav info: frames: %d, samplerate: %d, channels: %d, format: %d", info.frames, info.samplerate, info.channels, info.format);
|
||||
size_t bufSize = sizeof(int16_t) * info.frames * info.channels;
|
||||
auto * buf = static_cast<unsigned char *>(malloc(bufSize));
|
||||
size_t bufSize = sizeof(int16_t) * info.frames * info.channels;
|
||||
auto *buf = static_cast<unsigned char *>(malloc(bufSize));
|
||||
sf_count_t readFrames = sf_readf_short(handle, reinterpret_cast<int16_t *>(buf), info.frames);
|
||||
CC_ASSERT(readFrames == info.frames);
|
||||
|
||||
_result.pcmBuffer->insert(_result.pcmBuffer->end(), buf, buf + bufSize);
|
||||
_result.numChannels = info.channels;
|
||||
_result.sampleRate = info.samplerate;
|
||||
_result.numChannels = info.channels;
|
||||
_result.sampleRate = info.samplerate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = info.frames;
|
||||
_result.duration = static_cast<float>(1.0F * info.frames / _result.sampleRate); //NOLINT
|
||||
_result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = info.frames;
|
||||
_result.duration = static_cast<float>(1.0F * info.frames / _result.sampleRate); //NOLINT
|
||||
|
||||
free(buf);
|
||||
ret = true;
|
||||
|
||||
@@ -58,17 +58,17 @@ using namespace cc; //NOLINT
|
||||
|
||||
// Audio focus values synchronized with which in cocos/platform/android/java/src/com/cocos/lib/CocosNativeActivity.java
|
||||
namespace {
|
||||
AudioEngineImpl *gAudioImpl = nullptr;
|
||||
int outputSampleRate = 44100;
|
||||
int bufferSizeInFrames = 192;
|
||||
AudioEngineImpl *gAudioImpl = nullptr;
|
||||
int outputSampleRate = 44100;
|
||||
int bufferSizeInFrames = 192;
|
||||
|
||||
void getAudioInfo() {
|
||||
JNIEnv * env = JniHelper::getEnv();
|
||||
jclass audioSystem = env->FindClass("android/media/AudioSystem");
|
||||
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
|
||||
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
|
||||
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
|
||||
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
|
||||
JNIEnv *env = JniHelper::getEnv();
|
||||
jclass audioSystem = env->FindClass("android/media/AudioSystem");
|
||||
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
|
||||
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
|
||||
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
|
||||
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
@@ -97,8 +97,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) {
|
||||
if (cc::FileUtilsAndroid::getObbFile() != nullptr) {
|
||||
int64_t startV;
|
||||
int64_t lenV;
|
||||
fd = getObbAssetFileDescriptorJNI(url, &startV, &lenV);
|
||||
*start = static_cast<off_t>(startV);
|
||||
fd = getObbAssetFileDescriptorJNI(url, &startV, &lenV);
|
||||
*start = static_cast<off_t>(startV);
|
||||
*length = static_cast<off_t>(lenV);
|
||||
}
|
||||
if (fd <= 0) {
|
||||
@@ -170,8 +170,8 @@ bool AudioEngineImpl::init() {
|
||||
|
||||
// create output mix
|
||||
const SLInterfaceID outputMixIIDs[] = {};
|
||||
const SLboolean outputMixReqs[] = {};
|
||||
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
|
||||
const SLboolean outputMixReqs[] = {};
|
||||
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
|
||||
if (SL_RESULT_SUCCESS != result) {
|
||||
CC_LOG_ERROR("create output mix fail");
|
||||
break;
|
||||
|
||||
@@ -50,19 +50,19 @@ public:
|
||||
AudioEngineImpl();
|
||||
~AudioEngineImpl() override;
|
||||
|
||||
bool init();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
void pause(int audioID);
|
||||
void resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
bool init();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
void pause(int audioID);
|
||||
void resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
float getDuration(int audioID);
|
||||
float getDurationFromFile(const ccstd::string &filePath);
|
||||
float getCurrentTime(int audioID);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
|
||||
void uncache(const ccstd::string &filePath);
|
||||
void uncacheAll();
|
||||
@@ -82,7 +82,7 @@ private:
|
||||
SLObjectItf _outputMixObject;
|
||||
|
||||
//audioID,AudioInfo
|
||||
ccstd::unordered_map<int, IAudioPlayer *> _audioPlayers;
|
||||
ccstd::unordered_map<int, IAudioPlayer *> _audioPlayers;
|
||||
ccstd::unordered_map<int, std::function<void(int, const ccstd::string &)>> _callbackMap;
|
||||
|
||||
// UrlAudioPlayers which need to resumed while entering foreground
|
||||
|
||||
@@ -527,8 +527,9 @@ static inline bool setVolumeRampVariables(float newVolume, int32_t ramp,
|
||||
if (ramp != 0) {
|
||||
// when the ramp completes, *pPrevVolume is set to *pSetVolume, so there
|
||||
// is no computational mismatch; hence equality is checked here.
|
||||
ALOGD_IF(*pPrevVolume != *pSetVolume, "previous float ramp hasn't finished,"
|
||||
" prev:%f set_to:%f",
|
||||
ALOGD_IF(*pPrevVolume != *pSetVolume,
|
||||
"previous float ramp hasn't finished,"
|
||||
" prev:%f set_to:%f",
|
||||
*pPrevVolume, *pSetVolume);
|
||||
const float inc = (newVolume - *pPrevVolume) / ramp; // could be inf, nan, subnormal
|
||||
const float maxv = max(newVolume, *pPrevVolume); // could be inf, cannot be nan, subnormal
|
||||
@@ -558,8 +559,9 @@ static inline bool setVolumeRampVariables(float newVolume, int32_t ramp,
|
||||
// integer volume is U4.12 (to use 16 bit multiplies), but ramping uses U4.28.
|
||||
// when the ramp completes, *pIntPrevVolume is set to *pIntSetVolume << 16, so there
|
||||
// is no computational mismatch; hence equality is checked here.
|
||||
ALOGD_IF(*pIntPrevVolume != *pIntSetVolume << 16, "previous int ramp hasn't finished,"
|
||||
" prev:%d set_to:%d",
|
||||
ALOGD_IF(*pIntPrevVolume != *pIntSetVolume << 16,
|
||||
"previous int ramp hasn't finished,"
|
||||
" prev:%d set_to:%d",
|
||||
*pIntPrevVolume, *pIntSetVolume << 16);
|
||||
const int32_t inc = ((intVolume << 16) - *pIntPrevVolume) / ramp;
|
||||
|
||||
@@ -591,7 +593,6 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) {
|
||||
int32_t *valueBuf = reinterpret_cast<int32_t *>(value);
|
||||
|
||||
switch (target) {
|
||||
|
||||
case TRACK:
|
||||
switch (param) {
|
||||
case CHANNEL_MASK: {
|
||||
@@ -715,12 +716,13 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) {
|
||||
"bad parameters speed %f, pitch %f", playbackRate->mSpeed,
|
||||
playbackRate->mPitch);
|
||||
if (track.setPlaybackRate(*playbackRate)) {
|
||||
ALOGV("setParameter(TIMESTRETCH, PLAYBACK_RATE, STRETCH_MODE, FALLBACK_MODE "
|
||||
"%f %f %d %d",
|
||||
playbackRate->mSpeed,
|
||||
playbackRate->mPitch,
|
||||
playbackRate->mStretchMode,
|
||||
playbackRate->mFallbackMode);
|
||||
ALOGV(
|
||||
"setParameter(TIMESTRETCH, PLAYBACK_RATE, STRETCH_MODE, FALLBACK_MODE "
|
||||
"%f %f %d %d",
|
||||
playbackRate->mSpeed,
|
||||
playbackRate->mPitch,
|
||||
playbackRate->mStretchMode,
|
||||
playbackRate->mFallbackMode);
|
||||
// invalidateState(1 << name);
|
||||
}
|
||||
} break;
|
||||
@@ -757,9 +759,10 @@ bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSam
|
||||
const int resamplerChannelCount = false /*downmixerBufferProvider != NULL*/
|
||||
? mMixerChannelCount
|
||||
: channelCount;
|
||||
ALOGVV("Creating resampler:"
|
||||
" format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n",
|
||||
mMixerInFormat, resamplerChannelCount, devSampleRate, quality);
|
||||
ALOGVV(
|
||||
"Creating resampler:"
|
||||
" format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n",
|
||||
mMixerInFormat, resamplerChannelCount, devSampleRate, quality);
|
||||
resampler = AudioResampler::create(
|
||||
mMixerInFormat,
|
||||
resamplerChannelCount,
|
||||
@@ -1008,10 +1011,11 @@ void AudioMixer::process__validate(state_t *state, int64_t pts) {
|
||||
}
|
||||
}
|
||||
|
||||
ALOGV("mixer configuration change: %d activeTracks (%08x) "
|
||||
"all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
|
||||
countActiveTracks, state->enabledTracks,
|
||||
all16BitsStereoNoResample, resampling, volumeRamp);
|
||||
ALOGV(
|
||||
"mixer configuration change: %d activeTracks (%08x) "
|
||||
"all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
|
||||
countActiveTracks, state->enabledTracks,
|
||||
all16BitsStereoNoResample, resampling, volumeRamp);
|
||||
|
||||
state->hook(state, pts);
|
||||
|
||||
@@ -1521,7 +1525,6 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) {
|
||||
t.resampler->setPTS(pts);
|
||||
t.hook(&t, outTemp, numFrames, state->resampleTemp, aux);
|
||||
} else {
|
||||
|
||||
size_t outFrames = 0;
|
||||
|
||||
while (outFrames < numFrames) {
|
||||
@@ -1808,8 +1811,9 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) {
|
||||
// been enabled for mixing.
|
||||
if (in == NULL || (((uintptr_t)in) & 3)) {
|
||||
memset(out, 0, numFrames * channels * audio_bytes_per_sample(t->mMixerFormat));
|
||||
ALOGE_IF((((uintptr_t)in) & 3), "process_NoResampleOneTrack: bus error: "
|
||||
"buffer %p track %p, channels %d, needs %#x",
|
||||
ALOGE_IF((((uintptr_t)in) & 3),
|
||||
"process_NoResampleOneTrack: bus error: "
|
||||
"buffer %p track %p, channels %d, needs %#x",
|
||||
in, t, t->channelCount, t->needs);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ void AudioMixerController::initTrack(Track *track, ccstd::vector<Track *> &track
|
||||
return;
|
||||
|
||||
uint32_t channelMask = audio_channel_out_mask_from_count(2);
|
||||
int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT,
|
||||
int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT,
|
||||
AUDIO_SESSION_OUTPUT_MIX);
|
||||
if (name < 0) {
|
||||
// If we could not get the track name, it means that there're MAX_NUM_TRACKS tracks
|
||||
@@ -124,9 +124,9 @@ void AudioMixerController::initTrack(Track *track, ccstd::vector<Track *> &track
|
||||
_mixer->enable(name);
|
||||
|
||||
std::lock_guard<std::mutex> lk(track->_volumeDirtyMutex);
|
||||
gain_minifloat_packed_t volume = track->getVolumeLR();
|
||||
float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
|
||||
float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
|
||||
gain_minifloat_packed_t volume = track->getVolumeLR();
|
||||
float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
|
||||
float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
|
||||
|
||||
_mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &lVolume);
|
||||
_mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &rVolume);
|
||||
@@ -185,9 +185,9 @@ void AudioMixerController::mixOneFrame() {
|
||||
std::lock_guard<std::mutex> lk(track->_volumeDirtyMutex);
|
||||
|
||||
if (track->isVolumeDirty()) {
|
||||
gain_minifloat_packed_t volume = track->getVolumeLR();
|
||||
float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
|
||||
float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
|
||||
gain_minifloat_packed_t volume = track->getVolumeLR();
|
||||
float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
|
||||
float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
|
||||
|
||||
ALOGV("Track (name: %d)'s volume is dirty, update volume to L: %f, R: %f", name, lVolume, rVolume);
|
||||
|
||||
@@ -256,7 +256,7 @@ void AudioMixerController::mixOneFrame() {
|
||||
|
||||
_activeTracksMutex.unlock();
|
||||
|
||||
auto mixEnd = clockNow();
|
||||
auto mixEnd = clockNow();
|
||||
float mixInterval = intervalInMS(mixStart, mixEnd);
|
||||
ALOGV_IF(mixInterval > 1.0f, "Mix a frame waste: %fms", mixInterval);
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ class AudioMixer;
|
||||
class AudioMixerController {
|
||||
public:
|
||||
struct OutputBuffer {
|
||||
void * buf;
|
||||
void *buf;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
@@ -53,8 +53,8 @@ public:
|
||||
bool addTrack(Track *track);
|
||||
bool hasPlayingTacks();
|
||||
|
||||
void pause();
|
||||
void resume();
|
||||
void pause();
|
||||
void resume();
|
||||
inline bool isPaused() const { return _isPaused; };
|
||||
|
||||
void mixOneFrame();
|
||||
@@ -72,7 +72,7 @@ private:
|
||||
|
||||
AudioMixer *_mixer;
|
||||
|
||||
std::mutex _activeTracksMutex;
|
||||
std::mutex _activeTracksMutex;
|
||||
ccstd::vector<Track *> _activeTracks;
|
||||
|
||||
OutputBuffer _mixingBuffer;
|
||||
|
||||
@@ -61,7 +61,7 @@ static int getSystemAPILevel() {
|
||||
|
||||
struct AudioFileIndicator {
|
||||
ccstd::string extension;
|
||||
int smallSizeIndicator;
|
||||
int smallSizeIndicator;
|
||||
};
|
||||
|
||||
static AudioFileIndicator gAudioFileIndicator[] = {
|
||||
@@ -73,7 +73,7 @@ static AudioFileIndicator gAudioFileIndicator[] = {
|
||||
AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject,
|
||||
int deviceSampleRate, int bufferSizeInFrames,
|
||||
const FdGetterCallback &fdGetterCallback, //NOLINT(modernize-pass-by-value)
|
||||
ICallerThreadUtils * callerThreadUtils)
|
||||
ICallerThreadUtils *callerThreadUtils)
|
||||
: _engineItf(engineItf), _outputMixObject(outputMixObject), _deviceSampleRate(deviceSampleRate), _bufferSizeInFrames(bufferSizeInFrames), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) {
|
||||
ALOGI("deviceSampleRate: %d, bufferSizeInFrames: %d", _deviceSampleRate, _bufferSizeInFrames);
|
||||
if (getSystemAPILevel() >= 17) {
|
||||
@@ -124,22 +124,22 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const ccstd::string &audioFile
|
||||
if (info.isValid()) {
|
||||
if (isSmallFile(info)) {
|
||||
// Put an empty lambda to preloadEffect since we only want the future object to get PcmData
|
||||
auto pcmData = std::make_shared<PcmData>();
|
||||
auto isSucceed = std::make_shared<bool>(false);
|
||||
auto pcmData = std::make_shared<PcmData>();
|
||||
auto isSucceed = std::make_shared<bool>(false);
|
||||
auto isReturnFromCache = std::make_shared<bool>(false);
|
||||
auto isPreloadFinished = std::make_shared<bool>(false);
|
||||
|
||||
std::thread::id threadId = std::this_thread::get_id();
|
||||
|
||||
void * infoPtr = &info;
|
||||
ccstd::string url = info.url;
|
||||
void *infoPtr = &info;
|
||||
ccstd::string url = info.url;
|
||||
preloadEffect(
|
||||
info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data) {
|
||||
// If the callback is in the same thread as caller's, it means that we found it
|
||||
// in the cache
|
||||
*isReturnFromCache = std::this_thread::get_id() == threadId;
|
||||
*pcmData = std::move(data);
|
||||
*isSucceed = succeed;
|
||||
*pcmData = std::move(data);
|
||||
*isSucceed = succeed;
|
||||
*isPreloadFinished = true;
|
||||
ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str());
|
||||
},
|
||||
@@ -236,7 +236,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
if (preloadIter != _preloadCallbackMap.end()) {
|
||||
ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str());
|
||||
PreloadCallbackParam param;
|
||||
param.callback = cb;
|
||||
param.callback = cb;
|
||||
param.isPreloadInPlay2d = isPreloadInPlay2d;
|
||||
preloadIter->second.push_back(std::move(param));
|
||||
return;
|
||||
@@ -255,7 +255,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
_pcmCacheMutex.unlock();
|
||||
|
||||
PreloadCallbackParam param;
|
||||
param.callback = cb;
|
||||
param.callback = cb;
|
||||
param.isPreloadInPlay2d = isPreloadInPlay2d;
|
||||
ccstd::vector<PreloadCallbackParam> callbacks;
|
||||
callbacks.push_back(std::move(param));
|
||||
@@ -264,9 +264,9 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
|
||||
_threadPool->pushTask([this, audioFilePath](int /*tid*/) {
|
||||
ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str());
|
||||
PcmData d;
|
||||
PcmData d;
|
||||
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback);
|
||||
bool ret = decoder != nullptr && decoder->start();
|
||||
bool ret = decoder != nullptr && decoder->start();
|
||||
if (ret) {
|
||||
d = decoder->getResult();
|
||||
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
||||
@@ -278,7 +278,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
ALOGV("decode %s", (ret ? "succeed" : "failed"));
|
||||
|
||||
std::lock_guard<std::mutex> lk(_preloadCallbackMutex);
|
||||
auto && preloadIter = _preloadCallbackMap.find(audioFilePath);
|
||||
auto &&preloadIter = _preloadCallbackMap.find(audioFilePath);
|
||||
if (preloadIter != _preloadCallbackMap.end()) {
|
||||
auto &¶ms = preloadIter->second;
|
||||
ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), (int)params.size());
|
||||
@@ -303,14 +303,14 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
|
||||
const ccstd::string &audioFilePath) {
|
||||
AudioFileInfo info;
|
||||
long fileSize = 0; //NOLINT(google-runtime-int)
|
||||
off_t start = 0;
|
||||
off_t length = 0;
|
||||
int assetFd = -1;
|
||||
long fileSize = 0; //NOLINT(google-runtime-int)
|
||||
off_t start = 0;
|
||||
off_t length = 0;
|
||||
int assetFd = -1;
|
||||
|
||||
if (audioFilePath[0] != '/') {
|
||||
ccstd::string relativePath;
|
||||
size_t position = audioFilePath.find("@assets/");
|
||||
size_t position = audioFilePath.find("@assets/");
|
||||
|
||||
if (0 == position) {
|
||||
// "@assets/" is at the beginning of the path and we don't want it
|
||||
@@ -338,10 +338,10 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
|
||||
}
|
||||
}
|
||||
|
||||
info.url = audioFilePath;
|
||||
info.url = audioFilePath;
|
||||
info.assetFd = std::make_shared<AssetFd>(assetFd);
|
||||
info.start = start;
|
||||
info.length = fileSize;
|
||||
info.start = start;
|
||||
info.length = fileSize;
|
||||
|
||||
ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize);
|
||||
|
||||
@@ -350,9 +350,9 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
|
||||
|
||||
bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(readability-convert-member-functions-to-static)
|
||||
//REFINE: If file size is smaller than 100k, we think it's a small file. This value should be set by developers.
|
||||
auto & audioFileInfo = const_cast<AudioFileInfo &>(info);
|
||||
size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]);
|
||||
size_t pos = audioFileInfo.url.rfind('.');
|
||||
auto &audioFileInfo = const_cast<AudioFileInfo &>(info);
|
||||
size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]);
|
||||
size_t pos = audioFileInfo.url.rfind('.');
|
||||
ccstd::string extension;
|
||||
if (pos != ccstd::string::npos) {
|
||||
extension = audioFileInfo.url.substr(pos);
|
||||
@@ -373,7 +373,7 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read
|
||||
|
||||
float AudioPlayerProvider::getDurationFromFile(const ccstd::string &filePath) {
|
||||
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
||||
auto iter = _pcmCache.find(filePath);
|
||||
auto iter = _pcmCache.find(filePath);
|
||||
if (iter != _pcmCache.end()) {
|
||||
return iter->second.duration;
|
||||
}
|
||||
@@ -382,7 +382,7 @@ float AudioPlayerProvider::getDurationFromFile(const ccstd::string &filePath) {
|
||||
|
||||
void AudioPlayerProvider::clearPcmCache(const ccstd::string &audioFilePath) {
|
||||
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
||||
auto iter = _pcmCache.find(audioFilePath);
|
||||
auto iter = _pcmCache.find(audioFilePath);
|
||||
if (iter != _pcmCache.end()) {
|
||||
ALOGV("clear pcm cache: (%s)", audioFilePath.c_str());
|
||||
_pcmCache.erase(iter);
|
||||
@@ -397,7 +397,7 @@ void AudioPlayerProvider::clearAllPcmCaches() {
|
||||
}
|
||||
|
||||
PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const ccstd::string &url,
|
||||
const PcmData & pcmData) {
|
||||
const PcmData &pcmData) {
|
||||
PcmAudioPlayer *pcmPlayer = nullptr;
|
||||
if (pcmData.isValid()) {
|
||||
pcmPlayer = ccnew PcmAudioPlayer(_mixController, _callerThreadUtils);
|
||||
@@ -418,8 +418,8 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
|
||||
}
|
||||
|
||||
SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
|
||||
auto urlPlayer = ccnew UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
|
||||
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
|
||||
auto urlPlayer = ccnew UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
|
||||
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
|
||||
if (!ret) {
|
||||
SL_SAFE_DELETE(urlPlayer);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ public:
|
||||
void preloadEffect(const ccstd::string &audioFilePath, const PreloadCallback &cb);
|
||||
|
||||
float getDurationFromFile(const ccstd::string &filePath);
|
||||
void clearPcmCache(const ccstd::string &audioFilePath);
|
||||
void clearPcmCache(const ccstd::string &audioFilePath);
|
||||
|
||||
void clearAllPcmCaches();
|
||||
|
||||
@@ -68,10 +68,10 @@ public:
|
||||
|
||||
private:
|
||||
struct AudioFileInfo {
|
||||
ccstd::string url;
|
||||
ccstd::string url;
|
||||
std::shared_ptr<AssetFd> assetFd;
|
||||
off_t start{};
|
||||
off_t length;
|
||||
off_t start{};
|
||||
off_t length;
|
||||
|
||||
AudioFileInfo()
|
||||
: assetFd(nullptr) {}
|
||||
@@ -92,28 +92,28 @@ private:
|
||||
bool isSmallFile(const AudioFileInfo &info);
|
||||
|
||||
private:
|
||||
SLEngineItf _engineItf;
|
||||
SLObjectItf _outputMixObject;
|
||||
int _deviceSampleRate;
|
||||
int _bufferSizeInFrames;
|
||||
FdGetterCallback _fdGetterCallback;
|
||||
SLEngineItf _engineItf;
|
||||
SLObjectItf _outputMixObject;
|
||||
int _deviceSampleRate;
|
||||
int _bufferSizeInFrames;
|
||||
FdGetterCallback _fdGetterCallback;
|
||||
ICallerThreadUtils *_callerThreadUtils;
|
||||
|
||||
ccstd::unordered_map<ccstd::string, PcmData> _pcmCache;
|
||||
std::mutex _pcmCacheMutex;
|
||||
std::mutex _pcmCacheMutex;
|
||||
|
||||
struct PreloadCallbackParam {
|
||||
PreloadCallback callback;
|
||||
bool isPreloadInPlay2d;
|
||||
bool isPreloadInPlay2d;
|
||||
};
|
||||
|
||||
ccstd::unordered_map<ccstd::string, ccstd::vector<PreloadCallbackParam>> _preloadCallbackMap;
|
||||
std::mutex _preloadCallbackMutex;
|
||||
std::mutex _preloadCallbackMutex;
|
||||
|
||||
std::mutex _preloadWaitMutex;
|
||||
std::mutex _preloadWaitMutex;
|
||||
std::condition_variable _preloadWaitCond;
|
||||
|
||||
PcmAudioService * _pcmAudioService;
|
||||
PcmAudioService *_pcmAudioService;
|
||||
AudioMixerController *_mixController;
|
||||
|
||||
LegacyThreadPool *_threadPool;
|
||||
|
||||
@@ -140,7 +140,6 @@ static uint32_t currentMHz = 0;
|
||||
|
||||
AudioResampler *AudioResampler::create(audio_format_t format, int inChannelCount,
|
||||
int32_t sampleRate, src_quality quality) {
|
||||
|
||||
bool atFinalQuality;
|
||||
if (quality == DEFAULT_QUALITY) {
|
||||
// read the resampler default quality property the first time it is needed
|
||||
@@ -247,7 +246,6 @@ AudioResampler::AudioResampler(int inChannelCount,
|
||||
mLocalTimeFreq(0),
|
||||
mPTS(AudioBufferProvider::kInvalidPTS),
|
||||
mQuality(quality) {
|
||||
|
||||
const int maxChannels = 2; //cjh quality < DYN_LOW_QUALITY ? 2 : 8;
|
||||
if (inChannelCount < 1 || inChannelCount > maxChannels) {
|
||||
LOG_ALWAYS_FATAL("Unsupported sample format %d quality %d channels",
|
||||
@@ -296,7 +294,6 @@ void AudioResampler::setPTS(int64_t pts) {
|
||||
}
|
||||
|
||||
int64_t AudioResampler::calculateOutputPTS(int outputFrameIndex) {
|
||||
|
||||
if (mPTS == AudioBufferProvider::kInvalidPTS) {
|
||||
return AudioBufferProvider::kInvalidPTS;
|
||||
} else {
|
||||
@@ -314,7 +311,6 @@ void AudioResampler::reset() {
|
||||
|
||||
size_t AudioResamplerOrder1::resample(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
// should never happen, but we overflow if it does
|
||||
// ALOG_ASSERT(outFrameCount < 32767);
|
||||
|
||||
@@ -332,7 +328,6 @@ size_t AudioResamplerOrder1::resample(int32_t *out, size_t outFrameCount,
|
||||
|
||||
size_t AudioResamplerOrder1::resampleStereo16(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
int32_t vl = mVolume[0];
|
||||
int32_t vr = mVolume[1];
|
||||
|
||||
@@ -347,7 +342,6 @@ size_t AudioResamplerOrder1::resampleStereo16(int32_t *out, size_t outFrameCount
|
||||
// outFrameCount, inputIndex, phaseFraction, phaseIncrement);
|
||||
|
||||
while (outputIndex < outputSampleCount) {
|
||||
|
||||
// buffer is empty, fetch a new one
|
||||
while (mBuffer.frameCount == 0) {
|
||||
mBuffer.frameCount = inFrameCount;
|
||||
@@ -431,7 +425,6 @@ resampleStereo16_exit:
|
||||
|
||||
size_t AudioResamplerOrder1::resampleMono16(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
int32_t vl = mVolume[0];
|
||||
int32_t vr = mVolume[1];
|
||||
|
||||
@@ -566,17 +559,24 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmMono16Loop(int16_t *in,
|
||||
asm(
|
||||
"stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n"
|
||||
// get parameters
|
||||
" ldr r6, [sp, #" MO_PARAM5 " + 20]\n" // &phaseFraction
|
||||
" ldr r6, [r6]\n" // phaseFraction
|
||||
" ldr r7, [sp, #" MO_PARAM5 " + 8]\n" // &inputIndex
|
||||
" ldr r7, [r7]\n" // inputIndex
|
||||
" ldr r8, [sp, #" MO_PARAM5 " + 4]\n" // out
|
||||
" ldr r0, [sp, #" MO_PARAM5 " + 0]\n" // &outputIndex
|
||||
" ldr r0, [r0]\n" // outputIndex
|
||||
" add r8, r8, r0, asl #2\n" // curOut
|
||||
" ldr r9, [sp, #" MO_PARAM5 " + 24]\n" // phaseIncrement
|
||||
" ldr r10, [sp, #" MO_PARAM5 " + 12]\n" // vl
|
||||
" ldr r11, [sp, #" MO_PARAM5 " + 16]\n" // vr
|
||||
" ldr r6, [sp, #" MO_PARAM5
|
||||
" + 20]\n" // &phaseFraction
|
||||
" ldr r6, [r6]\n" // phaseFraction
|
||||
" ldr r7, [sp, #" MO_PARAM5
|
||||
" + 8]\n" // &inputIndex
|
||||
" ldr r7, [r7]\n" // inputIndex
|
||||
" ldr r8, [sp, #" MO_PARAM5
|
||||
" + 4]\n" // out
|
||||
" ldr r0, [sp, #" MO_PARAM5
|
||||
" + 0]\n" // &outputIndex
|
||||
" ldr r0, [r0]\n" // outputIndex
|
||||
" add r8, r8, r0, asl #2\n" // curOut
|
||||
" ldr r9, [sp, #" MO_PARAM5
|
||||
" + 24]\n" // phaseIncrement
|
||||
" ldr r10, [sp, #" MO_PARAM5
|
||||
" + 12]\n" // vl
|
||||
" ldr r11, [sp, #" MO_PARAM5
|
||||
" + 16]\n" // vr
|
||||
|
||||
// r0 pin, x0, Samp
|
||||
|
||||
@@ -632,15 +632,19 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmMono16Loop(int16_t *in,
|
||||
|
||||
" bic r6, r6, #0xC0000000\n" // phaseFraction & ...
|
||||
// save modified values
|
||||
" ldr r0, [sp, #" MO_PARAM5 " + 20]\n" // &phaseFraction
|
||||
" str r6, [r0]\n" // phaseFraction
|
||||
" ldr r0, [sp, #" MO_PARAM5 " + 8]\n" // &inputIndex
|
||||
" str r7, [r0]\n" // inputIndex
|
||||
" ldr r0, [sp, #" MO_PARAM5 " + 4]\n" // out
|
||||
" sub r8, r0\n" // curOut - out
|
||||
" asr r8, #2\n" // new outputIndex
|
||||
" ldr r0, [sp, #" MO_PARAM5 " + 0]\n" // &outputIndex
|
||||
" str r8, [r0]\n" // save outputIndex
|
||||
" ldr r0, [sp, #" MO_PARAM5
|
||||
" + 20]\n" // &phaseFraction
|
||||
" str r6, [r0]\n" // phaseFraction
|
||||
" ldr r0, [sp, #" MO_PARAM5
|
||||
" + 8]\n" // &inputIndex
|
||||
" str r7, [r0]\n" // inputIndex
|
||||
" ldr r0, [sp, #" MO_PARAM5
|
||||
" + 4]\n" // out
|
||||
" sub r8, r0\n" // curOut - out
|
||||
" asr r8, #2\n" // new outputIndex
|
||||
" ldr r0, [sp, #" MO_PARAM5
|
||||
" + 0]\n" // &outputIndex
|
||||
" str r8, [r0]\n" // save outputIndex
|
||||
|
||||
" ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc}\n");
|
||||
}
|
||||
@@ -683,17 +687,24 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmStereo16Loop(int16_t *in
|
||||
asm(
|
||||
"stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r12, lr}\n"
|
||||
// get parameters
|
||||
" ldr r6, [sp, #" ST_PARAM5 " + 20]\n" // &phaseFraction
|
||||
" ldr r6, [r6]\n" // phaseFraction
|
||||
" ldr r7, [sp, #" ST_PARAM5 " + 8]\n" // &inputIndex
|
||||
" ldr r7, [r7]\n" // inputIndex
|
||||
" ldr r8, [sp, #" ST_PARAM5 " + 4]\n" // out
|
||||
" ldr r0, [sp, #" ST_PARAM5 " + 0]\n" // &outputIndex
|
||||
" ldr r0, [r0]\n" // outputIndex
|
||||
" add r8, r8, r0, asl #2\n" // curOut
|
||||
" ldr r9, [sp, #" ST_PARAM5 " + 24]\n" // phaseIncrement
|
||||
" ldr r10, [sp, #" ST_PARAM5 " + 12]\n" // vl
|
||||
" ldr r11, [sp, #" ST_PARAM5 " + 16]\n" // vr
|
||||
" ldr r6, [sp, #" ST_PARAM5
|
||||
" + 20]\n" // &phaseFraction
|
||||
" ldr r6, [r6]\n" // phaseFraction
|
||||
" ldr r7, [sp, #" ST_PARAM5
|
||||
" + 8]\n" // &inputIndex
|
||||
" ldr r7, [r7]\n" // inputIndex
|
||||
" ldr r8, [sp, #" ST_PARAM5
|
||||
" + 4]\n" // out
|
||||
" ldr r0, [sp, #" ST_PARAM5
|
||||
" + 0]\n" // &outputIndex
|
||||
" ldr r0, [r0]\n" // outputIndex
|
||||
" add r8, r8, r0, asl #2\n" // curOut
|
||||
" ldr r9, [sp, #" ST_PARAM5
|
||||
" + 24]\n" // phaseIncrement
|
||||
" ldr r10, [sp, #" ST_PARAM5
|
||||
" + 12]\n" // vl
|
||||
" ldr r11, [sp, #" ST_PARAM5
|
||||
" + 16]\n" // vr
|
||||
|
||||
// r0 pin, x0, Samp
|
||||
|
||||
@@ -757,15 +768,19 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmStereo16Loop(int16_t *in
|
||||
|
||||
" bic r6, r6, #0xC0000000\n" // phaseFraction & ...
|
||||
// save modified values
|
||||
" ldr r0, [sp, #" ST_PARAM5 " + 20]\n" // &phaseFraction
|
||||
" str r6, [r0]\n" // phaseFraction
|
||||
" ldr r0, [sp, #" ST_PARAM5 " + 8]\n" // &inputIndex
|
||||
" str r7, [r0]\n" // inputIndex
|
||||
" ldr r0, [sp, #" ST_PARAM5 " + 4]\n" // out
|
||||
" sub r8, r0\n" // curOut - out
|
||||
" asr r8, #2\n" // new outputIndex
|
||||
" ldr r0, [sp, #" ST_PARAM5 " + 0]\n" // &outputIndex
|
||||
" str r8, [r0]\n" // save outputIndex
|
||||
" ldr r0, [sp, #" ST_PARAM5
|
||||
" + 20]\n" // &phaseFraction
|
||||
" str r6, [r0]\n" // phaseFraction
|
||||
" ldr r0, [sp, #" ST_PARAM5
|
||||
" + 8]\n" // &inputIndex
|
||||
" str r7, [r0]\n" // inputIndex
|
||||
" ldr r0, [sp, #" ST_PARAM5
|
||||
" + 4]\n" // out
|
||||
" sub r8, r0\n" // curOut - out
|
||||
" asr r8, #2\n" // new outputIndex
|
||||
" ldr r0, [sp, #" ST_PARAM5
|
||||
" + 0]\n" // &outputIndex
|
||||
" str r8, [r0]\n" // save outputIndex
|
||||
|
||||
" ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r12, pc}\n");
|
||||
}
|
||||
|
||||
@@ -43,10 +43,10 @@ public:
|
||||
// certain fixed rate conversions. Sample rate cannot be
|
||||
// changed dynamically.
|
||||
enum src_quality {
|
||||
DEFAULT_QUALITY = 0,
|
||||
LOW_QUALITY = 1,
|
||||
MED_QUALITY = 2,
|
||||
HIGH_QUALITY = 3,
|
||||
DEFAULT_QUALITY = 0,
|
||||
LOW_QUALITY = 1,
|
||||
MED_QUALITY = 2,
|
||||
HIGH_QUALITY = 3,
|
||||
VERY_HIGH_QUALITY = 4,
|
||||
};
|
||||
|
||||
@@ -82,7 +82,7 @@ public:
|
||||
virtual size_t resample(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) = 0;
|
||||
|
||||
virtual void reset();
|
||||
virtual void reset();
|
||||
virtual size_t getUnreleasedFrames() const { return mInputIndex; }
|
||||
|
||||
// called from destructor, so must not be virtual
|
||||
@@ -106,20 +106,20 @@ protected:
|
||||
|
||||
int64_t calculateOutputPTS(int outputFrameIndex);
|
||||
|
||||
const int32_t mChannelCount;
|
||||
const int32_t mSampleRate;
|
||||
int32_t mInSampleRate;
|
||||
const int32_t mChannelCount;
|
||||
const int32_t mSampleRate;
|
||||
int32_t mInSampleRate;
|
||||
AudioBufferProvider::Buffer mBuffer;
|
||||
union {
|
||||
int16_t mVolume[2];
|
||||
int16_t mVolume[2];
|
||||
uint32_t mVolumeRL;
|
||||
};
|
||||
int16_t mTargetVolume[2];
|
||||
size_t mInputIndex;
|
||||
int32_t mPhaseIncrement;
|
||||
int16_t mTargetVolume[2];
|
||||
size_t mInputIndex;
|
||||
int32_t mPhaseIncrement;
|
||||
uint32_t mPhaseFraction;
|
||||
uint64_t mLocalTimeFreq;
|
||||
int64_t mPTS;
|
||||
int64_t mPTS;
|
||||
|
||||
// returns the inFrameCount required to generate outFrameCount frames.
|
||||
//
|
||||
|
||||
@@ -34,7 +34,6 @@ void AudioResamplerCubic::init() {
|
||||
|
||||
size_t AudioResamplerCubic::resample(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
// should never happen, but we overflow if it does
|
||||
// ALOG_ASSERT(outFrameCount < 32767);
|
||||
|
||||
@@ -52,7 +51,6 @@ size_t AudioResamplerCubic::resample(int32_t *out, size_t outFrameCount,
|
||||
|
||||
size_t AudioResamplerCubic::resampleStereo16(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
int32_t vl = mVolume[0];
|
||||
int32_t vr = mVolume[1];
|
||||
|
||||
@@ -91,7 +89,6 @@ size_t AudioResamplerCubic::resampleStereo16(int32_t *out, size_t outFrameCount,
|
||||
|
||||
// time to fetch another sample
|
||||
while (indexIncrement--) {
|
||||
|
||||
inputIndex++;
|
||||
if (inputIndex == mBuffer.frameCount) {
|
||||
inputIndex = 0;
|
||||
@@ -121,7 +118,6 @@ save_state:
|
||||
|
||||
size_t AudioResamplerCubic::resampleMono16(int32_t *out, size_t outFrameCount,
|
||||
AudioBufferProvider *provider) {
|
||||
|
||||
int32_t vl = mVolume[0];
|
||||
int32_t vr = mVolume[1];
|
||||
|
||||
@@ -160,7 +156,6 @@ size_t AudioResamplerCubic::resampleMono16(int32_t *out, size_t outFrameCount,
|
||||
|
||||
// time to fetch another sample
|
||||
while (indexIncrement--) {
|
||||
|
||||
inputIndex++;
|
||||
if (inputIndex == mBuffer.frameCount) {
|
||||
inputIndex = 0;
|
||||
|
||||
@@ -63,7 +63,7 @@ namespace cc {
|
||||
//Determines the current algorithm used for stretching
|
||||
enum AudioTimestretchStretchMode : int32_t {
|
||||
AUDIO_TIMESTRETCH_STRETCH_DEFAULT = 0,
|
||||
AUDIO_TIMESTRETCH_STRETCH_SPEECH = 1,
|
||||
AUDIO_TIMESTRETCH_STRETCH_SPEECH = 1,
|
||||
//REFINE: add more stretch modes/algorithms
|
||||
};
|
||||
|
||||
@@ -79,15 +79,15 @@ enum AudioTimestretchStretchMode : int32_t {
|
||||
// FALLBACK_FAIL: will stop program execution and log a fatal error
|
||||
enum AudioTimestretchFallbackMode : int32_t {
|
||||
AUDIO_TIMESTRETCH_FALLBACK_CUT_REPEAT = -1,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_DEFAULT = 0,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_MUTE = 1,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_FAIL = 2,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_DEFAULT = 0,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_MUTE = 1,
|
||||
AUDIO_TIMESTRETCH_FALLBACK_FAIL = 2,
|
||||
};
|
||||
|
||||
struct AudioPlaybackRate {
|
||||
float mSpeed;
|
||||
float mPitch;
|
||||
enum AudioTimestretchStretchMode mStretchMode;
|
||||
float mSpeed;
|
||||
float mPitch;
|
||||
enum AudioTimestretchStretchMode mStretchMode;
|
||||
enum AudioTimestretchFallbackMode mFallbackMode;
|
||||
};
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ PcmAudioPlayer::~PcmAudioPlayer() {
|
||||
}
|
||||
|
||||
bool PcmAudioPlayer::prepare(const ccstd::string &url, const PcmData &decResult) {
|
||||
_url = url;
|
||||
_url = url;
|
||||
_decResult = decResult;
|
||||
|
||||
_track = ccnew Track(_decResult);
|
||||
@@ -64,7 +64,7 @@ bool PcmAudioPlayer::prepare(const ccstd::string &url, const PcmData &decResult)
|
||||
_track->onStateChanged = [this, callerThreadId](Track::State state) {
|
||||
// It maybe in sub thread
|
||||
Track::State prevState = _track->getPrevState();
|
||||
auto func = [this, state, prevState]() {
|
||||
auto func = [this, state, prevState]() {
|
||||
// It's in caller's thread
|
||||
if (state == Track::State::OVER && prevState != Track::State::STOPPED) {
|
||||
if (_playEventCallback != nullptr) {
|
||||
|
||||
@@ -82,13 +82,13 @@ private:
|
||||
virtual ~PcmAudioPlayer();
|
||||
|
||||
private:
|
||||
int _id;
|
||||
ccstd::string _url;
|
||||
PcmData _decResult;
|
||||
Track * _track;
|
||||
PlayEventCallback _playEventCallback;
|
||||
int _id;
|
||||
ccstd::string _url;
|
||||
PcmData _decResult;
|
||||
Track *_track;
|
||||
PlayEventCallback _playEventCallback;
|
||||
AudioMixerController *_controller;
|
||||
ICallerThreadUtils * _callerThreadUtils;
|
||||
ICallerThreadUtils *_callerThreadUtils;
|
||||
|
||||
friend class AudioPlayerProvider;
|
||||
};
|
||||
|
||||
@@ -80,9 +80,9 @@ void PcmAudioService::bqFetchBufferCallback(SLAndroidSimpleBufferQueueItf bq) {
|
||||
}
|
||||
|
||||
bool PcmAudioService::init(AudioMixerController *controller, int numChannels, int sampleRate, int bufferSizeInBytes) {
|
||||
_controller = controller;
|
||||
_numChannels = numChannels;
|
||||
_sampleRate = sampleRate;
|
||||
_controller = controller;
|
||||
_numChannels = numChannels;
|
||||
_sampleRate = sampleRate;
|
||||
_bufferSizeInBytes = bufferSizeInBytes;
|
||||
|
||||
SLuint32 channelMask = SL_SPEAKER_FRONT_CENTER;
|
||||
|
||||
@@ -60,9 +60,10 @@ status_t PcmBufferProvider::getNextBuffer(Buffer *buffer,
|
||||
buffer->frameCount = _numFrames - _nextFrame;
|
||||
}
|
||||
|
||||
ALOGVV("getNextBuffer() requested %zu frames out of %zu frames available,"
|
||||
" and returned %zu frames",
|
||||
requestedFrames, (size_t)(_numFrames - _nextFrame), buffer->frameCount);
|
||||
ALOGVV(
|
||||
"getNextBuffer() requested %zu frames out of %zu frames available,"
|
||||
" and returned %zu frames",
|
||||
requestedFrames, (size_t)(_numFrames - _nextFrame), buffer->frameCount);
|
||||
|
||||
_unrel = buffer->frameCount;
|
||||
if (buffer->frameCount > 0) {
|
||||
@@ -76,15 +77,17 @@ status_t PcmBufferProvider::getNextBuffer(Buffer *buffer,
|
||||
|
||||
void PcmBufferProvider::releaseBuffer(Buffer *buffer) {
|
||||
if (buffer->frameCount > _unrel) {
|
||||
ALOGVV("ERROR releaseBuffer() released %zu frames but only %zu available "
|
||||
"to release",
|
||||
buffer->frameCount, _unrel);
|
||||
ALOGVV(
|
||||
"ERROR releaseBuffer() released %zu frames but only %zu available "
|
||||
"to release",
|
||||
buffer->frameCount, _unrel);
|
||||
_nextFrame += _unrel;
|
||||
_unrel = 0;
|
||||
} else {
|
||||
ALOGVV("releaseBuffer() released %zu frames out of %zu frames available "
|
||||
"to release",
|
||||
buffer->frameCount, _unrel);
|
||||
ALOGVV(
|
||||
"releaseBuffer() released %zu frames out of %zu frames available "
|
||||
"to release",
|
||||
buffer->frameCount, _unrel);
|
||||
_nextFrame += buffer->frameCount;
|
||||
_unrel -= buffer->frameCount;
|
||||
}
|
||||
|
||||
@@ -41,70 +41,70 @@ PcmData::~PcmData() {
|
||||
|
||||
PcmData::PcmData(const PcmData &o) {
|
||||
// ALOGV("In the copy constructor of PcmData (%p)", this);
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
bitsPerSample = o.bitsPerSample;
|
||||
containerSize = o.containerSize;
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
}
|
||||
|
||||
PcmData::PcmData(PcmData &&o) {
|
||||
// ALOGV("In the move constructor of PcmData (%p)", this);
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
bitsPerSample = o.bitsPerSample;
|
||||
containerSize = o.containerSize;
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
o.reset();
|
||||
}
|
||||
|
||||
PcmData &PcmData::operator=(const PcmData &o) {
|
||||
// ALOGV("In the copy assignment of PcmData");
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
bitsPerSample = o.bitsPerSample;
|
||||
containerSize = o.containerSize;
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = o.pcmBuffer;
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = o.pcmBuffer;
|
||||
return *this;
|
||||
}
|
||||
|
||||
PcmData &PcmData::operator=(PcmData &&o) {
|
||||
// ALOGV("In the move assignment of PcmData");
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
numChannels = o.numChannels;
|
||||
sampleRate = o.sampleRate;
|
||||
bitsPerSample = o.bitsPerSample;
|
||||
containerSize = o.containerSize;
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
channelMask = o.channelMask;
|
||||
endianness = o.endianness;
|
||||
numFrames = o.numFrames;
|
||||
duration = o.duration;
|
||||
pcmBuffer = std::move(o.pcmBuffer);
|
||||
o.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
void PcmData::reset() {
|
||||
numChannels = -1;
|
||||
sampleRate = -1;
|
||||
numChannels = -1;
|
||||
sampleRate = -1;
|
||||
bitsPerSample = -1;
|
||||
containerSize = -1;
|
||||
channelMask = -1;
|
||||
endianness = -1;
|
||||
numFrames = -1;
|
||||
duration = -1.0f;
|
||||
pcmBuffer = nullptr;
|
||||
channelMask = -1;
|
||||
endianness = -1;
|
||||
numFrames = -1;
|
||||
duration = -1.0f;
|
||||
pcmBuffer = nullptr;
|
||||
}
|
||||
|
||||
bool PcmData::isValid() const {
|
||||
@@ -113,7 +113,7 @@ bool PcmData::isValid() const {
|
||||
|
||||
ccstd::string PcmData::toString() const {
|
||||
ccstd::string ret;
|
||||
char buf[256] = {0};
|
||||
char buf[256] = {0};
|
||||
|
||||
snprintf(buf, sizeof(buf),
|
||||
"numChannels: %d, sampleRate: %d, bitPerSample: %d, containerSize: %d, "
|
||||
|
||||
@@ -34,14 +34,14 @@ namespace cc {
|
||||
|
||||
struct PcmData {
|
||||
std::shared_ptr<ccstd::vector<char>> pcmBuffer;
|
||||
int numChannels;
|
||||
int sampleRate;
|
||||
int bitsPerSample;
|
||||
int containerSize;
|
||||
int channelMask;
|
||||
int endianness;
|
||||
int numFrames;
|
||||
float duration; // in seconds
|
||||
int numChannels;
|
||||
int sampleRate;
|
||||
int bitsPerSample;
|
||||
int containerSize;
|
||||
int channelMask;
|
||||
int endianness;
|
||||
int numFrames;
|
||||
float duration; // in seconds
|
||||
|
||||
PcmData();
|
||||
|
||||
|
||||
@@ -34,9 +34,9 @@ THE SOFTWARE.
|
||||
|
||||
namespace {
|
||||
|
||||
std::mutex __playerContainerMutex;
|
||||
std::mutex __playerContainerMutex;
|
||||
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer;
|
||||
std::once_flag __onceFlag;
|
||||
std::once_flag __onceFlag;
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -48,7 +48,7 @@ public:
|
||||
UrlAudioPlayer *thiz = (UrlAudioPlayer *)context;
|
||||
// We must use a mutex for the whole block of the following function invocation.
|
||||
std::lock_guard<std::mutex> lk(__playerContainerMutex);
|
||||
auto iter = std::find(__playerContainer.begin(), __playerContainer.end(), thiz);
|
||||
auto iter = std::find(__playerContainer.begin(), __playerContainer.end(), thiz);
|
||||
if (iter != __playerContainer.end()) {
|
||||
thiz->playEventCallback(caller, playEvent);
|
||||
}
|
||||
@@ -200,7 +200,7 @@ float UrlAudioPlayer::getVolume() const {
|
||||
|
||||
void UrlAudioPlayer::setAudioFocus(bool isFocus) {
|
||||
_isAudioFocus = isFocus;
|
||||
float volume = _isAudioFocus ? _volume : 0.0f;
|
||||
float volume = _isAudioFocus ? _volume : 0.0f;
|
||||
setVolumeToSLPlayer(volume);
|
||||
}
|
||||
|
||||
@@ -210,7 +210,7 @@ float UrlAudioPlayer::getDuration() const {
|
||||
}
|
||||
|
||||
SLmillisecond duration;
|
||||
SLresult r = (*_playItf)->GetDuration(_playItf, &duration);
|
||||
SLresult r = (*_playItf)->GetDuration(_playItf, &duration);
|
||||
SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getDuration failed");
|
||||
|
||||
if (duration == SL_TIME_UNKNOWN) {
|
||||
@@ -227,21 +227,21 @@ float UrlAudioPlayer::getDuration() const {
|
||||
|
||||
float UrlAudioPlayer::getPosition() const {
|
||||
SLmillisecond millisecond;
|
||||
SLresult r = (*_playItf)->GetPosition(_playItf, &millisecond);
|
||||
SLresult r = (*_playItf)->GetPosition(_playItf, &millisecond);
|
||||
SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getPosition failed");
|
||||
return millisecond / 1000.0f;
|
||||
}
|
||||
|
||||
bool UrlAudioPlayer::setPosition(float pos) {
|
||||
SLmillisecond millisecond = 1000.0f * pos;
|
||||
SLresult r = (*_seekItf)->SetPosition(_seekItf, millisecond, SL_SEEKMODE_ACCURATE);
|
||||
SLresult r = (*_seekItf)->SetPosition(_seekItf, millisecond, SL_SEEKMODE_ACCURATE);
|
||||
SL_RETURN_VAL_IF_FAILED(r, false, "UrlAudioPlayer::setPosition %f failed", pos);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std::shared_ptr<AssetFd> assetFd, int start,
|
||||
int length) {
|
||||
_url = url;
|
||||
_url = url;
|
||||
_assetFd = assetFd;
|
||||
|
||||
const char *locatorTypeStr = "UNKNOWN";
|
||||
@@ -259,7 +259,7 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std
|
||||
SLDataSource audioSrc;
|
||||
|
||||
SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED};
|
||||
audioSrc.pFormat = &formatMime;
|
||||
audioSrc.pFormat = &formatMime;
|
||||
|
||||
//Note: locFd & locUri should be outside of the following if/else block
|
||||
// Although locFd & locUri are only used inside if/else block, its lifecycle
|
||||
@@ -268,24 +268,24 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std
|
||||
// while invoking Engine::createAudioPlayer interface. So be care of change the position
|
||||
// of these two variables.
|
||||
SLDataLocator_AndroidFD locFd;
|
||||
SLDataLocator_URI locUri;
|
||||
SLDataLocator_URI locUri;
|
||||
|
||||
if (locatorType == SL_DATALOCATOR_ANDROIDFD) {
|
||||
locFd = {locatorType, _assetFd->getFd(), start, length};
|
||||
locFd = {locatorType, _assetFd->getFd(), start, length};
|
||||
audioSrc.pLocator = &locFd;
|
||||
} else if (locatorType == SL_DATALOCATOR_URI) {
|
||||
locUri = {locatorType, (SLchar *)_url.c_str()};
|
||||
locUri = {locatorType, (SLchar *)_url.c_str()};
|
||||
audioSrc.pLocator = &locUri;
|
||||
ALOGV("locUri: locatorType: %d", (int)locUri.locatorType);
|
||||
}
|
||||
|
||||
// configure audio sink
|
||||
SLDataLocator_OutputMix locOutmix = {SL_DATALOCATOR_OUTPUTMIX, _outputMixObj};
|
||||
SLDataSink audioSnk = {&locOutmix, nullptr};
|
||||
SLDataSink audioSnk = {&locOutmix, nullptr};
|
||||
|
||||
// create audio player
|
||||
const SLInterfaceID ids[3] = {SL_IID_SEEK, SL_IID_PREFETCHSTATUS, SL_IID_VOLUME};
|
||||
const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
|
||||
const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
|
||||
|
||||
SLresult result = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &audioSrc, &audioSnk, 3, ids, req);
|
||||
SL_RETURN_VAL_IF_FAILED(result, false, "CreateAudioPlayer failed");
|
||||
@@ -328,7 +328,7 @@ void UrlAudioPlayer::setLoop(bool isLoop) {
|
||||
_isLoop = isLoop;
|
||||
|
||||
SLboolean loopEnable = _isLoop ? SL_BOOLEAN_TRUE : SL_BOOLEAN_FALSE;
|
||||
SLresult r = (*_seekItf)->SetLoop(_seekItf, loopEnable, 0, SL_TIME_UNKNOWN);
|
||||
SLresult r = (*_seekItf)->SetLoop(_seekItf, loopEnable, 0, SL_TIME_UNKNOWN);
|
||||
SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setLoop %d failed", _isLoop ? 1 : 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -95,29 +95,29 @@ private:
|
||||
void setVolumeToSLPlayer(float volume);
|
||||
|
||||
private:
|
||||
SLEngineItf _engineItf;
|
||||
SLObjectItf _outputMixObj;
|
||||
SLEngineItf _engineItf;
|
||||
SLObjectItf _outputMixObj;
|
||||
ICallerThreadUtils *_callerThreadUtils;
|
||||
|
||||
int _id;
|
||||
int _id;
|
||||
ccstd::string _url;
|
||||
|
||||
std::shared_ptr<AssetFd> _assetFd;
|
||||
|
||||
SLObjectItf _playObj;
|
||||
SLPlayItf _playItf;
|
||||
SLSeekItf _seekItf;
|
||||
SLPlayItf _playItf;
|
||||
SLSeekItf _seekItf;
|
||||
SLVolumeItf _volumeItf;
|
||||
|
||||
float _volume;
|
||||
float _duration;
|
||||
bool _isLoop;
|
||||
bool _isAudioFocus;
|
||||
bool _isLoop;
|
||||
bool _isAudioFocus;
|
||||
State _state;
|
||||
|
||||
PlayEventCallback _playEventCallback;
|
||||
|
||||
std::thread::id _callerThreadId;
|
||||
std::thread::id _callerThreadId;
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
|
||||
friend class SLUrlAudioPlayerCallbackProxy;
|
||||
|
||||
@@ -528,7 +528,7 @@ static inline int16_t clamp16_from_float(float f) {
|
||||
static const int32_t limpos = (0x10f << 22) /*zero*/ + 32767; /* 0x43c07fff */
|
||||
|
||||
union {
|
||||
float f;
|
||||
float f;
|
||||
int32_t i;
|
||||
} u;
|
||||
|
||||
@@ -566,7 +566,7 @@ static inline uint8_t clamp8_from_float(float f) {
|
||||
static const int32_t limpos = (0x11f << 22) /*zero*/ + 255; /* 0x47c000ff */
|
||||
|
||||
union {
|
||||
float f;
|
||||
float f;
|
||||
int32_t i;
|
||||
} u;
|
||||
|
||||
@@ -591,7 +591,7 @@ static inline uint8_t clamp8_from_float(float f) {
|
||||
* depending on hardware and future implementation of this function.
|
||||
*/
|
||||
static inline int32_t clamp24_from_float(float f) {
|
||||
static const float scale = (float)(1 << 23);
|
||||
static const float scale = (float)(1 << 23);
|
||||
static const float limpos = 0x7fffff / (float)(1 << 23);
|
||||
static const float limneg = -0x800000 / (float)(1 << 23);
|
||||
|
||||
@@ -632,7 +632,7 @@ static inline int32_t clamp24_from_q8_23(int32_t ival) {
|
||||
* depending on hardware and future implementation of this function.
|
||||
*/
|
||||
static inline int32_t clampq4_27_from_float(float f) {
|
||||
static const float scale = (float)(1UL << 27);
|
||||
static const float scale = (float)(1UL << 27);
|
||||
static const float limpos = 16.;
|
||||
static const float limneg = -16.;
|
||||
|
||||
@@ -656,7 +656,7 @@ static inline int32_t clampq4_27_from_float(float f) {
|
||||
* depending on hardware and future implementation of this function.
|
||||
*/
|
||||
static inline int32_t clamp32_from_float(float f) {
|
||||
static const float scale = (float)(1UL << 31);
|
||||
static const float scale = (float)(1UL << 31);
|
||||
static const float limpos = 1.;
|
||||
static const float limneg = -1.;
|
||||
|
||||
@@ -727,7 +727,7 @@ static inline float float_from_u4_12(uint16_t uval) {
|
||||
* depending on hardware and future implementation of this function.
|
||||
*/
|
||||
static inline uint32_t u4_28_from_float(float f) {
|
||||
static const float scale = (float)(1 << 28);
|
||||
static const float scale = (float)(1 << 28);
|
||||
static const float limpos = 16.0f;
|
||||
|
||||
if (f <= 0.) {
|
||||
@@ -749,7 +749,7 @@ static inline uint32_t u4_28_from_float(float f) {
|
||||
* depending on hardware and future implementation of this function.
|
||||
*/
|
||||
static inline uint16_t u4_12_from_float(float f) {
|
||||
static const float scale = (float)(1 << 12);
|
||||
static const float scale = (float)(1 << 12);
|
||||
static const float limpos = 0xffff / (float)(1 << 12);
|
||||
|
||||
if (f <= 0.) {
|
||||
@@ -849,8 +849,8 @@ static inline int32_t mulAdd(int16_t in, int16_t v, int32_t a) {
|
||||
#if defined(__arm__) && !defined(__thumb__)
|
||||
int32_t out;
|
||||
asm("smlabb %[out], %[in], %[v], %[a] \n"
|
||||
: [out] "=r"(out)
|
||||
: [in] "%r"(in), [v] "r"(v), [a] "r"(a)
|
||||
: [ out ] "=r"(out)
|
||||
: [ in ] "%r"(in), [ v ] "r"(v), [ a ] "r"(a)
|
||||
:);
|
||||
return out;
|
||||
#else
|
||||
@@ -865,8 +865,8 @@ static inline int32_t mul(int16_t in, int16_t v) {
|
||||
#if defined(__arm__) && !defined(__thumb__)
|
||||
int32_t out;
|
||||
asm("smulbb %[out], %[in], %[v] \n"
|
||||
: [out] "=r"(out)
|
||||
: [in] "%r"(in), [v] "r"(v)
|
||||
: [ out ] "=r"(out)
|
||||
: [ in ] "%r"(in), [ v ] "r"(v)
|
||||
:);
|
||||
return out;
|
||||
#else
|
||||
@@ -882,13 +882,13 @@ static inline int32_t mulAddRL(int left, uint32_t inRL, uint32_t vRL, int32_t a)
|
||||
int32_t out;
|
||||
if (left) {
|
||||
asm("smlabb %[out], %[inRL], %[vRL], %[a] \n"
|
||||
: [out] "=r"(out)
|
||||
: [inRL] "%r"(inRL), [vRL] "r"(vRL), [a] "r"(a)
|
||||
: [ out ] "=r"(out)
|
||||
: [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL), [ a ] "r"(a)
|
||||
:);
|
||||
} else {
|
||||
asm("smlatt %[out], %[inRL], %[vRL], %[a] \n"
|
||||
: [out] "=r"(out)
|
||||
: [inRL] "%r"(inRL), [vRL] "r"(vRL), [a] "r"(a)
|
||||
: [ out ] "=r"(out)
|
||||
: [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL), [ a ] "r"(a)
|
||||
:);
|
||||
}
|
||||
return out;
|
||||
@@ -909,13 +909,13 @@ static inline int32_t mulRL(int left, uint32_t inRL, uint32_t vRL) {
|
||||
int32_t out;
|
||||
if (left) {
|
||||
asm("smulbb %[out], %[inRL], %[vRL] \n"
|
||||
: [out] "=r"(out)
|
||||
: [inRL] "%r"(inRL), [vRL] "r"(vRL)
|
||||
: [ out ] "=r"(out)
|
||||
: [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL)
|
||||
:);
|
||||
} else {
|
||||
asm("smultt %[out], %[inRL], %[vRL] \n"
|
||||
: [out] "=r"(out)
|
||||
: [inRL] "%r"(inRL), [vRL] "r"(vRL)
|
||||
: [ out ] "=r"(out)
|
||||
: [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL)
|
||||
:);
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -204,7 +204,6 @@ static ssize_t sourceReadAt(mp3_callbacks *callback, void *source, off64_t offse
|
||||
static bool resync(
|
||||
mp3_callbacks *callback, void *source, uint32_t match_header,
|
||||
off64_t *inout_pos, uint32_t *out_header) {
|
||||
|
||||
if (*inout_pos == 0) {
|
||||
// Skip an optional ID3 header if syncing at the very beginning
|
||||
// of the datasource.
|
||||
@@ -359,7 +358,6 @@ Mp3Reader::Mp3Reader() : mSource(NULL), mCallback(NULL) {
|
||||
|
||||
// Initialize the MP3 reader.
|
||||
bool Mp3Reader::init(mp3_callbacks *callback, void *source) {
|
||||
|
||||
mSource = source;
|
||||
mCallback = callback;
|
||||
// Open the file.
|
||||
@@ -385,7 +383,6 @@ bool Mp3Reader::init(mp3_callbacks *callback, void *source) {
|
||||
|
||||
// Get the next valid MP3 frame.
|
||||
bool Mp3Reader::getFrame(void *buffer, uint32_t *size) {
|
||||
|
||||
size_t frame_size;
|
||||
uint32_t bitrate;
|
||||
uint32_t num_samples;
|
||||
|
||||
@@ -38,14 +38,14 @@
|
||||
#define WAVE_FORMAT_EXTENSIBLE 0xFFFE
|
||||
|
||||
static snd_callbacks sDefaultCallback;
|
||||
static int sInited = 0;
|
||||
static int sInited = 0;
|
||||
|
||||
struct SNDFILE_ {
|
||||
uint8_t * temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping
|
||||
void * stream;
|
||||
size_t bytesPerFrame;
|
||||
size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE
|
||||
SF_INFO info;
|
||||
uint8_t *temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping
|
||||
void *stream;
|
||||
size_t bytesPerFrame;
|
||||
size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE
|
||||
SF_INFO info;
|
||||
snd_callbacks callback;
|
||||
};
|
||||
|
||||
@@ -93,12 +93,12 @@ static long tell_func(void *datasource) { //NOLINT(google-runtime-int,readabilit
|
||||
|
||||
static void lazyInit() {
|
||||
if (sInited == 0) {
|
||||
sDefaultCallback.open = open_func;
|
||||
sDefaultCallback.read = read_func;
|
||||
sDefaultCallback.seek = seek_func;
|
||||
sDefaultCallback.open = open_func;
|
||||
sDefaultCallback.read = read_func;
|
||||
sDefaultCallback.seek = seek_func;
|
||||
sDefaultCallback.close = close_func;
|
||||
sDefaultCallback.tell = tell_func;
|
||||
sInited = 1;
|
||||
sDefaultCallback.tell = tell_func;
|
||||
sInited = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,12 +134,12 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *
|
||||
|
||||
// don't attempt to parse all valid forms, just the most common ones
|
||||
unsigned char wav[12];
|
||||
size_t actual;
|
||||
unsigned riffSize;
|
||||
size_t remaining;
|
||||
int hadFmt = 0;
|
||||
int hadData = 0;
|
||||
long dataTell = 0L; //NOLINT(google-runtime-int)
|
||||
size_t actual;
|
||||
unsigned riffSize;
|
||||
size_t remaining;
|
||||
int hadFmt = 0;
|
||||
int hadData = 0;
|
||||
long dataTell = 0L; //NOLINT(google-runtime-int)
|
||||
|
||||
actual = handle->callback.read(wav, sizeof(char), sizeof(wav), stream);
|
||||
if (actual < 12) {
|
||||
@@ -207,8 +207,8 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned format = little2u(&fmt[0]);
|
||||
size_t minSize = 0;
|
||||
unsigned format = little2u(&fmt[0]);
|
||||
size_t minSize = 0;
|
||||
switch (format) {
|
||||
case WAVE_FORMAT_PCM:
|
||||
case WAVE_FORMAT_IEEE_FLOAT:
|
||||
@@ -264,10 +264,10 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned bytesPerFrame = (bitsPerSample >> 3) * channels;
|
||||
handle->bytesPerFrame = bytesPerFrame;
|
||||
unsigned bytesPerFrame = (bitsPerSample >> 3) * channels;
|
||||
handle->bytesPerFrame = bytesPerFrame;
|
||||
handle->info.samplerate = static_cast<int>(samplerate);
|
||||
handle->info.channels = static_cast<int>(channels);
|
||||
handle->info.channels = static_cast<int>(channels);
|
||||
switch (bitsPerSample) {
|
||||
case 8:
|
||||
handle->info.format |= SF_FORMAT_PCM_U8;
|
||||
@@ -300,9 +300,9 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
handle->remaining = chunkSize / handle->bytesPerFrame;
|
||||
handle->remaining = chunkSize / handle->bytesPerFrame;
|
||||
handle->info.frames = handle->remaining;
|
||||
dataTell = handle->callback.tell(stream);
|
||||
dataTell = handle->callback.tell(stream);
|
||||
if (chunkSize > 0) {
|
||||
handle->callback.seek(stream, static_cast<long>(chunkSize), SEEK_CUR); //NOLINT(google-runtime-int)
|
||||
}
|
||||
@@ -384,12 +384,12 @@ sf_count_t sf_readf_short(SNDFILE *handle, int16_t *ptr, sf_count_t desiredFrame
|
||||
desiredFrames = handle->remaining;
|
||||
}
|
||||
// does not check for numeric overflow
|
||||
size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
|
||||
size_t actualBytes;
|
||||
void * temp = nullptr;
|
||||
size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
|
||||
size_t actualBytes;
|
||||
void *temp = nullptr;
|
||||
unsigned format = handle->info.format & SF_FORMAT_SUBMASK;
|
||||
if (format == SF_FORMAT_PCM_32 || format == SF_FORMAT_FLOAT || format == SF_FORMAT_PCM_24) {
|
||||
temp = malloc(desiredBytes);
|
||||
temp = malloc(desiredBytes);
|
||||
actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream);
|
||||
} else {
|
||||
actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream);
|
||||
|
||||
@@ -32,9 +32,9 @@ using sf_count_t = int;
|
||||
|
||||
using SF_INFO = struct {
|
||||
sf_count_t frames;
|
||||
int samplerate;
|
||||
int channels;
|
||||
int format;
|
||||
int samplerate;
|
||||
int channels;
|
||||
int format;
|
||||
};
|
||||
|
||||
// opaque to clients
|
||||
|
||||
@@ -64,9 +64,9 @@ protected:
|
||||
void invokingLoadCallbacks();
|
||||
|
||||
//pcm data related stuff
|
||||
ALenum _format;
|
||||
ALsizei _sampleRate;
|
||||
float _duration;
|
||||
ALenum _format;
|
||||
ALsizei _sampleRate;
|
||||
float _duration;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _framesRead;
|
||||
|
||||
@@ -74,16 +74,16 @@ protected:
|
||||
* Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
ALuint _alBufferId;
|
||||
char * _pcmData;
|
||||
char *_pcmData;
|
||||
|
||||
/*Queue buffer related stuff
|
||||
* Streaming in openal when sizeInBytes greater then PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
char * _queBuffers[QUEUEBUFFER_NUM];
|
||||
ALsizei _queBufferSize[QUEUEBUFFER_NUM];
|
||||
char *_queBuffers[QUEUEBUFFER_NUM];
|
||||
ALsizei _queBufferSize[QUEUEBUFFER_NUM];
|
||||
uint32_t _queBufferFrames;
|
||||
|
||||
std::mutex _playCallbackMutex;
|
||||
std::mutex _playCallbackMutex;
|
||||
ccstd::vector<std::function<void()>> _playCallbacks;
|
||||
|
||||
// loadCallbacks doesn't need mutex since it's invoked only in Cocos thread.
|
||||
@@ -94,10 +94,10 @@ protected:
|
||||
State _state;
|
||||
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished;
|
||||
bool _isSkipReadDataTask;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished;
|
||||
bool _isSkipReadDataTask;
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
friend class AudioPlayer;
|
||||
|
||||
@@ -107,12 +107,12 @@ public:
|
||||
uint32_t getChannelCount() const;
|
||||
|
||||
private:
|
||||
bool _isOpened;
|
||||
bool _isOpened;
|
||||
ExtAudioFileRef _extRef;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _bytesPerFrame;
|
||||
uint32_t _sampleRate;
|
||||
uint32_t _channelCount;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _bytesPerFrame;
|
||||
uint32_t _sampleRate;
|
||||
uint32_t _channelCount;
|
||||
|
||||
AudioStreamBasicDescription _outputFormat;
|
||||
};
|
||||
|
||||
@@ -42,28 +42,28 @@ public:
|
||||
AudioEngineImpl();
|
||||
~AudioEngineImpl();
|
||||
|
||||
bool init();
|
||||
int play2d(const ccstd::string &fileFullPath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
bool pause(int audioID);
|
||||
bool resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
bool init();
|
||||
int play2d(const ccstd::string &fileFullPath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
bool pause(int audioID);
|
||||
bool resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
float getDuration(int audioID);
|
||||
float getDurationFromFile(const ccstd::string &fileFullPath);
|
||||
float getCurrentTime(int audioID);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
|
||||
void uncache(const ccstd::string &filePath);
|
||||
void uncacheAll();
|
||||
void uncache(const ccstd::string &filePath);
|
||||
void uncacheAll();
|
||||
AudioCache *preload(const ccstd::string &filePath, std::function<void(bool)> callback);
|
||||
void update(float dt);
|
||||
void update(float dt);
|
||||
|
||||
private:
|
||||
bool checkAudioIdValid(int audioID);
|
||||
void play2dImpl(AudioCache *cache, int audioID);
|
||||
bool checkAudioIdValid(int audioID);
|
||||
void play2dImpl(AudioCache *cache, int audioID);
|
||||
ALuint findValidSource();
|
||||
|
||||
static ALvoid myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid *userData);
|
||||
@@ -78,11 +78,11 @@ private:
|
||||
|
||||
//audioID,AudioInfo
|
||||
ccstd::unordered_map<int, AudioPlayer *> _audioPlayers;
|
||||
std::mutex _threadMutex;
|
||||
std::mutex _threadMutex;
|
||||
|
||||
bool _lazyInitLoop;
|
||||
|
||||
int _currentAudioID;
|
||||
int _currentAudioID;
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
@@ -159,8 +159,7 @@ void AudioEngineInterruptionListenerCallback(void *user_data, UInt32 interruptio
|
||||
}
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:&error];
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
}
|
||||
else if (isAudioSessionInterrupted) {
|
||||
} else if (isAudioSessionInterrupted) {
|
||||
isAudioSessionInterrupted = false;
|
||||
ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)");
|
||||
NSError *error = nil;
|
||||
@@ -635,7 +634,6 @@ void AudioEngineImpl::update(float dt) {
|
||||
delete player;
|
||||
_unusedSourcesPool.push_back(alSource);
|
||||
} else if (player->_ready && sourceState == AL_STOPPED) {
|
||||
|
||||
ccstd::string filePath;
|
||||
if (player->_finishCallbak) {
|
||||
auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID];
|
||||
|
||||
@@ -47,9 +47,9 @@ public:
|
||||
void destroy();
|
||||
|
||||
//queue buffer related stuff
|
||||
bool setTime(float time);
|
||||
bool setTime(float time);
|
||||
float getTime() { return _currTime; }
|
||||
bool setLoop(bool loop);
|
||||
bool setLoop(bool loop);
|
||||
|
||||
protected:
|
||||
void setCache(AudioCache *cache);
|
||||
@@ -59,25 +59,25 @@ protected:
|
||||
|
||||
AudioCache *_audioCache;
|
||||
|
||||
float _volume;
|
||||
bool _loop;
|
||||
float _volume;
|
||||
bool _loop;
|
||||
std::function<void(int, const ccstd::string &)> _finishCallbak;
|
||||
|
||||
bool _isDestroyed;
|
||||
bool _removeByAudioEngine;
|
||||
bool _ready;
|
||||
bool _isDestroyed;
|
||||
bool _removeByAudioEngine;
|
||||
bool _ready;
|
||||
ALuint _alSource;
|
||||
|
||||
//play by circular buffer
|
||||
float _currTime;
|
||||
bool _streamingSource;
|
||||
ALuint _bufferIds[QUEUEBUFFER_NUM];
|
||||
std::thread * _rotateBufferThread;
|
||||
float _currTime;
|
||||
bool _streamingSource;
|
||||
ALuint _bufferIds[QUEUEBUFFER_NUM];
|
||||
std::thread *_rotateBufferThread;
|
||||
std::condition_variable _sleepCondition;
|
||||
std::mutex _sleepMutex;
|
||||
bool _timeDirty;
|
||||
bool _isRotateThreadExited;
|
||||
std::atomic_bool _needWakeupRotateThread;
|
||||
std::mutex _sleepMutex;
|
||||
bool _timeDirty;
|
||||
bool _isRotateThreadExited;
|
||||
std::atomic_bool _needWakeupRotateThread;
|
||||
|
||||
std::mutex _play2dMutex;
|
||||
|
||||
|
||||
@@ -112,7 +112,8 @@ void AudioPlayer::destroy() {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed);
|
||||
}
|
||||
alSourceUnqueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); CHECK_AL_ERROR_DEBUG();
|
||||
alSourceUnqueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
}
|
||||
ALOGVV("UnqueueBuffers Before alSourceStop");
|
||||
#endif
|
||||
@@ -328,7 +329,6 @@ bool AudioPlayer::setLoop(bool loop) {
|
||||
|
||||
bool AudioPlayer::setTime(float time) {
|
||||
if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) {
|
||||
|
||||
_currTime = time;
|
||||
_timeDirty = true;
|
||||
|
||||
|
||||
@@ -334,11 +334,11 @@ protected:
|
||||
|
||||
struct AudioInfo {
|
||||
const ccstd::string *filePath;
|
||||
ProfileHelper * profileHelper;
|
||||
ProfileHelper *profileHelper;
|
||||
|
||||
float volume;
|
||||
bool loop;
|
||||
float duration;
|
||||
float volume;
|
||||
bool loop;
|
||||
float duration;
|
||||
AudioState state;
|
||||
|
||||
AudioInfo();
|
||||
@@ -372,9 +372,9 @@ protected:
|
||||
static bool sIsEnabled;
|
||||
|
||||
private:
|
||||
static float sVolumeFactor;
|
||||
static uint32_t sOnPauseListenerID;
|
||||
static uint32_t sOnResumeListenerID;
|
||||
static float sVolumeFactor;
|
||||
static uint32_t sOnPauseListenerID;
|
||||
static uint32_t sOnResumeListenerID;
|
||||
static ccstd::vector<int> sBreakAudioID;
|
||||
|
||||
static void onEnterBackground(const CustomEvent &);
|
||||
|
||||
@@ -57,7 +57,7 @@ AudioCache::AudioCache()
|
||||
: _format(-1), _sampleRate(0), _duration(0.0F), _totalFrames(0), _framesRead(0), _alBufferId(INVALID_AL_BUFFER_ID), _pcmData(nullptr), _queBufferFrames(0), _state(State::INITIAL), _isDestroyed(std::make_shared<bool>(false)), _id(++gIdIndex), _isLoadingFinished(false), _isSkipReadDataTask(false) {
|
||||
ALOGVV("AudioCache() %p, id=%u", this, _id);
|
||||
for (int i = 0; i < QUEUEBUFFER_NUM; ++i) {
|
||||
_queBuffers[i] = nullptr;
|
||||
_queBuffers[i] = nullptr;
|
||||
_queBufferSize[i] = 0;
|
||||
}
|
||||
}
|
||||
@@ -113,22 +113,22 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
}
|
||||
|
||||
const uint32_t originalTotalFrames = decoder->getTotalFrames();
|
||||
const uint32_t bytesPerFrame = decoder->getBytesPerFrame();
|
||||
const uint32_t sampleRate = decoder->getSampleRate();
|
||||
const uint32_t channelCount = decoder->getChannelCount();
|
||||
const uint32_t bytesPerFrame = decoder->getBytesPerFrame();
|
||||
const uint32_t sampleRate = decoder->getSampleRate();
|
||||
const uint32_t channelCount = decoder->getChannelCount();
|
||||
|
||||
uint32_t totalFrames = originalTotalFrames;
|
||||
uint32_t dataSize = totalFrames * bytesPerFrame;
|
||||
uint32_t totalFrames = originalTotalFrames;
|
||||
uint32_t dataSize = totalFrames * bytesPerFrame;
|
||||
uint32_t remainingFrames = totalFrames;
|
||||
uint32_t adjustFrames = 0;
|
||||
uint32_t adjustFrames = 0;
|
||||
|
||||
_format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
_sampleRate = static_cast<ALsizei>(sampleRate);
|
||||
_duration = 1.0F * totalFrames / sampleRate;
|
||||
_format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
_sampleRate = static_cast<ALsizei>(sampleRate);
|
||||
_duration = 1.0F * totalFrames / sampleRate;
|
||||
_totalFrames = totalFrames;
|
||||
|
||||
if (dataSize <= PCMDATA_CACHEMAXSIZE) {
|
||||
uint32_t framesRead = 0;
|
||||
uint32_t framesRead = 0;
|
||||
const uint32_t framesToReadOnce = std::min(totalFrames, static_cast<uint32_t>(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM));
|
||||
|
||||
ccstd::vector<char> adjustFrameBuf;
|
||||
@@ -225,7 +225,7 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame;
|
||||
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index) {
|
||||
_queBuffers[index] = static_cast<char *>(malloc(queBufferBytes));
|
||||
_queBuffers[index] = static_cast<char *>(malloc(queBufferBytes));
|
||||
_queBufferSize[index] = queBufferBytes;
|
||||
|
||||
decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]);
|
||||
|
||||
@@ -72,9 +72,9 @@ protected:
|
||||
void invokingLoadCallbacks();
|
||||
|
||||
//pcm data related stuff
|
||||
ALenum _format;
|
||||
ALsizei _sampleRate;
|
||||
float _duration;
|
||||
ALenum _format;
|
||||
ALsizei _sampleRate;
|
||||
float _duration;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _framesRead;
|
||||
|
||||
@@ -82,16 +82,16 @@ protected:
|
||||
* Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
ALuint _alBufferId;
|
||||
char * _pcmData;
|
||||
char *_pcmData;
|
||||
|
||||
/*Queue buffer related stuff
|
||||
* Streaming in OpenAL when sizeInBytes greater then PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
char * _queBuffers[QUEUEBUFFER_NUM];
|
||||
ALsizei _queBufferSize[QUEUEBUFFER_NUM];
|
||||
char *_queBuffers[QUEUEBUFFER_NUM];
|
||||
ALsizei _queBufferSize[QUEUEBUFFER_NUM];
|
||||
uint32_t _queBufferFrames;
|
||||
|
||||
std::mutex _playCallbackMutex;
|
||||
std::mutex _playCallbackMutex;
|
||||
ccstd::vector<std::function<void()>> _playCallbacks;
|
||||
|
||||
// loadCallbacks doesn't need mutex since it's invoked only in Cocos thread.
|
||||
@@ -102,10 +102,10 @@ protected:
|
||||
State _state;
|
||||
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished;
|
||||
bool _isSkipReadDataTask;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished;
|
||||
bool _isSkipReadDataTask;
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
friend class AudioPlayer;
|
||||
|
||||
@@ -52,7 +52,7 @@ bool AudioDecoder::isOpened() const {
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::readFixedFrames(uint32_t framesToRead, char *pcmBuf) {
|
||||
uint32_t framesRead = 0;
|
||||
uint32_t framesRead = 0;
|
||||
uint32_t framesReadOnce = 0;
|
||||
do {
|
||||
framesReadOnce = read(framesToRead - framesRead, pcmBuf + framesRead * _bytesPerFrame);
|
||||
|
||||
@@ -114,7 +114,7 @@ protected:
|
||||
AudioDecoder();
|
||||
virtual ~AudioDecoder();
|
||||
|
||||
bool _isOpened;
|
||||
bool _isOpened;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _bytesPerFrame;
|
||||
uint32_t _sampleRate;
|
||||
|
||||
@@ -32,10 +32,10 @@ class AudioDecoder;
|
||||
|
||||
class AudioDecoderManager {
|
||||
public:
|
||||
static bool init();
|
||||
static void destroy();
|
||||
static bool init();
|
||||
static void destroy();
|
||||
static AudioDecoder *createDecoder(const char *path);
|
||||
static void destroyDecoder(AudioDecoder *decoder);
|
||||
static void destroyDecoder(AudioDecoder *decoder);
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -80,10 +80,10 @@ AudioDecoderMp3::~AudioDecoderMp3() {
|
||||
bool AudioDecoderMp3::open(const char *path) {
|
||||
ccstd::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
|
||||
|
||||
long rate = 0; //NOLINT(google-runtime-int)
|
||||
int error = MPG123_OK;
|
||||
int mp3Encoding = 0;
|
||||
int channel = 0;
|
||||
long rate = 0; //NOLINT(google-runtime-int)
|
||||
int error = MPG123_OK;
|
||||
int mp3Encoding = 0;
|
||||
int channel = 0;
|
||||
do {
|
||||
_mpg123handle = mpg123_new(nullptr, &error);
|
||||
if (nullptr == _mpg123handle) {
|
||||
@@ -91,7 +91,7 @@ bool AudioDecoderMp3::open(const char *path) {
|
||||
break;
|
||||
}
|
||||
#if CC_PLATFORM_OHOS == CC_PLATFORM
|
||||
auto *fu = static_cast<FileUtilsOHOS *>(FileUtils::getInstance());
|
||||
auto *fu = static_cast<FileUtilsOHOS *>(FileUtils::getInstance());
|
||||
_fdAndDeleter = fu->getFd(fullPath);
|
||||
if (mpg123_open_fd(_mpg123handle, _fdAndDeleter.first) != MPG123_OK || mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK) {
|
||||
#else
|
||||
@@ -102,7 +102,7 @@ bool AudioDecoderMp3::open(const char *path) {
|
||||
}
|
||||
|
||||
_channelCount = channel;
|
||||
_sampleRate = rate;
|
||||
_sampleRate = rate;
|
||||
|
||||
if (mp3Encoding == MPG123_ENC_SIGNED_16) {
|
||||
_bytesPerFrame = 2 * _channelCount;
|
||||
@@ -152,8 +152,8 @@ void AudioDecoderMp3::close() {
|
||||
|
||||
uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char *pcmBuf) {
|
||||
size_t bytesToRead = framesToRead * _bytesPerFrame;
|
||||
size_t bytesRead = 0;
|
||||
int err = mpg123_read(_mpg123handle, reinterpret_cast<unsigned char *>(pcmBuf), bytesToRead, &bytesRead);
|
||||
size_t bytesRead = 0;
|
||||
int err = mpg123_read(_mpg123handle, reinterpret_cast<unsigned char *>(pcmBuf), bytesToRead, &bytesRead);
|
||||
if (err == MPG123_ERR) {
|
||||
ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle));
|
||||
return 0;
|
||||
|
||||
@@ -68,11 +68,11 @@ bool AudioDecoderOgg::open(const char *path) {
|
||||
#endif
|
||||
// header
|
||||
vorbis_info *vi = ov_info(&_vf, -1);
|
||||
_sampleRate = static_cast<uint32_t>(vi->rate);
|
||||
_channelCount = vi->channels;
|
||||
_bytesPerFrame = vi->channels * sizeof(int16_t);
|
||||
_totalFrames = static_cast<uint32_t>(ov_pcm_total(&_vf, -1));
|
||||
_isOpened = true;
|
||||
_sampleRate = static_cast<uint32_t>(vi->rate);
|
||||
_channelCount = vi->channels;
|
||||
_bytesPerFrame = vi->channels * sizeof(int16_t);
|
||||
_totalFrames = static_cast<uint32_t>(ov_pcm_total(&_vf, -1));
|
||||
_isOpened = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -86,12 +86,12 @@ void AudioDecoderOgg::close() {
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char *pcmBuf) {
|
||||
int currentSection = 0;
|
||||
auto bytesToRead = framesToRead * _bytesPerFrame;
|
||||
int currentSection = 0;
|
||||
auto bytesToRead = framesToRead * _bytesPerFrame;
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection);
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
int bitstream = 0;
|
||||
int bitstream = 0;
|
||||
auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, &bitstream);
|
||||
#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection);
|
||||
|
||||
@@ -57,8 +57,8 @@
|
||||
//IDEA: Move _winLog, winLog to a separated file
|
||||
static void _winLog(const char *format, va_list args) {
|
||||
static const int MAX_LOG_LENGTH = 16 * 1024;
|
||||
int bufferSize = MAX_LOG_LENGTH;
|
||||
char * buf = nullptr;
|
||||
int bufferSize = MAX_LOG_LENGTH;
|
||||
char *buf = nullptr;
|
||||
|
||||
do {
|
||||
buf = ccnew char[bufferSize];
|
||||
@@ -77,10 +77,10 @@ static void _winLog(const char *format, va_list args) {
|
||||
|
||||
strcat(buf, "\n");
|
||||
|
||||
int pos = 0;
|
||||
auto len = static_cast<int>(strlen(buf));
|
||||
char tempBuf[MAX_LOG_LENGTH + 1] = {0};
|
||||
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0};
|
||||
int pos = 0;
|
||||
auto len = static_cast<int>(strlen(buf));
|
||||
char tempBuf[MAX_LOG_LENGTH + 1] = {0};
|
||||
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0};
|
||||
|
||||
do {
|
||||
std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
|
||||
@@ -114,7 +114,7 @@ void audioLog(const char *format, ...) {
|
||||
|
||||
using namespace cc; //NOLINT
|
||||
|
||||
static ALCdevice * sALDevice = nullptr;
|
||||
static ALCdevice *sALDevice = nullptr;
|
||||
static ALCcontext *sALContext = nullptr;
|
||||
|
||||
AudioEngineImpl::AudioEngineImpl()
|
||||
@@ -167,7 +167,7 @@ bool AudioEngineImpl::init() {
|
||||
}
|
||||
|
||||
_scheduler = CC_CURRENT_ENGINE()->getScheduler();
|
||||
ret = AudioDecoderManager::init();
|
||||
ret = AudioDecoderManager::init();
|
||||
CC_LOG_DEBUG("OpenAL was initialized successfully!");
|
||||
}
|
||||
} while (false);
|
||||
@@ -180,10 +180,10 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, const std::f
|
||||
|
||||
auto it = _audioCaches.find(filePath);
|
||||
if (it == _audioCaches.end()) {
|
||||
audioCache = &_audioCaches[filePath];
|
||||
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
|
||||
unsigned int cacheId = audioCache->_id;
|
||||
auto isCacheDestroyed = audioCache->_isDestroyed;
|
||||
audioCache = &_audioCaches[filePath];
|
||||
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
|
||||
unsigned int cacheId = audioCache->_id;
|
||||
auto isCacheDestroyed = audioCache->_isDestroyed;
|
||||
AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() {
|
||||
if (*isCacheDestroyed) {
|
||||
ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
|
||||
@@ -207,8 +207,8 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
|
||||
return AudioEngine::INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
bool sourceFlag = false;
|
||||
ALuint alSource = 0;
|
||||
bool sourceFlag = false;
|
||||
ALuint alSource = 0;
|
||||
for (unsigned int src : _alSources) {
|
||||
alSource = src;
|
||||
|
||||
@@ -227,8 +227,8 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
|
||||
}
|
||||
|
||||
player->_alSource = alSource;
|
||||
player->_loop = loop;
|
||||
player->_volume = volume;
|
||||
player->_loop = loop;
|
||||
player->_volume = volume;
|
||||
|
||||
auto audioCache = preload(filePath, nullptr);
|
||||
if (audioCache == nullptr) {
|
||||
@@ -283,7 +283,7 @@ void AudioEngineImpl::setVolume(int audioID, float volume) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return;
|
||||
}
|
||||
auto player = _audioPlayers[audioID];
|
||||
auto player = _audioPlayers[audioID];
|
||||
player->_volume = volume;
|
||||
|
||||
if (player->_ready) {
|
||||
@@ -408,8 +408,8 @@ float AudioEngineImpl::getCurrentTime(int audioID) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return 0.0F;
|
||||
}
|
||||
float ret = 0.0F;
|
||||
auto player = _audioPlayers[audioID];
|
||||
float ret = 0.0F;
|
||||
auto player = _audioPlayers[audioID];
|
||||
if (player->_ready) {
|
||||
if (player->_streamingSource) {
|
||||
ret = player->getTime();
|
||||
@@ -430,7 +430,7 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return false;
|
||||
}
|
||||
bool ret = false;
|
||||
bool ret = false;
|
||||
auto player = _audioPlayers[audioID];
|
||||
|
||||
do {
|
||||
@@ -470,16 +470,16 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void(in
|
||||
}
|
||||
|
||||
void AudioEngineImpl::update(float /*dt*/) {
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
AudioPlayer *player;
|
||||
ALuint alSource;
|
||||
ALuint alSource;
|
||||
|
||||
// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
|
||||
|
||||
for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) {
|
||||
audioID = it->first;
|
||||
player = it->second;
|
||||
audioID = it->first;
|
||||
player = it->second;
|
||||
alSource = player->_alSource;
|
||||
alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
|
||||
|
||||
@@ -494,7 +494,7 @@ void AudioEngineImpl::update(float /*dt*/) {
|
||||
ccstd::string filePath;
|
||||
if (player->_finishCallbak) {
|
||||
auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID];
|
||||
filePath = *audioInfo.filePath;
|
||||
filePath = *audioInfo.filePath;
|
||||
}
|
||||
|
||||
AudioEngine::remove(audioID);
|
||||
|
||||
@@ -42,24 +42,24 @@ public:
|
||||
AudioEngineImpl();
|
||||
~AudioEngineImpl() override;
|
||||
|
||||
bool init();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
bool pause(int audioID);
|
||||
bool resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
bool init();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
bool pause(int audioID);
|
||||
bool resume(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
float getDuration(int audioID);
|
||||
float getDurationFromFile(const ccstd::string &filePath);
|
||||
float getCurrentTime(int audioID);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const ccstd::string &)> &callback);
|
||||
|
||||
void uncache(const ccstd::string &filePath);
|
||||
void uncacheAll();
|
||||
void uncache(const ccstd::string &filePath);
|
||||
void uncacheAll();
|
||||
AudioCache *preload(const ccstd::string &filePath, const std::function<void(bool)> &callback);
|
||||
void update(float dt);
|
||||
void update(float dt);
|
||||
|
||||
private:
|
||||
bool checkAudioIdValid(int audioID);
|
||||
@@ -75,11 +75,11 @@ private:
|
||||
|
||||
//audioID,AudioInfo
|
||||
ccstd::unordered_map<int, AudioPlayer *> _audioPlayers;
|
||||
std::mutex _threadMutex;
|
||||
std::mutex _threadMutex;
|
||||
|
||||
bool _lazyInitLoop;
|
||||
|
||||
int _currentAudioID;
|
||||
int _currentAudioID;
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
@@ -180,7 +180,7 @@ bool AudioPlayer::play2d() {
|
||||
alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
_rotateBufferThread = ccnew std::thread(&AudioPlayer::rotateBufferThread, this,
|
||||
_audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1);
|
||||
_audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1);
|
||||
} else {
|
||||
alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
@@ -204,7 +204,7 @@ bool AudioPlayer::play2d() {
|
||||
break;
|
||||
}
|
||||
_ready = true;
|
||||
ret = true;
|
||||
ret = true;
|
||||
} while (false);
|
||||
|
||||
if (!ret) {
|
||||
@@ -216,15 +216,15 @@ bool AudioPlayer::play2d() {
|
||||
}
|
||||
|
||||
void AudioPlayer::rotateBufferThread(int offsetFrame) {
|
||||
char * tmpBuffer = nullptr;
|
||||
AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str());
|
||||
char *tmpBuffer = nullptr;
|
||||
AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str());
|
||||
do {
|
||||
BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str()));
|
||||
|
||||
uint32_t framesRead = 0;
|
||||
uint32_t framesRead = 0;
|
||||
const uint32_t framesToRead = _audioCache->_queBufferFrames;
|
||||
const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame();
|
||||
tmpBuffer = static_cast<char *>(malloc(bufferSize));
|
||||
const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame();
|
||||
tmpBuffer = static_cast<char *>(malloc(bufferSize));
|
||||
memset(tmpBuffer, 0, bufferSize);
|
||||
|
||||
if (offsetFrame != 0) {
|
||||
@@ -232,8 +232,8 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) {
|
||||
}
|
||||
|
||||
ALint sourceState;
|
||||
ALint bufferProcessed = 0;
|
||||
bool needToExitThread = false;
|
||||
ALint bufferProcessed = 0;
|
||||
bool needToExitThread = false;
|
||||
|
||||
while (!_isDestroyed) {
|
||||
alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState);
|
||||
@@ -242,7 +242,7 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) {
|
||||
while (bufferProcessed > 0) {
|
||||
bufferProcessed--;
|
||||
if (_timeDirty) {
|
||||
_timeDirty = false;
|
||||
_timeDirty = false;
|
||||
offsetFrame = static_cast<int>(_currTime * decoder->getSampleRate());
|
||||
decoder->seek(offsetFrame);
|
||||
} else {
|
||||
@@ -307,7 +307,7 @@ bool AudioPlayer::setLoop(bool loop) {
|
||||
|
||||
bool AudioPlayer::setTime(float time) {
|
||||
if (!_isDestroyed && time >= 0.0F && time < _audioCache->_duration) {
|
||||
_currTime = time;
|
||||
_currTime = time;
|
||||
_timeDirty = true;
|
||||
|
||||
return true;
|
||||
|
||||
@@ -55,9 +55,9 @@ public:
|
||||
void destroy();
|
||||
|
||||
//queue buffer related stuff
|
||||
bool setTime(float time);
|
||||
bool setTime(float time);
|
||||
float getTime() { return _currTime; }
|
||||
bool setLoop(bool loop);
|
||||
bool setLoop(bool loop);
|
||||
|
||||
protected:
|
||||
void setCache(AudioCache *cache);
|
||||
@@ -66,24 +66,24 @@ protected:
|
||||
|
||||
AudioCache *_audioCache;
|
||||
|
||||
float _volume;
|
||||
bool _loop;
|
||||
float _volume;
|
||||
bool _loop;
|
||||
std::function<void(int, const ccstd::string &)> _finishCallbak;
|
||||
|
||||
bool _isDestroyed;
|
||||
bool _removeByAudioEngine;
|
||||
bool _ready;
|
||||
bool _isDestroyed;
|
||||
bool _removeByAudioEngine;
|
||||
bool _ready;
|
||||
ALuint _alSource;
|
||||
|
||||
//play by circular buffer
|
||||
float _currTime;
|
||||
bool _streamingSource;
|
||||
ALuint _bufferIds[3];
|
||||
std::thread * _rotateBufferThread;
|
||||
float _currTime;
|
||||
bool _streamingSource;
|
||||
ALuint _bufferIds[3];
|
||||
std::thread *_rotateBufferThread;
|
||||
std::condition_variable _sleepCondition;
|
||||
std::mutex _sleepMutex;
|
||||
bool _timeDirty;
|
||||
bool _isRotateThreadExited;
|
||||
std::mutex _sleepMutex;
|
||||
bool _timeDirty;
|
||||
bool _isRotateThreadExited;
|
||||
|
||||
std::mutex _play2dMutex;
|
||||
|
||||
|
||||
@@ -32,11 +32,11 @@
|
||||
|
||||
namespace {
|
||||
snd_callbacks wavCallbacks = {
|
||||
.open = cc::ohosOpen,
|
||||
.read = cc::ohosRead,
|
||||
.seek = cc::ohosSeek,
|
||||
.open = cc::ohosOpen,
|
||||
.read = cc::ohosRead,
|
||||
.seek = cc::ohosSeek,
|
||||
.close = cc::ohosClose,
|
||||
.tell = cc::ohosTell,
|
||||
.tell = cc::ohosTell,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,13 +52,13 @@ AudioDecoderWav::~AudioDecoderWav() {
|
||||
|
||||
bool AudioDecoderWav::open(const char *path) {
|
||||
_sndHandle = sf_open_read(path, &_sndInfo, &wavCallbacks, this);
|
||||
_isOpened = (_sndHandle != nullptr) && _sndInfo.frames > 0;
|
||||
_isOpened = (_sndHandle != nullptr) && _sndInfo.frames > 0;
|
||||
if (!_isOpened) return false;
|
||||
|
||||
_channelCount = _sndInfo.channels;
|
||||
_sampleRate = _sndInfo.samplerate;
|
||||
_channelCount = _sndInfo.channels;
|
||||
_sampleRate = _sndInfo.samplerate;
|
||||
_bytesPerFrame = 2 * _channelCount; // short
|
||||
_totalFrames = _sndInfo.frames;
|
||||
_totalFrames = _sndInfo.frames;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ void AudioDecoderWav::close() {
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderWav::read(uint32_t framesToRead, char *pcmBuf) {
|
||||
auto *output = reinterpret_cast<int16_t *>(pcmBuf);
|
||||
auto actualFrames = sf_readf_short(_sndHandle, output, framesToRead);
|
||||
auto *output = reinterpret_cast<int16_t *>(pcmBuf);
|
||||
auto actualFrames = sf_readf_short(_sndHandle, output, framesToRead);
|
||||
return actualFrames;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,14 +36,14 @@ public:
|
||||
AudioDecoderWav();
|
||||
~AudioDecoderWav() override;
|
||||
|
||||
bool open(const char *path) override;
|
||||
void close() override;
|
||||
bool open(const char *path) override;
|
||||
void close() override;
|
||||
uint32_t read(uint32_t framesToRead, char *pcmBuf) override;
|
||||
bool seek(uint32_t frameOffset) override;
|
||||
bool seek(uint32_t frameOffset) override;
|
||||
uint32_t tell() const override;
|
||||
|
||||
private:
|
||||
SF_INFO _sndInfo;
|
||||
SF_INFO _sndInfo;
|
||||
SNDFILE *_sndHandle{};
|
||||
};
|
||||
|
||||
|
||||
@@ -37,25 +37,25 @@ inline cc::FileUtilsOHOS *getFU() {
|
||||
|
||||
struct FatFd {
|
||||
union {
|
||||
FILE * fp;
|
||||
FILE *fp;
|
||||
RawFile *rf;
|
||||
} file;
|
||||
void *user;
|
||||
bool isRawFile;
|
||||
bool isRawFile;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
namespace cc {
|
||||
void *ohosOpen(const char *path, void *user) {
|
||||
bool isRawfile = false;
|
||||
const auto newPath = getFU()->expandPath(path, &isRawfile);
|
||||
auto * ret = ccnew FatFd();
|
||||
bool isRawfile = false;
|
||||
const auto newPath = getFU()->expandPath(path, &isRawfile);
|
||||
auto *ret = ccnew FatFd();
|
||||
if (isRawfile) {
|
||||
ret->file.rf = OpenRawFile(cc::FileUtilsOHOS::getResourceManager(), newPath.c_str());
|
||||
} else {
|
||||
ret->file.fp = fopen(newPath.c_str(), "rb");
|
||||
}
|
||||
ret->user = user;
|
||||
ret->user = user;
|
||||
ret->isRawFile = isRawfile;
|
||||
return ret;
|
||||
}
|
||||
@@ -78,7 +78,7 @@ int ohosSeek(void *datasource, long offset, int whence) { //NOLINT(google-runtim
|
||||
|
||||
int ohosClose(void *datasource) {
|
||||
auto *fatFd = static_cast<FatFd *>(datasource);
|
||||
int code = 0;
|
||||
int code = 0;
|
||||
if (fatFd->isRawFile) {
|
||||
CloseRawFile(fatFd->file.rf);
|
||||
code = 0;
|
||||
|
||||
@@ -37,9 +37,9 @@ template <typename T>
|
||||
class CachedArray final {
|
||||
public:
|
||||
explicit CachedArray(uint size = 1U) {
|
||||
_size = 0;
|
||||
_size = 0;
|
||||
_capacity = std::max(size, 1U);
|
||||
_array = ccnew T[_capacity];
|
||||
_array = ccnew T[_capacity];
|
||||
}
|
||||
|
||||
// The rule of five applies here
|
||||
@@ -55,29 +55,29 @@ public:
|
||||
CachedArray &operator=(const CachedArray &other) {
|
||||
if (this != &other) {
|
||||
delete[] _array;
|
||||
_size = other._size;
|
||||
_size = other._size;
|
||||
_capacity = other._capacity;
|
||||
_array = ccnew T[_capacity];
|
||||
_array = ccnew T[_capacity];
|
||||
memcpy(_array, other._array, _size * sizeof(T));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
CachedArray(CachedArray &&other) noexcept : _size(other._size), _capacity(other._capacity), _array(other._array) {
|
||||
other._size = 0;
|
||||
other._size = 0;
|
||||
other._capacity = 0;
|
||||
other._array = nullptr;
|
||||
other._array = nullptr;
|
||||
}
|
||||
|
||||
CachedArray &operator=(CachedArray &&other) noexcept {
|
||||
if (this != &other) {
|
||||
delete[] _array;
|
||||
_size = other._size;
|
||||
_capacity = other._capacity;
|
||||
_array = other._array;
|
||||
other._size = 0;
|
||||
_size = other._size;
|
||||
_capacity = other._capacity;
|
||||
_array = other._array;
|
||||
other._size = 0;
|
||||
other._capacity = 0;
|
||||
other._array = nullptr;
|
||||
other._array = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -93,12 +93,12 @@ public:
|
||||
|
||||
inline void clear() { _size = 0; }
|
||||
inline uint size() const { return _size; }
|
||||
inline T pop() { return _array[--_size]; }
|
||||
inline T pop() { return _array[--_size]; }
|
||||
|
||||
void reserve(uint size) {
|
||||
if (size > _capacity) {
|
||||
T *temp = _array;
|
||||
_array = ccnew T[size];
|
||||
_array = ccnew T[size];
|
||||
memcpy(_array, temp, _capacity * sizeof(T));
|
||||
_capacity = size;
|
||||
delete[] temp;
|
||||
@@ -108,7 +108,7 @@ public:
|
||||
void push(T item) {
|
||||
if (_size >= _capacity) {
|
||||
T *temp = _array;
|
||||
_array = ccnew T[_capacity * 2];
|
||||
_array = ccnew T[_capacity * 2];
|
||||
memcpy(_array, temp, _capacity * sizeof(T));
|
||||
_capacity *= 2;
|
||||
delete[] temp;
|
||||
@@ -118,9 +118,9 @@ public:
|
||||
|
||||
void concat(const CachedArray<T> &array) {
|
||||
if (_size + array._size > _capacity) {
|
||||
T * temp = _array;
|
||||
T *temp = _array;
|
||||
uint size = std::max(_capacity * 2, _size + array._size);
|
||||
_array = ccnew T[size];
|
||||
_array = ccnew T[size];
|
||||
memcpy(_array, temp, _size * sizeof(T));
|
||||
_capacity = size;
|
||||
delete[] temp;
|
||||
@@ -131,9 +131,9 @@ public:
|
||||
|
||||
void concat(T *array, uint count) {
|
||||
if (_size + count > _capacity) {
|
||||
T * temp = _array;
|
||||
T *temp = _array;
|
||||
uint size = std::max(_capacity * 2, _size + count);
|
||||
_array = ccnew T[size];
|
||||
_array = ccnew T[size];
|
||||
memcpy(_array, temp, _size * sizeof(T));
|
||||
_capacity = size;
|
||||
delete[] temp;
|
||||
@@ -159,9 +159,9 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
uint _size = 0;
|
||||
uint _size = 0;
|
||||
uint _capacity = 0;
|
||||
T * _array = nullptr;
|
||||
T *_array = nullptr;
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -68,10 +68,10 @@ void Data::move(Data &other) {
|
||||
clear();
|
||||
|
||||
_bytes = other._bytes;
|
||||
_size = other._size;
|
||||
_size = other._size;
|
||||
|
||||
other._bytes = nullptr;
|
||||
other._size = 0;
|
||||
other._size = 0;
|
||||
}
|
||||
|
||||
bool Data::isNull() const {
|
||||
@@ -90,7 +90,7 @@ void Data::copy(const unsigned char *bytes, uint32_t size) {
|
||||
clear();
|
||||
|
||||
if (size > 0) {
|
||||
_size = size;
|
||||
_size = size;
|
||||
_bytes = static_cast<unsigned char *>(malloc(sizeof(unsigned char) * _size));
|
||||
memcpy(_bytes, bytes, _size);
|
||||
}
|
||||
@@ -99,7 +99,7 @@ void Data::copy(const unsigned char *bytes, uint32_t size) {
|
||||
void Data::fastSet(unsigned char *bytes, uint32_t size) {
|
||||
free(_bytes);
|
||||
_bytes = bytes;
|
||||
_size = size;
|
||||
_size = size;
|
||||
}
|
||||
|
||||
void Data::resize(uint32_t size) {
|
||||
@@ -107,14 +107,14 @@ void Data::resize(uint32_t size) {
|
||||
if (_size == size) {
|
||||
return;
|
||||
}
|
||||
_size = size;
|
||||
_size = size;
|
||||
_bytes = static_cast<unsigned char *>(realloc(_bytes, sizeof(unsigned char) * _size));
|
||||
}
|
||||
|
||||
void Data::clear() {
|
||||
free(_bytes);
|
||||
_bytes = nullptr;
|
||||
_size = 0;
|
||||
_size = 0;
|
||||
}
|
||||
|
||||
uint8_t *Data::takeBuffer(uint32_t *size) {
|
||||
@@ -124,7 +124,7 @@ uint8_t *Data::takeBuffer(uint32_t *size) {
|
||||
}
|
||||
|
||||
_bytes = nullptr;
|
||||
_size = 0;
|
||||
_size = 0;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ public:
|
||||
inline bool operator<(IndexHandle const &rhs) const noexcept;
|
||||
inline bool operator==(IndexHandle const &rhs) const noexcept;
|
||||
inline bool operator!=(IndexHandle const &rhs) const noexcept;
|
||||
inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicitly
|
||||
inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicitly
|
||||
|
||||
static IndexType constexpr UNINITIALIZED{std::numeric_limits<IndexType>::max()};
|
||||
|
||||
|
||||
+13
-13
@@ -36,17 +36,17 @@ public:
|
||||
_mtx->lock();
|
||||
}
|
||||
UniqueLockedRef(UniqueLockedRef &&t) noexcept {
|
||||
_data = t._data;
|
||||
_mtx = t._mtx;
|
||||
_data = t._data;
|
||||
_mtx = t._mtx;
|
||||
t._data = nullptr;
|
||||
t._mtx = nullptr;
|
||||
t._mtx = nullptr;
|
||||
}
|
||||
|
||||
UniqueLockedRef &operator=(UniqueLockedRef &&t) noexcept {
|
||||
_data = t._data;
|
||||
_mtx = t._mtx;
|
||||
_data = t._data;
|
||||
_mtx = t._mtx;
|
||||
t._data = nullptr;
|
||||
t._mtx = nullptr;
|
||||
t._mtx = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -67,18 +67,18 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
T * _data{};
|
||||
T *_data{};
|
||||
LK *_mtx{};
|
||||
};
|
||||
|
||||
template <class T, class LK>
|
||||
class Locked {
|
||||
public:
|
||||
Locked() = default;
|
||||
Locked(const Locked &) = delete;
|
||||
Locked(Locked &&) = delete;
|
||||
Locked & operator=(const Locked &) = delete;
|
||||
Locked & operator=(Locked &&) = delete;
|
||||
Locked() = default;
|
||||
Locked(const Locked &) = delete;
|
||||
Locked(Locked &&) = delete;
|
||||
Locked &operator=(const Locked &) = delete;
|
||||
Locked &operator=(Locked &&) = delete;
|
||||
UniqueLockedRef<T, LK> lock() {
|
||||
UniqueLockedRef<T, LK> ref(&_data, &_mutex);
|
||||
return std::move(ref);
|
||||
@@ -86,7 +86,7 @@ public:
|
||||
|
||||
private:
|
||||
LK _mutex{};
|
||||
T _data{};
|
||||
T _data{};
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
@@ -60,7 +60,7 @@ LogLevel Log::slogLevel = LogLevel::LEVEL_DEBUG;
|
||||
LogLevel Log::slogLevel = LogLevel::INFO;
|
||||
#endif
|
||||
|
||||
FILE * Log::slogFile = nullptr;
|
||||
FILE *Log::slogFile = nullptr;
|
||||
const ccstd::vector<ccstd::string> LOG_LEVEL_DESCS{"FATAL", "ERROR", "WARN", "INFO", "DEBUG"};
|
||||
|
||||
void Log::setLogFile(const ccstd::string &filename) {
|
||||
@@ -76,9 +76,9 @@ void Log::setLogFile(const ccstd::string &filename) {
|
||||
msg += "------------------------------------------------------\n";
|
||||
|
||||
struct tm *tm_time;
|
||||
time_t ct_time;
|
||||
time_t ct_time;
|
||||
time(&ct_time);
|
||||
tm_time = localtime(&ct_time);
|
||||
tm_time = localtime(&ct_time);
|
||||
char dateBuffer[256] = {0};
|
||||
snprintf(dateBuffer, sizeof(dateBuffer), "LOG DATE: %04d-%02d-%02d %02d:%02d:%02d\n",
|
||||
tm_time->tm_year + 1900,
|
||||
@@ -106,13 +106,13 @@ void Log::close() {
|
||||
}
|
||||
|
||||
void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) {
|
||||
char buff[4096];
|
||||
char *p = buff;
|
||||
char buff[4096];
|
||||
char *p = buff;
|
||||
char *last = buff + sizeof(buff) - 3;
|
||||
|
||||
#if defined(LOG_USE_TIMESTAMP)
|
||||
struct tm *tmTime;
|
||||
time_t ctTime;
|
||||
time_t ctTime;
|
||||
time(&ctTime);
|
||||
tmTime = localtime(&ctTime);
|
||||
|
||||
@@ -126,7 +126,7 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) {
|
||||
// p += StringUtil::vprintf(p, last, formats, args);
|
||||
|
||||
std::ptrdiff_t count = (last - p);
|
||||
int ret = vsnprintf(p, count, formats, args);
|
||||
int ret = vsnprintf(p, count, formats, args);
|
||||
if (ret >= count - 1) {
|
||||
p += (count - 1);
|
||||
} else if (ret >= 0) {
|
||||
@@ -136,7 +136,7 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) {
|
||||
va_end(args);
|
||||
|
||||
*p++ = '\n';
|
||||
*p = 0;
|
||||
*p = 0;
|
||||
|
||||
if (slogFile) {
|
||||
fputs(buff, slogFile);
|
||||
|
||||
@@ -49,11 +49,11 @@ class CC_DLL Log {
|
||||
public:
|
||||
static LogLevel slogLevel; // for read only
|
||||
|
||||
static inline void setLogLevel(LogLevel level) { slogLevel = level; }
|
||||
static inline void setLogLevel(LogLevel level) { slogLevel = level; }
|
||||
static inline FILE *getLogFile() { return slogFile; }
|
||||
static void setLogFile(const ccstd::string &filename);
|
||||
static void close();
|
||||
static void logMessage(LogType type, LogLevel level, const char *formats, ...);
|
||||
static void setLogFile(const ccstd::string &filename);
|
||||
static void close();
|
||||
static void logMessage(LogType type, LogLevel level, const char *formats, ...);
|
||||
|
||||
private:
|
||||
static FILE *slogFile;
|
||||
|
||||
@@ -218,7 +218,7 @@ It should work same as apples CFSwapInt32LittleToHost(..)
|
||||
|
||||
#define CC_DISALLOW_COPY_MOVE_ASSIGN(TypeName) \
|
||||
TypeName(const TypeName &) = delete; \
|
||||
TypeName(TypeName &&) = delete; \
|
||||
TypeName(TypeName &&) = delete; \
|
||||
CC_DISALLOW_ASSIGN(TypeName)
|
||||
|
||||
#if (CC_COMPILER == CC_COMPILER_MSVC)
|
||||
|
||||
@@ -123,7 +123,7 @@ public:
|
||||
}
|
||||
|
||||
T *get() const { return _ptr; }
|
||||
operator T *() const { return _ptr; } // NOLINT
|
||||
operator T *() const { return _ptr; } // NOLINT
|
||||
T &operator*() const { return *_ptr; }
|
||||
T *operator->() const { return _ptr; }
|
||||
|
||||
@@ -180,7 +180,7 @@ public:
|
||||
void swap(T **pp) noexcept {
|
||||
T *p = _ptr;
|
||||
_ptr = *pp;
|
||||
*pp = p;
|
||||
*pp = p;
|
||||
}
|
||||
|
||||
void swap(IntrusivePtr<T> &r) noexcept { swap(&r._ptr); }
|
||||
@@ -193,7 +193,7 @@ private:
|
||||
// calling Release() once on the object when no longer using it.
|
||||
T *release() {
|
||||
T *retVal = _ptr;
|
||||
_ptr = nullptr;
|
||||
_ptr = nullptr;
|
||||
return retVal;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,21 +43,21 @@ public:
|
||||
template <typename T>
|
||||
static inline T randomReal(T min, T max) {
|
||||
std::uniform_real_distribution<T> dist(min, max);
|
||||
auto & mt = RandomHelper::getEngine();
|
||||
auto &mt = RandomHelper::getEngine();
|
||||
return dist(mt);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static inline T randomInt(T min, T max) {
|
||||
std::uniform_int_distribution<T> dist(min, max);
|
||||
auto & mt = RandomHelper::getEngine();
|
||||
auto &mt = RandomHelper::getEngine();
|
||||
return dist(mt);
|
||||
}
|
||||
|
||||
private:
|
||||
static inline std::mt19937 &getEngine() {
|
||||
static std::random_device seedGen;
|
||||
static std::mt19937 engine(seedGen());
|
||||
static std::mt19937 engine(seedGen());
|
||||
return engine;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -269,7 +269,7 @@ public:
|
||||
*/
|
||||
V getRandomObject() const {
|
||||
if (!_data.empty()) {
|
||||
auto randIdx = RandomHelper::randomInt<int>(0, static_cast<int>(_data.size()) - 1);
|
||||
auto randIdx = RandomHelper::randomInt<int>(0, static_cast<int>(_data.size()) - 1);
|
||||
const_iterator randIter = _data.begin();
|
||||
std::advance(randIter, randIdx);
|
||||
return randIter->second;
|
||||
|
||||
@@ -37,25 +37,25 @@
|
||||
|
||||
namespace {
|
||||
constexpr unsigned CC_REPEAT_FOREVER{UINT_MAX - 1};
|
||||
constexpr int MAX_FUNC_TO_PERFORM{30};
|
||||
constexpr int INITIAL_TIMER_COUND{10};
|
||||
constexpr int MAX_FUNC_TO_PERFORM{30};
|
||||
constexpr int INITIAL_TIMER_COUND{10};
|
||||
} // namespace
|
||||
|
||||
namespace cc {
|
||||
// implementation Timer
|
||||
|
||||
void Timer::setupTimerWithInterval(float seconds, unsigned int repeat, float delay) {
|
||||
_elapsed = -1;
|
||||
_interval = seconds;
|
||||
_delay = delay;
|
||||
_useDelay = _delay > 0.0F;
|
||||
_repeat = repeat;
|
||||
_elapsed = -1;
|
||||
_interval = seconds;
|
||||
_delay = delay;
|
||||
_useDelay = _delay > 0.0F;
|
||||
_repeat = repeat;
|
||||
_runForever = _repeat == CC_REPEAT_FOREVER;
|
||||
}
|
||||
|
||||
void Timer::update(float dt) {
|
||||
if (_elapsed == -1) {
|
||||
_elapsed = 0;
|
||||
_elapsed = 0;
|
||||
_timesExecuted = 0;
|
||||
return;
|
||||
}
|
||||
@@ -105,9 +105,9 @@ void Timer::update(float dt) {
|
||||
|
||||
bool TimerTargetCallback::initWithCallback(Scheduler *scheduler, const ccSchedulerFunc &callback, void *target, const ccstd::string &key, float seconds, unsigned int repeat, float delay) {
|
||||
_scheduler = scheduler;
|
||||
_target = target;
|
||||
_callback = callback;
|
||||
_key = key;
|
||||
_target = target;
|
||||
_callback = callback;
|
||||
_key = key;
|
||||
setupTimerWithInterval(seconds, repeat, delay);
|
||||
return true;
|
||||
}
|
||||
@@ -153,10 +153,10 @@ void Scheduler::schedule(const ccSchedulerFunc &callback, void *target, float in
|
||||
CC_ASSERT(target);
|
||||
CC_ASSERT(!key.empty());
|
||||
|
||||
auto iter = _hashForTimers.find(target);
|
||||
auto iter = _hashForTimers.find(target);
|
||||
HashTimerEntry *element = nullptr;
|
||||
if (iter == _hashForTimers.end()) {
|
||||
element = ccnew HashTimerEntry();
|
||||
element = ccnew HashTimerEntry();
|
||||
element->target = target;
|
||||
|
||||
_hashForTimers[target] = element;
|
||||
@@ -196,8 +196,8 @@ void Scheduler::unschedule(const ccstd::string &key, void *target) {
|
||||
auto iter = _hashForTimers.find(target);
|
||||
if (iter != _hashForTimers.end()) {
|
||||
HashTimerEntry *element = iter->second;
|
||||
int i = 0;
|
||||
auto & timers = element->timers;
|
||||
int i = 0;
|
||||
auto &timers = element->timers;
|
||||
|
||||
for (auto *t : timers) {
|
||||
auto *timer = dynamic_cast<TimerTargetCallback *>(t);
|
||||
@@ -270,7 +270,7 @@ void Scheduler::unscheduleAllForTarget(void *target) {
|
||||
auto iter = _hashForTimers.find(target);
|
||||
if (iter != _hashForTimers.end()) {
|
||||
HashTimerEntry *element = iter->second;
|
||||
auto & timers = element->timers;
|
||||
auto &timers = element->timers;
|
||||
if (std::find(timers.begin(), timers.end(), element->currentTimer) != timers.end() &&
|
||||
(!element->currentTimerSalvaged)) {
|
||||
element->currentTimer->addRef();
|
||||
@@ -340,14 +340,14 @@ void Scheduler::update(float dt) {
|
||||
// Iterate over all the custom selectors
|
||||
HashTimerEntry *elt = nullptr;
|
||||
for (auto iter = _hashForTimers.begin(); iter != _hashForTimers.end();) {
|
||||
elt = iter->second;
|
||||
_currentTarget = elt;
|
||||
elt = iter->second;
|
||||
_currentTarget = elt;
|
||||
_currentTargetSalvaged = false;
|
||||
|
||||
if (!_currentTarget->paused) {
|
||||
// The 'timers' array may change while inside this loop
|
||||
for (elt->timerIndex = 0; elt->timerIndex < static_cast<int>(elt->timers.size()); ++(elt->timerIndex)) {
|
||||
elt->currentTimer = elt->timers.at(elt->timerIndex);
|
||||
elt->currentTimer = elt->timers.at(elt->timerIndex);
|
||||
elt->currentTimerSalvaged = false;
|
||||
|
||||
elt->currentTimer->update(dt);
|
||||
@@ -376,7 +376,7 @@ void Scheduler::update(float dt) {
|
||||
}
|
||||
|
||||
_updateHashLocked = false;
|
||||
_currentTarget = nullptr;
|
||||
_currentTarget = nullptr;
|
||||
|
||||
//
|
||||
// Functions allocated from another thread
|
||||
|
||||
@@ -57,7 +57,7 @@ public:
|
||||
void setupTimerWithInterval(float seconds, unsigned int repeat, float delay);
|
||||
|
||||
virtual void trigger(float dt) = 0;
|
||||
virtual void cancel() = 0;
|
||||
virtual void cancel() = 0;
|
||||
|
||||
/** triggers the timer */
|
||||
void update(float dt);
|
||||
@@ -65,14 +65,14 @@ public:
|
||||
protected:
|
||||
Timer() = default;
|
||||
|
||||
Scheduler * _scheduler = nullptr;
|
||||
float _elapsed = 0.F;
|
||||
bool _runForever = false;
|
||||
bool _useDelay = false;
|
||||
Scheduler *_scheduler = nullptr;
|
||||
float _elapsed = 0.F;
|
||||
bool _runForever = false;
|
||||
bool _useDelay = false;
|
||||
unsigned int _timesExecuted = 0;
|
||||
unsigned int _repeat = 0; //0 = once, 1 is 2 x executed
|
||||
float _delay = 0.F;
|
||||
float _interval = 0.F;
|
||||
unsigned int _repeat = 0; //0 = once, 1 is 2 x executed
|
||||
float _delay = 0.F;
|
||||
float _interval = 0.F;
|
||||
};
|
||||
|
||||
class CC_DLL TimerTargetCallback final : public Timer {
|
||||
@@ -83,15 +83,15 @@ public:
|
||||
bool initWithCallback(Scheduler *scheduler, const ccSchedulerFunc &callback, void *target, const ccstd::string &key, float seconds, unsigned int repeat, float delay);
|
||||
|
||||
inline const ccSchedulerFunc &getCallback() const { return _callback; };
|
||||
inline const ccstd::string & getKey() const { return _key; };
|
||||
inline const ccstd::string &getKey() const { return _key; };
|
||||
|
||||
void trigger(float dt) override;
|
||||
void cancel() override;
|
||||
|
||||
private:
|
||||
void * _target = nullptr;
|
||||
void *_target = nullptr;
|
||||
ccSchedulerFunc _callback = nullptr;
|
||||
ccstd::string _key;
|
||||
ccstd::string _key;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -276,11 +276,11 @@ private:
|
||||
// Hash Element used for "selectors with interval"
|
||||
struct HashTimerEntry {
|
||||
ccstd::vector<Timer *> timers;
|
||||
void * target;
|
||||
int timerIndex;
|
||||
Timer * currentTimer;
|
||||
bool currentTimerSalvaged;
|
||||
bool paused;
|
||||
void *target;
|
||||
int timerIndex;
|
||||
Timer *currentTimer;
|
||||
bool currentTimerSalvaged;
|
||||
bool paused;
|
||||
};
|
||||
|
||||
void removeHashElement(struct HashTimerEntry *element);
|
||||
@@ -290,14 +290,14 @@ private:
|
||||
|
||||
// Used for "selectors with interval"
|
||||
ccstd::unordered_map<void *, HashTimerEntry *> _hashForTimers;
|
||||
struct HashTimerEntry * _currentTarget = nullptr;
|
||||
bool _currentTargetSalvaged = false;
|
||||
struct HashTimerEntry *_currentTarget = nullptr;
|
||||
bool _currentTargetSalvaged = false;
|
||||
// If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
|
||||
bool _updateHashLocked = false;
|
||||
|
||||
// Used for "perform Function"
|
||||
ccstd::vector<std::function<void()>> _functionsToPerform;
|
||||
std::mutex _performMutex;
|
||||
std::mutex _performMutex;
|
||||
};
|
||||
|
||||
// end of base group
|
||||
|
||||
@@ -58,22 +58,22 @@ public:
|
||||
StringPool() = default;
|
||||
~StringPool();
|
||||
StringPool(const StringPool &) = delete;
|
||||
StringPool(StringPool &&) = delete;
|
||||
StringPool(StringPool &&) = delete;
|
||||
StringPool &operator=(const StringPool &) = delete;
|
||||
StringPool &operator=(StringPool &&) = delete;
|
||||
|
||||
StringHandle stringToHandle(const char *str) noexcept;
|
||||
char const * handleToString(const StringHandle &handle) const noexcept;
|
||||
char const *handleToString(const StringHandle &handle) const noexcept;
|
||||
StringHandle find(const char *str) const noexcept;
|
||||
|
||||
private:
|
||||
StringHandle doStringToHandle(const char *str) noexcept;
|
||||
char const * doHandleToString(const StringHandle &handle) const noexcept;
|
||||
char const *doHandleToString(const StringHandle &handle) const noexcept;
|
||||
StringHandle doFind(const char *str) const noexcept;
|
||||
|
||||
ccstd::unordered_map<char const *, StringHandle, StringHasher, StringEqual> _stringToHandles{};
|
||||
ccstd::vector<char const *> _handleToStrings{};
|
||||
mutable ReadWriteLock _readWriteLock{};
|
||||
ccstd::vector<char const *> _handleToStrings{};
|
||||
mutable ReadWriteLock _readWriteLock{};
|
||||
};
|
||||
|
||||
using ThreadSafeStringPool = StringPool<true>;
|
||||
@@ -121,7 +121,7 @@ inline StringHandle StringPool<ThreadSafe>::doStringToHandle(const char *str) no
|
||||
|
||||
if (it == _stringToHandles.end()) {
|
||||
size_t const strLength = strlen(str) + 1;
|
||||
char *const strCache = ccnew char[strLength];
|
||||
char *const strCache = ccnew char[strLength];
|
||||
strcpy(strCache, str);
|
||||
StringHandle name(static_cast<StringHandle::IndexType>(_handleToStrings.size()), strCache);
|
||||
_handleToStrings.emplace_back(strCache);
|
||||
|
||||
@@ -47,7 +47,7 @@ int StringUtil::vprintf(char *buf, const char *last, const char *fmt, va_list ar
|
||||
if (last <= buf) return 0;
|
||||
|
||||
int count = (int)(last - buf);
|
||||
int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args);
|
||||
int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args);
|
||||
if (ret < 0) {
|
||||
if (errno == 0) {
|
||||
return count - 1;
|
||||
@@ -65,7 +65,7 @@ int StringUtil::vprintf(char *buf, const char *last, const char *fmt, va_list ar
|
||||
}
|
||||
|
||||
auto count = static_cast<int>(last - buf);
|
||||
int ret = vsnprintf(buf, count, fmt, args);
|
||||
int ret = vsnprintf(buf, count, fmt, args);
|
||||
if (ret >= count - 1) {
|
||||
return count - 1;
|
||||
}
|
||||
@@ -85,7 +85,7 @@ int StringUtil::printf(char *buf, const char *last, const char *fmt, ...) {
|
||||
}
|
||||
|
||||
ccstd::string StringUtil::format(const char *fmt, ...) {
|
||||
char sz[4096];
|
||||
char sz[4096];
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(sz, sz + sizeof(sz) - 1, fmt, args);
|
||||
@@ -164,11 +164,11 @@ ccstd::string &StringUtil::toupper(ccstd::string &str) {
|
||||
}
|
||||
|
||||
ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member-functions-to-static)
|
||||
uint8_t * outGzip{nullptr};
|
||||
uint8_t * outBase64{nullptr};
|
||||
auto * input = reinterpret_cast<unsigned char *>(const_cast<char *>(_str.c_str()));
|
||||
auto lenOfBase64 = base64Decode(input, static_cast<unsigned int>(_str.size()), &outBase64);
|
||||
auto lenofUnzip = ZipUtils::inflateMemory(outBase64, static_cast<uint32_t>(lenOfBase64), &outGzip);
|
||||
uint8_t *outGzip{nullptr};
|
||||
uint8_t *outBase64{nullptr};
|
||||
auto *input = reinterpret_cast<unsigned char *>(const_cast<char *>(_str.c_str()));
|
||||
auto lenOfBase64 = base64Decode(input, static_cast<unsigned int>(_str.size()), &outBase64);
|
||||
auto lenofUnzip = ZipUtils::inflateMemory(outBase64, static_cast<uint32_t>(lenOfBase64), &outGzip);
|
||||
ccstd::string ret(outGzip, outGzip + lenofUnzip);
|
||||
free(outGzip);
|
||||
free(outBase64);
|
||||
|
||||
@@ -36,14 +36,14 @@ namespace cc {
|
||||
|
||||
class CC_DLL StringUtil {
|
||||
public:
|
||||
static int vprintf(char *buf, const char *last, const char *fmt, va_list args);
|
||||
static int printf(char *buf, const char *last, const char *fmt, ...);
|
||||
static ccstd::string format(const char *fmt, ...);
|
||||
static int vprintf(char *buf, const char *last, const char *fmt, va_list args);
|
||||
static int printf(char *buf, const char *last, const char *fmt, ...);
|
||||
static ccstd::string format(const char *fmt, ...);
|
||||
static ccstd::vector<ccstd::string> split(const ccstd::string &str, const ccstd::string &delims, uint maxSplits = 0);
|
||||
static ccstd::string & replace(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr);
|
||||
static ccstd::string & replaceAll(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr);
|
||||
static ccstd::string & tolower(ccstd::string &str);
|
||||
static ccstd::string & toupper(ccstd::string &str);
|
||||
static ccstd::string &replace(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr);
|
||||
static ccstd::string &replaceAll(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr);
|
||||
static ccstd::string &tolower(ccstd::string &str);
|
||||
static ccstd::string &toupper(ccstd::string &str);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -108,7 +108,7 @@ LegacyThreadPool::~LegacyThreadPool() {
|
||||
|
||||
// number of idle threads
|
||||
int LegacyThreadPool::getIdleThreadNum() const {
|
||||
auto * thiz = const_cast<LegacyThreadPool *>(this);
|
||||
auto *thiz = const_cast<LegacyThreadPool *>(this);
|
||||
std::lock_guard<std::mutex> lk(thiz->_idleThreadNumMutex);
|
||||
return _idleThreadNum;
|
||||
}
|
||||
@@ -131,7 +131,7 @@ void LegacyThreadPool::init() {
|
||||
_initedFlags[i] = std::make_shared<std::atomic<bool>>(true);
|
||||
++_initedThreadNum;
|
||||
} else {
|
||||
_abortFlags[i] = std::make_shared<std::atomic<bool>>(true);
|
||||
_abortFlags[i] = std::make_shared<std::atomic<bool>>(true);
|
||||
_initedFlags[i] = std::make_shared<std::atomic<bool>>(false);
|
||||
}
|
||||
}
|
||||
@@ -143,7 +143,7 @@ bool LegacyThreadPool::tryShrinkPool() {
|
||||
auto before = std::chrono::high_resolution_clock::now();
|
||||
|
||||
ccstd::vector<int> threadIDsToJoin;
|
||||
int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep);
|
||||
int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep);
|
||||
|
||||
for (int i = 0; i < _maxThreadNum; ++i) {
|
||||
if ((int)threadIDsToJoin.size() >= maxThreadNumToJoin) {
|
||||
@@ -201,7 +201,7 @@ void LegacyThreadPool::stretchPool(int count) {
|
||||
}
|
||||
|
||||
if (newThreadCount > 0) {
|
||||
auto after = std::chrono::high_resolution_clock::now();
|
||||
auto after = std::chrono::high_resolution_clock::now();
|
||||
float seconds = TIME_MINUS(after, before);
|
||||
|
||||
LOGD("stretch pool from %d to %d, waste %f seconds\n", oldThreadCount, _initedThreadNum,
|
||||
@@ -210,7 +210,7 @@ void LegacyThreadPool::stretchPool(int count) {
|
||||
}
|
||||
|
||||
void LegacyThreadPool::pushTask(const std::function<void(int)> &runnable,
|
||||
TaskType type /* = DEFAULT*/) {
|
||||
TaskType type /* = DEFAULT*/) {
|
||||
if (!_isFixedSize) {
|
||||
_idleThreadNumMutex.lock();
|
||||
int idleNum = _idleThreadNum;
|
||||
@@ -218,7 +218,7 @@ void LegacyThreadPool::pushTask(const std::function<void(int)> &runnable,
|
||||
|
||||
if (idleNum > _minThreadNum) {
|
||||
if (_taskQueue.empty()) {
|
||||
auto now = std::chrono::high_resolution_clock::now();
|
||||
auto now = std::chrono::high_resolution_clock::now();
|
||||
float seconds = TIME_MINUS(now, _lastShrinkTime);
|
||||
if (seconds > _shrinkInterval) {
|
||||
tryShrinkPool();
|
||||
@@ -235,7 +235,7 @@ void LegacyThreadPool::pushTask(const std::function<void(int)> &runnable,
|
||||
});
|
||||
|
||||
Task task;
|
||||
task.type = type;
|
||||
task.type = type;
|
||||
task.callback = callback;
|
||||
_taskQueue.push(task);
|
||||
|
||||
@@ -340,8 +340,8 @@ void LegacyThreadPool::setThread(int tid) {
|
||||
_abortFlags[tid]); // a copy of the shared ptr to the flag
|
||||
auto f = [this, tid, abortPtr /* a copy of the shared ptr to the abort */]() {
|
||||
std::atomic<bool> &abort = *abortPtr;
|
||||
Task task;
|
||||
bool isPop = _taskQueue.pop(task);
|
||||
Task task;
|
||||
bool isPop = _taskQueue.pop(task);
|
||||
while (true) {
|
||||
while (isPop) { // if there is anything in the queue
|
||||
std::unique_ptr<std::function<void(int)>> func(
|
||||
|
||||
@@ -143,7 +143,7 @@ private:
|
||||
|
||||
void stretchPool(int count);
|
||||
|
||||
ccstd::vector<std::unique_ptr<std::thread>> _threads;
|
||||
ccstd::vector<std::unique_ptr<std::thread>> _threads;
|
||||
ccstd::vector<std::shared_ptr<std::atomic<bool>>> _abortFlags;
|
||||
ccstd::vector<std::shared_ptr<std::atomic<bool>>> _idleFlags;
|
||||
ccstd::vector<std::shared_ptr<std::atomic<bool>>> _initedFlags;
|
||||
@@ -168,39 +168,39 @@ private:
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
auto thiz = const_cast<ThreadSafeQueue *>(this);
|
||||
auto thiz = const_cast<ThreadSafeQueue *>(this);
|
||||
std::unique_lock<std::mutex> lock(thiz->mutex);
|
||||
return this->q.empty();
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
auto thiz = const_cast<ThreadSafeQueue *>(this);
|
||||
auto thiz = const_cast<ThreadSafeQueue *>(this);
|
||||
std::unique_lock<std::mutex> lock(thiz->mutex);
|
||||
return this->q.size();
|
||||
}
|
||||
|
||||
private:
|
||||
ccstd::queue<T> q;
|
||||
std::mutex mutex;
|
||||
std::mutex mutex;
|
||||
};
|
||||
|
||||
struct Task {
|
||||
TaskType type;
|
||||
TaskType type;
|
||||
std::function<void(int)> *callback;
|
||||
};
|
||||
|
||||
static LegacyThreadPool *_instance;
|
||||
|
||||
ThreadSafeQueue<Task> _taskQueue;
|
||||
std::atomic<bool> _isDone{false};
|
||||
std::atomic<bool> _isStop{false};
|
||||
std::atomic<bool> _isDone{false};
|
||||
std::atomic<bool> _isStop{false};
|
||||
|
||||
//IDEA: std::atomic<int> isn't supported by ndk-r10e while compiling with `armeabi` arch.
|
||||
// So using a mutex here instead.
|
||||
int _idleThreadNum{0}; // how many threads are waiting
|
||||
int _idleThreadNum{0}; // how many threads are waiting
|
||||
std::mutex _idleThreadNumMutex;
|
||||
|
||||
std::mutex _mutex;
|
||||
std::mutex _mutex;
|
||||
std::condition_variable _cv;
|
||||
|
||||
int _minThreadNum{0};
|
||||
@@ -208,10 +208,10 @@ private:
|
||||
int _initedThreadNum{0};
|
||||
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> _lastShrinkTime;
|
||||
float _shrinkInterval{5};
|
||||
int _shrinkStep{2};
|
||||
int _stretchStep{2};
|
||||
bool _isFixedSize{false};
|
||||
float _shrinkInterval{5};
|
||||
int _shrinkStep{2};
|
||||
int _stretchStep{2};
|
||||
bool _isFixedSize{false};
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -40,7 +40,7 @@ void Timer::reset() {
|
||||
|
||||
int64_t Timer::getMicroseconds() const {
|
||||
auto currentTime = Clock::now();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - _startTime).count();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - _startTime).count();
|
||||
if (duration < 0) {
|
||||
duration = 0;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ int64_t Timer::getMicroseconds() const {
|
||||
|
||||
int64_t Timer::getMilliseconds() const {
|
||||
auto currentTime = Clock::now();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - _startTime).count();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - _startTime).count();
|
||||
if (duration < 0) {
|
||||
duration = 0;
|
||||
}
|
||||
|
||||
@@ -34,15 +34,15 @@ namespace utils {
|
||||
|
||||
class CC_DLL Timer {
|
||||
public:
|
||||
using Clock = std::chrono::high_resolution_clock;
|
||||
using Clock = std::chrono::high_resolution_clock;
|
||||
using TimePoint = Clock::time_point;
|
||||
|
||||
explicit Timer(bool doReset = true);
|
||||
|
||||
void reset();
|
||||
void reset();
|
||||
int64_t getMicroseconds() const;
|
||||
int64_t getMilliseconds() const;
|
||||
float getSeconds(bool highPrecision = false) const;
|
||||
float getSeconds(bool highPrecision = false) const;
|
||||
|
||||
private:
|
||||
TimePoint _startTime;
|
||||
|
||||
+35
-35
@@ -29,7 +29,7 @@
|
||||
#include "base/Macros.h"
|
||||
#include "base/std/container/unordered_map.h"
|
||||
|
||||
using uint = std::uint32_t;
|
||||
using uint = std::uint32_t;
|
||||
using ushort = std::uint16_t;
|
||||
|
||||
#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX) // linux has typedef ulong
|
||||
@@ -45,38 +45,38 @@ using index_t = int32_t;
|
||||
#define CC_ENUM_CONVERSION_OPERATOR(T) \
|
||||
inline std::underlying_type<T>::type toNumber(const T v) { return static_cast<std::underlying_type<T>::type>(v); }
|
||||
|
||||
#define CC_ENUM_BITWISE_OPERATORS(T) \
|
||||
inline bool operator!(const T v) { return !static_cast<std::underlying_type<T>::type>(v); } \
|
||||
inline T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type<T>::type>(v)); } \
|
||||
inline bool operator||(const T lhs, const T rhs) { return (static_cast<std::underlying_type<T>::type>(lhs) || static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline bool operator&&(const T lhs, const T rhs) { return (static_cast<std::underlying_type<T>::type>(lhs) && static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator|(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) | static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator&(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) & static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator^(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) ^ static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator+(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) + static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) + rhs); } \
|
||||
inline void operator|=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) | static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline void operator&=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) & static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline void operator^=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) ^ static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline bool hasFlag(const T flags, const T flagToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
|
||||
} \
|
||||
inline bool hasAnyFlags(const T flags, const T flagsToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
|
||||
} \
|
||||
inline bool hasAllFlags(const T flags, const T flagsToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
|
||||
} \
|
||||
inline T addFlags(T &flags, const T flagsToAdd) { \
|
||||
flags |= flagsToAdd; \
|
||||
return flags; \
|
||||
} \
|
||||
inline T removeFlags(T &flags, const T flagsToRemove) { \
|
||||
flags &= ~flagsToRemove; \
|
||||
return flags; \
|
||||
} \
|
||||
#define CC_ENUM_BITWISE_OPERATORS(T) \
|
||||
inline bool operator!(const T v) { return !static_cast<std::underlying_type<T>::type>(v); } \
|
||||
inline T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type<T>::type>(v)); } \
|
||||
inline bool operator||(const T lhs, const T rhs) { return (static_cast<std::underlying_type<T>::type>(lhs) || static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline bool operator&&(const T lhs, const T rhs) { return (static_cast<std::underlying_type<T>::type>(lhs) && static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator|(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) | static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator&(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) & static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator^(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) ^ static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator+(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) + static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) + rhs); } \
|
||||
inline void operator|=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) | static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline void operator&=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) & static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline void operator^=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type<T>::type>(lhs) ^ static_cast<std::underlying_type<T>::type>(rhs)); } \
|
||||
inline bool hasFlag(const T flags, const T flagToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
|
||||
} \
|
||||
inline bool hasAnyFlags(const T flags, const T flagsToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
|
||||
} \
|
||||
inline bool hasAllFlags(const T flags, const T flagsToTest) { \
|
||||
using ValueType = std::underlying_type<T>::type; \
|
||||
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
|
||||
} \
|
||||
inline T addFlags(T &flags, const T flagsToAdd) { \
|
||||
flags |= flagsToAdd; \
|
||||
return flags; \
|
||||
} \
|
||||
inline T removeFlags(T &flags, const T flagsToRemove) { \
|
||||
flags &= ~flagsToRemove; \
|
||||
return flags; \
|
||||
} \
|
||||
CC_ENUM_CONVERSION_OPERATOR(T)
|
||||
|
||||
+10
-10
@@ -174,7 +174,7 @@ bool utfConvert(
|
||||
constexpr int mostBytesPerCharacter = 4;
|
||||
|
||||
const size_t maxNumberOfChars = from.length(); // all UTFs at most one element represents one character.
|
||||
const size_t numberOfOut = maxNumberOfChars * mostBytesPerCharacter / sizeof(To);
|
||||
const size_t numberOfOut = maxNumberOfChars * mostBytesPerCharacter / sizeof(To);
|
||||
|
||||
std::basic_string<To> working(numberOfOut, 0);
|
||||
|
||||
@@ -183,7 +183,7 @@ bool utfConvert(
|
||||
|
||||
auto outbeg = reinterpret_cast<typename ToTrait::ArgType *>(&working[0]);
|
||||
auto outend = outbeg + working.length();
|
||||
auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion);
|
||||
auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion);
|
||||
if (r != conversionOK) {
|
||||
return false;
|
||||
}
|
||||
@@ -195,9 +195,9 @@ bool utfConvert(
|
||||
};
|
||||
|
||||
CC_DLL void UTF8LooseFix(const ccstd::string &in, ccstd::string &out) { //NOLINT
|
||||
const auto *p = reinterpret_cast<const UTF8 *>(in.c_str());
|
||||
const auto *end = reinterpret_cast<const UTF8 *>(in.c_str() + in.size());
|
||||
unsigned ucharLen = 0;
|
||||
const auto *p = reinterpret_cast<const UTF8 *>(in.c_str());
|
||||
const auto *end = reinterpret_cast<const UTF8 *>(in.c_str() + in.size());
|
||||
unsigned ucharLen = 0;
|
||||
while (p < end) {
|
||||
ucharLen = getNumBytesForUTF8(*p);
|
||||
if (isLegalUTF8Sequence(p, p + ucharLen)) {
|
||||
@@ -237,11 +237,11 @@ bool UTF32ToUTF16(const std::u32string &utf32, std::u16string &outUtf16) { //NOL
|
||||
|
||||
#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS)
|
||||
ccstd::string getStringUTFCharsJNI(JNIEnv *env, jstring srcjStr, bool *ret) {
|
||||
ccstd::string utf8Str;
|
||||
auto * unicodeChar = static_cast<const uint16_t *>(env->GetStringChars(srcjStr, nullptr));
|
||||
size_t unicodeCharLength = env->GetStringLength(srcjStr);
|
||||
ccstd::string utf8Str;
|
||||
auto *unicodeChar = static_cast<const uint16_t *>(env->GetStringChars(srcjStr, nullptr));
|
||||
size_t unicodeCharLength = env->GetStringLength(srcjStr);
|
||||
const std::u16string unicodeStr(reinterpret_cast<const char16_t *>(unicodeChar), unicodeCharLength);
|
||||
bool flag = UTF16ToUTF8(unicodeStr, utf8Str);
|
||||
bool flag = UTF16ToUTF8(unicodeStr, utf8Str);
|
||||
|
||||
if (ret) {
|
||||
*ret = flag;
|
||||
@@ -256,7 +256,7 @@ ccstd::string getStringUTFCharsJNI(JNIEnv *env, jstring srcjStr, bool *ret) {
|
||||
|
||||
jstring newStringUTFJNI(JNIEnv *env, const ccstd::string &utf8Str, bool *ret) {
|
||||
std::u16string utf16Str;
|
||||
bool flag = cc::StringUtils::UTF8ToUTF16(utf8Str, utf16Str);
|
||||
bool flag = cc::StringUtils::UTF8ToUTF16(utf8Str, utf16Str);
|
||||
|
||||
if (ret) {
|
||||
*ret = flag;
|
||||
|
||||
@@ -189,7 +189,7 @@ class CC_DLL StringUTF8 {
|
||||
public:
|
||||
struct CharUTF8 {
|
||||
ccstd::string _char;
|
||||
bool isAnsi() { return _char.size() == 1; }
|
||||
bool isAnsi() { return _char.size() == 1; }
|
||||
};
|
||||
using CharUTF8Store = ccstd::vector<CharUTF8>;
|
||||
|
||||
@@ -198,7 +198,7 @@ public:
|
||||
~StringUTF8() = default;
|
||||
|
||||
std::size_t length() const;
|
||||
void replace(const ccstd::string &newStr);
|
||||
void replace(const ccstd::string &newStr);
|
||||
|
||||
ccstd::string getAsCharSequence() const;
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user