// TagLib behind the C door `CottonTagReader.h` describes. One file in, one // JSON object out: the whitelisted fields only, so nothing a file carries // beyond them (the iTunes purchaser atoms first of all) is ever asked for. #include "CottonTagReader.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { std::string quoted(const std::string &text) { std::string out = "\""; for (unsigned char c : text) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (c < 0x20) { char escaped[8]; std::snprintf(escaped, sizeof escaped, "\\u%04x", c); out += escaped; } else { out += static_cast(c); } } } return out + "\""; } struct Json { std::string body; void field(const char *key, const std::string &value) { if (!body.empty()) body += ","; body += quoted(key) + ":" + value; } void text(const char *key, const std::string &value) { if (!value.empty()) field(key, quoted(value)); } void number(const char *key, double value) { if (!std::isfinite(value)) return; char written[32]; std::snprintf(written, sizeof written, "%.6g", value); field(key, written); } void whole(const char *key, long value) { if (value > 0) field(key, std::to_string(value)); } }; std::string first(const TagLib::PropertyMap &map, const char *key) { auto found = map.find(key); if (found == map.end() || found->second.isEmpty()) return ""; std::string value = found->second.front().to8Bit(true); // Trim the ends: a tag is words, not their padding. const char *space = " \t\r\n"; auto start = value.find_first_not_of(space); if (start == std::string::npos) return ""; return value.substr(start, value.find_last_not_of(space) - start + 1); } /// The first of `keys` the map says something for: one field, several /// spellings (Vorbis' LABEL and ORGANIZATION, say). std::string any(const TagLib::PropertyMap &map, std::initializer_list keys) { for (const char *key : keys) { std::string value = first(map, key); if (!value.empty()) return value; } return ""; } /// Every value of `key`, joined: a release type tagged as several /// (`album`, `live`) is read whole, as the core's `release_type` splits it. std::string joined(const TagLib::PropertyMap &map, const char *key) { auto found = map.find(key); if (found == map.end()) return ""; std::string out; for (const auto &value : found->second) { std::string text = value.to8Bit(true); if (text.find_first_not_of(" \t\r\n") == std::string::npos) continue; if (!out.empty()) out += "; "; out += text; } return out; } /// `3` or `3/12`: the number, and the count after the slash. void numbered(const std::string &text, long &number, long &of) { number = std::strtol(text.c_str(), nullptr, 10); auto slash = text.find('/'); of = slash == std::string::npos ? 0 : std::strtol(text.c_str() + slash + 1, nullptr, 10); } /// "-6.54 dB" → -6.54; NaN when it says no number. double decibels(const std::string &text) { if (text.empty()) return NAN; char *end = nullptr; double value = std::strtod(text.c_str(), &end); return end == text.c_str() ? NAN : value; } /// An R128 gain (Q7.8 against -23 LUFS) as ReplayGain's dB (against -18). double r128(const std::string &text) { if (text.empty()) return NAN; char *end = nullptr; long value = std::strtol(text.c_str(), &end, 10); return end == text.c_str() ? NAN : static_cast(value) / 256.0 + 5.0; } /// An ID3v2 tag's first SYLT frame in milliseconds, as LRC text. std::string synced(TagLib::ID3v2::Tag *tag) { if (!tag) return ""; const auto &frames = tag->frameListMap()["SYLT"]; for (auto *frame : frames) { auto *lyrics = dynamic_cast(frame); if (!lyrics || lyrics->timestampFormat() != TagLib::ID3v2::SynchronizedLyricsFrame::AbsoluteMilliseconds) continue; std::string lrc; for (const auto &line : lyrics->synchedText()) { unsigned int ms = line.time; char mark[24]; std::snprintf(mark, sizeof mark, "[%02u:%02u.%02u]", ms / 60000, (ms / 1000) % 60, (ms % 1000) / 10); lrc += mark + line.text.to8Bit(true) + "\n"; } if (!lrc.empty()) return lrc; } return ""; } TagLib::ID3v2::Tag *id3v2(TagLib::File *file) { if (auto *mpeg = dynamic_cast(file)) return mpeg->hasID3v2Tag() ? mpeg->ID3v2Tag() : nullptr; if (auto *wav = dynamic_cast(file)) return wav->hasID3v2Tag() ? wav->ID3v2Tag() : nullptr; if (auto *aiff = dynamic_cast(file)) return aiff->hasID3v2Tag() ? aiff->tag() : nullptr; return nullptr; } /// The first picture, a front cover first, written to `path`; its type. std::string picture(TagLib::File *file, const char *path) { if (!path) return ""; auto pictures = file->complexProperties("PICTURE"); if (pictures.isEmpty()) return ""; const TagLib::VariantMap *chosen = &pictures.front(); for (const auto &candidate : pictures) { if (candidate.value("pictureType").toString() == "Front Cover") { chosen = &candidate; break; } } TagLib::ByteVector data = chosen->value("data").toByteVector(); if (data.isEmpty()) return ""; FILE *out = std::fopen(path, "wb"); if (!out) return ""; bool whole = std::fwrite(data.data(), 1, data.size(), out) == data.size(); std::fclose(out); if (!whole) return ""; std::string type = chosen->value("mimeType").toString().to8Bit(true); if (type.empty()) { // A picture with no type said: its first bytes say it. type = data.startsWith("\x89PNG") ? "image/png" : "image/jpeg"; } return type; } } // namespace extern "C" char *cotton_tags_read(const char *path, const char *picture_path) { if (!path) return nullptr; TagLib::FileRef ref(path, true, TagLib::AudioProperties::Average); if (ref.isNull() || !ref.file() || !ref.file()->isValid()) return nullptr; TagLib::File *file = ref.file(); const TagLib::PropertyMap map = file->properties(); Json tags; tags.text("title", first(map, "TITLE")); tags.text("artist", first(map, "ARTIST")); tags.text("album", first(map, "ALBUM")); tags.text("albumArtist", first(map, "ALBUMARTIST")); long number = 0, of = 0; numbered(first(map, "TRACKNUMBER"), number, of); tags.whole("track", number); numbered(first(map, "DISCNUMBER"), number, of); tags.whole("disc", number); if (of <= 0) { long total = 0, unused = 0; numbered(any(map, {"DISCTOTAL", "TOTALDISCS"}), total, unused); of = total; } tags.whole("discs", of); std::string date = any(map, {"DATE", "YEAR", "RELEASEDATE", "ORIGINALDATE", "ORIGINALYEAR"}); tags.text("year", date.substr(0, 4)); tags.text("genre", first(map, "GENRE")); tags.text("composer", first(map, "COMPOSER")); std::string compilation = first(map, "COMPILATION"); if (!compilation.empty()) { bool no = compilation == "0" || compilation == "false" || compilation == "False" || compilation == "FALSE"; tags.field("compilation", no ? "false" : "true"); } tags.text("lyrics", first(map, "LYRICS")); tags.text("syncedLyrics", synced(id3v2(file))); tags.number("trackGain", decibels(first(map, "REPLAYGAIN_TRACK_GAIN"))); tags.number("trackPeak", decibels(first(map, "REPLAYGAIN_TRACK_PEAK"))); tags.number("albumGain", decibels(first(map, "REPLAYGAIN_ALBUM_GAIN"))); tags.number("albumPeak", decibels(first(map, "REPLAYGAIN_ALBUM_PEAK"))); if (map.find("REPLAYGAIN_TRACK_GAIN") == map.end()) tags.number("trackGain", r128(first(map, "R128_TRACK_GAIN"))); if (map.find("REPLAYGAIN_ALBUM_GAIN") == map.end()) tags.number("albumGain", r128(first(map, "R128_ALBUM_GAIN"))); tags.text("isrc", first(map, "ISRC")); // TagLib's MUSICBRAINZ_TRACKID is the recording in every family (Vorbis' // MUSICBRAINZ_TRACKID, ID3's UFID, MP4's `MusicBrainz Track Id`), as // lofty's MusicBrainzRecordingId is on the Mac; MUSICBRAINZ_RELEASETRACKID // is the track on the release, a different id that never stands in for it. tags.text("mbRecording", first(map, "MUSICBRAINZ_TRACKID")); tags.text("mbReleaseTrack", first(map, "MUSICBRAINZ_RELEASETRACKID")); tags.text("mbRelease", first(map, "MUSICBRAINZ_ALBUMID")); tags.text("mbReleaseGroup", first(map, "MUSICBRAINZ_RELEASEGROUPID")); tags.text("mbArtist", first(map, "MUSICBRAINZ_ARTISTID")); tags.text("mbAlbumArtist", first(map, "MUSICBRAINZ_ALBUMARTISTID")); // TagLib folds ID3's TSOP / TSO2 / TDOR / TPUB and MP4's soar / soaa and // `----:com.apple.iTunes:` atoms into these names. tags.text("artistSort", first(map, "ARTISTSORT")); tags.text("albumArtistSort", first(map, "ALBUMARTISTSORT")); tags.text("originalDate", any(map, {"ORIGINALDATE", "ORIGINALYEAR"})); tags.text("label", any(map, {"LABEL", "ORGANIZATION", "PUBLISHER"})); tags.text("catalogNumber", first(map, "CATALOGNUMBER")); tags.text("barcode", first(map, "BARCODE")); std::string kind = joined(map, "RELEASETYPE"); tags.text("releaseType", kind.empty() ? joined(map, "MUSICBRAINZ_ALBUMTYPE") : kind); if (auto *audio = file->audioProperties()) { tags.number("duration", audio->lengthInMilliseconds() / 1000.0); tags.whole("bitrate", audio->bitrate()); tags.whole("sampleRate", audio->sampleRate()); } if (auto *mp4 = dynamic_cast(file)) { if (auto *audio = mp4->audioProperties()) { if (audio->codec() == TagLib::MP4::Properties::ALAC) tags.field("lossless", "true"); else if (audio->codec() == TagLib::MP4::Properties::AAC) tags.field("lossless", "false"); } } std::string type = picture(file, picture_path); std::string out = "{\"tags\":{" + tags.body + "},\"picture\":" + (type.empty() ? "null" : quoted(type)) + "}"; char *answer = static_cast(std::malloc(out.size() + 1)); if (!answer) return nullptr; std::memcpy(answer, out.c_str(), out.size() + 1); return answer; } extern "C" void cotton_tags_free(char *json) { std::free(json); }