Tag Parser  6.5.1
C++ library for reading and writing MP4 (iTunes), ID3, Vorbis, Opus, FLAC and Matroska tags
oggstream.cpp
Go to the documentation of this file.
1 #include "./oggstream.h"
2 #include "./oggcontainer.h"
3 
4 #include "../vorbis/vorbispackagetypes.h"
5 #include "../vorbis/vorbisidentificationheader.h"
6 
7 #include "../opus/opusidentificationheader.h"
8 
9 #include "../flac/flactooggmappingheader.h"
10 
11 #include "../mediafileinfo.h"
12 #include "../exceptions.h"
13 #include "../mediaformat.h"
14 
15 #include <c++utilities/chrono/timespan.h>
16 
17 #include <iostream>
18 #include <functional>
19 
20 using namespace std;
21 using namespace std::placeholders;
22 using namespace ChronoUtilities;
23 
24 namespace Media {
25 
34 OggStream::OggStream(OggContainer &container, vector<OggPage>::size_type startPage) :
35  AbstractTrack(container.stream(), container.m_iterator.pages()[startPage].startOffset()),
36  m_startPage(startPage),
37  m_container(container),
38  m_currentSequenceNumber(0)
39 {}
40 
45 {}
46 
48 {
49  static const string context("parsing OGG page header");
50 
51  // read basic information from first page
52  OggIterator &iterator = m_container.m_iterator;
53  const OggPage &firstPage = iterator.pages()[m_startPage];
54  m_version = firstPage.streamStructureVersion();
55  m_id = firstPage.streamSerialNumber();
56 
57  // ensure iterator is setup properly
58  iterator.setFilter(firstPage.streamSerialNumber());
59  iterator.setPageIndex(m_startPage);
60 
61  // iterate through segments using OggIterator
62  for(bool hasIdentificationHeader = false, hasCommentHeader = false; iterator && (!hasIdentificationHeader || !hasCommentHeader); ++iterator) {
63  const uint32 currentSize = iterator.currentSegmentSize();
64  if(currentSize >= 8) {
65  // determine stream format
66  inputStream().seekg(iterator.currentSegmentOffset());
67  const uint64 sig = reader().readUInt64BE();
68 
69  if((sig & 0x00ffffffffffff00u) == 0x00766F7262697300u) {
70  // Vorbis header detected
71  switch(m_format.general) {
75  break;
77  break;
78  default:
79  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
80  continue;
81  }
82 
83  // check header type
84  switch(sig >> 56) {
86  if(!hasIdentificationHeader) {
87  // parse identification header
89  ind.parseHeader(iterator);
90  m_version = ind.version();
91  m_channelCount = ind.channels();
93  if(ind.nominalBitrate()) {
94  m_bitrate = ind.nominalBitrate();
95  } else if(ind.maxBitrate() == ind.minBitrate()) {
96  m_bitrate = ind.maxBitrate();
97  }
98  if(m_bitrate != 0.0) {
99  m_bitrate /= 1000.0;
100  }
101  calculateDurationViaSampleCount();
102  hasIdentificationHeader = true;
103  } else {
104  addNotification(NotificationType::Critical, "Vorbis identification header appears more than once. Oversupplied occurrence will be ignored.", context);
105  }
106  break;
108  // Vorbis comment found -> notify container about comment
109  if(!hasCommentHeader) {
110  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), false, GeneralMediaFormat::Vorbis);
111  hasCommentHeader = true;
112  } else {
113  addNotification(NotificationType::Critical, "Vorbis comment header appears more than once. Oversupplied occurrence will be ignored.", context);
114  }
115  break;
117  break; // TODO
118  default:
119  ;
120  }
121 
122  } else if(sig == 0x4F70757348656164u) {
123  // Opus header detected
124  switch(m_format.general) {
128  break;
130  break;
131  default:
132  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
133  continue;
134  }
135  if(!hasIdentificationHeader) {
136  // parse identification header
138  ind.parseHeader(iterator);
139  m_version = ind.version();
140  m_channelCount = ind.channels();
142  calculateDurationViaSampleCount(ind.preSkip());
143  hasIdentificationHeader = true;
144  } else {
145  addNotification(NotificationType::Critical, "Opus identification header appears more than once. Oversupplied occurrence will be ignored.", context);
146  }
147 
148  } else if(sig == 0x4F70757354616773u) {
149  // Opus comment detected
150  switch(m_format.general) {
154  break;
156  break;
157  default:
158  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
159  continue;
160  }
161 
162  // notify container about comment
163  if(!hasCommentHeader) {
164  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), false, GeneralMediaFormat::Opus);
165  hasCommentHeader = true;
166  } else {
167  addNotification(NotificationType::Critical, "Opus tags/comment header appears more than once. Oversupplied occurrence will be ignored.", context);
168  }
169 
170  } else if((sig & 0xFFFFFFFFFF000000u) == 0x7F464C4143000000u) {
171  // FLAC header detected
172  switch(m_format.general) {
176  break;
178  break;
179  default:
180  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
181  continue;
182  }
183 
184  if(!hasIdentificationHeader) {
185  // parse FLAC-to-Ogg mapping header
186  FlacToOggMappingHeader mapping;
187  const FlacMetaDataBlockStreamInfo &streamInfo = mapping.streamInfo();
188  mapping.parseHeader(iterator);
189  m_bitsPerSample = streamInfo.bitsPerSample();
190  m_channelCount = streamInfo.channelCount();
191  m_samplingFrequency = streamInfo.samplingFrequency();
192  m_sampleCount = streamInfo.totalSampleCount();
193  calculateDurationViaSampleCount();
194  hasIdentificationHeader = true;
195  } else {
196  addNotification(NotificationType::Critical, "FLAC-to-Ogg mapping header appears more than once. Oversupplied occurrence will be ignored.", context);
197  }
198 
199  if(!hasCommentHeader) {
200  // a Vorbis comment should be following
201  if(++iterator) {
202  char buff[4];
203  iterator.read(buff, 4);
205  header.parseHeader(buff);
207  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), header.isLast(), GeneralMediaFormat::Flac);
208  hasCommentHeader = true;
209  } else {
210  addNotification(NotificationType::Critical, "OGG page after FLAC-to-Ogg mapping header doesn't contain Vorbis comment.", context);
211  }
212  } else {
213  addNotification(NotificationType::Critical, "No more OGG pages after FLAC-to-Ogg mapping header (Vorbis comment expected).", context);
214  }
215  }
216 
217  } else if((sig & 0x00ffffffffffff00u) == 0x007468656F726100u) {
218  // Theora header detected
219  switch(m_format.general) {
223  break;
225  break;
226  default:
227  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
228  continue;
229  }
230  // TODO: read more information about Theora stream
231 
232  } else if((sig & 0xFFFFFFFFFFFF0000u) == 0x5370656578200000u) {
233  // Speex header detected
234  switch(m_format.general) {
238  break;
240  break;
241  default:
242  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
243  continue;
244  }
245  // TODO: read more information about Speex stream
246  } else if(sig == 0x595556344D504547u) {
247  // YUV4MPEG header detected
248  switch(m_format.general) {
252  m_chromaFormat = "YUV";
253  break;
255  break;
256  default:
257  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
258  continue;
259  }
260  // TODO: read more information about YUV4MPEG stream
261  }
262  // currently only Vorbis, Opus, Theora, Speex and YUV4MPEG can be detected, TODO: detect more formats
263 
264  } else {
265  // just ignore segments of only 8 byte or even less
266  // TODO: print warning?
267  }
268 
269  // TODO: reduce code duplication
270  }
271 
272  // estimate duration from size and bitrate if sample count and sample rate could not be determined
273  if(m_duration.isNull() && m_size && m_bitrate != 0.0) {
274  // calculate duration from stream size and bitrate, assuming 1 % overhead
275  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_size) / (m_bitrate * 125.0) * 1.1);
276  }
277  m_headerValid = true;
278 }
279 
280 void OggStream::calculateDurationViaSampleCount(uint16 preSkip)
281 {
282  // define predicate for finding pages of this stream by its stream serial number
283  const auto pred = bind(&OggPage::matchesStreamSerialNumber, _1, m_id);
284 
285  // determine sample count
286  const auto &iterator = m_container.m_iterator;
287  if(!m_sampleCount && iterator.areAllPagesFetched()) {
288  const auto &pages = iterator.pages();
289  const auto firstPage = find_if(pages.cbegin(), pages.cend(), pred);
290  const auto lastPage = find_if(pages.crbegin(), pages.crend(), pred);
291  if(firstPage != pages.cend() && lastPage != pages.crend()) {
292  m_sampleCount = lastPage->absoluteGranulePosition() - firstPage->absoluteGranulePosition();
293  // must apply "pre-skip" here to calculate effective sample count and duration?
294  if(m_sampleCount > preSkip) {
295  m_sampleCount -= preSkip;
296  } else {
297  m_sampleCount = 0;
298  }
299  }
300  }
301 
302  // actually calculate the duration
303  if(m_sampleCount && m_samplingFrequency != 0.0) {
304  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_sampleCount) / m_samplingFrequency);
305  }
306 }
307 
308 }
std::vector< uint32 >::size_type currentSegmentIndex() const
Returns the index of the current segment (in the current page) if the iterator is valid; otherwise an...
Definition: oggiterator.h:193
uint32 currentSegmentSize() const
Returns the size of the current segment.
Definition: oggiterator.h:229
byte type() const
Returns the block type.
Definition: flacmetadata.h:89
void parseHeader(const char *buffer)
Parses the FLAC "METADATA_BLOCK_HEADER" which is read using the specified iterator.
byte isLast() const
Returns whether this is the last metadata block before the audio blocks.
Definition: flacmetadata.h:72
bool matchesStreamSerialNumber(uint32 streamSerialNumber) const
Returns whether the stream serial number of the current instance matches the specified one...
Definition: oggpage.h:165
The FlacMetaDataBlockHeader class is a FLAC "METADATA_BLOCK_HEADER" parser and maker.
Definition: flacmetadata.h:38
std::istream & inputStream()
Returns the associated input stream.
GeneralMediaFormat general
Definition: mediaformat.h:274
const std::vector< OggPage > & pages() const
Returns a vector of containing the OGG pages that have been fetched yet.
Definition: oggiterator.h:122
void setPageIndex(std::vector< OggPage >::size_type index)
Sets the current page index.
Definition: oggiterator.h:172
The AbstractTrack class parses and stores technical information about video, audio and other kinds of...
Definition: abstracttrack.h:40
STL namespace.
~OggStream()
Destroys the track.
Definition: oggstream.cpp:44
void addNotification(const Notification &notification)
This method is meant to be called by the derived class to add a notification.
void setFilter(uint32 streamSerialId)
Allows to filter pages by the specified streamSerialId.
Definition: oggiterator.h:242
uint32 streamSerialNumber() const
Returns the stream serial number.
Definition: oggpage.h:156
The FlacToOggMappingHeader class is a FLAC-to-Ogg mapping header parser.
byte channels() const
Returns the number of channels for the Opus stream.
The FlacMetaDataBlockStreamInfo class is a FLAC "METADATA_BLOCK_STREAMINFO" parser.
Definition: flacmetadata.h:119
The OggPage class is used to parse OGG pages.
Definition: oggpage.h:14
IoUtilities::BinaryReader & reader()
Returns a binary reader for the associated stream.
void parseHeader(OggIterator &iterator)
Parses the Vorbis identification header which is read using the specified iterator.
byte streamStructureVersion() const
Returns the stream structure version.
Definition: oggpage.h:92
uint16 preSkip() const
Returns "pre-skip" value for the Opus stream.
uint32 sampleRate() const
Returns the INPUT sample rate.
std::vector< OggPage >::size_type currentPageIndex() const
Returns the index of the current page if the iterator is valid; otherwise an undefined index is retur...
Definition: oggiterator.h:163
byte bitsPerSample() const
Returns the bits per sample.
Definition: flacmetadata.h:229
uint64 currentSegmentOffset() const
Returns the start offset of the current segment in the input stream if the iterator is valid; otherwi...
Definition: oggiterator.h:202
void read(char *buffer, std::size_t count)
Reads count bytes from the OGG stream and writes it to the specified buffer.
The VorbisIdentificationHeader class is a Vorbis identification header parser.
uint64 totalSampleCount() const
Returns the total samples in stream.
Definition: flacmetadata.h:242
ChronoUtilities::TimeSpan m_duration
The OpusIdentificationHeader class is an Opus identification header parser.
byte channelCount() const
Returns the number of channels.
Definition: flacmetadata.h:217
byte version() const
Returns the version (which should be 1 currently).
Implementation of Media::AbstractContainer for OGG files.
Definition: oggcontainer.h:127
const char * m_chromaFormat
The OggIterator class helps iterating through all segments of an OGG bitstream.
Definition: oggiterator.h:11
void parseHeader(OggIterator &iterator)
Parses the FLAC-to-Ogg mapping header which is read using the specified iterator. ...
Contains all classes and functions of the TagInfo library.
Definition: exceptions.h:9
uint32 samplingFrequency() const
Returns the sampling frequency in Hz.
Definition: flacmetadata.h:207
void parseHeader(OggIterator &iterator)
Parses the Opus identification header which is read using the specified iterator. ...
const FlacMetaDataBlockStreamInfo & streamInfo() const
Returns the stream info.
void internalParseHeader()
This method is internally called to parse header information.
Definition: oggstream.cpp:47