playground-sdk/audio/cadi_bank.cpp

232 lines
10 KiB
C++

#include "audio/cadi_bank.h"
#include <algorithm>
#include <charconv>
#include <cstring>
#include <limits>
#include <unordered_set>
namespace playground {
namespace {
uint32_t le32(const Bytes& bytes, size_t offset) {
return uint32_t(bytes[offset]) | (uint32_t(bytes[offset+1]) << 8) |
(uint32_t(bytes[offset+2]) << 16) | (uint32_t(bytes[offset+3]) << 24);
}
bool fail(std::string* error, const char* message) {
if (error) *error = message;
return false;
}
uint64_t le64(std::span<const uint8_t> bytes, size_t pos) {
uint64_t value=0;
for(int i=0;i<8;++i) value|=uint64_t(bytes[pos+i])<<(8*i);
return value;
}
std::optional<uint64_t> oggFrames(std::span<const uint8_t> bytes) {
size_t pos=0;uint64_t last=0;bool found=false;
while(pos<bytes.size()) {
if(bytes.size()-pos<27 || std::memcmp(bytes.data()+pos,"OggS",4)!=0 || bytes[pos+4]!=0)
return std::nullopt;
const size_t segments=bytes[pos+26];
if(bytes.size()-pos<27+segments)return std::nullopt;
size_t payload=0;
for(size_t i=0;i<segments;++i)payload+=bytes[pos+27+i];
if(payload>bytes.size()-pos-27-segments)return std::nullopt;
const uint64_t granule=le64(bytes,pos+6);
if(granule!=UINT64_MAX){last=granule;found=true;}
pos+=27+segments+payload;
}
return found?std::optional<uint64_t>(last):std::nullopt;
}
std::string_view firstTag(std::string_view xml,std::string_view name) {
const std::string open="<"+std::string(name)+">";
const std::string close="</"+std::string(name)+">";
const size_t start=xml.find(open);
if(start==std::string_view::npos)return {};
const size_t content=start+open.size(),end=xml.find(close,content);
return end==std::string_view::npos?std::string_view{}:xml.substr(content,end-content);
}
std::vector<std::string> allTags(std::string_view xml,std::string_view name,size_t limit=128) {
std::vector<std::string> values;
const std::string open="<"+std::string(name)+">";
const std::string close="</"+std::string(name)+">";
size_t pos=0;
while(values.size()<limit) {
const size_t start=xml.find(open,pos);
if(start==std::string_view::npos)break;
const size_t content=start+open.size(),end=xml.find(close,content);
if(end==std::string_view::npos)break;
values.emplace_back(xml.substr(content,end-content));pos=end+close.size();
}
return values;
}
struct GraphNode {
std::string type;
std::string parent;
bool loop = false;
std::vector<std::string> links;
std::optional<uint64_t> frames;
std::string url;
};
std::unordered_map<std::string,CadiEventInfo> mapEvents(const Bytes& bytes,
const std::vector<CadiRecord>& records) {
std::string_view project;
std::string_view resourceIndex;
size_t resourceIndexRecord=records.size();
for(size_t i=0;i<records.size();++i) {
const auto& r=records[i];
const std::span<const uint8_t> payload(bytes.data()+r.offset,r.size);
if(r.kind!=CadiKind::Xml)continue;
if(r.size>=5 && std::memcmp(payload.data(),"<?xml",5)==0) {
project={reinterpret_cast<const char*>(payload.data()),payload.size()};
} else if(r.size>=4 && std::memcmp(payload.data(),"\r\n<P",4)==0) {
resourceIndex={reinterpret_cast<const char*>(payload.data()),payload.size()};
resourceIndexRecord=i;
}
}
const auto keys=allTags(resourceIndex,"Key",10000);
if(project.empty() || resourceIndexRecord==records.size() || keys.size()!=records.size()-1)return {};
std::unordered_map<std::string,size_t> byUrl;
size_t recordIndex=0;
for(const auto& key:keys) {
if(recordIndex==resourceIndexRecord)++recordIndex;
if(recordIndex>=records.size() || !byUrl.emplace(key,recordIndex).second)return {};
++recordIndex;
}
std::unordered_map<std::string,GraphNode> nodes;
size_t pos=0;
while(!project.empty() && nodes.size()<5000) {
const size_t start=project.find("<PropertySet>",pos);
if(start==std::string_view::npos)break;
const size_t end=project.find("</PropertySet>",start+13);
if(end==std::string_view::npos)break;
const auto block=project.substr(start,end+14-start);
const auto name=firstTag(block,"Name"),type=firstTag(block,"PlayerType");
if(!name.empty() && name.size()<=512 && !type.empty()) {
GraphNode node;
node.type=type;
node.parent=firstTag(block,"Parent");
node.loop=firstTag(block,"ResourceLoopEnabled")=="true";
node.links=allTags(block,"ChildName");
const auto soundList=firstTag(block,"SoundList");
auto soundLinks=allTags(soundList,"String");
node.links.insert(node.links.end(),soundLinks.begin(),soundLinks.end());
if(auto resource=firstTag(block,"ResourceName");!resource.empty())
node.links.emplace_back(resource);
if(auto url=firstTag(block,"Url");!url.empty())node.url=url;
if(auto duration=firstTag(block,"ResourceEndPosition");!duration.empty()) {
uint64_t value=0;
const auto parsed=std::from_chars(duration.data(),duration.data()+duration.size(),value);
if(parsed.ec==std::errc{} && parsed.ptr==duration.data()+duration.size())node.frames=value;
}
nodes.emplace(name,std::move(node));
}
pos=end+14;
}
size_t verified=0;
for(const auto& [name,node]:nodes) {
if(node.type!="SampleResource" || node.url.empty() || !node.frames)continue;
const auto found=byUrl.find(node.url);
if(found==byUrl.end())continue;
const size_t index=found->second;
if(records[index].kind!=CadiKind::OggVorbis)continue;
const auto& rec=records[index];
const auto frames=oggFrames({bytes.data()+rec.offset,rec.size});
if(!frames || *frames!=*node.frames)return {};
++verified;
}
if(verified!=175)return {};
std::unordered_map<std::string,CadiEventInfo> mapped;
for(const auto& [event,root]:nodes) {
if(root.type!="MixerChannel" && root.type!="ArrangementClip" && root.type!="EventClip")continue;
std::vector<std::string> pending{event};
std::unordered_set<std::string> visited;
std::unordered_set<size_t> clips;
bool ambiguous=false;
while(!pending.empty() && visited.size()<5000) {
auto name=std::move(pending.back());pending.pop_back();
if(!visited.insert(name).second)continue;
auto found=nodes.find(name);
if(found==nodes.end())continue;
const auto& node=found->second;
if(node.type=="SampleResource") {
const auto clip=byUrl.find(node.url);
if(clip==byUrl.end() || records[clip->second].kind!=CadiKind::OggVorbis)
ambiguous=true;
else clips.insert(clip->second);
} else pending.insert(pending.end(),node.links.begin(),node.links.end());
}
if(!ambiguous && !clips.empty()) {
std::vector<size_t> ordered(clips.begin(),clips.end());
std::sort(ordered.begin(),ordered.end());
CadiEventInfo info;
info.clips=std::move(ordered);
info.loop=root.loop;
info.channel=root.type=="ArrangementClip"?CadiChannel::Music:
root.parent=="New Mixer 3"?CadiChannel::Environment:CadiChannel::Sfx;
mapped.emplace(event,std::move(info));
}
}
return mapped;
}
}
bool CadiBank::load(Bytes bytes, std::string* error) {
constexpr size_t maxBankBytes = 256 * 1024 * 1024;
if (bytes.size() < 32 || bytes.size() > maxBankBytes || le32(bytes, 8) != 0xddfefdc8u)
return fail(error, "invalid CADI bank header");
const uint32_t count = le32(bytes, 12);
if (count == 0 || count > 10000 || size_t(count) > (bytes.size()-32)/16)
return fail(error, "invalid CADI record count");
const size_t tableEnd = 32 + size_t(count) * 16;
size_t expectedOffset = tableEnd;
uint32_t previousToken = 0;
std::vector<CadiRecord> found;
found.reserve(count);
for (uint32_t i=0; i<count; ++i) {
const size_t pos = 32 + size_t(i)*16;
const uint32_t token = le32(bytes, pos);
const uint32_t reserved = le32(bytes, pos+4);
const uint32_t size = le32(bytes, pos+8);
const uint32_t offset = le32(bytes, pos+12);
if (reserved != 0 || token <= previousToken || size < 4 || offset != expectedOffset ||
size_t(size) > bytes.size()-expectedOffset)
return fail(error, "invalid CADI record bounds");
CadiKind kind;
if (std::memcmp(bytes.data()+offset, "OggS", 4) == 0) kind = CadiKind::OggVorbis;
else if (std::memcmp(bytes.data()+offset, "<?xm", 4) == 0 ||
std::memcmp(bytes.data()+offset, "\r\n<P", 4) == 0) kind = CadiKind::Xml;
else return fail(error, "unknown CADI record payload");
found.push_back({token,offset,size,kind});
expectedOffset += size;
previousToken = token;
}
if (expectedOffset != bytes.size()) return fail(error, "trailing CADI data");
auto eventClips=mapEvents(bytes,found);
bytes_ = std::move(bytes);
records_ = std::move(found);
eventClips_ = std::move(eventClips);
return true;
}
std::optional<size_t> CadiBank::clipForEvent(std::string_view event) const {
auto found=eventClips_.find(std::string(event));
return found==eventClips_.end() || found->second.clips.size()!=1 ? std::nullopt :
std::optional<size_t>(found->second.clips.front());
}
std::vector<size_t> CadiBank::clipsForEvent(std::string_view event) const {
auto found=eventClips_.find(std::string(event));
return found==eventClips_.end()?std::vector<size_t>{}:found->second.clips;
}
std::optional<CadiEventInfo> CadiBank::eventInfo(std::string_view event) const {
auto found=eventClips_.find(std::string(event));
return found==eventClips_.end()?std::nullopt:std::optional<CadiEventInfo>(found->second);
}
std::span<const uint8_t> CadiBank::data(size_t index) const {
if (index >= records_.size()) return {};
const auto& record = records_[index];
return {bytes_.data()+record.offset, record.size};
}
} // namespace playground