Index: branches/SHM-dev/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/SHM-dev/source/Lib/TLibCommon/NAL.h	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibCommon/NAL.h	(revision 1319)
@@ -51,4 +51,9 @@
   UInt        m_nuhLayerId;  ///< nuh_layer_id
 
+  NALUnit(const NALUnit &src)
+  :m_nalUnitType (src.m_nalUnitType)
+  ,m_temporalId  (src.m_temporalId)
+  ,m_nuhLayerId  (src.m_nuhLayerId)
+  { }
   /** construct an NALunit structure with given header values. */
   NALUnit(
@@ -61,6 +66,8 @@
   {}
 
-  /** default constructor - no initialization; must be perfomed by user */
+  /** default constructor - no initialization; must be performed by user */
   NALUnit() {}
+
+  virtual ~NALUnit() { }
 
   /** returns true if the NALunit is a slice NALunit */
Index: branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1319)
@@ -60,20 +60,34 @@
 }
 
-TComInputBitstream::TComInputBitstream(std::vector<uint8_t>* buf)
-{
-  m_fifo = buf;
-  m_fifo_idx = 0;
-  m_held_bits = 0;
-  m_num_held_bits = 0;
-  m_numBitsRead = 0;
-}
-
-TComInputBitstream::~TComInputBitstream()
-{
-}
+
+TComInputBitstream::TComInputBitstream()
+: m_fifo()
+, m_emulationPreventionByteLocation()
+, m_fifo_idx(0)
+, m_num_held_bits(0)
+, m_held_bits(0)
+, m_numBitsRead(0)
+{ }
+
+TComInputBitstream::TComInputBitstream(const TComInputBitstream &src)
+: m_fifo(src.m_fifo)
+, m_emulationPreventionByteLocation(src.m_emulationPreventionByteLocation)
+, m_fifo_idx(src.m_fifo_idx)
+, m_num_held_bits(src.m_num_held_bits)
+, m_held_bits(src.m_held_bits)
+, m_numBitsRead(src.m_numBitsRead)
+{ }
 
 // ====================================================================================================================
 // Public member functions
 // ====================================================================================================================
+
+Void TComInputBitstream::resetToStart()
+{
+  m_fifo_idx=0;
+  m_num_held_bits=0;
+  m_held_bits=0;
+  m_numBitsRead=0;
+}
 
 Char* TComOutputBitstream::getByteStream() const
@@ -283,12 +297,12 @@
   UInt aligned_word = 0;
   UInt num_bytes_to_load = (uiNumberOfBits - 1) >> 3;
-  assert(m_fifo_idx + num_bytes_to_load < m_fifo->size());
+  assert(m_fifo_idx + num_bytes_to_load < m_fifo.size());
 
   switch (num_bytes_to_load)
   {
-  case 3: aligned_word  = (*m_fifo)[m_fifo_idx++] << 24;
-  case 2: aligned_word |= (*m_fifo)[m_fifo_idx++] << 16;
-  case 1: aligned_word |= (*m_fifo)[m_fifo_idx++] <<  8;
-  case 0: aligned_word |= (*m_fifo)[m_fifo_idx++];
+  case 3: aligned_word  = m_fifo[m_fifo_idx++] << 24;
+  case 2: aligned_word |= m_fifo[m_fifo_idx++] << 16;
+  case 1: aligned_word |= m_fifo[m_fifo_idx++] <<  8;
+  case 0: aligned_word |= m_fifo[m_fifo_idx++];
   }
 
@@ -351,28 +365,37 @@
 {
   UInt uiNumBytes = uiNumBits/8;
-  std::vector<uint8_t>* buf = new std::vector<uint8_t>;
-  UInt uiByte;
-  for (UInt ui = 0; ui < uiNumBytes; ui++)
-  {
-    read(8, uiByte);
-    buf->push_back(uiByte);
+  TComInputBitstream *pResult = new TComInputBitstream;
+
+  std::vector<uint8_t> &buf = pResult->getFifo();
+  buf.reserve((uiNumBits+7)>>3);
+
+  if (m_num_held_bits == 0)
+  {
+    std::size_t currentOutputBufferSize=buf.size();
+    const UInt uiNumBytesToReadFromFifo = std::min<UInt>(uiNumBytes, m_fifo.size() - m_fifo_idx);
+    buf.resize(currentOutputBufferSize+uiNumBytes);
+    memcpy(&(buf[currentOutputBufferSize]), &(m_fifo[m_fifo_idx]), uiNumBytesToReadFromFifo); m_fifo_idx+=uiNumBytesToReadFromFifo;
+    if (uiNumBytesToReadFromFifo != uiNumBytes)
+    {
+      memset(&(buf[currentOutputBufferSize+uiNumBytesToReadFromFifo]), 0, uiNumBytes - uiNumBytesToReadFromFifo);
+    }
+  }
+  else
+  {
+    for (UInt ui = 0; ui < uiNumBytes; ui++)
+    {
+      UInt uiByte;
+      read(8, uiByte);
+      buf.push_back(uiByte);
+    }
   }
   if (uiNumBits&0x7)
   {
-    uiByte = 0;
+    UInt uiByte = 0;
     read(uiNumBits&0x7, uiByte);
     uiByte <<= 8-(uiNumBits&0x7);
-    buf->push_back(uiByte);
-  }
-  return new TComInputBitstream(buf);
-}
-
-/**
- - delete internal fifo
- */
-Void TComInputBitstream::deleteFifo()
-{
-  delete m_fifo;
-  m_fifo = NULL;
+    buf.push_back(uiByte);
+  }
+  return pResult;
 }
 
