Tag Parser 12.1.0
C++ library for reading and writing MP4 (iTunes), ID3, Vorbis, Opus, FLAC and Matroska tags
Loading...
Searching...
No Matches
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());
107 return std::string(rating());
108 case KnownField::Bpm:
109 return std::string(bpm());
110 default:
111 return std::string();
112 }
113}
114
116{
117 using namespace VorbisCommentIds;
118 // clang-format off
119 static const std::map<std::string_view, KnownField, CaseInsensitiveStringComparer> fieldMap({
120 { album(), KnownField::Album },
121 { artist(), KnownField::Artist },
122 { comment(), KnownField::Comment },
123 { cover(), KnownField::Cover },
124 { date(), KnownField::RecordDate },
125 { year(), KnownField::RecordDate },
126 { title(), KnownField::Title },
127 { genre(), KnownField::Genre },
128 { trackNumber(), KnownField::TrackPosition },
129 { diskNumber(), KnownField::DiskPosition },
130 { partNumber(), KnownField::PartNumber },
131 { composer(), KnownField::Composer },
132 { encoder(), KnownField::Encoder },
133 { encodedBy(), KnownField::EncodedBy },
134 { encoderSettings(), KnownField::EncoderSettings },
135 { description(), KnownField::Description },
136 { grouping(), KnownField::Grouping },
137 { label(), KnownField::RecordLabel },
138 { performer(), KnownField::Performers },
139 { lyricist(), KnownField::Lyricist },
140 { lyrics(), KnownField::Lyrics },
141 { albumArtist(), KnownField::AlbumArtist },
142 { conductor(), KnownField::Conductor },
143 { copyright(), KnownField::Copyright },
144 { license(), KnownField::License },
145 { director(), KnownField::Director },
146 { isrc(), KnownField::ISRC },
147 { rating(), KnownField::Rating },
148 { bpm(), KnownField::Bpm },
149 });
150 // clang-format on
151 const auto knownField(fieldMap.find(id));
152 return knownField != fieldMap.cend() ? knownField->second : KnownField::Invalid;
153}
154
158template <class StreamType> void VorbisComment::internalParse(StreamType &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
159{
160 // prepare parsing
161 static const string context("parsing Vorbis comment");
162 const auto startOffset = static_cast<std::uint64_t>(stream.tellg());
163 try {
164 // read signature: 0x3 + "vorbis"
165 char sig[8];
166 bool skipSignature = flags & VorbisCommentFlags::NoSignature;
167 if (!skipSignature) {
169 stream.read(sig, 7);
170 skipSignature = (BE::toInt<std::uint64_t>(sig) & 0xffffffffffffff00u) == 0x03766F7262697300u;
171 }
172 if (skipSignature) {
173 // read vendor (length prefixed string)
174 {
176 stream.read(sig, 4);
177 const auto vendorSize = LE::toUInt32(sig);
178 if (vendorSize <= maxSize) {
179 auto buff = make_unique<char[]>(vendorSize);
180 stream.read(buff.get(), vendorSize);
181 m_vendor.assignData(std::move(buff), vendorSize, TagDataType::Text, TagTextEncoding::Utf8);
182 // TODO: Is the vendor string actually UTF-8 (like the field values)?
183 } else {
184 diag.emplace_back(DiagLevel::Critical, "Vendor information is truncated.", context);
185 throw TruncatedDataException();
186 }
187 maxSize -= vendorSize;
188 }
189 // read field count
191 stream.read(sig, 4);
192 std::uint32_t fieldCount = LE::toUInt32(sig);
193 for (std::uint32_t i = 0; i < fieldCount; ++i) {
194 // read fields
195 VorbisCommentField field;
196 try {
197 field.parse(stream, maxSize, diag);
198 fields().emplace(field.id(), std::move(field));
199 } catch (const TruncatedDataException &) {
200 throw;
201 } catch (const Failure &) {
202 // nothing to do here since notifications will be added anyways
203 }
204 }
205 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
206 stream.ignore(); // skip framing byte
207 }
208 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
209 // turn "YEAR" into "DATE" (unless "DATE" exists)
210 // note: "DATE" is an official field and "YEAR" only an unofficial one but present in some files. In consistency with
211 // MediaInfo and VLC player it is treated like "DATE" here.
212 static const auto dateFieldId = std::string(VorbisCommentIds::date()), yearFieldId = std::string(VorbisCommentIds::year());
213 if (fields().find(dateFieldId) == fields().end()) {
214 const auto [first, end] = fields().equal_range(yearFieldId);
215 for (auto i = first; i != end; ++i) {
216 fields().emplace(dateFieldId, std::move(i->second));
217 }
218 fields().erase(first, end);
219 }
220 } else {
221 diag.emplace_back(DiagLevel::Critical, "Signature is invalid.", context);
222 throw InvalidDataException();
223 }
224 } catch (const TruncatedDataException &) {
225 m_size = static_cast<std::uint64_t>(stream.tellg()) - startOffset;
226 diag.emplace_back(DiagLevel::Critical, "Vorbis comment is truncated.", context);
227 throw;
228 }
229
230 // warn if there are bytes left in the last segment of the Ogg packet containing the comment
231 if constexpr (std::is_same_v<std::decay_t<StreamType>, OggIterator>) {
232 auto bytesRemaining = std::uint64_t();
233 if (stream) {
234 bytesRemaining = stream.remainingBytesInCurrentSegment();
235 if (stream.currentPage().isLastSegmentUnconcluded()) {
236 stream.nextSegment();
237 if (stream) {
238 bytesRemaining += stream.remainingBytesInCurrentSegment();
239 }
240 }
241 }
242 if (bytesRemaining) {
243 diag.emplace_back(DiagLevel::Warning, argsToString(bytesRemaining, " bytes left in last segment."), context);
244 }
245 }
246}
247
256{
257 internalParse(iterator, iterator.streamSize(), flags, diag);
258}
259
267void VorbisComment::parse(istream &stream, std::uint64_t maxSize, VorbisCommentFlags flags, Diagnostics &diag)
268{
269 internalParse(stream, maxSize, flags, diag);
270}
271
279void VorbisComment::make(std::ostream &stream, VorbisCommentFlags flags, Diagnostics &diag)
280{
281 // prepare making
282 static const string context("making Vorbis comment");
283 string vendor;
284 try {
285 m_vendor.toString(vendor);
286 } catch (const ConversionException &) {
287 diag.emplace_back(DiagLevel::Warning, "Can not convert the assigned vendor to string.", context);
288 }
289 BinaryWriter writer(&stream);
290 if (!(flags & VorbisCommentFlags::NoSignature)) {
291 // write signature
292 static const char sig[7] = { 0x03, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73 };
293 stream.write(sig, sizeof(sig));
294 }
295 // write vendor
296 writer.writeUInt32LE(static_cast<std::uint32_t>(vendor.size()));
297 writer.writeString(vendor);
298 // write field count later
299 const auto fieldCountOffset = stream.tellp();
300 writer.writeUInt32LE(0);
301 // write fields
302 std::uint32_t fieldsWritten = 0;
303 for (auto &i : fields()) {
304 VorbisCommentField &field = i.second;
305 if (!field.value().isEmpty()) {
306 try {
307 if (field.make(writer, flags, diag)) {
308 ++fieldsWritten;
309 }
310 } catch (const Failure &) {
311 }
312 }
313 }
314 // write field count
315 const auto framingByteOffset = stream.tellp();
316 stream.seekp(fieldCountOffset);
317 writer.writeUInt32LE(fieldsWritten);
318 stream.seekp(framingByteOffset);
319 // write framing byte
320 if (!(flags & VorbisCommentFlags::NoFramingByte)) {
321 stream.put(0x01);
322 }
323}
324
325} // namespace TagParser
The Diagnostics class is a container for DiagMessage.
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
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).
TagValue & value()
Returns the value of the current TagField.
The TagValue class wraps values of different types.
Definition tagvalue.h:147
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:450
bool isEmpty() const
Returns whether no or an empty value is assigned.
Definition tagvalue.h:490
std::uint64_t m_size
Definition tag.h:204
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.
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.
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 year()
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:29
VorbisCommentFlags
The VorbisCommentFlags enum specifies flags which controls parsing and making of Vorbis comments.