<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Bluish Coder: theora</title>
 <link href="http://bluishcoder.co.nz/tag/theora/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>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>
 
 <entry>
   <title>Decoding Theora files using libtheora</title>
   <link href="http://bluishcoder.co.nz/2009/06/25/decoding-theora-files-using-libtheora.html"/>
   <updated>2009-06-25T20:33:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2009/06/25/decoding-theora-files-using-libtheora</id>
   <content type="html">&lt;p&gt;My last post covered &lt;a href=&quot;http://bluishcoder.co.nz/2009/06/24/reading-ogg-files-using-libogg.html&quot;&gt;read Ogg files using libogg&lt;/a&gt;. The resulting program didn&#39;t do much but it covered the basic steps needed to get an &lt;a href=&quot;http://www.xiph.org/ogg/doc/libogg/ogg_packet.html&quot;&gt;ogg_packet&lt;/a&gt; which we need to decode the data in the stream. The thing step I want to cover is decoding Theora streams using &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/&quot;&gt;libtheora&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the previous post I stored a count of the number of packets in the OggStream object. For theora decoding we need a number of different objects to be stored. I encapsulate this in a TheoraDecode structure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class TheoraDecode { 
  ...
  th_info mInfo;
  th_comment mComment;
  th_setup_info *mSetup;
  th_dec_ctx* mCtx;
  ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;http://theora.org/doc/libtheora-1.0/structth__info.html&quot;&gt;th_info&lt;/a&gt;, &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/structth__comment.html&quot;&gt;th_comment&lt;/a&gt; and &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/theoradec_8h.html#b71cd2657455cc27d6c0127c66a89f28&quot;&gt;th_setup_info&lt;/a&gt; contain data read from the Theora headers. The Theora stream contains three headers packets. These are the info, comment and setup headers. There is one object for holding each of these as we read the headers. The &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/theoradec_8h.html#843d70bb02563885a8d54b9c1a781729&quot;&gt;th_dec_ctx&lt;/a&gt; object holds information that the decoder requires to keep track of the decoding process.&lt;/p&gt;