Index: branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 1319)
@@ -163,8 +163,8 @@
 class TComInputBitstream
 {
-  std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
-  std::vector<UInt> m_emulationPreventionByteLocation;
-
 protected:
+  std::vector<uint8_t> m_fifo; /// FIFO for storage of complete bytes
+  std::vector<UInt>    m_emulationPreventionByteLocation;
+
   UInt m_fifo_idx; /// Read index into m_fifo
 
@@ -175,10 +175,11 @@
 public:
   /**
-   * Create a new bitstream reader object that reads from buf.  Ownership
-   * of buf remains with the callee, although the constructed object
-   * will hold a reference to buf
-   */
-  TComInputBitstream(std::vector<uint8_t>* buf);
-  ~TComInputBitstream();
+   * Create a new bitstream reader object that reads from buf.
+   */
+  TComInputBitstream();
+  virtual ~TComInputBitstream() { }
+  TComInputBitstream(const TComInputBitstream &src);
+
+  Void resetToStart();
 
   // interface for decoding
@@ -187,6 +188,6 @@
   Void        readByte        ( UInt &ruiBits )
   {
-    assert(m_fifo_idx < m_fifo->size());
-    ruiBits = (*m_fifo)[m_fifo_idx++];
+    assert(m_fifo_idx < m_fifo.size());
+    ruiBits = m_fifo[m_fifo_idx++];
   }
 
@@ -194,5 +195,5 @@
   {
     assert(m_fifo_idx > 0);
-    byte = (*m_fifo)[m_fifo_idx - 1];
+    byte = m_fifo[m_fifo_idx - 1];
   }
 
@@ -209,18 +210,18 @@
   UInt     readByte() { UInt tmp; readByte( tmp ); return tmp; }
   UInt getNumBitsUntilByteAligned() { return m_num_held_bits & (0x7); }
-  UInt getNumBitsLeft() { return 8*((UInt)m_fifo->size() - m_fifo_idx) + m_num_held_bits; }
+  UInt getNumBitsLeft() { return 8*((UInt)m_fifo.size() - m_fifo_idx) + m_num_held_bits; }
   TComInputBitstream *extractSubstream( UInt uiNumBits ); // Read the nominated number of bits, and return as a bitstream.
-  Void                deleteFifo(); // Delete internal fifo of bitstream.
   UInt  getNumBitsRead() { return m_numBitsRead; }
   UInt readByteAlignment();
 
-  Void      pushEmulationPreventionByteLocation ( UInt pos )                  { m_emulationPreventionByteLocation.push_back( pos ); }
-  UInt      numEmulationPreventionBytesRead     ()                            { return (UInt) m_emulationPreventionByteLocation.size();    }
-  std::vector<UInt>  getEmulationPreventionByteLocation  ()                   { return m_emulationPreventionByteLocation;           }
-  UInt      getEmulationPreventionByteLocation  ( UInt idx )                  { return m_emulationPreventionByteLocation[ idx ];    }
-  Void      clearEmulationPreventionByteLocation()                            { m_emulationPreventionByteLocation.clear();          }
-  Void      setEmulationPreventionByteLocation  ( std::vector<UInt> vec )     { m_emulationPreventionByteLocation = vec;            }
-
-  const std::vector<uint8_t> *getFifo() const { return m_fifo; }
+  Void      pushEmulationPreventionByteLocation ( UInt pos )                         { m_emulationPreventionByteLocation.push_back( pos ); }
+  UInt      numEmulationPreventionBytesRead     ()                                   { return (UInt) m_emulationPreventionByteLocation.size();    }
+  const std::vector<UInt> &getEmulationPreventionByteLocation  () const              { return m_emulationPreventionByteLocation;           }
+  UInt      getEmulationPreventionByteLocation  ( UInt idx )                         { return m_emulationPreventionByteLocation[ idx ];    }
+  Void      clearEmulationPreventionByteLocation()                                   { m_emulationPreventionByteLocation.clear();          }
+  Void      setEmulationPreventionByteLocation  ( const std::vector<UInt> &vec )     { m_emulationPreventionByteLocation = vec;            }
+
+  const std::vector<uint8_t> &getFifo() const { return m_fifo; }
+        std::vector<uint8_t> &getFifo()       { return m_fifo; }
 };
 
