Tag Parser 11.2.1
C++ library for reading and writing MP4 (iTunes), ID3, Vorbis, Opus, FLAC and Matroska tags
vorbiscomment.cpp
Go to the documentation of this file.
1#include "./vorbiscomment.h"
3
4#include "../ogg/oggiterator.h"
5
6#include "../diagnostics.h"
7#include "../exceptions.h"
8
9#include <c++utilities/conversion/stringbuilder.h>
10#include <c++utilities/io/binaryreader.h>
11#include <c++utilities/io/binarywriter.h>
12#include <c++utilities/io/copy.h>
13
14#include <map>
15#include <memory>
16
17using namespace std;
18using namespace CppUtilities;
19
20namespace TagParser {
21
28{
29 switch (field) {
31 return vendor();
32 default:
34 }
35}
36
38{
39 switch (field) {
42 return true;
43 default:
45 }
46}
47
49{
50 using namespace VorbisCommentIds;
51 switch (field) {
53 return std::string(album());
55 return std::string(artist());
57 return std::string(comment());
59 return std::string(cover());
61 return std::string(date());
63 return std::string(title());
65 return std::string(genre());
67 return std::string(trackNumber());
69 return std::string(diskNumber());
71 return std::string(partNumber());
73 return std::string(composer());
75 return std::string(encoder());
77 return std::string(encodedBy());
79 return std::string(encoderSettings());
81 return std::string(description());
83 return std::string(grouping());
85 return std::string(label());
87 return std::string(performer());
89 return std::string(language());
91 return std::string(lyricist());
93 return std::string(lyrics());
95 return std::string(albumArtist());
97 return std::string(conductor());
99 return std::string(copyright());
101 return std::string(license());
103 return std::string(director());
104 case KnownField::ISRC:
105 return std::string(isrc());
106 default:
107 return std::string();
108 }
109}
110
112{
113 using namespace VorbisCommentIds;
114 // clang-format off
115 static const std::map<std::string_view, KnownField, CaseInsensitiveStringComparer> fieldMap({
142 { isrc(), KnownField::ISRC },
143 });
144 // clang-format on
145 const auto knownField(fieldMap.find(id));
146 return knownField != fieldMap.cend() ? knownField->second : KnownField::Invalid;
147}
148
152template <class StreamType> void VorbisComment::internalParse(StreamType &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
153{
154 // prepare parsing
155 static const string context("parsing Vorbis comment");
156 const auto startOffset = static_cast<std::uint64_t>(stream.tellg());
157 try {
158 // read signature: 0x3 + "vorbis"
159 char sig[8];
160 bool skipSignature = flags & VorbisCommentFlags::NoSignature;
161 if (!skipSignature) {
163 stream.read(sig, 7);
164 skipSignature = (BE::toUInt64(sig) & 0xffffffffffffff00u) == 0x03766F7262697300u;
165 }
166 if (skipSignature) {
167 // read vendor (length prefixed string)
168 {
170 stream.read(sig, 4);
171 const auto vendorSize = LE::toUInt32(sig);
172 if (vendorSize <= maxSize) {
173 auto buff = make_unique<char[]>(vendorSize);
174 stream.read(buff.get(), vendorSize);
175 m_vendor.assignData(move(buff), vendorSize, TagDataType::Text, TagTextEncoding::Utf8);
176 // TODO: Is the vendor string actually UTF-8 (like the field values)?
177 } else {
178 diag.emplace_back(DiagLevel::Critical, "Vendor information is truncated.", context);
179 throw TruncatedDataException();
180 }
181 maxSize -= vendorSize;
182 }
183 // read field count
185 stream.read(sig, 4);
186 std::uint32_t fieldCount = LE::toUInt32(sig);
187 for (std::uint32_t i = 0; i < fieldCount; ++i) {
188 // read fields
189 VorbisCommentField field;
190 try {
191 field.parse(stream, maxSize, diag);
192 fields().emplace(field.id(), move(field));
193 } catch (const TruncatedDataException &) {
194 throw;
195 } catch (const Failure &) {
196 // nothing to do here since notifications will be added anyways
197 }
198 }
199 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
200 stream.ignore(); // skip framing byte
201 }
202 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
203 // turn "YEAR" into "DATE" (unless "DATE" exists)
204 // note: "DATE" is an official field and "YEAR" only an unofficial one but present in some files. In consistency with
205 // MediaInfo and VLC player it is treated like "DATE" here.
206 static const auto dateFieldId = std::string(VorbisCommentIds::date()), yearFieldId = std::string(VorbisCommentIds::year());
207 if (fields().find(dateFieldId) == fields().end()) {
208 const auto [first, end] = fields().equal_range(yearFieldId);
209 for (auto i = first; i != end; ++i) {
210 fields().emplace(dateFieldId, std::move(i->second));
211 }
212 fields().erase(first, end);
213 }
214 } else {
215 diag.emplace_back(DiagLevel::Critical, "Signature is invalid.", context);
216 throw InvalidDataException();
217 }
218 } catch (const TruncatedDataException &) {
219 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
220 diag.emplace_back(DiagLevel::Critical, "Vorbis comment is truncated.", context);
221 throw;
222 }
223
224 // warn if there are bytes left in the last segment of the Ogg packet containing the comment
225 if constexpr (std::is_same_v<std::decay_t<StreamType>, OggIterator>) {
226 auto bytesRemaining = std::uint64_t();
227 if (stream) {
228 bytesRemaining = stream.remainingBytesInCurrentSegment();
229 if (stream.currentPage().isLastSegmentUnconcluded()) {
230 stream.nextSegment();
231 if (stream) {
232 bytesRemaining += stream.remainingBytesInCurrentSegment();
233 }
234 }
235 }
236 if (bytesRemaining) {
237 diag.emplace_back(DiagLevel::Warning, argsToString(bytesRemaining, " bytes left in last segment."), context);
238 }
239 }
240}
241
250{
251 internalParse(iterator, iterator.streamSize(), flags, diag);
252}
253
261void VorbisComment::parse(istream &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
262{
263 internalParse(stream, maxSize, flags, diag);
264}
265
273void VorbisComment::make(std::ostream &stream, VorbisCommentFlags flags, Diagnostics &diag)
274{
275 // prepare making
276 static const string context("making Vorbis comment");
277 string vendor;
278 try {
279 m_vendor.toString(vendor);
280 } catch (const ConversionException &) {
281 diag.emplace_back(DiagLevel::Warning, "Can not convert the assigned vendor to string.", context);
282 }
283 BinaryWriter writer(&stream);
284 if (!(flags & VorbisCommentFlags::NoSignature)) {
285 // write signature
286 static const char sig[7] = { 0x03, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73 };
287 stream.write(sig, sizeof(sig));
288 }
289 // write vendor
290 writer.writeUInt32LE(static_cast<std::uint32_t>(vendor.size()));
291 writer.writeString(vendor);
292 // write field count later
293 const auto fieldCountOffset = stream.tellp();
294 writer.writeUInt32LE(0);
295 // write fields
296 std::uint32_t fieldsWritten = 0;
297 for (auto &i : fields()) {
298 VorbisCommentField &field = i.second;
299 if (!field.value().isEmpty()) {
300 try {
301 if (field.make(writer, flags, diag)) {
302 ++fieldsWritten;
303 }
304 } catch (const Failure &) {
305 }
306 }
307 }
308 // write field count
309 const auto framingByteOffset = stream.tellp();
310 stream.seekp(fieldCountOffset);
311 writer.writeUInt32LE(fieldsWritten);
312 stream.seekp(framingByteOffset);
313 // write framing byte
314 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
315 stream.put(0x01);
316 }
317}
318
319} // namespace TagParser
The Diagnostics class is a container for DiagMessage.
Definition: diagnostics.h:156
The class inherits from std::exception and serves as base class for exceptions thrown by the elements...
Definition: exceptions.h:11
bool setValue(const IdentifierType &id, const TagValue &value)
Assigns the given value to the field with the specified id.
typename FieldMapBasedTagTraits< VorbisComment >::FieldType::IdentifierType IdentifierType
Definition: fieldbasedtag.h:36
const TagValue & value(const IdentifierType &id) const
Returns the value of the field with the specified id.
const std::multimap< IdentifierType, FieldType, Compare > & fields() const
Returns the fields of the tag by providing direct access to the field map of the tag.
KnownField knownField(const IdentifierType &id) const
Returns the field for the specified ID.
The OggIterator class helps iterating through all segments of an OGG bitstream.
Definition: oggiterator.h:11
std::uint64_t streamSize() const
Returns the stream size (which has been specified when constructing the iterator).
Definition: oggiterator.h:117
TagValue & value()
Returns the value of the current TagField.
The TagValue class wraps values of different types.
Definition: tagvalue.h:95
void assignData(const char *data, std::size_t length, TagDataType type=TagDataType::Binary, TagTextEncoding encoding=TagTextEncoding::Latin1)
std::string toString(TagTextEncoding encoding=TagTextEncoding::Unspecified) const
Converts the value of the current TagValue object to its equivalent std::string representation.
Definition: tagvalue.h:485
bool isEmpty() const
Returns whether no or an empty value is assigned.
Definition: tagvalue.h:525
std::uint64_t m_size
Definition: tag.h:215
The VorbisCommentField class is used by VorbisComment to store the fields.
bool make(CppUtilities::BinaryWriter &writer, VorbisCommentFlags flags, Diagnostics &diag)
Writes the field to a stream using the specified writer.
void make(std::ostream &stream, VorbisCommentFlags flags, Diagnostics &diag)
Writes tag information to the specified stream.
const TagValue & vendor() const
Returns the vendor.
Definition: vorbiscomment.h:76
void parse(OggIterator &iterator, VorbisCommentFlags flags, Diagnostics &diag)
Parses tag information using the specified OGG iterator.
IdentifierType internallyGetFieldId(KnownField field) const
void setVendor(const TagValue &vendor)
Sets the vendor.
Definition: vorbiscomment.h:85
const TagValue & value(KnownField field) const override
Returns the value of the specified field.
bool setValue(KnownField field, const TagValue &value) override
Assigns the given value to the specified field.
KnownField internallyGetKnownField(const IdentifierType &id) const
#define CHECK_MAX_SIZE(sizeDenotation)
Throws TruncatedDataException() if the specified sizeDenotation exceeds maxSize; otherwise maxSize is...
Definition: exceptions.h:70
constexpr TAG_PARSER_EXPORT std::string_view album()
Definition: matroskatagid.h:90
constexpr TAG_PARSER_EXPORT std::string_view encoderSettings()
constexpr TAG_PARSER_EXPORT std::string_view encodedBy()
constexpr TAG_PARSER_EXPORT std::string_view description()
constexpr TAG_PARSER_EXPORT std::string_view isrc()
constexpr TAG_PARSER_EXPORT std::string_view title()
Definition: matroskatagid.h:44
constexpr TAG_PARSER_EXPORT std::string_view comment()
constexpr TAG_PARSER_EXPORT std::string_view language()
constexpr TAG_PARSER_EXPORT std::string_view composer()
constexpr TAG_PARSER_EXPORT std::string_view partNumber()
Definition: matroskatagid.h:33
constexpr TAG_PARSER_EXPORT std::string_view conductor()
constexpr TAG_PARSER_EXPORT std::string_view director()
constexpr TAG_PARSER_EXPORT std::string_view genre()
constexpr TAG_PARSER_EXPORT std::string_view artist()
Definition: matroskatagid.h:86
constexpr TAG_PARSER_EXPORT std::string_view copyright()
constexpr TAG_PARSER_EXPORT std::string_view lyrics()
constexpr TAG_PARSER_EXPORT std::string_view encoder()
constexpr TAG_PARSER_EXPORT std::string_view license()
constexpr TAG_PARSER_EXPORT std::string_view lyricist()
constexpr TAG_PARSER_EXPORT std::string_view trackNumber()
constexpr TAG_PARSER_EXPORT std::string_view performer()
constexpr TAG_PARSER_EXPORT std::string_view year()
constexpr TAG_PARSER_EXPORT std::string_view albumArtist()
constexpr TAG_PARSER_EXPORT std::string_view diskNumber()
constexpr TAG_PARSER_EXPORT std::string_view cover()
constexpr TAG_PARSER_EXPORT std::string_view grouping()
constexpr TAG_PARSER_EXPORT std::string_view date()
Contains all classes and functions of the TagInfo library.
Definition: aaccodebook.h:10
KnownField
Specifies the field.
Definition: tag.h:42
VorbisCommentFlags
The VorbisCommentFlags enum specifies flags which controls parsing and making of Vorbis comments.