&lt;p&gt;th_info and th_comment need to be initialized using &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__basefuncs.html#g430d9c605816a6ca0bdce3a0b965b926&quot;&gt;th_info_init&lt;/a&gt; and &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__basefuncs.html#g6c8ab25988e7ea9d7b1e31a54cf58f09&quot;&gt;th_comment_init&lt;/a&gt;. Notice that th_setup_info is a pointer. This needs to be free&#39;d when we&#39;re finished with it using &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#gdef55431b68aaa59d0d7b32b2f118f27&quot;&gt;th_setup_free&lt;/a&gt;. The decoder context object also needs to be free&#39;d. Use &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#gfb6684ad8ba507b71112bc9de148e7d0&quot;&gt;th_decode_free&lt;/a&gt;. A convenient place to do this is in the TheoraDecode constructor and destructor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class TheoraDecode {
  ...
  TheoraDecode() :
    mSetup(0),
    mCtx(0)
  {
    th_info_init(&amp;amp;mInfo);
    th_comment_init(&amp;amp;mComment);
  }

  ~TheoraDecode() {
    th_setup_free(mSetup);
    th_decode_free(mCtx);
  }   
  ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The TheoraDecode object is stored in the OggStream structure. The OggStream stucture also gets a field holding the type of the stream (Theora, Vorbis, Unknown, etc) and a boolean indicating whether the headers have been read:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class OggStream
{
  ...
  int mSerial;
  ogg_stream_state mState;
  StreamType mType;
  bool mHeadersRead;
  TheoraDecode mTheora;
  ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once we get the ogg_packet from an Ogg stream we need to find out if it is a Theora stream. The approach I&#39;m using to do this is to attempt to extract a Theora header from it. If this succeeds, it&#39;s a Theora stream. &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#g006d01d36fbe64768c571e6a12b7fc50&quot;&gt;th_decode_headerin&lt;/a&gt; will attempt to decode a header packet. A return value of &#39;0&#39; indicates that we got a Theora data packet (presumably the headers have been read already). This function gets passed the info, comment, and setup objects and it will populate them with data as it reads the headers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ogg_packet* packet = ...got this previously...;
int ret = th_decode_headerin(&amp;amp;stream-&amp;gt;mTheora.mInfo,
                             &amp;amp;stream-&amp;gt;mTheora.mComment,
                             &amp;amp;stream-&amp;gt;mTheora.mSetup,
                             packet);
if (ret == TH_ENOTFORMAT)
  return; // Not a theora header

if (ret &amp;gt; 0) {
  // This is a theora header packet
  stream-&amp;gt;mType = TYPE_THEORA;
  return;
}

assert(ret == 0);
// This is not a header packet. It is the first 
// video data packet.
stream-&amp;gt;mTheora.mCtx = 
  th_decode_alloc(&amp;amp;stream-&amp;gt;mTheora.mInfo, 
                  stream-&amp;gt;mTheora.mSetup);
assert(stream-&amp;gt;mTheora.mCtx != NULL);
stream-&amp;gt;mHeadersRead = true;
...decode data packet...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example code we attempt to decode the header. If it fails it bails out, possibly to try decoding the packet using libvorbis or some other means. If it succeeds the stream is marked as type TYPE_THEORA so we can handle it specially later.&lt;/p&gt;

&lt;p&gt;If all headers packets are read and we got the first data packet then we call &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#g0ef07a9a97849054aa606c595a2d807e&quot;&gt;th_decode_alloc&lt;/a&gt; to get a decode context to decode the data.&lt;/p&gt;

&lt;p&gt;Once the headers are all read, the next step is to decode each Theora data packet. To do this we first call &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#g31c814bf09b2232aff69c57ae20f04eb&quot;&gt;th_decode_packetin&lt;/a&gt;. This adds the packet to the decoder. A return value of &#39;0&#39; means we can get a decoded frame as a result of adding the packet. A call to &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/group__decfuncs.html#ga9cc8af63fa8540e0fc95572f259cdcb&quot;&gt;th_decode_ycbcr_out&lt;/a&gt; gets the decoded YUV data, stored in a &lt;a href=&quot;http://theora.org/doc/libtheora-1.0/codec_8h.html#343f7cfabad179cc4fe527cf06873f45&quot;&gt;th_ycbcr_buffer&lt;/a&gt; object. This is basically an array of the YUV data.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ogg_int64_t granulepos = -1;
int ret = th_decode_packetin(stream-&amp;gt;mTheora.mCtx,
                             packet,
                             &amp;amp;granulepos);
assert(ret == 0);

th_ycbcr_buffer buffer;
ret = th_decode_ycbcr_out(stream-&amp;gt;mTheora.mCtx, buffer);
assert(ret == 0);
...copy yuv data to SDL YUV overlay...
...display overlay...
...sleep for 1 frame...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &#39;granulepos&#39; returned by the th_decode_packetin call holds information regarding the presentation time of this frame, and what frame contains the keyframe that is needed for this frame if it is not a keyframe. I&#39;ll write more about this in a future post when I cover synchronising the audio and video. For now it&#39;s going to be ignored.&lt;/p&gt;

&lt;p&gt;Once we have the YUV data I use SDL to create a surface, and a YUV overlay. This allows SDL to do the YUV to RGB conversion for me. I won&#39;t copy the code for this since it&#39;s not particularly relevant to using the libtheora API - you can see it in the &lt;a href=&quot;http://github.com/doublec/plogg/&quot;&gt;github repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once the YUV data is blit to the screen the final step is to sleep for the period of one frame so the video can playback at approximately the right framerate. The framerate of the video is stored in the th_info object that we got from the headers. It is represented as the fraction of two numbers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;float framerate = 
  float(stream-&amp;gt;mTheora.mInfo.fps_numerator) / 
  float(stream-&amp;gt;mTheora.mInfo.fps_denominator);
SDL_Delay((1.0/framerate)*1000);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With all that in place, running the program with an Ogg file containing a Theora stream should play the video at the right framerate. Adding Vorbis playback is almost as easy - the main difficulty is synchronising the audio and video. I&#39;ll cover these topics in a later post.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Daily Motion, OLPC and Theora</title>
   <link href="http://bluishcoder.co.nz/2009/01/28/daily-motion-olpc-and-theora.html"/>
   <updated>2009-01-28T14:17:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2009/01/28/daily-motion-olpc-and-theora</id>
   <content type="html">&lt;p&gt;A while back it was &lt;a href=&quot;http://www.readwriteweb.com/archives/olpc_daily_motion_partner_on_o.php&quot;&gt;announced that Daily Motion&lt;/a&gt;, an online video site, had opened an OLPC channel for sharing videos encoded using Theora for playback on OLPC&#39;s.&lt;/p&gt;

&lt;p&gt;The channel, &lt;a href=&quot;http://olpc.dailymotion.com/&quot;&gt;http://olpc.dailymotion.com&lt;/a&gt;, contains theora videos aimed at the OLPC audience. What&#39;s nice is that the videos playback in Firefox 3.1 using the native Theora support and don&#39;t require a plugin, for example &lt;a href=&quot;http://olpc.dailymotion.com/popular/video/x43efw_une-vision-de-lunivers-simulation_tech&quot;&gt;this video&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Looking at the Daily Motion page it seems they use the &amp;lt;object&gt; element to playback the Ogg Theora file, which uses the internal decoder and player user interface. This is a nice result from the adding of support for &lt;a href=&quot;https://bugzilla.mozilla.org/show_bug.cgi?id=448603&quot;&gt;direct loading of Ogg files&lt;/a&gt; that &lt;a href=&quot;http://weblogs.mozillazine.org/roc/&quot;&gt;Robert&lt;/a&gt; worked on.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>liboggplay playback performance</title>
   <link href="http://bluishcoder.co.nz/2009/01/22/liboggplay-playback-performance.html"/>
   <updated>2009-01-22T12:21:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2009/01/22/liboggplay-playback-performance</id>
   <content type="html">&lt;p&gt;I made a tweak to &lt;a href=&quot;http://tinyvid.tv/&quot;&gt;tinyvid.tv&lt;/a&gt; yesterday to transcode &lt;a href=&quot;http://www.youtube.com/&quot;&gt;youtube&lt;/a&gt; high definition videos if the HD version is available. This results in &lt;a href=&quot;http://media.tinyvid.tv/ah2ebubqurvy.ogg&quot;&gt;bigger videos&lt;/a&gt; and therefore stresses the performance of the video implementation in Firefox.&lt;/p&gt;

&lt;p&gt;I&#39;m not tweaking any parameters when transcoding so it&#39;s possible that I could produce a Theora file with better playback characteristics. In particular I don&#39;t have the bandwidth to stream a file of this size. Instead I have to wait until a large portion is downloaded before playing it back. But even then playback performance is terrible.&lt;/p&gt;

&lt;p&gt;With the file fully buffered on my dual core multi-gigabyte, multi-gigahertz laptop the sound stutters and the playback is slow. Not a great experience.&lt;/p&gt;

&lt;p&gt;I tried playback of the &lt;a href=&quot;http://media.tinyvid.tv/ah2ebubqurvy.ogg&quot;&gt;ogg file&lt;/a&gt; with the example player from &lt;a href=&quot;http://wiki.xiph.org/index.php/OggPlay&quot;&gt;liboggplay&lt;/a&gt;. The playback performance is exactly the same as within Firefox. No surprise there since I use liboggplay in the implementation.&lt;/p&gt;

&lt;p&gt;It&#39;s not a limitation with &lt;a href=&quot;http://www.theora.org/&quot;&gt;libtheora&lt;/a&gt; as the playback using libtheora&#39;s example player is very good. Low CPU usage, full framerate, great sound. So it looks to me like it&#39;s either a liboggplay issue, or an issue with the way I&#39;m using liboggplay. I&#39;ve raised a &lt;a href=&quot;http://trac.annodex.net/ticket/448&quot;&gt;trac ticket&lt;/a&gt; with the liboggplay developers to see if they can offer any advice.&lt;/p&gt;

&lt;p&gt;I&#39;ve also raised &lt;a href=&quot;https://bugzilla.mozilla.org/show_bug.cgi?id=474540&quot;&gt;bug 474540&lt;/a&gt; in the Mozilla bugtracking system to track the fix to apply for Firefox.&lt;/p&gt;

&lt;p&gt;Non-HD videos play fine for me, it&#39;s when they get to about 720p that things fall apart. The fact that libtheora plays these well makes me confident that we can get the performance for these files much much better.&lt;/p&gt;
</content>
 </entry>
 
 
</feed>