Index: branches/SHM-dev/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 1319)
@@ -51,5 +51,5 @@
 ParameterSetMap<TComSPS> ParameterSetManager::m_spsMap(MAX_NUM_SPS);
 ParameterSetMap<TComPPS> ParameterSetManager::m_ppsMap(MAX_NUM_PPS);
-TComVPS ParameterSetManager::m_activeVPS;
+Int ParameterSetManager::m_activeVPSId = -1;
 #endif
 
@@ -2790,17 +2790,13 @@
 ParameterSetManager::ParameterSetManager()
 #if SVC_EXTENSION
-: m_activeSPS()
+: m_activePPSId(-1)
 #else
 : m_vpsMap(MAX_NUM_VPS)
 , m_spsMap(MAX_NUM_SPS)
 , m_ppsMap(MAX_NUM_PPS)
-, m_activeVPS()
-, m_activeSPS()
-#endif
-{
-#if !SVC_EXTENSION
-  m_activeVPS.setVPSId(-1);
-#endif
-  m_activeSPS.setSPSId(-1);
+, m_activeVPSId(-1)
+#endif
+, m_activeSPSId(-1)
+{
 }
 
@@ -2812,28 +2808,28 @@
 //! activate a SPS from a active parameter sets SEI message
 //! \returns true, if activation is successful
-Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
-{
-  TComSPS *sps = m_spsMap.getPS(spsId);
-  if (sps)
-  {
-    Int vpsId = sps->getVPSId();
-    TComVPS *vps = m_vpsMap.getPS(vpsId);
-    if (vps)
-    {
-      m_activeVPS = *(vps);
-      m_activeSPS = *(sps);
-      return true;
-    }
-    else
-    {
-      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
-    }
-  }
-  else
-  {
-    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
-  }
-  return false;
-}
+//Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
+//{
+//  TComSPS *sps = m_spsMap.getPS(spsId);
+//  if (sps)
+//  {
+//    Int vpsId = sps->getVPSId();
+//    TComVPS *vps = m_vpsMap.getPS(vpsId);
+//    if (vps)
+//    {
+//      m_activeVPS = *(vps);
+//      m_activeSPS = *(sps);
+//      return true;
+//    }
+//    else
+//    {
+//      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
+//    }
+//  }
+//  else
+//  {
+//    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
+//  }
+//  return false;
+//}
 
 //! activate a PPS and depending on isIDR parameter also SPS and VPS
@@ -2844,37 +2840,41 @@
   if (pps)
   {
+#if SVC_EXTENSION
+    m_activePPSId = ppsId;
+#endif
     Int spsId = pps->getSPSId();
-    if (!isIRAP && (spsId != m_activeSPS.getSPSId() ))
+    if (!isIRAP && (spsId != m_activeSPSId ))
     {
       printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
-      return false;
-    }
-    TComSPS *sps = m_spsMap.getPS(spsId);
-    if (sps)
-    {
-      Int vpsId = sps->getVPSId();
-      if (!isIRAP && (vpsId != m_activeVPS.getVPSId() ))
-      {
-        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
-        return false;
-      }
-      TComVPS *vps =m_vpsMap.getPS(vpsId);
-      if (vps)
-      {
-        m_activeVPS = *(vps);
-        m_activeSPS = *(sps);
-#if SVC_EXTENSION
-        m_activePPS = *(pps);
-#endif
-        return true;
+    }
+    else
+    {
+      TComSPS *sps = m_spsMap.getPS(spsId);
+      if (sps)
+      {
+        Int vpsId = sps->getVPSId();
+        if (!isIRAP && (vpsId != m_activeVPSId ))
+        {
+          printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
+        }
+        else
+        {
+          TComVPS *vps =m_vpsMap.getPS(vpsId);
+          if (vps)
+          {
+            m_activeVPSId = vpsId;
+            m_activeSPSId = spsId;
+            return true;
+          }
+          else
+          {
+            printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
+          }
+        }
       }
       else
       {
-        printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
-      }
-    }
-    else
-    {
-      printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
+        printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
+      }
     }
   }
@@ -2883,4 +2883,8 @@
     printf("Warning: tried to activate non-existing PPS.");
   }
+
+  // Failed to activate if reach here.
+  m_activeSPSId=-1;
+  m_activeVPSId=-1;
   return false;
 }
@@ -2905,5 +2909,5 @@
 }
 
-Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> *pNewData)
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData)
 {
   if (!bChanged)
@@ -2922,5 +2926,5 @@
       else
       {
-        const UChar *pNewDataArray=&(*pNewData)[0];
+        const UChar *pNewDataArray=&(newData)[0];
         const UChar *pOldDataArray=&(*pOldData)[0];
         if (memcmp(pOldDataArray, pNewDataArray, pOldData->size()))
Index: branches/SHM-dev/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/SHM-dev/source/Lib/TLibCommon/TComSlice.h	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibCommon/TComSlice.h	(revision 1319)
@@ -2502,5 +2502,5 @@
 
 
-Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> *pNewData);
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData);
 
 template <class T> class ParameterSetMap
@@ -2528,5 +2528,5 @@
   }
 
-  Void storePS(Int psId, T *ps, const std::vector<UChar> *pNaluData)
+  Void storePS(Int psId, T *ps, const std::vector<UChar> &naluData)
   {
     assert ( psId < m_maxId );
@@ -2536,5 +2536,5 @@
 
       // work out changed flag
-      calculateParameterSetChangedFlag(mapData.bChanged, mapData.pNaluData, pNaluData);
+      calculateParameterSetChangedFlag(mapData.bChanged, mapData.pNaluData, naluData);
       delete m_paramsetMap[psId].pNaluData;
       delete m_paramsetMap[psId].parameterSet;
@@ -2547,13 +2547,6 @@
       m_paramsetMap[psId].bChanged = false;
     }
-    if (pNaluData)
-    {
-      m_paramsetMap[psId].pNaluData=new std::vector<UChar>;
-      *(m_paramsetMap[psId].pNaluData) = *pNaluData;
-    }
-    else
-    {
-      m_paramsetMap[psId].pNaluData=0;
-    }
+    m_paramsetMap[psId].pNaluData=new std::vector<UChar>;
+    *(m_paramsetMap[psId].pNaluData) = naluData;
   }
 
@@ -2578,5 +2571,12 @@
   T* getPS(Int psId)
   {
-    return ( m_paramsetMap.find(psId) == m_paramsetMap.end() ) ? NULL : m_paramsetMap[psId].parameterSet;
+    typename std::map<Int,MapData<T> >::iterator it=m_paramsetMap.find(psId);
+    return ( it == m_paramsetMap.end() ) ? NULL : (it)->second.parameterSet;
+  }
+
+  const T* getPS(Int psId) const
+  {
+    typename std::map<Int,MapData<T> >::const_iterator it=m_paramsetMap.find(psId);
+    return ( it == m_paramsetMap.end() ) ? NULL : (it)->second.parameterSet;
   }
 
@@ -2598,5 +2598,5 @@
 
   //! store sequence parameter set and take ownership of it
-  Void           storeVPS(TComVPS *vps, const std::vector<UChar> *pNaluData) { m_vpsMap.storePS( vps->getVPSId(), vps, pNaluData); };
+  Void           storeVPS(TComVPS *vps, const std::vector<UChar> &naluData) { m_vpsMap.storePS( vps->getVPSId(), vps, naluData); };
   //! get pointer to existing video parameter set
   TComVPS*       getVPS(Int vpsId)                                           { return m_vpsMap.getPS(vpsId); };
@@ -2606,5 +2606,5 @@
 
   //! store sequence parameter set and take ownership of it
-  Void           storeSPS(TComSPS *sps, const std::vector<UChar> *pNaluData) { m_spsMap.storePS( sps->getSPSId(), sps, pNaluData); };
+  Void           storeSPS(TComSPS *sps, const std::vector<UChar> &naluData) { m_spsMap.storePS( sps->getSPSId(), sps, naluData); };
   //! get pointer to existing sequence parameter set
   TComSPS*       getSPS(Int spsId)                                           { return m_spsMap.getPS(spsId); };
@@ -2614,5 +2614,5 @@
 
   //! store picture parameter set and take ownership of it
-  Void           storePPS(TComPPS *pps, const std::vector<UChar> *pNaluData) { m_ppsMap.storePS( pps->getPPSId(), pps, pNaluData); };
+  Void           storePPS(TComPPS *pps, const std::vector<UChar> &naluData) { m_ppsMap.storePS( pps->getPPSId(), pps, naluData); };
   //! get pointer to existing picture parameter set
   TComPPS*       getPPS(Int ppsId)                                           { return m_ppsMap.getPS(ppsId); };
@@ -2623,5 +2623,5 @@
   //! activate a SPS from a active parameter sets SEI message
   //! \returns true, if activation is successful
-  Bool           activateSPSWithSEI(Int SPSId);
+  // Bool           activateSPSWithSEI(Int SPSId);
 
   //! activate a PPS and depending on isIDR parameter also SPS and VPS
@@ -2629,9 +2629,9 @@
   Bool           activatePPS(Int ppsId, Bool isIRAP);
 
