Tag Parser  6.4.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  // predicate for finding pages of this stream by its stream serial number
62  const auto pred = bind(&OggPage::matchesStreamSerialNumber, _1, firstPage.streamSerialNumber());
63 
64  // iterate through segments using OggIterator
65  for(bool hasIdentificationHeader = false, hasCommentHeader = false; iterator && (!hasIdentificationHeader || !hasCommentHeader); ++iterator) {
66  const uint32 currentSize = iterator.currentSegmentSize();
67  if(currentSize >= 8) {
68  // determine stream format
69  inputStream().seekg(iterator.currentSegmentOffset());
70  const uint64 sig = reader().readUInt64BE();
71 
72  if((sig & 0x00ffffffffffff00u) == 0x00766F7262697300u) {
73  // Vorbis header detected
74  // set Vorbis as format
75  switch(m_format.general) {
79  break;
81  break;
82  default:
83  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
84  continue;
85  }
86 
87  // check header type
88  switch(sig >> 56) {
90  if(!hasIdentificationHeader) {
91  // parse identification header
93  ind.parseHeader(iterator);
94  m_version = ind.version();
95  m_channelCount = ind.channels();
97  if(ind.nominalBitrate()) {
98  m_bitrate = ind.nominalBitrate();
99  } else if(ind.maxBitrate() == ind.minBitrate()) {
100  m_bitrate = ind.maxBitrate();
101  }
102  if(m_bitrate) {
103  m_bitrate = static_cast<double>(m_bitrate) / 1000.0;
104  }
105  // determine sample count and duration if all pages have been fetched
106  if(iterator.areAllPagesFetched()) {
107  const auto &pages = iterator.pages();
108  const auto firstPage = find_if(pages.cbegin(), pages.cend(), pred);
109  const auto lastPage = find_if(pages.crbegin(), pages.crend(), pred);
110  if(firstPage != pages.cend() && lastPage != pages.crend()) {
111  m_sampleCount = lastPage->absoluteGranulePosition() - firstPage->absoluteGranulePosition();
112  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_sampleCount) / m_samplingFrequency);
113  }
114  }
115  hasIdentificationHeader = true;
116  } else {
117  addNotification(NotificationType::Critical, "Vorbis identification header appears more than once. Oversupplied occurrence will be ignored.", context);
118  }
119  break;
121  // Vorbis comment found -> notify container about comment
122  if(!hasCommentHeader) {
123  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), false, GeneralMediaFormat::Vorbis);
124  hasCommentHeader = true;
125  } else {
126  addNotification(NotificationType::Critical, "Vorbis comment header appears more than once. Oversupplied occurrence will be ignored.", context);
127  }
128  break;
130  break; // TODO
131  default:
132  ;
133  }
134 
135  } else if(sig == 0x4F70757348656164u) {
136  // Opus header detected
137  // set Opus as format
138  switch(m_format.general) {
142  break;
144  break;
145  default:
146  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
147  continue;
148  }
149  if(!hasIdentificationHeader) {
150  // parse identification header
152  ind.parseHeader(iterator);
153  m_version = ind.version();
154  m_channelCount = ind.channels();
156  // determine sample count and duration if all pages have been fetched
157  if(iterator.areAllPagesFetched()) {
158  const auto &pages = iterator.pages();
159  const auto firstPage = find_if(pages.cbegin(), pages.cend(), pred);
160  const auto lastPage = find_if(pages.crbegin(), pages.crend(), pred);
161  if(firstPage != pages.cend() && lastPage != pages.crend()) {
162  m_sampleCount = lastPage->absoluteGranulePosition() - firstPage->absoluteGranulePosition();
163  // must apply "pre-skip" here do calculate effective sample count and duration?
164  if(m_sampleCount > ind.preSkip()) {
165  m_sampleCount -= ind.preSkip();
166  } else {
167  m_sampleCount = 0;
168  }
169  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_sampleCount) / m_samplingFrequency);
170  }
171  }
172  hasIdentificationHeader = true;
173  } else {
174  addNotification(NotificationType::Critical, "Opus identification header appears more than once. Oversupplied occurrence will be ignored.", context);
175  }
176 
177  } else if(sig == 0x4F70757354616773u) {
178  // Opus comment detected
179  // set Opus as format
180  switch(m_format.general) {
184  break;
186  break;
187  default:
188  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
189  continue;
190  }
191 
192  // notify container about comment
193  if(!hasCommentHeader) {
194  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), false, GeneralMediaFormat::Opus);
195  hasCommentHeader = true;
196  } else {
197  addNotification(NotificationType::Critical, "Opus tags/comment header appears more than once. Oversupplied occurrence will be ignored.", context);
198  }
199 
200  } else if((sig & 0xFFFFFFFFFF000000u) == 0x7F464C4143000000u) {
201  // FLAC header detected
202  // set FLAC as format
203  switch(m_format.general) {
207  break;
209  break;
210  default:
211  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
212  continue;
213  }
214 
215  if(!hasIdentificationHeader) {
216  // parse FLAC-to-Ogg mapping header
217  FlacToOggMappingHeader mapping;
218  const FlacMetaDataBlockStreamInfo &streamInfo = mapping.streamInfo();
219  mapping.parseHeader(iterator);
220  m_bitsPerSample = streamInfo.bitsPerSample();
221  m_channelCount = streamInfo.channelCount();
222  m_samplingFrequency = streamInfo.samplingFrequency();
223  m_sampleCount = streamInfo.totalSampleCount();
224  if(!m_sampleCount && iterator.areAllPagesFetched()) {
225  const auto &pages = iterator.pages();
226  const auto firstPage = find_if(pages.cbegin(), pages.cend(), pred);
227  const auto lastPage = find_if(pages.crbegin(), pages.crend(), pred);
228  if(firstPage != pages.cend() && lastPage != pages.crend()) {
229  m_sampleCount = lastPage->absoluteGranulePosition() - firstPage->absoluteGranulePosition();
230  }
231  }
232  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_sampleCount) / m_samplingFrequency);
233  hasIdentificationHeader = true;
234  } else {
235  addNotification(NotificationType::Critical, "FLAC-to-Ogg mapping header appears more than once. Oversupplied occurrence will be ignored.", context);
236  }
237 
238  if(!hasCommentHeader) {
239  // a Vorbis comment should be following
240  if(++iterator) {
241  char buff[4];
242  iterator.read(buff, 4);
244  header.parseHeader(buff);
246  m_container.announceComment(iterator.currentPageIndex(), iterator.currentSegmentIndex(), header.isLast(), GeneralMediaFormat::Flac);
247  hasCommentHeader = true;
248  } else {
249  addNotification(NotificationType::Critical, "OGG page after FLAC-to-Ogg mapping header doesn't contain Vorbis comment.", context);
250  }
251  } else {
252  addNotification(NotificationType::Critical, "No more OGG pages after FLAC-to-Ogg mapping header (Vorbis comment expected).", context);
253  }
254  }
255 
256  } else if((sig & 0x00ffffffffffff00u) == 0x007468656F726100u) {
257  // Theora header detected
258  // set Theora as format
259  switch(m_format.general) {
263  break;
265  break;
266  default:
267  addNotification(NotificationType::Warning, "Stream format is inconsistent.", context);
268  continue;
269  }
270  // TODO: read more information about Theora stream
271 
272  } // currently only Vorbis, Opus and Theora can be detected, TODO: detect more formats
273 
274  } else {
275  // just ignore segments of only 8 byte or even less
276  // TODO: print warning?
277  }
278 
279  // TODO: reduce code duplication
280  }
281 
282  if(m_duration.isNull() && m_size && m_bitrate) {
283  // calculate duration from stream size and bitrate, assuming 1 % overhead
284  m_duration = TimeSpan::fromSeconds(static_cast<double>(m_size) / (m_bitrate * 125.0) * 1.1);
285  }
286  m_headerValid = true;
287 }
288 
289 }
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:271
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
uint64 absoluteGranulePosition() const
Returns the absolute granule position.
Definition: oggpage.h:143
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
bool areAllPagesFetched() const
Returns an indication whether all pages have been fetched.
Definition: oggiterator.h:268
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