<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Bluish Coder: vorbis</title>
 <link href="http://bluishcoder.co.nz/tag/vorbis/atom.xml" rel="self"/>
 <link href="http://bluishcoder.co.nz/"/>
 <updated>2020-07-10T16:25:05+12:00</updated>
 <id>http://bluishcoder.co.nz/</id>
 <author>
   <name>Bluishcoder</name>
   <email>admin@bluishcoder.co.nz</email>
 </author>

 
 <entry>
   <title>Vorbis Player implemented in Pure</title>
   <link href="http://bluishcoder.co.nz/2010/02/25/vorbis-player-written-in-pure.html"/>
   <updated>2010-02-25T14:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2010/02/25/vorbis-player-written-in-pure</id>
   <content type="html">&lt;p&gt;After writing the &lt;a href=&quot;http://bluishcoder.co.nz/2010/02/20/pure-preforking-echo-server-example.html&quot;&gt;preforking echo server example&lt;/a&gt; in &lt;a href=&quot;http://code.google.com/p/pure-lang/&quot;&gt;Pure&lt;/a&gt; I wanted to try something a bit more complex. I&#39;ve written Ogg players in various languages before so I decided to do one in Pure to compare. Here&#39;s some of the ones I&#39;ve written in the past:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2009/03/oggplayer-simple-ogg-player-using.html&quot;&gt;oggplayer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2009/06/26/decoding-vorbis-files-with-libvorbis.html&quot;&gt;plogg&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tech.groups.yahoo.com/group/iolanguage/message/11610&quot;&gt;Io Language Addons&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2007/05/ogg-theora-support-for-factor.html&quot;&gt;Factor Ogg Player&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;An unreleased Haskell Vorbis player&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I wrapped the libogg and libvorbis libraries using the Pure FFI. A program &#39;pure-gen&#39; is included with Pure that will generate FFI wrappers given a C include file. I ran this against libogg and libvorbis. The generated Pure wrappers look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;extern int ogg_page_version(ogg_page*);
extern int ogg_page_continued(ogg_page*);
extern int ogg_page_bos(ogg_page*);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see Pure FFI definitions look very much like the C definitions.&lt;/p&gt;

&lt;p&gt;I decided to model an Ogg file as a list of physical pages. This is esentially a list containing elements of the libogg ogg_page object. I have a Pure function that will take this list of pages and return a list of packets for each logical bitstream in the file. For vorbis playback I take this list of packets for the vorbis bitstream and produce a list of decoded PCM data.&lt;/p&gt;

&lt;p&gt;Pure is a strict language by default but provides an &#39;&amp;amp;&#39; special form to perform lazy evaluation. I use this to make sure all the returned lists mentioned above are lazy. Playing the lazy list of decoded PCM data never loads the entire file in memory. The file is read, converted into packets and decoded as each element of the PCM data list is requested.&lt;/p&gt;

&lt;p&gt;For audio playback I use &lt;a href=&quot;http://connect.creativelabs.com/openal/default.aspx&quot;&gt;OpenAL&lt;/a&gt;. I queue the PCM data to an OpenAL source up to a limit of 50 queued items, removing them as they get processed and adding new ones when room becomes available.&lt;/p&gt;