-  const TComVPS* getActiveVPS()const { return &m_activeVPS; };
-  const TComSPS* getActiveSPS()const { return &m_activeSPS; };
+  const TComVPS* getActiveVPS()const { return m_vpsMap.getPS(m_activeVPSId); };
+  const TComSPS* getActiveSPS()const { return m_spsMap.getPS(m_activeSPSId); };
 
 #if SVC_EXTENSION
-  const TComPPS* getActivePPS()const { return &m_activePPS; };
+  const TComPPS* getActivePPS()const { return m_ppsMap.getPS(m_activePPSId); };
 #endif
 
@@ -2643,6 +2643,6 @@
   static ParameterSetMap<TComPPS> m_ppsMap;
 
-  TComPPS                  m_activePPS;
-  static TComVPS           m_activeVPS;
+  Int    m_activePPSId;
+  static Int m_activeVPSId; // -1 for nothing active;
 #else
   ParameterSetMap<TComVPS> m_vpsMap;
@@ -2650,8 +2650,8 @@
   ParameterSetMap<TComPPS> m_ppsMap;
 
-  TComVPS                  m_activeVPS; // used for SEI message
-#endif
-
-  TComSPS                  m_activeSPS; // used for SEI message
+  Int m_activeVPSId; // -1 for nothing active
+#endif
+
+  Int m_activeSPSId; // -1 for nothing active
 };
 
Index: branches/SHM-dev/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 1319)
@@ -34,5 +34,5 @@
 /**
  \file     NALread.cpp
- \brief    reading funtionality for NAL units
+ \brief    reading functionality for NAL units
  */
 
@@ -105,5 +105,5 @@
 Void readNalUnitHeader(InputNALUnit& nalu)
 {
-  TComInputBitstream& bs = *nalu.m_Bitstream;
+  TComInputBitstream& bs = nalu.getBitstream();
 
   Bool forbidden_zero_bit = bs.read(1);           // forbidden_zero_bit
@@ -165,13 +165,11 @@
  * a bitstream
  */
-Void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
+Void read(InputNALUnit& nalu)
 {
-  /* perform anti-emulation prevention */
-  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
-  convertPayloadToRBSP(nalUnitBuf, pcBitstream, (nalUnitBuf[0] & 64) == 0);
-
-  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
-  nalu.m_Bitstream->setEmulationPreventionByteLocation(pcBitstream->getEmulationPreventionByteLocation());
-  delete pcBitstream;
+  TComInputBitstream &bitstream = nalu.getBitstream();
+  vector<uint8_t>& nalUnitBuf=bitstream.getFifo();
+  // perform anti-emulation prevention
+  convertPayloadToRBSP(nalUnitBuf, &bitstream, (nalUnitBuf[0] & 64) == 0);
+  bitstream.resetToStart();
   readNalUnitHeader(nalu);
 }
Index: branches/SHM-dev/source/Lib/TLibDecoder/NALread.h
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/NALread.h	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/NALread.h	(revision 1319)
@@ -34,5 +34,5 @@
 /**
  \file     NALread.h
- \brief    reading funtionality for NAL units
+ \brief    reading functionality for NAL units
  */
 
@@ -53,13 +53,19 @@
  * bitstream object.
  */
-struct InputNALUnit : public NALUnit
+class InputNALUnit : public NALUnit
 {
-  InputNALUnit() : m_Bitstream(0) {};
-  ~InputNALUnit() { delete m_Bitstream; }
+  private:
+    TComInputBitstream m_Bitstream;
 
-  TComInputBitstream* m_Bitstream;
+  public:
+    InputNALUnit(const InputNALUnit &src) : NALUnit(src), m_Bitstream(src.m_Bitstream) {};
+    InputNALUnit() : m_Bitstream() {};
+    virtual ~InputNALUnit() { }
+    const TComInputBitstream &getBitstream() const { return m_Bitstream; }
+          TComInputBitstream &getBitstream()       { return m_Bitstream; }
 };
 
-Void read(InputNALUnit& nalu, std::vector<uint8_t>& nalUnitBuf);
+Void read(InputNALUnit& nalu);
+Void readNalUnitHeader(InputNALUnit& nalu);
 
 //! \}
Index: branches/SHM-dev/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 1319)
@@ -471,5 +471,4 @@
 
   /* restore primary bitstream for sei_message */
-  getBitstream()->deleteFifo();
   delete getBitstream();
   setBitstream(bs);
Index: branches/SHM-dev/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1319)
@@ -154,5 +154,4 @@
   for (UInt ui = 0; ui < uiNumSubstreams; ui++)
   {
-    ppcSubstreams[ui]->deleteFifo();
     delete ppcSubstreams[ui];
   }
Index: branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1319)
@@ -63,9 +63,46 @@
 
 TDecTop::TDecTop()
