Tag Parser 11.1.0
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(encoderSettings());
79 return std::string(description());
81 return std::string(grouping());
83 return std::string(label());
85 return std::string(performer());
87 return std::string(language());
89 return std::string(lyricist());
91 return std::string(lyrics());
93 return std::string(albumArtist());
95 return std::string(conductor());
97 return std::string(copyright());
98 default:
99 return std::string();
100 }
101}
102
104{
105 using namespace VorbisCommentIds;
106 // clang-format off
107 static const std::map<std::string_view, KnownField, CaseInsensitiveStringComparer> fieldMap({
131 });
132 // clang-format on
133 const auto knownField(fieldMap.find(id));
134 return knownField != fieldMap.cend() ? knownField->second : KnownField::Invalid;
135}
136
140template <class StreamType> void VorbisComment::internalParse(StreamType &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
141{
142 // prepare parsing
143 static const string context("parsing Vorbis comment");
144 const auto startOffset = static_cast<std::uint64_t>(stream.tellg());
145 try {
146 // read signature: 0x3 + "vorbis"
147 char sig[8];
148 bool skipSignature = flags & VorbisCommentFlags::NoSignature;
149 if (!skipSignature) {
151 stream.read(sig, 7);
152 skipSignature = (BE::toUInt64(sig) & 0xffffffffffffff00u) == 0x03766F7262697300u;
153 }
154 if (skipSignature) {
155 // read vendor (length prefixed string)
156 {
158 stream.read(sig, 4);
159 const auto vendorSize = LE::toUInt32(sig);
160 if (vendorSize <= maxSize) {
161 auto buff = make_unique<char[]>(vendorSize);
162 stream.read(buff.get(), vendorSize);
163 m_vendor.assignData(move(buff), vendorSize, TagDataType::Text, TagTextEncoding::Utf8);
164 // TODO: Is the vendor string actually UTF-8 (like the field values)?
165 } else {
166 diag.emplace_back(DiagLevel::Critical, "Vendor information is truncated.", context);
167 throw TruncatedDataException();
168 }
169 maxSize -= vendorSize;
170 }
171 // read field count
173 stream.read(sig, 4);
174 std::uint32_t fieldCount = LE::toUInt32(sig);
175 for (std::uint32_t i = 0; i < fieldCount; ++i) {
176 // read fields
177 VorbisCommentField field;
178 try {
179 field.parse(stream, maxSize, diag);
180 fields().emplace(field.id(), move(field));
181 } catch (const TruncatedDataException &) {
182 throw;
183 } catch (const Failure &) {
184 // nothing to do here since notifications will be added anyways
185 }
186 }
187 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
188 stream.ignore(); // skip framing byte
189 }
190 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
191 // turn "YEAR" into "DATE" (unless "DATE" exists)
192 // note: "DATE" is an official field and "YEAR" only an unofficial one but present in some files. In consistency with
193 // MediaInfo and VLC player it is treated like "DATE" here.
194 static const auto dateFieldId = std::string(VorbisCommentIds::date()), yearFieldId = std::string(VorbisCommentIds::year());
195 if (fields().find(dateFieldId) == fields().end()) {
196 const auto [first, end] = fields().equal_range(yearFieldId);
197 for (auto i = first; i != end; ++i) {
198 fields().emplace(dateFieldId, std::move(i->second));
199 }
200 fields().erase(first, end);
201 }
202 } else {
203 diag.emplace_back(DiagLevel::Critical, "Signature is invalid.", context);
204 throw InvalidDataException();
205 }
206 } catch (const TruncatedDataException &) {
207 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
208 diag.emplace_back(DiagLevel::Critical, "Vorbis comment is truncated.", context);
209 throw;
210 }
211
212 // warn if there are bytes left in the last segment of the Ogg packet containing the comment
213 if constexpr (std::is_same_v<std::decay_t<StreamType>, OggIterator>) {
214 auto bytesRemaining = std::uint64_t();
215 if (stream) {
216 bytesRemaining = stream.remainingBytesInCurrentSegment();
217 if (stream.currentPage().isLastSegmentUnconcluded()) {
218 stream.nextSegment();
219 if (stream) {
220 bytesRemaining += stream.remainingBytesInCurrentSegment();
221 }
222 }
223 }
224 if (bytesRemaining) {
225 diag.emplace_back(DiagLevel::Warning, argsToString(bytesRemaining, " bytes left in last segment."), context);
226 }
227 }
228}
229
238{
239 internalParse(iterator, iterator.streamSize(), flags, diag);
240}
241
249void VorbisComment::parse(istream &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
250{
251 internalParse(stream, maxSize, flags, diag);
252}
253
261void VorbisComment::make(std::ostream &stream, VorbisCommentFlags flags, Diagnostics &diag)
262{
263 // prepare making
264 static const string context("making Vorbis comment");
265 string vendor;
266 try {
267 m_vendor.toString(vendor);
268 } catch (const ConversionException &) {
269 diag.emplace_back(DiagLevel::Warning, "Can not convert the assigned vendor to string.", context);
270 }
271 BinaryWriter writer(&stream);
272 if (!(flags & VorbisCommentFlags::NoSignature)) {
273 // write signature
274 static const char sig[7] = { 0x03, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73 };
275 stream.write(sig, sizeof(sig));
276 }
277 // write vendor
278 writer.writeUInt32LE(static_cast<std::uint32_t>(vendor.size()));
279 writer.writeString(vendor);
280 // write field count later
281 const auto fieldCountOffset = stream.tellp();
282 writer.writeUInt32LE(0);
283 // write fields
284 std::uint32_t fieldsWritten = 0;
285 for (auto &i : fields()) {
286 VorbisCommentField &field = i.second;
287 if (!field.value().isEmpty()) {
288 try {
289 if (field.make(writer, flags, diag)) {
290 ++fieldsWritten;
291 }
292 } catch (const Failure &) {
293 }
294 }
295 }
296 // write field count
297 const auto framingByteOffset = stream.tellp();
298 stream.seekp(fieldCountOffset);
299 writer.writeUInt32LE(fieldsWritten);
300 stream.seekp(framingByteOffset);
301 // write framing byte
302 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
303 stream.put(0x01);
304 }
305}
306
307} // 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:214
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 description()
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 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 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.