&lt;p&gt;Here&#39;s what some of the API to process the Ogg files looks like in Pure. First load the player code. This will also load the Ogg, Vorbis and OpenAL wrappers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ pure -i player.pure
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From the Pure REPL, play a vorbis file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; play_vorbis (sources!0) &quot;test.ogg&quot;;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Load an Ogg file getting a lazy list of all pages in the file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; using namespace ogg;
&amp;gt; let p = file_pages &quot;test.ogg&quot;;
&amp;gt; p;
ogg_page (#&amp;lt;pointer 0x9e61cc8&amp;gt;,[...]):#&amp;lt;thunk 0xb7259b38&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get a list of all packets and the serial number of the first logical bitstream in the list of pages:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let (stream1,serialno) = packets p;
&amp;gt; serialno;
1426627898
&amp;gt; stream1;
ogg_packet (#&amp;lt;pointer 0x9dd98f0&amp;gt;,[...]):#&amp;lt;thunk 0xb725bce0&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get the next logical bitstream:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let p2 = filter (\x-&amp;gt;ogg_page_serialno x ~= serialno) p;
&amp;gt; p2;
#&amp;lt;thunk 0xb725dc30&amp;gt;
&amp;gt; let (stream2,serialno2) = packets p2;
&amp;gt; serialno2;
629367739
&amp;gt; stream2;
ogg_packet (#&amp;lt;pointer 0x9cfcf08&amp;gt;,[...]):#&amp;lt;thunk 0xb725c988&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that all these results are lazily evaluated so the entire
file is not loaded into memory. If we look at the original list
of pages you&#39;ll see what has been read so far (two pages):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; p;
ogg_page (...):ogg_page (...):#&amp;lt;thunk 0xb725dd98&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get all the streams in the file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let s = all_streams p;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get all the vorbis streams:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let v = vorbis_streams s;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get the first vorbis stream. I ignore the serial number here (this is what the _ does):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let (v1, _) = v!0;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Decode the vorbis header packets and intialize a vorbis decoder
for the first vorbis stream:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let decoder = vorbis_header v1;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Get a lazy list of all the decoded PCM data from the vorbis stream:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; let pcm = pcm_data decoder;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The mechanics of getting the decoding floating point data from libvorbis into Pure and then back to the OpenAL C API is made easier due to it being possible to easily convert to and from raw C pointers and Pure matrix objects.&lt;/p&gt;

&lt;p&gt;For example, the data returned from the vorbis call to decode the data is an array of pointers pointing to an array of floats. To convert this to a Pure matrix with dimensions (c,n) where &#39;c&#39; is the number of channels and &#39;n&#39; is the number of samples:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;vorbis_synthesis_read dsp samples $$ matrix m
when
  f0 = get_pointer data;
  floats = [get_pointer (f0+(x*4))|x=0..(channels-1)];
  m = map (float_matrix samples) floats;
end;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code uses a list comprehension to return a list of &#39;pointer to array of floats&#39;. One pointer for each channel in the audio data. It then maps over this list producing a new list containing a matrix of float&#39;s. This is list of matrices each of which contains the audio data for a channel. The &#39;matrix m&#39; call converts this to a single matrix of dimensions (c,n).&lt;/p&gt;

&lt;p&gt;OpenAL expects the data as a pointer to a contiguous matrix of floats with dimensions (n,c) so when writing to OpenAL the matrix needs to be transposed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;play_pcm source rate pcm@(x:xs) =
  ....
  queue_sample source rate (transpose x) $$
  play source $$
  play_pcm source rate xs;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This transposed matrix is later converted from floats to 16 bit integers and &#39;packed&#39; so it is contiguous in memory, and a pointer to the raw memory passed to OpenAL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;buffer16 s = pack (map clamp s);  
...
data = buffer16 ...pcmdata...;
alBufferData ... (cooked (short_pointer NULL data)) ((#data) * (sizeof sshort_t)) ...;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &#39;cooked&#39; call means the C memory has &#39;free&#39; called on it when nothing in Pure is holding onto it anymore.&lt;/p&gt;

&lt;p&gt;One downside with lazy lists is it can be easy to accidently read the entire file and decode everything before playing. This will cause issues with large Ogg files. I managed to avoid that and files play in constant memory. An &lt;a href=&quot;http://okmij.org/ftp/Streams.html&quot;&gt;iteratee&lt;/a&gt; style approach might be interesting to try as an alternative to lazy lists. I&#39;d like to try decoding Theora files and doing a/v sync in Pure at some point as well.&lt;/p&gt;

&lt;p&gt;I haven&#39;t used Pure much but it seemed to be fairly simple to put this together. I&#39;d be interested in feedback on the approach (using lazy lists) and Pure style issues in the code.&lt;/p&gt;

&lt;p&gt;The code for this is at &lt;a href=&quot;http://github.com/doublec/pure-ogg-player&quot;&gt;http://github.com/doublec/pure-ogg-player&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Playing Ogg files with audio and video in sync</title>
   <link href="http://bluishcoder.co.nz/2009/06/27/playing-ogg-files-with-audio-and-video.html"/>
   <updated>2009-06-27T22:07:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2009/06/27/playing-ogg-files-with-audio-and-video</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2009/06/26/decoding-vorbis-files-with-libvorbis.html&quot;&gt;My last post in this series&lt;/a&gt; had Vorbis audio playing but with Theora video out of sync. This post will go through an approach to keeping the video in sync with the audio.&lt;/p&gt;

&lt;p&gt;To get video in sync with the audio we need a timer incrementing from when we start playback. We can&#39;t use the system clock for this as it is not necessarily keeping the same time as the audio or video being played. The system clock can drift slightly and over time this audio and video to get out of sync.&lt;/p&gt;

&lt;p&gt;The audio library I&#39;m using, libsydneyaudio, has an API call that allows getting the playback position of the sound sample being played by the audio system. This is a value in bytes. Since we know the sample rate and number of channels of the audio stream we can compute a time value from this. Synchronisation becomes a matter of continuously feeding the audio to libsydneybackend, querying the current position, converting it to a time value, and displaying the frame for that time.&lt;/p&gt;

&lt;p&gt;The time for a particular frame is returned by the call to &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#g31c814bf09b2232aff69c57ae20f04eb&quot;&gt;th_decode_packetin&lt;/a&gt;. The last parameter is a pointer to hold the &#39;granulepos&#39; of the decoded frame. The Theora spec explains that the granulepos can be used to compute the time that this frame should be displayed up to. That is, when this time is exceeded this frame should no longer be displayed. It also enables computing the location of the keyframe that this frame depends on - I&#39;ll cover what this means when I write about how to do seeking.&lt;/p&gt;

&lt;p&gt;The libtheora API &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__basefuncs.html#g707e1e281de788af0df39ef00f3fb432&quot;&gt;th_granule_time&lt;/a&gt; converts a &#39;granulepos&#39; to an absolute time in seconds. So decoding a frame gives us &#39;granulepos&#39;. We store this so we know when to stop displaying the frame. We track the audio position, convert it to a time. If it exceeds this value we decode the next frame and display that. Here&#39;s a breakdown of the steps:
* Read the headers from the Ogg file. Stop when we hit the first data packet.
* Read packets from the audio stream in the Ogg file. For each audio packet:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;ul&amp;gt;
&amp;lt;li&amp;gt;Decode the audio data and write it to the audio hardware.&amp;lt;/li&amp;gt;
&amp;lt;li&amp;gt;Get the current playback position of the audio and convert it to an absolute time value.&amp;lt;/li&amp;gt;
&amp;lt;li&amp;gt;Convert the last granulepos read (defaulting to zero if none have been read) to an absolute time value using the libtheora API.&amp;lt;/li&amp;gt;
&amp;lt;li&amp;gt;If the audio time is greater than the video time:   
    &amp;lt;ol&amp;gt;
      &amp;lt;li&amp;gt;Read a packet from the Theora stream.&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Decode that packet and display it&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Store the granulepos from that decoded frame so we know when to display the next frame.&amp;lt;/li&amp;gt;
    &amp;lt;/ol&amp;gt;
&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that the structure of the program is different to the last few articles. We no longer read all packets from the stream, processing them as we get them. Instead we specifically process the audio packets and only handle the video when it&#39;s time to display them. Since we are driving our a/v sync off the audio clock we must continously feed the audio data. I think it tends to be a better user experience to have flawless audio with video frame skipping rather than skipping audio but smooth video. Worse is to have both skipping of course.&lt;/p&gt;

&lt;p&gt;The example code for this article is in the &#39;&lt;a href=&quot;http://github.com/doublec/plogg/tree/part4_avsync&quot;&gt;part4_avsync&lt;/a&gt;&#39; branch on github.&lt;/p&gt;

&lt;p&gt;This example takes a slightly different approach to reading headers. I use &lt;a href=&quot;http://www.xiph.org/ogg/doc/libogg/ogg_stream_packetpeek.html&quot;&gt;ogg_stream_packetpeek&lt;/a&gt; to peek ahead in the bitstream for a packet and do the header processing on the peeked packet. If it is a header I then consume the packet. This is done so I don&#39;t consume the first data packet when reading the headers. I want the data packets to be consumed in a particular order (audio, followed by video when needed).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Process all available header packets in the stream. When we hit
// the first data stream we don&#39;t decode it, instead we
// return. The caller can then choose to process whatever data
// streams it wants to deal with.
ogg_packet packet;
while (!headersDone &amp;amp;&amp;amp;
       (ret = ogg_stream_packetpeek(&amp;amp;stream-&amp;gt;mState, &amp;amp;packet)) != 0) {
assert(ret == 1);

// A packet is available. If it is not a header packet we exit.
// If it is a header packet, process it as normal.
headersDone = headersDone || handle_theora_header(stream, &amp;amp;packet);
headersDone = headersDone || handle_vorbis_header(stream, &amp;amp;packet);
if (!headersDone) {
  // Consume the packet
  ret = ogg_stream_packetout(&amp;amp;stream-&amp;gt;mState, &amp;amp;packet);
  assert(ret == 1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To read packets for a particular stream I use a &#39;read_packet&#39; function that operates on a stream passed as a parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;bool OggDecoder::read_packet(istream&amp;amp; is, 
                             ogg_sync_state* state, 
                             OggStream* stream, 
                             ogg_packet* packet) {
  int ret = 0;
  while ((ret = ogg_stream_packetout(&amp;amp;stream-&amp;gt;mState, packet)) != 1) {
    ogg_page page;
    if (!read_page(is, state, &amp;amp;page))
      return false;

    int serial = ogg_page_serialno(&amp;amp;page);
    assert(mStreams.find(serial) != mStreams.end());
    OggStream* pageStream = mStreams[serial];

    // Drop data for streams we&#39;re not interested in.
    if (stream-&amp;gt;mActive) {
      ret = ogg_stream_pagein(&amp;amp;pageStream-&amp;gt;mState, &amp;amp;page);
      assert(ret == 0);
    }
  }
  return true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we need to read a new page (to be able to get more packets) we check the stream for the read page and if it is not for the stream we want we store the packet in the bitstream for that page so it can be retrieved later. I&#39;ve added an &#39;active&#39; flag to the streams so we can ignore streams that we aren&#39;t intersted in. We don&#39;t want to continuously buffer data for alternative audio tracks we aren&#39;t playing for example. The streams are marked inactive when the headers are finished reading.&lt;/p&gt;

&lt;p&gt;The code that does the checking to see if it&#39;s time to display a frame is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// At this point we&#39;ve written some audio data to the sound
// system. Now we check to see if it&#39;s time to display a video
// frame.
//
// The granule position of a video frame represents the time
// that that frame should be displayed up to. So we get the
// current time, compare it to the last granule position read.
// If the time is greater than that it&#39;s time to display a new
// video frame.
//
// The time is obtained from the audio system - this represents
// the time of the audio data that the user is currently
// listening to. In this way the video frame should be synced up
// to the audio the user is hearing.
//
ogg_int64_t position = 0;
int ret = sa_stream_get_position(mAudio, SA_POSITION_WRITE_SOFTWARE, &amp;amp;position);
assert(ret == SA_SUCCESS);
float audio_time = 
  float(position) /
  float(audio-&amp;gt;mVorbis.mInfo.rate) /
  float(audio-&amp;gt;mVorbis.mInfo.channels) /
  sizeof(short);

float video_time = th_granule_time(video-&amp;gt;mTheora.mCtx, mGranulepos);
if (audio_time &amp;gt; video_time) {
  // Decode one frame and display it. If no frame is available we
  // don&#39;t do anything.
  ogg_packet packet;
  if (read_packet(is, &amp;amp;state, video, &amp;amp;packet)) {
    handle_theora_data(video, &amp;amp;packet); 
    video_time = th_granule_time(video-&amp;gt;mTheora.mCtx, mGranulepos);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code for decoding and display the Theora video is similar to the &lt;a href=&quot;http://bluishcoder.co.nz/2009/06/26-decoding-theora-files-using-libtheora.html&quot;&gt;Theora decoding article&lt;/a&gt;. The main difference is we store the granulepos in mGranulepos so we know when to stop displaying the frame.&lt;/p&gt;

&lt;p&gt;This version of &#39;plogg&#39; should play Ogg files with a Theora and Vorbis track in sync. It does not play Theora files with no audio track - we can&#39;t synchronise to the audio clock if there is no audio. This can be worked around by falling back to delaying for the required framerate as the previous Theora example did.&lt;/p&gt;

&lt;p&gt;The a/v sync is not perfect however. If the video is large and decoding keyframes takes a while then we can fall behind in displaying the video and go out of sync. This is because we only play one frame when we check the time. One approach to fixing this is to decode, but not display, all frames up until the audio time rather than just the next time.&lt;/p&gt;

&lt;p&gt;The other issue is that the API call we are using to write to the audio hardware is blocking. This is using up valuable time that we could be using to decode a frame. When the write to the sound hardware returns we have very little time to decode a frame before glitches start appearing in the audio due to buffer underruns. Try playing a larger video and the audio and video will skip (depending on the speed of your hardware). This isn&#39;t a pleasant experience. Because of the blocking audio writes we can&#39;t skip more than one frame due to the frame decoding time taking too long causing audio skip.&lt;/p&gt;

&lt;p&gt;The fixes for these aren&#39;t too complex and I&#39;ll go through it in my next article. The basic approach is to move to an asynchronous method of writing the audio, skip displaying frames when needed (to reduce the cost of the YUV decoding), skip decoding frames if possible (depending on location of keyframes we can do this), and to check how much audio data we have queued before decoding to always ensure we won&#39;t drop audio while decoding.&lt;/p&gt;

&lt;p&gt;With these fixes in place I can play the 1080p Ogg version of &lt;a href=&quot;http://www.bigbuckbunny.org/index.php/download/&quot;&gt;Big Buck Bunny&lt;/a&gt; on a Macbook laptop (running Arch Linux) with no audio interruption  and with a/v syncing correctly. There is a fair amount of frame skipping however but it&#39;s a lot more watchable than if you try playing it without these modifications in place. And better than watching with the video lagging further and further behind the longer you watch it. Further improvements can be made to reduce the frame skipping by utilising threads to take advantage of extra core&#39;s on the PC.&lt;/p&gt;

&lt;p&gt;After the followup article on improving the a/v sync I&#39;ll look at covering seeking.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Decoding Vorbis files with libvorbis</title>
   <link href="http://bluishcoder.co.nz/2009/06/26/decoding-vorbis-files-with-libvorbis.html"/>
   <updated>2009-06-26T14:08:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2009/06/26/decoding-vorbis-files-with-libvorbis</id>
   <content type="html">&lt;p&gt;Decoding Vorbis streams require a very similar approach to that used when &lt;a href=&quot;http://bluishcoder.co.nz/2009/06/25/decoding-theora-files-using-libtheora.html&quot;&gt;decoding Theora streams&lt;/a&gt;. The public interface to the libvorbis library is very similar to that used by libtheora. Unfortunately the &lt;a href=&quot;http://www.xiph.org/vorbis/doc/&quot;&gt;libvorbis documentation&lt;/a&gt; doesn&#39;t contain an API reference that I could find so I&#39;m following the approached used by the example programs.&lt;/p&gt;

&lt;p&gt;Assuming we have already obtained an &lt;a href=&quot;http://www.xiph.org/ogg/doc/libogg/ogg_packet.html&quot;&gt;ogg_packet&lt;/a&gt;, the general steps to follow to decode and play Vorbis streams are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Call vorbis_synthesis_headerin to see if the packet is a Vorbis header packet. This is passed a vorbis_info and vorbis_comment object to hold the information read from those header packets. The return value of this function is zero if the packet is a Vorbis header packet. Unfortunately it doesn&#39;t return a value to see that it&#39;s a Vorbis data packet. To check for this you need to check if the stream is a Vorbis stream (by knowing you&#39;ve previously read Vorbis headers from it) and the return value is OV_ENOTVORBIS.&lt;/li&gt;
&lt;li&gt;Once all the header packets are read create a vorbis_dsp_state and vorbis_block object. Initialize these with vorbis_synthesis_init and vorbis_block_init respectively. These objects hold the state of the Vorbis decoding. vorbis_synthesis_init is passed the vorbis_info object that was filled in during the reading of the header packets.&lt;/li&gt;
&lt;li&gt;For each data packet:
 &lt;ol&gt;
 &lt;li&gt;Call vorbis_synthesis passing it the vorbis_block created above and the ogg_packet containing the packet data. If this succeeds (by returning zero), call vorbis_synthesis_blockin passing it the vorbis_dsp_state and vorbis_block objects. This call copies the data from the packet into the Vorbis objects ready for decoding.&lt;/li&gt;
  &lt;li&gt;Call vorbis_synthesis_pcmout to get an pointer to an array of floating point values for the sound samples. This will return the number of samples in the array. The array is indexed by channel number, followed by sample number. Once obtained this sound data can be sent to the sound hardware to play the audio.&lt;/li&gt;
 &lt;li&gt;Call vorbis_synthesis_read, passing it the vorbis_dsp_state object and the number of sound samples consumed. This allows you to consume less data than vorbis_synthesis_pcmout returned. This is useful if you can&#39;t write all the data to the sound hardware without blocking.&lt;/li&gt;
 &lt;/ol&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;In the example code in the &lt;a href=&quot;http://github.com/doublec/plogg/tree/master&quot;&gt;github repository&lt;/a&gt; I create a VorbisDecode object that holds the objects needed for decoding. This is similar to the TheoraDecode object mentioned in my &lt;a href=&quot;http://bluishcoder.co.nz/2009/06/25/decoding-theora-files-using-libtheora.html&quot;&gt;Theora post&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class VorbisDecode {
  ...
  vorbis_info mInfo;
  vorbis_comment mComment;
  vorbis_dsp_state mDsp;
  vorbis_block mBlock;
  ...
      VorbisDecode()
  {
    vorbis_info_init(&amp;amp;mInfo);
    vorbis_comment_init(&amp;amp;mComment);    
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I added a TYPE_VORBIS value to the StreamType enum and the stream is set to this type when a Vorbis header is successfully decoded:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  int ret = vorbis_synthesis_headerin(&amp;amp;stream-&amp;gt;mVorbis.mInfo,
                      &amp;amp;stream-&amp;gt;mVorbis.mComment,
                      packet);
  if (stream-&amp;gt;mType == TYPE_VORBIS &amp;amp;&amp;amp; ret == OV_ENOTVORBIS) {
    // First data packet
    ret = vorbis_synthesis_init(&amp;amp;stream-&amp;gt;mVorbis.mDsp, &amp;amp;stream-&amp;gt;mVorbis.mInfo);
    assert(ret == 0);
    ret = vorbis_block_init(&amp;amp;stream-&amp;gt;mVorbis.mDsp, &amp;amp;stream-&amp;gt;mVorbis.mBlock);
    assert(ret == 0);
    stream-&amp;gt;mHeadersRead = true;
    handle_vorbis_data(stream, packet);
  }
  else if (ret == 0) {
    stream-&amp;gt;mType = TYPE_VORBIS;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The example program uses libsydneyaudio for audio output. This requires sound samples to be written as signed short values. When I get the floating point data from Vorbis I convert this to signed short and send it to libsydneyaudio:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  int ret = 0;

  if (vorbis_synthesis(&amp;amp;stream-&amp;gt;mVorbis.mBlock, packet) == 0) {
    ret = vorbis_synthesis_blockin(&amp;amp;stream-&amp;gt;mVorbis.mDsp, &amp;amp;stream-&amp;gt;mVorbis.mBlock);
    assert(ret == 0);
  }
  float** pcm = 0;
  int samples = 0;
  while ((samples = vorbis_synthesis_pcmout(&amp;amp;stream-&amp;gt;mVorbis.mDsp, &amp;amp;pcm)) &amp;gt; 0) {
    if (!mAudio) {
      ret = sa_stream_create_pcm(&amp;amp;mAudio,
                 NULL,
                 SA_MODE_WRONLY,
                 SA_PCM_FORMAT_S16_NE,
                 stream-&amp;gt;mVorbis.mInfo.rate,
                 stream-&amp;gt;mVorbis.mInfo.channels);
      assert(ret == SA_SUCCESS);

      ret = sa_stream_open(mAudio);
      assert(ret == SA_SUCCESS);
    }

    if (mAudio) {
      short buffer[samples * stream-&amp;gt;mVorbis.mInfo.channels];
      short* p = buffer;
      for (int i=0;i &amp;lt; samples; ++i) {
        for(int j=0; j &amp;lt; stream-&amp;gt;mVorbis.mInfo.channels; ++j) {
          int v = static_cast&amp;lt;int&amp;gt;(floorf(0.5 + pcm[j][i]*32767.0));
          if (v &amp;gt; 32767) v = 32767;
          if (v &amp;lt;-32768) v = -32768;
          *p++ = v;
        }
      }

      ret = sa_stream_write(mAudio, buffer, sizeof(buffer));
      assert(ret == SA_SUCCESS);
    }

    ret = vorbis_synthesis_read(&amp;amp;stream-&amp;gt;mVorbis.mDsp, samples);
    assert(ret == 0);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A couple of minor changes were also made to the example program:
1. Continue processing pages and packets when the &#39;end of file&#39; is reached. Otherwise a few packets that are buffered after we&#39;ve reached the end of the file will be missed.
2. After reading a page don&#39;t just try to read one packet, call &lt;a href=&quot;http://www.xiph.org/ogg/doc/libogg/ogg_stream_packetout.html&quot;&gt;ogg_stream_packetout&lt;/a&gt; until it returns a result saying there are no more packets. This means we process all the packets from the page immediately and prevents a build up of buffered data.&lt;/p&gt;

&lt;p&gt;The code for this example is in the &#39;part3_vorbis&#39; branch of the github repository. This also includes the Theora code but does not do any a/v synchronisation.  Files containing Theora streams will show the video data but it will not play smoothly and will not be synchronised with the audio. Fixing that is the topic of the next post in this series.&lt;/p&gt;
</content>
 </entry>
 
 
</feed>