-  : m_pDecodedSEIOutputStream(NULL),
-    m_warningMessageSkipPicture(false)
-{
-  m_pcPic = 0;
-  m_iMaxRefPicNum = 0;
+  : m_iMaxRefPicNum(0)
+  , m_associatedIRAPType(NAL_UNIT_INVALID)
+  , m_pocCRA(0)
+  , m_pocRandomAccess(MAX_INT)
+  , m_cListPic()
+  , m_parameterSetManager()
+  , m_apcSlicePilot(NULL)
+  , m_SEIs()
+  , m_cPrediction()
+  , m_cTrQuant()
+  , m_cGopDecoder()
+  , m_cSliceDecoder()
+  , m_cCuDecoder()
+  , m_cEntropyDecoder()
+  , m_cCavlcDecoder()
+  , m_cSbacDecoder()
+  , m_cBinCABAC()
+  , m_seiReader()
+  , m_cLoopFilter()
+  , m_cSAO()
+  , m_pcPic(NULL)
+#if !SVC_EXTENSION
+  , m_prevPOC(MAX_INT)
+#endif
+  , m_prevTid0POC(0)
+  , m_bFirstSliceInPicture(true)
+#if !SVC_EXTENSION
+  , m_bFirstSliceInSequence(true)
+#endif
+  , m_prevSliceSkipped(false)
+  , m_skippedPOC(0)
+  , m_bFirstSliceInBitstream(true)
+  , m_lastPOCNoOutputPriorPics(-1)
+  , m_isNoOutputPriorPics(false)
+  , m_craNoRaslOutputFlag(false)
+#if O0043_BEST_EFFORT_DECODING
+  , m_forceDecodeBitDepth(8)
+#endif
+  , m_pDecodedSEIOutputStream(NULL)
+  , m_warningMessageSkipPicture(false)
+  , m_prefixSEINALUs()
+{
 #if ENC_DEC_TRACE
   if (g_hTrace == NULL)
@@ -76,21 +113,4 @@
   g_nSymbolCounter = 0;
 #endif
-  m_associatedIRAPType = NAL_UNIT_INVALID;
-  m_pocCRA = 0;
-  m_pocRandomAccess = MAX_INT;
-#if !SVC_EXTENSION
-  m_prevPOC                = MAX_INT;
-#endif
-  m_prevTid0POC            = 0;
-  m_bFirstSliceInPicture    = true;
-#if !SVC_EXTENSION
-  m_bFirstSliceInSequence   = true;
-#endif
-  m_prevSliceSkipped = false;
-  m_skippedPOC = 0;
-  m_bFirstSliceInBitstream  = true;
-  m_lastPOCNoOutputPriorPics = -1;
-  m_craNoRaslOutputFlag = false;
-  m_isNoOutputPriorPics = false;
 
 #if SVC_EXTENSION 
@@ -133,4 +153,9 @@
   }
 #endif
+  while (!m_prefixSEINALUs.empty())
+  {
+    delete m_prefixSEINALUs.front();
+    m_prefixSEINALUs.pop_front();
+  }
 #if CGS_3D_ASYMLUT
   if(m_pColorMappedPic)
@@ -431,4 +456,6 @@
       assert (0);
     }
+
+    xParsePrefixSEImessages();
 
 #if RExt__HIGH_BIT_DEPTH_SUPPORT==0
@@ -699,4 +726,6 @@
     }
 
+    xParsePrefixSEImessages();
+
     // Check if any new SEI has arrived
      if(!m_SEIs.empty())
@@ -709,5 +738,39 @@
      }
   }
-
+}
+
+
+Void TDecTop::xParsePrefixSEIsForUnknownVCLNal()
+{
+  while (!m_prefixSEINALUs.empty())
+  {
+    // do nothing?
+    printf("Discarding Prefix SEI associated with unknown VCL NAL unit.\n");
+    delete m_prefixSEINALUs.front();
+  }
+  // TODO: discard following suffix SEIs as well?
+}
+
+
+Void TDecTop::xParsePrefixSEImessages()
+{
+#if SVC_EXTENSION
+    if (m_prevSliceSkipped) // No need to decode SEI messages of a skipped access unit
+    {
+      return;
+    }
+#endif
+
+  while (!m_prefixSEINALUs.empty())
+  {
+    InputNALUnit &nalu=*m_prefixSEINALUs.front();
+#if LAYERS_NOT_PRESENT_SEI
+    m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#else
+    m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#endif
+    delete m_prefixSEINALUs.front();
+    m_prefixSEINALUs.pop_front();
+  }
 }
 
@@ -783,4 +846,6 @@
     m_apcSlicePilot->setPOC(m_skippedPOC);
   }
+
+  xUpdatePreviousTid0POC(m_apcSlicePilot);
 
   m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
@@ -1795,5 +1860,5 @@
 
   //  Decode a picture
-  m_cGopDecoder.decompressSlice(nalu.m_Bitstream, m_pcPic);
+  m_cGopDecoder.decompressSlice(&(nalu.getBitstream()), m_pcPic);
 
 #if SVC_EXTENSION
