#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../src/capi/formats/taglib_lame.h" #include "../src/capi/taglib_mp4_atoms.h" #include "../src/capi/taglib_mp4_freeform.h" #include "../src/capi/taglib_id3_duplicate.h" #include "../src/capi/taglib_intpair.h" #include "../src/capi/taglib_asf_multi_value.h" #include "../src/capi/taglib_asf_properties.h" #include "../src/capi/taglib_mp4_advisory.h" #include "../src/capi/taglib_mp4_genre.h" #include "../src/capi/core/vector_stream.h" #include #include #include #include using namespace emscripten; using taglib_wasm::VectorStream; // Forward declarations class TagWrapper; class AudioPropertiesWrapper; // Wrapper classes for Tag and AudioProperties that ensure proper lifetime management class TagWrapper { private: TagLib::Tag* tag; public: TagWrapper() : tag(nullptr) {} TagWrapper(TagLib::Tag* t) : tag(t) {} std::string title() const { return tag ? tag->title().toCString(true) : ""; } std::string artist() const { return tag ? tag->artist().toCString(true) : ""; } std::string album() const { return tag ? tag->album().toCString(true) : ""; } std::string comment() const { return tag ? tag->comment().toCString(true) : ""; } std::string genre() const { return tag ? tag->genre().toCString(true) : ""; } unsigned int year() const { if (!tag) return 0; unsigned int y = tag->year(); if (y != 0) return y; TagLib::PropertyMap props = tag->properties(); // Raw ASF attributes (e.g. a lowercase "date" attribute) must be // visible here too — the WASI mirror reads the merged map, so // without this the two backends disagree on year (taglib-984r). taglib_wasm::merge_asf_unsupported_properties_into( dynamic_cast(tag), props); auto it = props.find("DATE"); if (it != props.end() && !it->second.isEmpty()) { y = it->second.front().toInt(); } return y; } unsigned int track() const { return tag ? tag->track() : 0; } void setTitle(const std::string& value) { if (tag) tag->setTitle(TagLib::String(value, TagLib::String::UTF8)); } void setArtist(const std::string& value) { if (tag) tag->setArtist(TagLib::String(value, TagLib::String::UTF8)); } void setAlbum(const std::string& value) { if (tag) tag->setAlbum(TagLib::String(value, TagLib::String::UTF8)); } void setComment(const std::string& value) { if (tag) tag->setComment(TagLib::String(value, TagLib::String::UTF8)); } void setGenre(const std::string& value) { if (tag) tag->setGenre(TagLib::String(value, TagLib::String::UTF8)); } void setYear(unsigned int value) { if (tag) tag->setYear(value); } void setTrack(unsigned int value) { if (tag) tag->setTrack(value); } }; class AudioPropertiesWrapper { private: TagLib::AudioProperties* props; TagLib::File* file; public: AudioPropertiesWrapper() : props(nullptr), file(nullptr) {} AudioPropertiesWrapper(TagLib::AudioProperties* p, TagLib::File* f) : props(p), file(f) {} int lengthInSeconds() const { return props ? props->lengthInSeconds() : 0; } int lengthInMilliseconds() const { return props ? props->lengthInMilliseconds() : 0; } int bitrate() const { return props ? props->bitrate() : 0; } int sampleRate() const { return props ? props->sampleRate() : 0; } int channels() const { return props ? props->channels() : 0; } // OpusHead output gain in dB (Opus only; 0.0 for any other format). // TagLib exposes the raw Q7.8 fixed-point value; dB = raw / 256.0. double outputGainDb() const { if (auto* opusProps = dynamic_cast(props)) { return static_cast(opusProps->outputGain()) / 256.0; } return 0.0; } int bitsPerSample() const { if (!props) return 0; // MP4/M4A files if (TagLib::MP4::Properties* mp4Props = dynamic_cast(props)) { return mp4Props->bitsPerSample(); } // FLAC files else if (TagLib::FLAC::Properties* flacProps = dynamic_cast(props)) { return flacProps->bitsPerSample(); } // WAV files else if (TagLib::RIFF::WAV::Properties* wavProps = dynamic_cast(props)) { return wavProps->bitsPerSample(); } // AIFF files else if (TagLib::RIFF::AIFF::Properties* aiffProps = dynamic_cast(props)) { return aiffProps->bitsPerSample(); } // WavPack files else if (TagLib::WavPack::Properties* wvProps = dynamic_cast(props)) { return wvProps->bitsPerSample(); } // TrueAudio files else if (TagLib::TrueAudio::Properties* ttaProps = dynamic_cast(props)) { return ttaProps->bitsPerSample(); } // ASF/WMA files else if (TagLib::ASF::Properties* asfProps = dynamic_cast(props)) { return asfProps->bitsPerSample(); } // Matroska files else if (TagLib::Matroska::Properties* mkProps = dynamic_cast(props)) { return mkProps->bitsPerSample(); } return 0; } std::string codec() const { if (!props || !file) return "unknown"; // MP4/M4A files if (TagLib::MP4::Properties* mp4Props = dynamic_cast(props)) { // TagLib 2.3.2 detects AC-3/E-AC-3/FLAC/DTS/Opus sample entries in // MP4 (previously all non-ALAC tracks read as AAC). Twin of the // switch in src/capi/taglib_audio_props.cpp — keep in sync. switch (mp4Props->codec()) { case TagLib::MP4::Properties::AAC: return "AAC"; case TagLib::MP4::Properties::ALAC: return "ALAC"; case TagLib::MP4::Properties::AC3: return "AC-3"; case TagLib::MP4::Properties::EAC3: return "E-AC-3"; case TagLib::MP4::Properties::FLAC: return "FLAC"; case TagLib::MP4::Properties::DTS: return "DTS"; case TagLib::MP4::Properties::Opus: return "Opus"; default: return "unknown"; } } // MP3 files. ADTS (raw .aac) is parsed by MPEG::File too, so the codec // comes from the stream header, not the file class (taglib-v4n). else if (dynamic_cast(file)) { if (TagLib::MPEG::Properties* mpegProps = dynamic_cast(props)) { if (mpegProps->isADTS()) return "AAC"; } return "MP3"; } // FLAC files else if (dynamic_cast(file)) { return "FLAC"; } // OGG Vorbis files else if (dynamic_cast(file)) { return "Vorbis"; } // OGG Opus files else if (dynamic_cast(file)) { return "Opus"; } // OGG FLAC / Speex: twin of the WASI shim's Ogg branches // (src/capi/taglib_audio_props.cpp) — keep both backends in sync. else if (dynamic_cast(file)) { return "FLAC"; } else if (dynamic_cast(file)) { return "Speex"; } // WAV files else if (TagLib::RIFF::WAV::File* wavFile = dynamic_cast(file)) { // WAV can contain various codecs, but we'll report PCM for uncompressed if (TagLib::RIFF::WAV::Properties* wavProps = dynamic_cast(props)) { unsigned int format = wavProps->format(); if (format == 1) return "PCM"; else if (format == 3) return "IEEEFloat"; else return "WAV"; } return "WAV"; } // AIFF files else if (dynamic_cast(file)) { return "PCM"; // AIFF is typically uncompressed PCM } // WavPack files else if (dynamic_cast(file)) { return "WavPack"; } // TrueAudio files else if (dynamic_cast(file)) { return "TTA"; } // ASF/WMA files else if (dynamic_cast(file)) { return "WMA"; } // Matroska files - report codec name from container else if (auto* mkFile = dynamic_cast(file)) { auto* mkProps = dynamic_cast(mkFile->audioProperties()); if (mkProps) { TagLib::String cn = mkProps->codecName(); if (!cn.isEmpty()) { std::string name = cn.to8Bit(true); if (name.find("OPUS") != std::string::npos) return "Opus"; if (name.find("VORBIS") != std::string::npos) return "Vorbis"; if (name.find("FLAC") != std::string::npos) return "FLAC"; if (name.find("PCM") != std::string::npos) return "PCM"; if (name.find("TRUEHD") != std::string::npos) return "TrueHD"; if (name.find("AAC") != std::string::npos) return "AAC"; if (name.find("MPEG") != std::string::npos) return "MP3"; } } return "unknown"; } return "unknown"; } bool isLossless() const { std::string codecName = codec(); // Lossless codecs if (codecName == "ALAC" || // Apple Lossless codecName == "FLAC" || // Free Lossless Audio Codec codecName == "PCM" || // Uncompressed PCM (WAV/AIFF) codecName == "IEEEFloat" || // Uncompressed floating point codecName == "WavPack" || // WavPack lossless codecName == "TTA") { // TrueAudio lossless return true; } // Lossy codecs if (codecName == "AAC" || // Advanced Audio Coding codecName == "MP3" || // MPEG Layer 3 codecName == "Vorbis" || // Ogg Vorbis codecName == "Opus") { // Opus return false; } // Unknown codec - assume lossy return false; } int mpegVersion() const { if (!props) return 0; if (auto* mpegProps = dynamic_cast(props)) { return mpegProps->version() == TagLib::MPEG::Header::Version1 ? 1 : 2; } return 0; } int mpegLayer() const { if (!props) return 0; if (auto* mpegProps = dynamic_cast(props)) { return mpegProps->layer(); } return 0; } std::string bitrateMode() const { if (!props || !file) return ""; auto* mpegFile = dynamic_cast(file); auto* mpegProps = dynamic_cast(props); if (!mpegFile || !mpegProps) return ""; long firstFrame = mpegFile->firstFrameOffset(); if (firstFrame < 0) return ""; mpegFile->seek(firstFrame); TagLib::ByteVector frameBytes = mpegFile->readBlock(taglib_wasm::kRequiredFirstFrameBytes); int rawVersion = static_cast(mpegProps->version()); int rawChannelMode = static_cast(mpegProps->channelMode()); auto lame = taglib_wasm::parseLameInfo( reinterpret_cast(frameBytes.data()), static_cast(frameBytes.size()), rawVersion, rawChannelMode); if (lame.valid && lame.mode != taglib_wasm::BitrateMode::Unknown) { const char* str = taglib_wasm::modeString(lame.mode); return str ? std::string(str) : std::string(); } return ""; } bool isEncrypted() const { if (!props) return false; if (auto* mp4Props = dynamic_cast(props)) { return mp4Props->isEncrypted(); } if (auto* asfProps = dynamic_cast(props)) { return asfProps->isEncrypted(); } return false; } int formatVersion() const { if (!props) return 0; if (auto* apeProps = dynamic_cast(props)) { return apeProps->version(); } if (auto* wvProps = dynamic_cast(props)) { return wvProps->version(); } if (auto* ttaProps = dynamic_cast(props)) { return ttaProps->ttaVersion(); } if (auto* mpcProps = dynamic_cast(props)) { return mpcProps->mpcVersion(); } if (auto* shnProps = dynamic_cast(props)) { return shnProps->shortenVersion(); } return 0; } std::string containerFormat() const { if (!file) return "unknown"; // Detect container format based on file type if (TagLib::MPEG::File* mpegFile = dynamic_cast(file)) { // ADTS (raw .aac) rides in MPEG::File but is its own container. if (TagLib::MPEG::Properties* mpegProps = dynamic_cast(mpegFile->audioProperties())) { if (mpegProps->isADTS()) return "ADTS"; } return "MP3"; } else if (dynamic_cast(file)) { return "MP4"; // Includes .m4a files (ISO Base Media File Format) } else if (dynamic_cast(file)) { return "FLAC"; } else if (dynamic_cast(file) || dynamic_cast(file) || dynamic_cast(file) || dynamic_cast(file)) { return "OGG"; } else if (dynamic_cast(file)) { return "WAV"; } else if (dynamic_cast(file)) { return "AIFF"; } else if (dynamic_cast(file)) { return "WavPack"; } else if (dynamic_cast(file)) { return "TTA"; } else if (dynamic_cast(file)) { return "ASF"; } else if (dynamic_cast(file)) { return "Matroska"; } return "unknown"; } }; // Picture wrapper class for managing album art/cover images class PictureWrapper { public: std::string mimeType; val data; int type; std::string description; PictureWrapper() : type(3) {} // Default to FrontCover PictureWrapper(const std::string& mime, const val& imgData, int picType, const std::string& desc) : mimeType(mime), data(imgData), type(picType), description(desc) {} }; // taglib-b67: MPEG::File::save()'s default Duplicate mode synchronizes // ID3v1<->ID3v2 through TagLib::Tag's typed getters/setters (title(), // artist(), ...), not through raw frame bytes. Each of these getters reads // exactly one ID3v2 frame ID (see id3v2tag.cpp title()/artist()/album()/ // comment()/genre()/year()/track()). If a raw UnknownFrame is written to one // of these IDs, the typed getter can't decode it and reads back "" — and if // the paired ID3v1 field is also empty, the sync calls setTitle("") (etc.), // which ID3v2::Tag::setTextFrame() treats as "delete this frame" instead of // leaving the raw bytes alone. A raw write to any OTHER frame ID (PRIV, // RGAD, SYTC, ...) is invisible to Tag's typed interface and can never // trigger this, so only these IDs need the DoNotDuplicate escape hatch. static const std::set ID3V1_MAPPED_FRAME_IDS = { "TIT2", "TPE1", "TALB", "COMM", "TCON", "TDRC", "TRCK", }; // Typed MP4 freeform values cross Embind as raw bytes (taglib-gja). static val mp4_freeform_bytes_to_val(const std::string& bytes) { if (bytes.empty()) return val::global("Uint8Array").new_(0); val view = val(emscripten::typed_memory_view( bytes.size(), reinterpret_cast(bytes.data()))); return view.call("slice"); } static std::string mp4_freeform_val_to_bytes(const val& value) { if (value.isUndefined() || value.isNull()) return {}; std::vector bytes = emscripten::convertJSArrayToNumberVector( val::global("Uint8Array").call("from", value)); return std::string(reinterpret_cast(bytes.data()), bytes.size()); } // Helper class to manage stream lifetime class FileHandle { private: std::unique_ptr stream; // taglib-f5hp: fileRef is the SOLE owner of the TagLib::File. There is // deliberately no `std::unique_ptr file` member beside it: // TagLib::FileRef(File*) takes ownership (fileref.h:208-212) and its private // destructor is `delete file`, so a second owning pointer double-frees the // File on teardown. That corrupted the allocator, which aborts as a Wasm // `unreachable` -- uncatchable, and deferred all the way to dispose(). std::unique_ptr fileRef; // taglib-b67: frame IDs (from ID3V1_MAPPED_FRAME_IDS) currently holding a // raw-written (UnknownFrame) value on this handle. Non-empty => save() // must skip MPEG::File's default Duplicate sync (see comment above) to // avoid it clobbering these frames; cleared per-ID once no raw frame // remains under that ID, so unrelated raw writes (PRIV, RGAD, ...) and // fully-removed raw writes don't disable normal ID3v1/ID3v2 sync. std::set rawMappedFrameIds; public: FileHandle() = default; bool loadFromBuffer(const val& jsBuffer) { try { unsigned int length = jsBuffer["length"].as(); if (length == 0) return false; // Allocate a temporary buffer and bulk-copy JS data via // typed_memory_view, then move it into VectorStream. std::vector buf(length, '\0'); val memoryView = val(emscripten::typed_memory_view( length, reinterpret_cast(buf.data()))); memoryView.call("set", jsBuffer); // Sniffed while `buf` still owns its bytes: VectorStream takes // ownership of the storage below, and the tracker signatures need // most of the file (S3M's "SCRM" sits at 44, MOD's tag at 1080), so // a fixed 12-byte header is not enough to see them. const std::string format = detectFormat(buf.data(), buf.size()); stream = std::make_unique(std::move(buf)); stream->seek(0, TagLib::IOStream::Beginning); // Try to create FileRef first fileRef = std::make_unique(stream.get()); if (!fileRef->isNull() && fileRef->file() && fileRef->file()->isValid()) { // MP4 genre precedence: the string ©gen beats a preceding gnre // (taglib-lna2). The in-memory tag is this backend's write // model, so resolving it at load fixes tag().genre, // properties(), getMP4Item("©gen") and save() at once. taglib_wasm::resolve_mp4_genre_precedence(fileRef->file()); return true; } // If FileRef failed, try specific file types based on format detection. // Owned locally only until FileRef takes over below — see the // taglib-f5hp note on the member declarations. // // The tracker modules are reachable ONLY here: this stream has no // name, so FileRef's extension route cannot fire, and upstream // FileRef::detectByContent has no TAGLIB_WITH_MOD branch (nor does // Mod/S3M/IT/XM expose isSupported()), so content detection can // never resolve them (taglib-uat8). Twin of the WASI shim, which // sniffs and constructs them in src/capi/taglib_boundary.c and // src/capi/taglib_shim_common.cpp. stream->seek(0, TagLib::IOStream::Beginning); std::unique_ptr detected; if (format == "mp3") { detected.reset(new TagLib::MPEG::File(stream.get())); } else if (format == "flac") { detected.reset(new TagLib::FLAC::File(stream.get())); } else if (format == "ogg") { detected.reset(new TagLib::Ogg::Vorbis::File(stream.get())); } else if (format == "mp4") { detected.reset(new TagLib::MP4::File(stream.get())); } else if (format == "wav") { detected.reset(new TagLib::RIFF::WAV::File(stream.get())); } else if (format == "aiff") { detected.reset(new TagLib::RIFF::AIFF::File(stream.get())); } else if (format == "matroska") { detected.reset(new TagLib::Matroska::File(stream.get())); } else if (format == "mod") { detected.reset(new TagLib::Mod::File(stream.get())); } else if (format == "s3m") { detected.reset(new TagLib::S3M::File(stream.get())); } else if (format == "it") { detected.reset(new TagLib::IT::File(stream.get())); } else if (format == "xm") { detected.reset(new TagLib::XM::File(stream.get())); } if (detected && detected->isValid()) { // release(), not get(): FileRef deletes what it is handed, so // letting `detected` keep ownership too would free it twice. fileRef = std::make_unique(detected.release()); taglib_wasm::resolve_mp4_genre_precedence(fileRef->file()); return !fileRef->isNull(); } return false; } catch (...) { return false; } } bool isValid() const { return fileRef && !fileRef->isNull(); } bool save() { if (!fileRef) return false; // ASF multi-value attributes are rotated by TagLib's render+parse // (ECDO/MLO split); right-rotate before render, restore after save // (taglib-ilrg). Inert for every other format. Twin of // save_preserving_id3() in src/capi/taglib_write.cpp. taglib_wasm::ASFMultiValueRotationGuard asfGuard(fileRef->file()); auto* mpegFile = dynamic_cast(fileRef->file()); if (!mpegFile) return fileRef->save(); // Two separate reasons to suppress MPEG::File's default Duplicate sync, // handled in this order because they are not interchangeable — see // save_preserving_id3() in src/capi/taglib_write.cpp, the WASI twin. bool skipTagLibDuplicate = !rawMappedFrameIds.empty(); // taglib-b67 if (!skipTagLibDuplicate && taglib_wasm::id3_duplicate_would_destroy(mpegFile)) { // taglib-9m0w: run the sync losslessly rather than skip it. taglib_wasm::duplicate_id3_tags_losslessly(mpegFile); skipTagLibDuplicate = true; } if (!skipTagLibDuplicate) return fileRef->save(); return mpegFile->save(TagLib::MPEG::File::AllTags, TagLib::File::StripOthers, TagLib::ID3v2::v4, TagLib::File::DoNotDuplicate); } TagWrapper getTag() { TagLib::Tag* t = fileRef ? fileRef->tag() : nullptr; return TagWrapper(t); } AudioPropertiesWrapper getAudioProperties() { TagLib::AudioProperties* p = fileRef ? fileRef->audioProperties() : nullptr; TagLib::File* f = fileRef ? fileRef->file() : nullptr; return AudioPropertiesWrapper(p, f); } TagLib::File* getFile() { return fileRef ? fileRef->file() : nullptr; } std::string getFormat() const { if (!fileRef || !fileRef->file()) return "unknown"; TagLib::File* f = fileRef->file(); if (TagLib::MPEG::File* mpegFile = dynamic_cast(f)) { // ADTS (raw .aac) shares MPEG::File; report the stream identity, // matching the WASI adapter's container-derived format (taglib-v4n). if (TagLib::MPEG::Properties* mpegProps = dynamic_cast(mpegFile->audioProperties())) { if (mpegProps->isADTS()) return "AAC"; } return "MP3"; } if (dynamic_cast(f)) return "MP4"; if (dynamic_cast(f)) return "FLAC"; if (dynamic_cast(f)) return "OGG"; if (dynamic_cast(f)) return "OPUS"; // FLAC-in-Ogg and Speex carry their own declared FileType members // (taglib-f6a3); Ogg Vorbis alone stays "OGG". Twin of the WASI // adapter's codec-derived mapping (audio-properties.ts). if (dynamic_cast(f)) return "OggFLAC"; if (dynamic_cast(f)) return "SPEEX"; if (dynamic_cast(f)) return "WAV"; if (dynamic_cast(f)) return "AIFF"; if (dynamic_cast(f)) return "WV"; if (dynamic_cast(f)) return "TTA"; if (dynamic_cast(f)) return "ASF"; // Twin of the WASI adapter's CONTAINER_TO_FORMAT table // (src/runtime/wasi-adapter/audio-properties.ts) — every container the // snapshot can name resolves to the same declared FileType on either // backend, "Shorten" -> "SHN" included (taglib-uat8). if (dynamic_cast(f)) return "APE"; if (dynamic_cast(f)) return "DSF"; if (dynamic_cast(f)) return "DSDIFF"; if (dynamic_cast(f)) return "MPC"; if (dynamic_cast(f)) return "SHN"; if (dynamic_cast(f)) return "MOD"; if (dynamic_cast(f)) return "S3M"; if (dynamic_cast(f)) return "IT"; if (dynamic_cast(f)) return "XM"; if (dynamic_cast(f)) return "MATROSKA"; return "unknown"; } val getProperties() const { val obj = val::object(); if (fileRef && fileRef->file()) { TagLib::PropertyMap properties = fileRef->file()->properties(); // See merge_id3v1_only_properties(): TagUnion reports ID3v2 alone, // so an ID3v1-only value would otherwise be invisible (taglib-nft5). taglib_wasm::merge_id3v1_only_properties(fileRef->file(), properties); taglib_wasm::merge_asf_unsupported_properties(fileRef->file(), properties); // MP4 content advisory: the rtng item is invisible to the // property map; surface it under ITUNESADVISORY (taglib-an30). taglib_wasm::merge_mp4_rtng_advisory(fileRef->file(), properties); for (const auto& prop : properties) { val array = val::array(); for (const auto& value : prop.second) { array.call("push", std::string(value.toCString(true))); } obj.set(std::string(prop.first.toCString(true)), array); } } return obj; } void setProperties(const val& properties) { if (!fileRef || !fileRef->file()) return; TagLib::PropertyMap propMap; // Iterate over JavaScript object properties val keys = val::global("Object").call("keys", properties); int length = keys["length"].as(); // Exact atom names JS is creating this save (taglib-bnhl). Reserved key, // never a property: a brand-new atom's casing cannot be captured from // the file, so the caller supplies it. std::vector mp4Names; for (int i = 0; i < length; i++) { std::string key = keys[i].as(); val values = properties[key]; if (key == "_mp4ItemNames") { if (values.isArray()) { int n = values["length"].as(); for (int j = 0; j < n; j++) { mp4Names.push_back(values[j].as()); } } continue; } if (values.isArray()) { TagLib::StringList stringList; int valueCount = values["length"].as(); for (int j = 0; j < valueCount; j++) { stringList.append(TagLib::String(values[j].as(), TagLib::String::UTF8)); } propMap[TagLib::String(key, TagLib::String::UTF8)] = stringList; } } // Fold a caller's separate TRACKTOTAL/DISCTOTAL into the number field // for formats that store the pair in one atom/frame (MP4 trkn/disk, // ID3v2 TRCK/TPOS). The WASI shim does the same before its write; // without it TagLib stores the total in a non-standard freeform atom / // TXXX frame that ordinary players do not read. if (taglib_wasm::uses_intpair_format(fileRef->file())) { taglib_wasm::merge_intpair_properties(propMap); } // Snapshot the real freeform atom names off the file BEFORE the // PropertyMap write mangles their casing, add the ones JS is creating, // and repair afterwards (taglib-bnhl). auto captured = capture_mp4_freeform_names(fileRef->file()); for (auto& n : mp4Names) captured.push_back(std::move(n)); // The map carries ID3v1's merged comment (taglib-nft5), which must not // materialise as a second COMM frame (taglib-o3sl). Unlike the WASI // shim there are no typed mirrors after this write, so the withdrawal // can follow it directly. const auto commentGuard = taglib_wasm::capture_id3v2_comment_guard(fileRef->file()); // MP4 content advisory: apply to the native rtng item and hand // setProperties the effective map (taglib-an30). const TagLib::PropertyMap effective = taglib_wasm::normalize_advisory_write(fileRef->file(), propMap); // Capture AFTER normalize: an advisory clear removes its freeform atom // directly, and that removal must not be undone by the restore. auto freeformItems = taglib_wasm::capture_mp4_freeform_items(fileRef->file()); const TagLib::PropertyMap ignored = fileRef->file()->setProperties(effective); taglib_wasm::apply_asf_properties(fileRef->file(), effective, ignored); restore_mp4_freeform_names(fileRef->file(), captured); taglib_wasm::restore_mp4_freeform_items(fileRef->file(), freeformItems, effective); taglib_wasm::apply_id3v2_comment_guard(fileRef->file(), commentGuard); } std::string getProperty(const std::string& key) const { if (!fileRef || !fileRef->file()) return ""; TagLib::PropertyMap properties = fileRef->file()->properties(); taglib_wasm::merge_id3v1_only_properties(fileRef->file(), properties); taglib_wasm::merge_asf_unsupported_properties(fileRef->file(), properties); taglib_wasm::merge_mp4_rtng_advisory(fileRef->file(), properties); TagLib::String tagKey(key, TagLib::String::UTF8); if (properties.contains(tagKey) && !properties[tagKey].isEmpty()) { return std::string(properties[tagKey].front().toCString(true)); } return ""; } void setProperty(const std::string& key, const std::string& value) { if (!fileRef || !fileRef->file()) return; // Merge before the read-modify-write: without it this rewrites the map // WITHOUT any ID3v1-only value, and setProperties then drops it // (taglib-nft5). Every C++ site that round-trips the map needs this. TagLib::PropertyMap properties = fileRef->file()->properties(); taglib_wasm::merge_id3v1_only_properties(fileRef->file(), properties); taglib_wasm::merge_asf_unsupported_properties(fileRef->file(), properties); TagLib::StringList values; values.append(TagLib::String(value, TagLib::String::UTF8)); properties[TagLib::String(key, TagLib::String::UTF8)] = values; // Same fold as setProperties: a single TRACKTOTAL/DISCTOTAL write must // land inside trkn/disk (or TRCK/TPOS), not in a separate freeform // atom/frame. if (taglib_wasm::uses_intpair_format(fileRef->file())) { taglib_wasm::merge_intpair_properties(properties); } // See setProperties: capture before, restore after (taglib-bnhl), and // withdraw the merged-comment frame the write materialises (taglib-o3sl). auto captured = capture_mp4_freeform_names(fileRef->file()); const auto commentGuard = taglib_wasm::capture_id3v2_comment_guard(fileRef->file()); const TagLib::PropertyMap effective = taglib_wasm::normalize_advisory_write(fileRef->file(), properties); auto freeformItems = taglib_wasm::capture_mp4_freeform_items(fileRef->file()); // ASF: untranslated keys (merged above) return as ignoredProps and // must be written as real attributes, exactly like setProperties — // without this, setProperty on a WMA silently drops them (review // taglib-984r). const TagLib::PropertyMap ignored = fileRef->file()->setProperties(effective); taglib_wasm::apply_asf_properties(fileRef->file(), effective, ignored); restore_mp4_freeform_names(fileRef->file(), captured); taglib_wasm::restore_mp4_freeform_items(fileRef->file(), freeformItems, effective); taglib_wasm::apply_id3v2_comment_guard(fileRef->file(), commentGuard); } // MP4-specific methods bool isMP4() const { return fileRef && dynamic_cast(fileRef->file()) != nullptr; } std::string getMP4Item(const std::string& key) const { if (!fileRef || !fileRef->file()) return ""; TagLib::MP4::File* mp4File = dynamic_cast(fileRef->file()); if (!mp4File || !mp4File->tag()) return ""; TagLib::MP4::Tag* tag = mp4File->tag(); TagLib::String tagKey(key, TagLib::String::UTF8); if (tag->contains(tagKey)) { TagLib::MP4::Item item = tag->item(tagKey); if (item.isValid()) { if (item.type() == TagLib::MP4::Item::Type::Int) { return std::to_string(item.toInt()); } else if (item.type() == TagLib::MP4::Item::Type::StringList && !item.toStringList().isEmpty()) { return std::string(item.toStringList().front().toCString(true)); } else if (item.type() == TagLib::MP4::Item::Type::Bool) { return item.toBool() ? "true" : "false"; } else if (item.type() == TagLib::MP4::Item::Type::Byte) { return std::to_string(item.toByte()); } } } return ""; } void setMP4Item(const std::string& key, const std::string& value) { if (!fileRef || !fileRef->file()) return; TagLib::MP4::File* mp4File = dynamic_cast(fileRef->file()); if (!mp4File || !mp4File->tag()) return; TagLib::MP4::Tag* tag = mp4File->tag(); TagLib::String tagKey(key, TagLib::String::UTF8); // Try to parse as integer first char* endptr; long intValue = strtol(value.c_str(), &endptr, 10); if (*endptr == '\0') { // It's a valid integer tag->setItem(tagKey, TagLib::MP4::Item(static_cast(intValue))); } else { // Store as string tag->setItem(tagKey, TagLib::MP4::Item(TagLib::String(value, TagLib::String::UTF8))); } } void removeMP4Item(const std::string& key) { if (!fileRef || !fileRef->file()) return; TagLib::MP4::File* mp4File = dynamic_cast(fileRef->file()); if (!mp4File || !mp4File->tag()) return; TagLib::MP4::Tag* tag = mp4File->tag(); TagLib::String tagKey(key, TagLib::String::UTF8); if (tag->contains(tagKey)) { tag->removeItem(tagKey); } } // Typed freeform atoms (taglib-gja): values are raw bytes on the boundary; // the adapter converts them to/from string/number/Uint8Array by type. val getMP4FreeformItems() const { val items = val::array(); if (!fileRef || !fileRef->file()) return items; const auto entries = taglib_wasm::collect_mp4_freeform_entries(fileRef->file()); int index = 0; for (const auto& entry : entries) { val item = val::object(); item.set("mean", entry.mean); item.set("name", entry.name); item.set("type", entry.type); item.set("value", mp4_freeform_bytes_to_val(entry.value)); items.set(index++, item); } return items; } void setMP4FreeformItems(const val& items) { if (!fileRef || !fileRef->file()) return; std::vector entries; if (items.isArray()) { int count = items["length"].as(); for (int i = 0; i < count; i++) { val item = items[i]; taglib_wasm::MP4FreeformEntry entry; entry.mean = item["mean"].as(); entry.name = item["name"].as(); entry.type = item["type"].as(); entry.value = mp4_freeform_val_to_bytes(item["value"]); entries.push_back(std::move(entry)); } } taglib_wasm::apply_mp4_freeform_entries(fileRef->file(), entries); } private: // Signature sniffing over the caller's raw buffer. Takes a view rather than // a std::string so the deep signatures cost no copy — the tracker tags sit // at offset 44 (S3M) and 1080 (MOD), well past a 12-byte header read. std::string detectFormat(const char* d, size_t size) const { if (size < 12) return "unknown"; // MP3 - Look for ID3 header or MPEG sync if (size >= 3 && (memcmp(d, "ID3", 3) == 0 || (size >= 2 && (unsigned char)d[0] == 0xFF && ((unsigned char)d[1] & 0xE0) == 0xE0))) { return "mp3"; } // MP4/M4A - Look for ftyp box if (size >= 12 && memcmp(d + 4, "ftyp", 4) == 0) { return "mp4"; } // FLAC - Look for fLaC signature if (size >= 4 && memcmp(d, "fLaC", 4) == 0) { return "flac"; } // OGG - Look for OggS signature if (size >= 4 && memcmp(d, "OggS", 4) == 0) { return "ogg"; } // WAV - Look for RIFF header if (size >= 12 && memcmp(d, "RIFF", 4) == 0 && memcmp(d + 8, "WAVE", 4) == 0) { return "wav"; } // AIFF - Look for FORM header if (size >= 12 && memcmp(d, "FORM", 4) == 0 && memcmp(d + 8, "AIFF", 4) == 0) { return "aiff"; } // Matroska/WebM - EBML signature if (size >= 4 && (unsigned char)d[0] == 0x1A && (unsigned char)d[1] == 0x45 && (unsigned char)d[2] == 0xDF && (unsigned char)d[3] == 0xA3) { return "matroska"; } // Tracker modules. Byte-for-byte the same signatures the WASI shim's // sniffer uses (src/capi/taglib_boundary.c, detect_format_at) so both // backends accept the same files; order matters only for MOD, whose // 1080-byte offset is the deepest check (taglib-uat8). // IT (Impulse Tracker): "IMPM" if (size >= 4 && memcmp(d, "IMPM", 4) == 0) { return "it"; } // XM (Extended Module): "Extended Module: " header if (size >= 17 && memcmp(d, "Extended Module:", 16) == 0) { return "xm"; } // S3M (Scream Tracker 3): "SCRM" at offset 44 if (size >= 48 && memcmp(d + 44, "SCRM", 4) == 0) { return "s3m"; } // MOD (ProTracker): channel tag at offset 1080 if (size >= 1084) { const char* sig = d + 1080; if (memcmp(sig, "M.K.", 4) == 0 || memcmp(sig, "M!K!", 4) == 0 || memcmp(sig, "FLT4", 4) == 0 || memcmp(sig, "FLT8", 4) == 0 || memcmp(sig, "4CHN", 4) == 0 || memcmp(sig, "6CHN", 4) == 0 || memcmp(sig, "8CHN", 4) == 0) { return "mod"; } } return "unknown"; } // Convert a TagLib::ByteVector to a JavaScript Uint8Array using a single // native bulk copy via typed_memory_view instead of a byte-by-byte loop. // typed_memory_view(n, ptr) creates a Uint8Array view backed by WASM memory; // passing it to new Uint8Array(...) performs a single native copy into JS. static val byteVectorToUint8Array(const TagLib::ByteVector& bv) { if (bv.isEmpty()) return val::global("Uint8Array").new_(0); auto view = emscripten::typed_memory_view( bv.size(), reinterpret_cast(bv.data())); return val::global("Uint8Array").new_(view); } // Copy a JavaScript Uint8Array into a TagLib::ByteVector using a single // native bulk copy. convertJSArrayToNumberVector uses typed_memory_view + // _emval_array_to_memory_view (dst.set(src)) internally — one native call. // NOTE: vecFromJSArray must NOT be used here; it loops byte-by-byte. static TagLib::ByteVector uint8ArrayToByteVector(const val& jsArray) { const auto vec = emscripten::convertJSArrayToNumberVector(jsArray); if (vec.empty()) return TagLib::ByteVector(); return TagLib::ByteVector(reinterpret_cast(vec.data()), static_cast(vec.size())); } public: // Get the current file buffer after modifications val getBuffer() const { if (stream && stream->bufSize() > 0) { size_t sz = stream->bufSize(); auto view = emscripten::typed_memory_view( sz, reinterpret_cast(stream->bufData())); return val::global("Uint8Array").new_(view); } return val::global("Uint8Array").new_(0); } // Get all pictures from the audio file val getPictures() const { val pictures = val::array(); if (!fileRef || !fileRef->file()) return pictures; TagLib::File* f = fileRef->file(); // Handle MP3 files (ID3v2) if (TagLib::MPEG::File* mpegFile = dynamic_cast(f)) { if (mpegFile->hasID3v2Tag()) { TagLib::ID3v2::Tag* id3v2Tag = mpegFile->ID3v2Tag(); const TagLib::ID3v2::FrameList& frameList = id3v2Tag->frameList("APIC"); for (const auto& frame : frameList) { if (TagLib::ID3v2::AttachedPictureFrame* pictureFrame = dynamic_cast(frame)) { val pictureObj = val::object(); pictureObj.set("mimeType", std::string(pictureFrame->mimeType().toCString(true))); pictureObj.set("type", static_cast(pictureFrame->type())); pictureObj.set("description", std::string(pictureFrame->description().toCString(true))); // Convert picture data to Uint8Array (fast bulk copy) TagLib::ByteVector picData = pictureFrame->picture(); pictureObj.set("data", byteVectorToUint8Array(picData)); pictures.call("push", pictureObj); } } } } // Handle MP4/M4A files else if (TagLib::MP4::File* mp4File = dynamic_cast(f)) { if (mp4File->tag() && mp4File->tag()->contains("covr")) { TagLib::MP4::Item coverItem = mp4File->tag()->item("covr"); if (coverItem.isValid() && coverItem.type() == TagLib::MP4::Item::Type::CoverArtList) { TagLib::MP4::CoverArtList coverList = coverItem.toCoverArtList(); for (const auto& cover : coverList) { val pictureObj = val::object(); // Determine MIME type from format std::string mimeType; switch (cover.format()) { case TagLib::MP4::CoverArt::JPEG: mimeType = "image/jpeg"; break; case TagLib::MP4::CoverArt::PNG: mimeType = "image/png"; break; case TagLib::MP4::CoverArt::BMP: mimeType = "image/bmp"; break; case TagLib::MP4::CoverArt::GIF: mimeType = "image/gif"; break; default: mimeType = "image/unknown"; } pictureObj.set("mimeType", mimeType); pictureObj.set("type", 3); // FrontCover for MP4 pictureObj.set("description", ""); // Convert picture data to Uint8Array (fast bulk copy) TagLib::ByteVector picData = cover.data(); pictureObj.set("data", byteVectorToUint8Array(picData)); pictures.call("push", pictureObj); } } } } // Handle FLAC files else if (TagLib::FLAC::File* flacFile = dynamic_cast(f)) { const TagLib::List& pictureList = flacFile->pictureList(); for (const auto& picture : pictureList) { val pictureObj = val::object(); pictureObj.set("mimeType", std::string(picture->mimeType().toCString(true))); pictureObj.set("type", static_cast(picture->type())); pictureObj.set("description", std::string(picture->description().toCString(true))); // Convert picture data to Uint8Array (fast bulk copy) TagLib::ByteVector picData = picture->data(); pictureObj.set("data", byteVectorToUint8Array(picData)); pictures.call("push", pictureObj); } } // Handle Ogg Vorbis/Opus files else if (TagLib::Ogg::Vorbis::File* vorbisFile = dynamic_cast(f)) { if (vorbisFile->tag()) { const TagLib::List& pictureList = vorbisFile->tag()->pictureList(); for (const auto& picture : pictureList) { val pictureObj = val::object(); pictureObj.set("mimeType", std::string(picture->mimeType().toCString(true))); pictureObj.set("type", static_cast(picture->type())); pictureObj.set("description", std::string(picture->description().toCString(true))); // Convert picture data to Uint8Array (fast bulk copy) TagLib::ByteVector picData = picture->data(); pictureObj.set("data", byteVectorToUint8Array(picData)); pictures.call("push", pictureObj); } } } return pictures; } // Set pictures in the audio file (replace all existing) void setPictures(const val& pictures) { if (!fileRef || !fileRef->file() || !pictures.isArray()) return; TagLib::File* f = fileRef->file(); int length = pictures["length"].as(); // Handle MP3 files (ID3v2) if (TagLib::MPEG::File* mpegFile = dynamic_cast(f)) { if (!mpegFile->hasID3v2Tag()) { mpegFile->ID3v2Tag(true); // Create ID3v2 tag if it doesn't exist } TagLib::ID3v2::Tag* id3v2Tag = mpegFile->ID3v2Tag(); // Remove all existing APIC frames id3v2Tag->removeFrames("APIC"); // Add new pictures for (int i = 0; i < length; i++) { val picture = pictures[i]; TagLib::ID3v2::AttachedPictureFrame* frame = new TagLib::ID3v2::AttachedPictureFrame(); frame->setMimeType(TagLib::String(picture["mimeType"].as(), TagLib::String::UTF8)); frame->setType(static_cast(picture["type"].as())); frame->setDescription(TagLib::String(picture["description"].as(), TagLib::String::UTF8)); // Convert Uint8Array to ByteVector (fast bulk copy) frame->setPicture(uint8ArrayToByteVector(picture["data"])); id3v2Tag->addFrame(frame); } } // Handle MP4/M4A files else if (TagLib::MP4::File* mp4File = dynamic_cast(f)) { if (!mp4File->tag()) return; TagLib::MP4::Tag* tag = mp4File->tag(); TagLib::MP4::CoverArtList coverList; for (int i = 0; i < length; i++) { val picture = pictures[i]; // Determine format from MIME type TagLib::MP4::CoverArt::Format format = TagLib::MP4::CoverArt::Unknown; std::string mimeType = picture["mimeType"].as(); if (mimeType == "image/jpeg" || mimeType == "image/jpg") { format = TagLib::MP4::CoverArt::JPEG; } else if (mimeType == "image/png") { format = TagLib::MP4::CoverArt::PNG; } else if (mimeType == "image/bmp") { format = TagLib::MP4::CoverArt::BMP; } else if (mimeType == "image/gif") { format = TagLib::MP4::CoverArt::GIF; } // Convert Uint8Array to ByteVector (fast bulk copy) TagLib::MP4::CoverArt coverArt(format, uint8ArrayToByteVector(picture["data"])); coverList.append(coverArt); } if (!coverList.isEmpty()) { tag->setItem("covr", TagLib::MP4::Item(coverList)); } else { tag->removeItem("covr"); } } // Handle FLAC files else if (TagLib::FLAC::File* flacFile = dynamic_cast(f)) { // Remove all existing pictures flacFile->removePictures(); // Add new pictures for (int i = 0; i < length; i++) { val picture = pictures[i]; TagLib::FLAC::Picture* flacPicture = new TagLib::FLAC::Picture(); flacPicture->setMimeType(TagLib::String(picture["mimeType"].as(), TagLib::String::UTF8)); flacPicture->setType(static_cast(picture["type"].as())); flacPicture->setDescription(TagLib::String(picture["description"].as(), TagLib::String::UTF8)); // Convert Uint8Array to ByteVector (fast bulk copy) flacPicture->setData(uint8ArrayToByteVector(picture["data"])); flacFile->addPicture(flacPicture); } } // Handle Ogg Vorbis files else if (TagLib::Ogg::Vorbis::File* vorbisFile = dynamic_cast(f)) { if (!vorbisFile->tag()) return; // Remove all existing pictures vorbisFile->tag()->removeAllPictures(); // Add new pictures for (int i = 0; i < length; i++) { val picture = pictures[i]; TagLib::FLAC::Picture* flacPicture = new TagLib::FLAC::Picture(); flacPicture->setMimeType(TagLib::String(picture["mimeType"].as(), TagLib::String::UTF8)); flacPicture->setType(static_cast(picture["type"].as())); flacPicture->setDescription(TagLib::String(picture["description"].as(), TagLib::String::UTF8)); // Convert Uint8Array to ByteVector (fast bulk copy) flacPicture->setData(uint8ArrayToByteVector(picture["data"])); vorbisFile->tag()->addPicture(flacPicture); } } } // Add a single picture to the audio file void addPicture(const val& picture) { if (!fileRef || !fileRef->file()) return; // Get existing pictures val existingPictures = getPictures(); // Add the new picture existingPictures.call("push", picture); // Set all pictures setPictures(existingPictures); } // Remove all pictures from the audio file void removePictures() { val emptyArray = val::array(); setPictures(emptyArray); } // Get all chapters from the audio file (ID3v2 CHAP / MP4 QuickTime > Nero). // Returns array of {startTimeMs, endTimeMs?, title?, id?, source}. val getChapters() const { val chapters = val::array(); if (!fileRef || !fileRef->file()) return chapters; TagLib::File* f = fileRef->file(); if (auto* mpegFile = dynamic_cast(f)) { if (!mpegFile->hasID3v2Tag()) return chapters; TagLib::ID3v2::Tag* tag = mpegFile->ID3v2Tag(); for (const auto& frame : tag->frameList("CHAP")) { auto* chap = dynamic_cast(frame); if (!chap) continue; val obj = val::object(); obj.set("id", std::string(chap->elementID().data(), chap->elementID().size())); obj.set("startTimeMs", static_cast(chap->startTime())); obj.set("endTimeMs", static_cast(chap->endTime())); obj.set("source", std::string("id3")); auto embedded = chap->embeddedFrameList("TIT2"); if (!embedded.isEmpty()) { if (auto* tit2 = dynamic_cast( embedded.front())) obj.set("title", std::string(tit2->toString().toCString(true))); } chapters.call("push", obj); } } else if (auto* mp4File = dynamic_cast(f)) { TagLib::MP4::ChapterList list = mp4File->qtChapters(); const char* source = "quicktime"; if (list.isEmpty()) { list = mp4File->neroChapters(); source = "nero"; } for (const auto& ch : list) { val obj = val::object(); long long st = ch.startTime(); obj.set("startTimeMs", static_cast(st < 0 ? 0 : st)); obj.set("source", std::string(source)); if (!ch.title().isEmpty()) obj.set("title", std::string(ch.title().toCString(true))); chapters.call("push", obj); } } return chapters; } // Replace all chapters. mp4Style is "quicktime" (default) | "nero" | "both". void setChapters(const val& chapters, const std::string& mp4Style) { if (!fileRef || !fileRef->file() || !chapters.isArray()) return; TagLib::File* f = fileRef->file(); int length = chapters["length"].as(); if (auto* mpegFile = dynamic_cast(f)) { if (!mpegFile->hasID3v2Tag()) mpegFile->ID3v2Tag(true); TagLib::ID3v2::Tag* tag = mpegFile->ID3v2Tag(); tag->removeFrames("CHAP"); for (int i = 0; i < length; i++) { val c = chapters[i]; std::string id = (c["id"].isUndefined() || c["id"].isNull()) ? ("chap" + std::to_string(i)) : c["id"].as(); if (id.empty()) id = "chap" + std::to_string(i); unsigned int start = c["startTimeMs"].isUndefined() ? 0u : static_cast(c["startTimeMs"].as()); unsigned int end = c["endTimeMs"].isUndefined() ? 0u : static_cast(c["endTimeMs"].as()); TagLib::ID3v2::FrameList embedded; if (!c["title"].isUndefined() && !c["title"].isNull()) { std::string title = c["title"].as(); if (!title.empty()) { auto* tit2 = new TagLib::ID3v2::TextIdentificationFrame("TIT2"); tit2->setText(TagLib::String(title, TagLib::String::UTF8)); embedded.append(tit2); } } tag->addFrame(new TagLib::ID3v2::ChapterFrame( TagLib::ByteVector(id.c_str(), static_cast(id.size())), start, end, 0xFFFFFFFF, 0xFFFFFFFF, embedded)); } } else if (auto* mp4File = dynamic_cast(f)) { TagLib::MP4::ChapterList list; for (int i = 0; i < length; i++) { val c = chapters[i]; std::string title = (!c["title"].isUndefined() && !c["title"].isNull()) ? c["title"].as() : ""; long long start = c["startTimeMs"].isUndefined() ? 0LL : static_cast(c["startTimeMs"].as()); list.append(TagLib::MP4::Chapter( TagLib::String(title, TagLib::String::UTF8), start)); } const bool wantQt = (mp4Style != "nero"); const bool wantNero = (mp4Style == "nero" || mp4Style == "both"); mp4File->setQtChapters(wantQt ? list : TagLib::MP4::ChapterList()); if (!wantNero) { mp4File->setNeroChapters(TagLib::MP4::ChapterList()); } else if (list.size() > 255) { TagLib::MP4::ChapterList capped; for (unsigned int j = 0; j < 255; j++) capped.append(list[j]); mp4File->setNeroChapters(capped); } else { mp4File->setNeroChapters(list); } } } // BWF bext/iXML — raw passthrough for WAV and FLAC. Parsing is done in TS. val getBextData() const { if (!fileRef || !fileRef->file()) return val::undefined(); TagLib::File* f = fileRef->file(); TagLib::ByteVector bv; if (auto* wav = dynamic_cast(f)) { if (!wav->hasBEXTData()) return val::undefined(); bv = wav->BEXTData(); } else if (auto* flac = dynamic_cast(f)) { if (!flac->hasBEXTData()) return val::undefined(); bv = flac->BEXTData(); } else { return val::undefined(); } return byteVectorToUint8Array(bv); } void setBextData(const val& data) { if (!fileRef || !fileRef->file()) return; TagLib::File* f = fileRef->file(); TagLib::ByteVector bv = (data.isNull() || data.isUndefined()) ? TagLib::ByteVector() : uint8ArrayToByteVector(data); if (auto* wav = dynamic_cast(f)) wav->setBEXTData(bv); else if (auto* flac = dynamic_cast(f)) flac->setBEXTData(bv); } val getIxml() const { if (!fileRef || !fileRef->file()) return val::undefined(); TagLib::File* f = fileRef->file(); if (auto* wav = dynamic_cast(f)) { if (!wav->hasiXMLData()) return val::undefined(); return val(std::string(wav->iXMLData().toCString(true))); } if (auto* flac = dynamic_cast(f)) { if (!flac->hasiXMLData()) return val::undefined(); return val(std::string(flac->iXMLData().toCString(true))); } return val::undefined(); } void setIxml(const val& data) { if (!fileRef || !fileRef->file()) return; TagLib::File* f = fileRef->file(); TagLib::String s = (data.isNull() || data.isUndefined()) ? TagLib::String() : TagLib::String(data.as(), TagLib::String::UTF8); if (auto* wav = dynamic_cast(f)) wav->setiXMLData(s); else if (auto* flac = dynamic_cast(f)) flac->setiXMLData(s); } // FLAC ID3v1/v2 detection. Returns {v1:false,v2:false} for non-FLAC files // (their ID3 tags, if any, are the native format). Uses the in-memory tag // pointer rather than FLAC::File::hasID3vNTag() so the result reflects a // pending strip() on the same handle — hasID3vNTag checks the on-disk // location which is not cleared until save() runs. val hasId3Tags() const { val obj = val::object(); obj.set("v1", false); obj.set("v2", false); if (!fileRef || !fileRef->file()) return obj; auto* flac = dynamic_cast(fileRef->file()); if (!flac) return obj; obj.set("v1", flac->ID3v1Tag() != nullptr); obj.set("v2", flac->ID3v2Tag() != nullptr); return obj; } // Strip spurious ID3 tags from a FLAC file. Caller passes {v1, v2} // booleans. No-op on non-FLAC files. The change takes effect on save(). void stripId3Tags(const val& opts) { if (!fileRef || !fileRef->file()) return; if (opts.isNull() || opts.isUndefined()) return; auto* flac = dynamic_cast(fileRef->file()); if (!flac) return; int mask = 0; val v1 = opts["v1"]; val v2 = opts["v2"]; if (!v1.isUndefined() && v1.as()) mask |= TagLib::FLAC::File::ID3v1; if (!v2.isUndefined() && v2.as()) mask |= TagLib::FLAC::File::ID3v2; if (mask) flac->strip(mask); } // Get all ratings from the audio file // Returns array of {rating: number (0.0-1.0), email: string, counter: number} val getRatings() const { val ratings = val::array(); if (!fileRef || !fileRef->file()) return ratings; TagLib::File* f = fileRef->file(); // Handle MP3 files (ID3v2 POPM frames) if (TagLib::MPEG::File* mpegFile = dynamic_cast(f)) { if (mpegFile->hasID3v2Tag()) { TagLib::ID3v2::Tag* id3v2Tag = mpegFile->ID3v2Tag(); const TagLib::ID3v2::FrameList& frameList = id3v2Tag->frameList("POPM"); for (const auto& frame : frameList) { if (TagLib::ID3v2::PopularimeterFrame* popmFrame = dynamic_cast(frame)) { val ratingObj = val::object(); // Normalize rating from 0-255 to 0.0-1.0 ratingObj.set("rating", popmFrame->rating() / 255.0); ratingObj.set("email", std::string(popmFrame->email().toCString(true))); ratingObj.set("counter", static_cast(popmFrame->counter())); ratings.call("push", ratingObj); } } } } // Handle FLAC files (Vorbis RATING field) else if (TagLib::FLAC::File* flacFile = dynamic_cast(f)) { if (flacFile->xiphComment()) { TagLib::Ogg::XiphComment* xiphComment = flacFile->xiphComment(); if (xiphComment->contains("RATING")) { TagLib::StringList ratingValues = xiphComment->fieldListMap()["RATING"]; for (const auto& ratingStr : ratingValues) { try { double r = std::stod(ratingStr.toCString()); // Normalize to 0.0-1.0 if not already if (r > 1.0) r = r / 100.0; val ratingObj = val::object(); ratingObj.set("rating", r); ratingObj.set("email", std::string("")); ratingObj.set("counter", 0); ratings.call("push", ratingObj); } catch (...) { // Skip invalid rating values } } } } } // Handle Ogg Vorbis files (Vorbis RATING field) else if (TagLib::Ogg::Vorbis::File* vorbisFile = dynamic_cast(f)) { if (vorbisFile->tag()) { TagLib::Ogg::XiphComment* xiphComment = vorbisFile->tag(); if (xiphComment->contains("RATING")) { TagLib::StringList ratingValues = xiphComment->fieldListMap()["RATING"]; for (const auto& ratingStr : ratingValues) { try { double r = std::stod(ratingStr.toCString()); // Normalize to 0.0-1.0 if not already if (r > 1.0) r = r / 100.0; val ratingObj = val::object(); ratingObj.set("rating", r); ratingObj.set("email", std::string("")); ratingObj.set("counter", 0); ratings.call("push", ratingObj); } catch (...) { // Skip invalid rating values } } } } } // Handle Ogg Opus files (Vorbis RATING field) else if (TagLib::Ogg::Opus::File* opusFile = dynamic_cast(f)) { if (opusFile->tag()) { TagLib::Ogg::XiphComment* xiphComment = opusFile->tag(); if (xiphComment->contains("RATING")) { TagLib::StringList ratingValues = xiphComment->fieldListMap()["RATING"]; for (const auto& ratingStr : ratingValues) { try { double r = std::stod(ratingStr.toCString()); // Normalize to 0.0-1.0 if not already if (r > 1.0) r = r / 100.0; val ratingObj = val::object(); ratingObj.set("rating", r); ratingObj.set("email", std::string("")); ratingObj.set("counter", 0); ratings.call("push", ratingObj); } catch (...) { // Skip invalid rating values } } } } } // Handle MP4/M4A files (freeform rating atom) else if (TagLib::MP4::File* mp4File = dynamic_cast(f)) { if (mp4File->tag()) { // Try various known rating atoms const char* ratingAtoms[] = { "----:com.apple.iTunes:RATING", "----:com.apple.iTunes:rating", "rate" }; for (const char* atomName : ratingAtoms) { if (mp4File->tag()->contains(atomName)) { TagLib::MP4::Item item = mp4File->tag()->item(atomName); if (item.isValid()) { double r = 0.0; if (item.type() == TagLib::MP4::Item::Type::Int) { // Integer rating (0-100 or 0-255) int intVal = item.toInt(); r = (intVal > 100) ? intVal / 255.0 : intVal / 100.0; } else if (item.type() == TagLib::MP4::Item::Type::StringList && !item.toStringList().isEmpty()) { try { r = std::stod(item.toStringList().front().toCString()); if (r > 1.0) r = r / 100.0; } catch (...) {} } val ratingObj = val::object(); ratingObj.set("rating", r); ratingObj.set("email", std::string("")); ratingObj.set("counter", 0); ratings.call("push", ratingObj); break; // Found a rating, stop searching } } } } } return ratings; } // Set ratings in the audio file (replace all existing) void setRatings(const val& ratings) { if (!fileRef || !fileRef->file() || !ratings.isArray()) return; TagLib::File* f = fileRef->file(); int length = ratings["length"].as(); // Handle MP3 files (ID3v2 POPM frames) if (TagLib::MPEG::File* mpegFile = dynamic_cast(f)) { if (!mpegFile->hasID3v2Tag()) { mpegFile->ID3v2Tag(true); // Create ID3v2 tag if it doesn't exist } TagLib::ID3v2::Tag* id3v2Tag = mpegFile->ID3v2Tag(); // Remove all existing POPM frames id3v2Tag->removeFrames("POPM"); // Add new POPM frames for (int i = 0; i < length; i++) { val r = ratings[i]; auto* popmFrame = new TagLib::ID3v2::PopularimeterFrame(); // Convert normalized 0.0-1.0 to 0-255 double normalized = r["rating"].as(); popmFrame->setRating(static_cast(normalized * 255)); if (r.hasOwnProperty("email") && !r["email"].isNull() && !r["email"].isUndefined()) { std::string email = r["email"].as(); popmFrame->setEmail(TagLib::String(email, TagLib::String::UTF8)); } if (r.hasOwnProperty("counter") && !r["counter"].isNull() && !r["counter"].isUndefined()) { popmFrame->setCounter(r["counter"].as()); } id3v2Tag->addFrame(popmFrame); } } // Handle FLAC files (Vorbis RATING field) else if (TagLib::FLAC::File* flacFile = dynamic_cast(f)) { if (flacFile->xiphComment()) { TagLib::Ogg::XiphComment* xiphComment = flacFile->xiphComment(); // Remove existing RATING fields xiphComment->removeFields("RATING"); // Add new RATING fields (store as 0.0-1.0 string) for (int i = 0; i < length; i++) { val r = ratings[i]; double normalized = r["rating"].as(); std::string ratingStr = std::to_string(normalized); xiphComment->addField("RATING", TagLib::String(ratingStr, TagLib::String::UTF8)); } } } // Handle Ogg Vorbis files (Vorbis RATING field) else if (TagLib::Ogg::Vorbis::File* vorbisFile = dynamic_cast(f)) { if (vorbisFile->tag()) { TagLib::Ogg::XiphComment* xiphComment = vorbisFile->tag(); // Remove existing RATING fields xiphComment->removeFields("RATING"); // Add new RATING fields for (int i = 0; i < length; i++) { val r = ratings[i]; double normalized = r["rating"].as(); std::string ratingStr = std::to_string(normalized); xiphComment->addField("RATING", TagLib::String(ratingStr, TagLib::String::UTF8)); } } } // Handle Ogg Opus files (Vorbis RATING field) else if (TagLib::Ogg::Opus::File* opusFile = dynamic_cast(f)) { if (opusFile->tag()) { TagLib::Ogg::XiphComment* xiphComment = opusFile->tag(); // Remove existing RATING fields xiphComment->removeFields("RATING"); // Add new RATING fields for (int i = 0; i < length; i++) { val r = ratings[i]; double normalized = r["rating"].as(); std::string ratingStr = std::to_string(normalized); xiphComment->addField("RATING", TagLib::String(ratingStr, TagLib::String::UTF8)); } } } // Handle MP4/M4A files (freeform rating atom) else if (TagLib::MP4::File* mp4File = dynamic_cast(f)) { if (mp4File->tag()) { // Remove existing rating atoms mp4File->tag()->removeItem("----:com.apple.iTunes:RATING"); // Add new rating (use first one, MP4 typically has single rating) if (length > 0) { val r = ratings[0]; double normalized = r["rating"].as(); std::string ratingStr = std::to_string(normalized); mp4File->tag()->setItem("----:com.apple.iTunes:RATING", TagLib::MP4::Item(TagLib::StringList(TagLib::String(ratingStr, TagLib::String::UTF8)))); } } } } // Raw ID3v2 frames (taglib-b67, MP3 only). data = frame BODY bytes. // idFilter "" = all frames. Writes construct UnknownFrame (byte-identity; // deliberately NOT FrameFactory — see the taglib-b67 design spec). val getId3v2Frames(const std::string& idFilter) const { val frames = val::array(); if (!fileRef || !fileRef->file()) return frames; auto* mpegFile = dynamic_cast(fileRef->file()); if (!mpegFile || !mpegFile->hasID3v2Tag()) return frames; if (!idFilter.empty() && idFilter.size() != 4) return frames; for (const auto& frame : mpegFile->ID3v2Tag()->frameList()) { TagLib::ByteVector id = frame->frameID(); if (!idFilter.empty() && (id.size() != 4 || std::memcmp(id.data(), idFilter.data(), 4) != 0)) { continue; } TagLib::ByteVector rendered = frame->render(); TagLib::ByteVector body = rendered.mid(frame->headerSize()); unsigned int flags = 0; if (rendered.size() >= 10) { flags = (static_cast(rendered[8]) << 8) | static_cast(rendered[9]); } val obj = val::object(); obj.set("id", std::string(id.data(), id.size())); obj.set("data", byteVectorToUint8Array(body)); obj.set("flags", flags); frames.call("push", obj); } return frames; } void setId3v2Frames(const std::string& id, const val& bodies) { if (!fileRef || !fileRef->file() || id.size() != 4) return; auto* mpegFile = dynamic_cast(fileRef->file()); if (!mpegFile) return; TagLib::ByteVector idBv(id.data(), 4); int length = bodies.isArray() ? bodies["length"].as() : 0; if (length == 0) { if (mpegFile->hasID3v2Tag()) { mpegFile->ID3v2Tag()->removeFrames(idBv); } rawMappedFrameIds.erase(id); return; } if (ID3V1_MAPPED_FRAME_IDS.count(id)) { rawMappedFrameIds.insert(id); } TagLib::ID3v2::Tag* tag = mpegFile->ID3v2Tag(true); tag->removeFrames(idBv); for (int i = 0; i < length; i++) { TagLib::ByteVector body = uint8ArrayToByteVector(bodies[i]); TagLib::ByteVector full; full.append(idBv); full.append(TagLib::ID3v2::SynchData::fromUInt(body.size())); full.append(TagLib::ByteVector("\0\0", 2)); // zero flags (v1) full.append(body); tag->addFrame(new TagLib::ID3v2::UnknownFrame(full)); } } void removeId3v2Frames(const std::string& id) { setId3v2Frames(id, val::array()); } // Explicitly destroy all resources void destroy() { // Reset unique_ptrs to release memory immediately. fileRef owns the // TagLib::File and must go before the stream it reads from; there is no // separate `file` pointer to reset, because a second owner here is what // freed the File twice and trapped (taglib-f5hp). fileRef.reset(); stream.reset(); } }; EMSCRIPTEN_BINDINGS(taglib) { // FileHandle class - main entry point class_("FileHandle") .constructor<>() .function("loadFromBuffer", &FileHandle::loadFromBuffer) .function("isValid", &FileHandle::isValid) .function("save", &FileHandle::save) .function("getFormat", &FileHandle::getFormat) .function("getProperties", &FileHandle::getProperties) .function("setProperties", &FileHandle::setProperties) .function("getProperty", &FileHandle::getProperty) .function("setProperty", &FileHandle::setProperty) .function("isMP4", &FileHandle::isMP4) .function("getMP4Item", &FileHandle::getMP4Item) .function("setMP4Item", &FileHandle::setMP4Item) .function("removeMP4Item", &FileHandle::removeMP4Item) .function("getMP4FreeformItems", &FileHandle::getMP4FreeformItems) .function("setMP4FreeformItems", &FileHandle::setMP4FreeformItems) .function("getTag", &FileHandle::getTag) .function("getAudioProperties", &FileHandle::getAudioProperties) .function("getBuffer", &FileHandle::getBuffer) .function("getPictures", &FileHandle::getPictures) .function("setPictures", &FileHandle::setPictures) .function("addPicture", &FileHandle::addPicture) .function("removePictures", &FileHandle::removePictures) .function("getChapters", &FileHandle::getChapters) .function("setChapters", &FileHandle::setChapters) .function("getBextData", &FileHandle::getBextData) .function("setBextData", &FileHandle::setBextData) .function("getIxml", &FileHandle::getIxml) .function("setIxml", &FileHandle::setIxml) .function("getRatings", &FileHandle::getRatings) .function("setRatings", &FileHandle::setRatings) .function("getId3v2Frames", &FileHandle::getId3v2Frames) .function("setId3v2Frames", &FileHandle::setId3v2Frames) .function("removeId3v2Frames", &FileHandle::removeId3v2Frames) .function("hasId3Tags", &FileHandle::hasId3Tags) .function("stripId3Tags", &FileHandle::stripId3Tags) .function("destroy", &FileHandle::destroy); // TagWrapper class class_("TagWrapper") .constructor<>() .function("title", &TagWrapper::title) .function("artist", &TagWrapper::artist) .function("album", &TagWrapper::album) .function("comment", &TagWrapper::comment) .function("genre", &TagWrapper::genre) .function("year", &TagWrapper::year) .function("track", &TagWrapper::track) .function("setTitle", &TagWrapper::setTitle) .function("setArtist", &TagWrapper::setArtist) .function("setAlbum", &TagWrapper::setAlbum) .function("setComment", &TagWrapper::setComment) .function("setGenre", &TagWrapper::setGenre) .function("setYear", &TagWrapper::setYear) .function("setTrack", &TagWrapper::setTrack); // AudioPropertiesWrapper class class_("AudioPropertiesWrapper") .constructor<>() .function("lengthInSeconds", &AudioPropertiesWrapper::lengthInSeconds) .function("lengthInMilliseconds", &AudioPropertiesWrapper::lengthInMilliseconds) .function("bitrate", &AudioPropertiesWrapper::bitrate) .function("sampleRate", &AudioPropertiesWrapper::sampleRate) .function("channels", &AudioPropertiesWrapper::channels) .function("bitsPerSample", &AudioPropertiesWrapper::bitsPerSample) .function("codec", &AudioPropertiesWrapper::codec) .function("isLossless", &AudioPropertiesWrapper::isLossless) .function("containerFormat", &AudioPropertiesWrapper::containerFormat) .function("mpegVersion", &AudioPropertiesWrapper::mpegVersion) .function("mpegLayer", &AudioPropertiesWrapper::mpegLayer) .function("bitrateMode", &AudioPropertiesWrapper::bitrateMode) .function("isEncrypted", &AudioPropertiesWrapper::isEncrypted) .function("formatVersion", &AudioPropertiesWrapper::formatVersion) .function("outputGainDb", &AudioPropertiesWrapper::outputGainDb); // PictureWrapper class class_("PictureWrapper") .constructor<>() .property("mimeType", &PictureWrapper::mimeType) .property("data", &PictureWrapper::data) .property("type", &PictureWrapper::type) .property("description", &PictureWrapper::description); // Register shared_ptr for FileHandle register_vector("StringVector"); // Helper function to create a FileHandle from buffer function("createFileHandle", +[]() -> FileHandle* { return new FileHandle(); }, allow_raw_pointers()); // Version information function("getVersion", +[]() -> std::string { return std::to_string(TAGLIB_MAJOR_VERSION) + "." + std::to_string(TAGLIB_MINOR_VERSION) + "." + std::to_string(TAGLIB_PATCH_VERSION); }); }