@@ -1808,10 +1873,10 @@
 }
 
-Void TDecTop::xDecodeVPS(const std::vector<UChar> *pNaluData)
+Void TDecTop::xDecodeVPS(const std::vector<UChar> &naluData)
 {
   TComVPS* vps = new TComVPS();
 
   m_cEntropyDecoder.decodeVPS( vps );
-  m_parameterSetManager.storeVPS(vps, pNaluData);
+  m_parameterSetManager.storeVPS(vps, naluData);
 #if SVC_EXTENSION
   checkValueOfTargetOutputLayerSetIdx(vps);
@@ -1837,5 +1902,5 @@
 }
 
-Void TDecTop::xDecodeSPS(const std::vector<UChar> *pNaluData)
+Void TDecTop::xDecodeSPS(const std::vector<UChar> &naluData)
 {
   TComSPS* sps = new TComSPS();
@@ -1847,11 +1912,11 @@
 #endif
   m_cEntropyDecoder.decodeSPS( sps );
-  m_parameterSetManager.storeSPS(sps, pNaluData);
+  m_parameterSetManager.storeSPS(sps, naluData);
 }
 
 #if CGS_3D_ASYMLUT
-Void TDecTop::xDecodePPS( const std::vector<UChar> *pNaluData, TCom3DAsymLUT * pc3DAsymLUT )
+Void TDecTop::xDecodePPS( const std::vector<UChar> &naluData, TCom3DAsymLUT * pc3DAsymLUT )
 #else
-Void TDecTop::xDecodePPS(const std::vector<UChar> *pNaluData)
+Void TDecTop::xDecodePPS(const std::vector<UChar> &naluData)
 #endif
 {
@@ -1866,57 +1931,5 @@
   m_cEntropyDecoder.decodePPS( pps );
 #endif
-  m_parameterSetManager.storePPS( pps, pNaluData);
-}
-
-Void TDecTop::xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType )
-{
-  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
-  {
-#if SVC_EXTENSION
-    if (m_prevSliceSkipped) // No need to decode SEI messages of a skipped access unit
-    {
-      return;
-    }
-#endif
-#if LAYERS_NOT_PRESENT_SEI
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream  );
-#else
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
-#endif
-  }
-  else
-  {
-#if LAYERS_NOT_PRESENT_SEI
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream  );
-#else
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
-#endif
-    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
-    if (activeParamSets.size()>0)
-    {
-      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
-#if R0247_SEI_ACTIVE
-      assert(seiAps->activeSeqParameterSetId.size()>0);
-      if( !getLayerDec(0)->m_parameterSetManager.activateSPSWithSEI( seiAps->activeSeqParameterSetId[0] ) )
-      {
-        printf ("Warning SPS activation with Active parameter set SEI failed");
-      }
-      for (Int c=1 ; c <= seiAps->numSpsIdsMinus1; c++)
-      {
-        Int layerIdx = seiAps->layerSpsIdx[c];
-        if( !getLayerDec(layerIdx)->m_parameterSetManager.activateSPSWithSEI( seiAps->activeSeqParameterSetId[layerIdx] ) )
-        {
-          printf ("Warning SPS activation with Active parameter set SEI failed");
-        }
-      }
-#else
-      assert(seiAps->activeSeqParameterSetId.size()>0);
-      if (! m_parameterSetManager.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0] ))
-      {
-        printf ("Warning SPS activation with Active parameter set SEI failed");
-      }
-#endif
-    }
-  }
+  m_parameterSetManager.storePPS( pps, naluData);
 }
 
@@ -1937,5 +1950,5 @@
   // Initialize entropy decoder
   m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
-  m_cEntropyDecoder.setBitstream      (nalu.m_Bitstream);
+  m_cEntropyDecoder.setBitstream      (&(nalu.getBitstream()));
 
 #if SVC_EXTENSION
@@ -1952,7 +1965,7 @@
       assert( nalu.m_nuhLayerId == 0 ); // Non-conforming bitstream. The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
 #endif
-      xDecodeVPS(nalu.m_Bitstream->getFifo());
+      xDecodeVPS(nalu.getBitstream().getFifo());
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS, nalu.getBitstream().readByteAlignment(), 0);
 #endif
 #if SVC_EXTENSION
@@ -1962,7 +1975,7 @@
 
     case NAL_UNIT_SPS:
-      xDecodeSPS(nalu.m_Bitstream->getFifo());
+      xDecodeSPS(nalu.getBitstream().getFifo());
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS, nalu.getBitstream().readByteAlignment(), 0);
 #endif
       return false;
@@ -1970,14 +1983,18 @@
     case NAL_UNIT_PPS:
 #if CGS_3D_ASYMLUT
-      xDecodePPS( nalu.m_Bitstream->getFifo(), &m_c3DAsymLUTPPS );
+      xDecodePPS( nalu.getBitstream().getFifo(), &m_c3DAsymLUTPPS );
 #else
-      xDecodePPS(nalu.m_Bitstream->getFifo());
+      xDecodePPS(nalu.getBitstream().getFifo());
 #endif
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS, nalu.getBitstream().readByteAlignment(),0);
 #endif
       return false;
 
     case NAL_UNIT_PREFIX_SEI:
+      // Buffer up prefix SEI messages until SPS of associated VCL is known.
+      m_prefixSEINALUs.push_back(new InputNALUnit(nalu));
+      return false;
+
     case NAL_UNIT_SUFFIX_SEI:
 #if SVC_EXTENSION
@@ -1987,5 +2004,16 @@
       }
 #endif
-      xDecodeSEI( nalu.m_Bitstream, nalu.m_nalUnitType );
+      if (m_pcPic)
+      {
+#if SVC_EXTENSION
+        m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#else
+        m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#endif
+      }
+      else
+      {
+        printf ("Note: received suffix SEI but no picture currently active.\n");
+      }
       return false;
 
@@ -2079,4 +2107,7 @@
     case NAL_UNIT_RESERVED_VCL30:
     case NAL_UNIT_RESERVED_VCL31:
+      printf ("Note: found reserved VCL NAL unit.\n");
+      xParsePrefixSEIsForUnknownVCLNal();
+      return false;
 
     case NAL_UNIT_RESERVED_NVCL41:
Index: branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 1319)
@@ -56,5 +56,5 @@
 #include "SEIread.h"
 
-struct InputNALUnit;
+class InputNALUnit;
 
 //! \ingroup TLibDecoder
@@ -79,5 +79,5 @@
   TComSlice*              m_apcSlicePilot;
 
-  SEIMessages             m_SEIs; ///< List of SEI messages that have been received before the first slice and between slices
+  SEIMessages             m_SEIs; ///< List of SEI messages that have been received before the first slice and between slices, excluding prefix SEIs...
 
   // functional classes
@@ -123,4 +123,6 @@
 
   Bool                    m_warningMessageSkipPicture;
+
+  std::list<InputNALUnit*> m_prefixSEINALUs; /// Buffered up prefix SEI NAL Units.
 
 #if SVC_EXTENSION
@@ -277,13 +279,15 @@
   Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
 #endif
-  Void      xDecodeVPS(const std::vector<UChar> *pNaluData);
-  Void      xDecodeSPS(const std::vector<UChar> *pNaluData);
+  Void      xDecodeVPS(const std::vector<UChar> &naluData);
+  Void      xDecodeSPS(const std::vector<UChar> &naluData);  
 #if CGS_3D_ASYMLUT
-  Void      xDecodePPS(const std::vector<UChar> *pNaluData, TCom3DAsymLUT *pc3DAsymLUT);
+  Void      xDecodePPS(const std::vector<UChar> &naluData, TCom3DAsymLUT *pc3DAsymLUT);
 #else
-  Void      xDecodePPS(const std::vector<UChar> *pNaluData);
+  Void      xDecodePPS(const std::vector<UChar> &naluData);
 #endif
   Void      xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType );
   Void      xUpdatePreviousTid0POC( TComSlice *pSlice ) { if ((pSlice->getTLayer()==0) && (pSlice->isReferenceNalu() && (pSlice->getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (pSlice->getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) { m_prevTid0POC=pSlice->getPOC(); } }
+  Void      xParsePrefixSEImessages();
+  Void      xParsePrefixSEIsForUnknownVCLNal();
 
 
Index: branches/SHM-dev/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/SHM-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1318)
+++ branches/SHM-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1319)
@@ -79,7 +79,4 @@
   case SEI::ACTIVE_PARAMETER_SETS:
     xWriteSEIActiveParameterSets(*static_cast<const SEIActiveParameterSets*>(& sei));
-    break; 
-  case SEI::DECODED_PICTURE_HASH:
-    xWriteSEIDecodedPictureHash(*static_cast<const SEIDecodedPictureHash*>(&sei));
     break;
 #if SVC_EXTENSION
@@ -97,4 +94,9 @@
     xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps);
     break;
+#endif
+  case SEI::DECODED_PICTURE_HASH:
+    xWriteSEIDecodedPictureHash(*static_cast<const SEIDecodedPictureHash*>(&sei));
+    break;
+#if !SVC_EXTENSION
   case SEI::BUFFERING_PERIOD:
     xWriteSEIBufferingPeriod(*static_cast<const SEIBufferingPeriod*>(&sei), sps);
@@ -398,5 +400,5 @@
   if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
   {
-    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay");
+    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay_increment");
   }
   WRITE_FLAG( sei.m_dpbOutputDuDelayPresentFlag, "dpb_output_du_delay_present_flag");
