IMF MCA labels
[asdcplib.git] / src / MXF.cpp
index ae45e0780b8c42d4bc477fb790899becbd81eb99..d3351efeb8176a41e16953b4bea1d96bbaaab381 100755 (executable)
@@ -1,5 +1,5 @@
 /*
-Copyright (c) 2005-2006, John Hurst
+Copyright (c) 2005-2013, John Hurst
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -29,80 +29,38 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     \brief   MXF objects
 */
 
-#define ASDCP_DECLARE_MDD
-#include "MDD.h"
 #include "MXF.h"
-#include <hex_utils.h>
+#include "Metadata.h"
+#include <KM_log.h>
 
-//------------------------------------------------------------------------------------------
-//
-
-const ui32_t kl_length = ASDCP::SMPTE_UL_LENGTH + ASDCP::MXF_BER_LENGTH;
-
-const byte_t mdd_key[] = { 0x06, 0x0e, 0x2b, 0x34 };
-
-//
-const ASDCP::MDDEntry*
-ASDCP::GetMDDEntry(const byte_t* ul_buf)
-{
-  ui32_t t_idx = 0;
-  ui32_t k_idx = 8;
-
-  // must be a pointer to a SMPTE UL
-  if ( ul_buf == 0 || memcmp(mdd_key, ul_buf, 4) != 0 )
-    return 0;
-
-  // advance to first matching element
-  // TODO: optimize using binary search
-  while ( s_MDD_Table[t_idx].ul != 0
-         && s_MDD_Table[t_idx].ul[k_idx] != ul_buf[k_idx] )
-    t_idx++;
-
-  if ( s_MDD_Table[t_idx].ul == 0 )
-    return 0;
-
-  // match successive elements
-  while ( s_MDD_Table[t_idx].ul != 0
-         && k_idx < SMPTE_UL_LENGTH - 1
-         && s_MDD_Table[t_idx].ul[k_idx] == ul_buf[k_idx] )
-    {
-      if ( s_MDD_Table[t_idx].ul[k_idx+1] == ul_buf[k_idx+1] )
-       {
-         k_idx++;
-       }
-      else
-       {
-         while ( s_MDD_Table[t_idx].ul != 0
-                 && s_MDD_Table[t_idx].ul[k_idx] == ul_buf[k_idx]
-                 && s_MDD_Table[t_idx].ul[k_idx+1] != ul_buf[k_idx+1] )
-           t_idx++;
-             
-         while ( s_MDD_Table[t_idx].ul[k_idx] != ul_buf[k_idx] )
-           k_idx--;
-       }
-    }
+using Kumu::DefaultLogSink;
+using Kumu::GenRandomValue;
 
-  return (s_MDD_Table[t_idx].ul == 0 ? 0 : &s_MDD_Table[t_idx]);
-}
+// index segments must be < 64K
+// NOTE: this value may too high if advanced index entry elements are used.
+const ui32_t CBRIndexEntriesPerSegment = 5000;
 
 //------------------------------------------------------------------------------------------
 //
 
 //
 ASDCP::Result_t
-ASDCP::MXF::SeekToRIP(const ASDCP::FileReader& Reader)
+ASDCP::MXF::SeekToRIP(const Kumu::FileReader& Reader)
 {
-  ASDCP::fpos_t end_pos;
+  Kumu::fpos_t end_pos;
 
   // go to the end - 4 bytes
-  Result_t result = Reader.Seek(0, ASDCP::SP_END);
+  Result_t result = Reader.Seek(0, Kumu::SP_END);
 
   if ( ASDCP_SUCCESS(result) )
     result = Reader.Tell(&end_pos);
 
   if ( ASDCP_SUCCESS(result)
        && end_pos < (SMPTE_UL_LENGTH+MXF_BER_LENGTH) )
-    result = RESULT_FAIL;  // File is smaller than an empty packet!
+    {
+      DefaultLogSink().Error("File is smaller than an empty KLV packet.\n");
+      result = RESULT_FAIL;
+    }
 
   if ( ASDCP_SUCCESS(result) )
     result = Reader.Seek(end_pos - 4);
@@ -117,15 +75,21 @@ ASDCP::MXF::SeekToRIP(const ASDCP::FileReader& Reader)
       result = Reader.Read(intbuf, MXF_BER_LENGTH, &read_count);
 
       if ( ASDCP_SUCCESS(result) && read_count != 4 )
-       result = RESULT_FAIL;
+       {
+         DefaultLogSink().Error("RIP contains fewer than four bytes.\n");
+         result = RESULT_FAIL;
+       }
     }
 
   if ( ASDCP_SUCCESS(result) )
     {
-      rip_size = ASDCP_i32_BE(cp2i<ui32_t>(intbuf));
+      rip_size = KM_i32_BE(Kumu::cp2i<ui32_t>(intbuf));
 
       if ( rip_size > end_pos ) // RIP can't be bigger than the file
-       return RESULT_FAIL;
+       {
+         DefaultLogSink().Error("RIP size impossibly large.\n");
+         return RESULT_FAIL;
+       }
     }
 
   // reposition to start of RIP
@@ -137,14 +101,32 @@ ASDCP::MXF::SeekToRIP(const ASDCP::FileReader& Reader)
 
 //
 ASDCP::Result_t
-ASDCP::MXF::RIP::InitFromFile(const ASDCP::FileReader& Reader)
+ASDCP::MXF::RIP::GetPairBySID(ui32_t SID, Pair& outPair) const
+{
+  Array<Pair>::const_iterator pi = PairArray.begin();
+  for ( ; pi != PairArray.end(); pi++ )
+    {
+      if ( (*pi).BodySID == SID )
+       {
+         outPair = *pi;
+         return RESULT_OK;
+       }
+    }
+
+  return RESULT_FAIL;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::RIP::InitFromFile(const Kumu::FileReader& Reader)
 {
-  Result_t result = KLVFilePacket::InitFromFile(Reader, s_MDD_Table[MDDindex_RandomIndexMetadata].ul);
+  assert(m_Dict);
+  Result_t result = KLVFilePacket::InitFromFile(Reader, m_Dict->ul(MDD_RandomIndexMetadata));
 
   if ( ASDCP_SUCCESS(result) )
     {
-      MemIOReader MemRDR(m_ValueStart, m_ValueLength - 4);
-      result =  PairArray.ReadFrom(MemRDR);
+      Kumu::MemIOReader MemRDR(m_ValueStart, m_ValueLength - 4);
+      result = PairArray.Unarchive(&MemRDR) ? RESULT_OK : RESULT_KLV_CODING;
     }
 
   if ( ASDCP_FAILURE(result) )
@@ -155,9 +137,32 @@ ASDCP::MXF::RIP::InitFromFile(const ASDCP::FileReader& Reader)
 
 //
 ASDCP::Result_t
-ASDCP::MXF::RIP::WriteToFile(ASDCP::FileWriter& Writer)
+ASDCP::MXF::RIP::WriteToFile(Kumu::FileWriter& Writer)
 {
-  Result_t result = WriteKLToFile(Writer, s_MDD_Table[MDDindex_RandomIndexMetadata].ul, 0);
+  assert(m_Dict);
+  ASDCP::FrameBuffer Buffer;
+  ui32_t RIPSize = ( PairArray.size() * (sizeof(ui32_t) + sizeof(ui64_t)) ) + 4;
+  Result_t result = Buffer.Capacity(RIPSize);
+
+  if ( ASDCP_SUCCESS(result) )
+    result = WriteKLToFile(Writer, m_Dict->ul(MDD_RandomIndexMetadata), RIPSize);
+
+  if ( ASDCP_SUCCESS(result) )
+    {
+      result = RESULT_KLV_CODING;
+
+      Kumu::MemIOWriter MemWRT(Buffer.Data(), Buffer.Capacity());
+      if ( PairArray.Archive(&MemWRT) )
+       if ( MemWRT.WriteUi32BE(RIPSize + 20) )
+         {
+           Buffer.Size(MemWRT.Length());
+           result = RESULT_OK;
+         }
+    }
+
+  if ( ASDCP_SUCCESS(result) )
+    result = Writer.Write(Buffer.RoData(), Buffer.Size());
+
   return result;
 }
 
@@ -168,40 +173,150 @@ ASDCP::MXF::RIP::Dump(FILE* stream)
   if ( stream == 0 )
     stream = stderr;
 
-  KLVFilePacket::Dump(stream, false);
+  KLVFilePacket::Dump(stream, *m_Dict, false);
   PairArray.Dump(stream, false);
+}
+
+//------------------------------------------------------------------------------------------
+//
+
+//
+ASDCP::MXF::Partition::PacketList::~PacketList() {
+  while ( ! m_List.empty() )
+    {
+      delete m_List.back();
+      m_List.pop_back();
+    }
+}
+
+//
+void
+ASDCP::MXF::Partition::PacketList::AddPacket(InterchangeObject* ThePacket) // takes ownership
+{
+  assert(ThePacket);
+  m_Map.insert(std::map<UUID, InterchangeObject*>::value_type(ThePacket->InstanceUID, ThePacket));
+  m_List.push_back(ThePacket);
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::Partition::PacketList::GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object)
+{
+  ASDCP_TEST_NULL(Object);
+
+  std::map<UUID, InterchangeObject*>::iterator mi = m_Map.find(ObjectID);
+  
+  if ( mi == m_Map.end() )
+    {
+      *Object = 0;
+      return RESULT_FAIL;
+    }
+
+  *Object = (*mi).second;
+  return RESULT_OK;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::Partition::PacketList::GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object)
+{
+  ASDCP_TEST_NULL(ObjectID);
+  ASDCP_TEST_NULL(Object);
+  std::list<InterchangeObject*>::iterator li;
+  *Object = 0;
+
+  for ( li = m_List.begin(); li != m_List.end(); li++ )
+    {
+      if ( (*li)->HasUL(ObjectID) )
+       {
+         *Object = *li;
+         return RESULT_OK;
+       }
+    }
+
+  return RESULT_FAIL;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::Partition::PacketList::GetMDObjectsByType(const byte_t* ObjectID, std::list<InterchangeObject*>& ObjectList)
+{
+  ASDCP_TEST_NULL(ObjectID);
+  std::list<InterchangeObject*>::iterator li;
+
+  for ( li = m_List.begin(); li != m_List.end(); li++ )
+    {
+      if ( (*li)->HasUL(ObjectID) )
+       ObjectList.push_back(*li);
+    }
 
-  fputs("==========================================================================\n", stream);
+  return ObjectList.empty() ? RESULT_FAIL : RESULT_OK;
 }
 
 //------------------------------------------------------------------------------------------
 //
 
+
+ASDCP::MXF::Partition::Partition(const Dictionary*& d) :
+  m_Dict(d),
+  MajorVersion(1), MinorVersion(2),
+  KAGSize(1), ThisPartition(0), PreviousPartition(0),
+  FooterPartition(0), HeaderByteCount(0), IndexByteCount(0), IndexSID(0),
+  BodyOffset(0), BodySID(0)
+{
+  m_PacketList = new PacketList;
+}
+
+ASDCP::MXF::Partition::~Partition()
+{
+}
+
+// takes ownership
+void
+ASDCP::MXF::Partition::AddChildObject(InterchangeObject* Object)
+{
+  assert(Object);
+
+  if ( ! Object->InstanceUID.HasValue() )
+    GenRandomValue(Object->InstanceUID);
+
+  m_PacketList->AddPacket(Object);
+}
+
 //
 ASDCP::Result_t
-ASDCP::MXF::Partition::InitFromFile(const ASDCP::FileReader& Reader)
+ASDCP::MXF::Partition::InitFromFile(const Kumu::FileReader& Reader)
 {
   Result_t result = KLVFilePacket::InitFromFile(Reader);
   // test the UL
   // could be one of several values
-
   if ( ASDCP_SUCCESS(result) )
-    {
-      MemIOReader MemRDR(m_ValueStart, m_ValueLength);
-      result = MemRDR.ReadUi16BE(&MajorVersion);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi16BE(&MinorVersion);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi32BE(&KAGSize);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&ThisPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&PreviousPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&FooterPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&HeaderByteCount);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&IndexByteCount);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi32BE(&IndexSID);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi64BE(&BodyOffset);
-      if ( ASDCP_SUCCESS(result) )  result = MemRDR.ReadUi32BE(&BodySID);
-      if ( ASDCP_SUCCESS(result) )  result = OperationalPattern.ReadFrom(MemRDR);
-      if ( ASDCP_SUCCESS(result) )  result = EssenceContainers.ReadFrom(MemRDR);
-    }
+    result = ASDCP::MXF::Partition::InitFromBuffer(m_ValueStart, m_ValueLength);
+  
+  return result;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::Partition::InitFromBuffer(const byte_t* p, ui32_t l)
+{
+  Kumu::MemIOReader MemRDR(p, l);
+  Result_t result = RESULT_KLV_CODING;
+
+  if ( MemRDR.ReadUi16BE(&MajorVersion) )
+    if ( MemRDR.ReadUi16BE(&MinorVersion) )
+      if ( MemRDR.ReadUi32BE(&KAGSize) )
+       if ( MemRDR.ReadUi64BE(&ThisPartition) )
+         if ( MemRDR.ReadUi64BE(&PreviousPartition) )
+           if ( MemRDR.ReadUi64BE(&FooterPartition) )
+             if ( MemRDR.ReadUi64BE(&HeaderByteCount) )
+               if ( MemRDR.ReadUi64BE(&IndexByteCount) )
+                 if ( MemRDR.ReadUi32BE(&IndexSID) )
+                   if ( MemRDR.ReadUi64BE(&BodyOffset) )
+                     if ( MemRDR.ReadUi32BE(&BodySID) )
+                       if ( OperationalPattern.Unarchive(&MemRDR) )
+                         if ( EssenceContainers.Unarchive(&MemRDR) )
+                           result = RESULT_OK;
 
   if ( ASDCP_FAILURE(result) )
     DefaultLogSink().Error("Failed to initialize Partition\n");
@@ -211,67 +326,84 @@ ASDCP::MXF::Partition::InitFromFile(const ASDCP::FileReader& Reader)
 
 //
 ASDCP::Result_t
-ASDCP::MXF::Partition::WriteToFile(ASDCP::FileWriter& Writer)
+ASDCP::MXF::Partition::WriteToFile(Kumu::FileWriter& Writer, UL& PartitionLabel)
 {
-  Result_t result = m_Buffer.Capacity(1024);
+  ASDCP::FrameBuffer Buffer;
+  Result_t result = Buffer.Capacity(1024);
 
   if ( ASDCP_SUCCESS(result) )
     {
-      MemIOWriter MemWRT(m_Buffer.Data(), m_Buffer.Capacity());
-      result = MemWRT.WriteUi16BE(MajorVersion);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi16BE(MinorVersion);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi32BE(KAGSize);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(ThisPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(PreviousPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(FooterPartition);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(HeaderByteCount);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(IndexByteCount);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi32BE(IndexSID);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi64BE(BodyOffset);
-      if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi32BE(BodySID);
-      if ( ASDCP_SUCCESS(result) )  result = OperationalPattern.WriteTo(MemWRT);
-      if ( ASDCP_SUCCESS(result) )  result = EssenceContainers.WriteTo(MemWRT);
-      if ( ASDCP_SUCCESS(result) )  m_Buffer.Size(MemWRT.Size());
+      Kumu::MemIOWriter MemWRT(Buffer.Data(), Buffer.Capacity());
+      result = RESULT_KLV_CODING;
+      if ( MemWRT.WriteUi16BE(MajorVersion) )
+       if ( MemWRT.WriteUi16BE(MinorVersion) )
+         if ( MemWRT.WriteUi32BE(KAGSize) )
+           if ( MemWRT.WriteUi64BE(ThisPartition) )
+             if ( MemWRT.WriteUi64BE(PreviousPartition) )
+               if ( MemWRT.WriteUi64BE(FooterPartition) )
+                 if ( MemWRT.WriteUi64BE(HeaderByteCount) )
+                   if ( MemWRT.WriteUi64BE(IndexByteCount) )
+                     if ( MemWRT.WriteUi32BE(IndexSID) )
+                       if ( MemWRT.WriteUi64BE(BodyOffset) )
+                         if ( MemWRT.WriteUi32BE(BodySID) )
+                           if ( OperationalPattern.Archive(&MemWRT) )
+                             if ( EssenceContainers.Archive(&MemWRT) )
+                               {
+                                 Buffer.Size(MemWRT.Length());
+                                 result = RESULT_OK;
+                               }
     }
 
   if ( ASDCP_SUCCESS(result) )
     {
-      ui32_t write_count; // this is subclassed, so the UL is only right some of the time
-      result = WriteKLToFile(Writer, s_MDD_Table[MDDindex_ClosedCompleteHeader].ul, m_Buffer.Size());
+      ui32_t write_count;
+      result = WriteKLToFile(Writer, PartitionLabel.Value(), Buffer.Size());
 
       if ( ASDCP_SUCCESS(result) )
-       result = Writer.Write(m_Buffer.RoData(), m_Buffer.Size(), &write_count);
+       result = Writer.Write(Buffer.RoData(), Buffer.Size(), &write_count);
     }
 
   return result;
 }
 
+//
+ui32_t
+ASDCP::MXF::Partition::ArchiveSize()
+{
+  return ( kl_length
+          + sizeof(ui16_t) + sizeof(ui16_t)
+          + sizeof(ui32_t)
+          + sizeof(ui64_t) + sizeof(ui64_t) + sizeof(ui64_t) + sizeof(ui64_t) + sizeof(ui64_t)
+          + sizeof(ui32_t)
+          + sizeof(ui64_t)
+          + sizeof(ui32_t)
+          + SMPTE_UL_LENGTH
+          + sizeof(ui32_t) + sizeof(ui32_t) + ( UUIDlen * EssenceContainers.size() ) );
+}
+
 //
 void
 ASDCP::MXF::Partition::Dump(FILE* stream)
 {
   char identbuf[IdentBufferLen];
-  char intbuf[IntBufferLen];
 
   if ( stream == 0 )
     stream = stderr;
 
-  KLVFilePacket::Dump(stream, false);
+  KLVFilePacket::Dump(stream, *m_Dict, false);
   fprintf(stream, "  MajorVersion       = %hu\n", MajorVersion);
   fprintf(stream, "  MinorVersion       = %hu\n", MinorVersion);
-  fprintf(stream, "  KAGSize            = %lu\n", KAGSize);
-  fprintf(stream, "  ThisPartition      = %s\n",  ui64sz(ThisPartition, intbuf));
-  fprintf(stream, "  PreviousPartition  = %s\n",  ui64sz(PreviousPartition, intbuf));
-  fprintf(stream, "  FooterPartition    = %s\n",  ui64sz(FooterPartition, intbuf));
-  fprintf(stream, "  HeaderByteCount    = %s\n",  ui64sz(HeaderByteCount, intbuf));
-  fprintf(stream, "  IndexByteCount     = %s\n",  ui64sz(IndexByteCount, intbuf));
-  fprintf(stream, "  IndexSID           = %lu\n", IndexSID);
-  fprintf(stream, "  BodyOffset         = %s\n",  ui64sz(BodyOffset, intbuf));
-  fprintf(stream, "  BodySID            = %lu\n", BodySID);
-  fprintf(stream, "  OperationalPattern = %s\n",  OperationalPattern.ToString(identbuf));
-  fputs("Essence Containers:\n", stream); EssenceContainers.Dump(stream, false);
-
-  fputs("==========================================================================\n", stream);
+  fprintf(stream, "  KAGSize            = %u\n",  KAGSize);
+  fprintf(stream, "  ThisPartition      = %s\n",  ui64sz(ThisPartition, identbuf));
+  fprintf(stream, "  PreviousPartition  = %s\n",  ui64sz(PreviousPartition, identbuf));
+  fprintf(stream, "  FooterPartition    = %s\n",  ui64sz(FooterPartition, identbuf));
+  fprintf(stream, "  HeaderByteCount    = %s\n",  ui64sz(HeaderByteCount, identbuf));
+  fprintf(stream, "  IndexByteCount     = %s\n",  ui64sz(IndexByteCount, identbuf));
+  fprintf(stream, "  IndexSID           = %u\n",  IndexSID);
+  fprintf(stream, "  BodyOffset         = %s\n",  ui64sz(BodyOffset, identbuf));
+  fprintf(stream, "  BodySID            = %u\n",  BodySID);
+  fprintf(stream, "  OperationalPattern = %s\n",  OperationalPattern.EncodeString(identbuf, IdentBufferLen));
+  fputs("Essence Containers:\n", stream); EssenceContainers.Dump(stream);
 }
 
 
@@ -292,7 +424,9 @@ public:
 
 
 //
-ASDCP::MXF::Primer::Primer() {}
+ASDCP::MXF::Primer::Primer(const Dictionary*& d) : m_LocalTag(0xff), m_Dict(d) {
+  m_UL = m_Dict->ul(MDD_Primer);
+}
 
 //
 ASDCP::MXF::Primer::~Primer() {}
@@ -309,12 +443,13 @@ ASDCP::MXF::Primer::ClearTagList()
 ASDCP::Result_t
 ASDCP::MXF::Primer::InitFromBuffer(const byte_t* p, ui32_t l)
 {
-  Result_t result = KLVPacket::InitFromBuffer(p, l, s_MDD_Table[MDDindex_Primer].ul);
+  assert(m_Dict);
+  Result_t result = KLVPacket::InitFromBuffer(p, l, m_Dict->ul(MDD_Primer));
 
   if ( ASDCP_SUCCESS(result) )
     {
-      MemIOReader MemRDR(m_ValueStart, m_ValueLength);
-      result = LocalTagEntryBatch.ReadFrom(MemRDR);
+      Kumu::MemIOReader MemRDR(m_ValueStart, m_ValueLength);
+      result = LocalTagEntryBatch.Unarchive(&MemRDR) ? RESULT_OK : RESULT_KLV_CODING;
     }
 
   if ( ASDCP_SUCCESS(result) )
@@ -329,47 +464,75 @@ ASDCP::MXF::Primer::InitFromBuffer(const byte_t* p, ui32_t l)
   return result;
 }
 
+//
+ASDCP::Result_t
+ASDCP::MXF::Primer::WriteToFile(Kumu::FileWriter& Writer)
+{
+  ASDCP::FrameBuffer Buffer;
+  Result_t result = Buffer.Capacity(128*1024);
+
+  if ( ASDCP_SUCCESS(result) )
+    result = WriteToBuffer(Buffer);
+
+  if ( ASDCP_SUCCESS(result) )
+  result = Writer.Write(Buffer.RoData(), Buffer.Size());
+
+  return result;
+}
+
 //
 ASDCP::Result_t
 ASDCP::MXF::Primer::WriteToBuffer(ASDCP::FrameBuffer& Buffer)
 {
-  MemIOWriter MemWRT(Buffer.Data(), Buffer.Capacity());
-  Result_t result = LocalTagEntryBatch.WriteTo(MemWRT);
-  Buffer.Size(MemWRT.Size());
-#if 0
+  assert(m_Dict);
+  ASDCP::FrameBuffer LocalTagBuffer;
+  Kumu::MemIOWriter MemWRT(Buffer.Data() + kl_length, Buffer.Capacity() - kl_length);
+  Result_t result = LocalTagEntryBatch.Archive(&MemWRT) ? RESULT_OK : RESULT_KLV_CODING;
+
   if ( ASDCP_SUCCESS(result) )
     {
-      ui32_t write_count;
-      result = WriteKLToFile(Writer, s_MDD_Table[MDDindex_Primer].ul, Buffer.Size());
+      ui32_t packet_length = MemWRT.Length();
+      result = WriteKLToBuffer(Buffer, packet_length);
 
       if ( ASDCP_SUCCESS(result) )
-       result = Writer.Write(Buffer.RoData(), Buffer.Size(), &write_count);
+       Buffer.Size(Buffer.Size() + packet_length);
     }
-#endif
 
   return result;
 }
 
 //
 ASDCP::Result_t
-ASDCP::MXF::Primer::InsertTag(const ASDCP::UL& Key, ASDCP::TagValue& Tag)
+ASDCP::MXF::Primer::InsertTag(const MDDEntry& Entry, ASDCP::TagValue& Tag)
 {
   assert(m_Lookup);
-
-  std::map<UL, TagValue>::iterator i = m_Lookup->find(Key);
+  UL TestUL(Entry.ul);
+  std::map<UL, TagValue>::iterator i = m_Lookup->find(TestUL);
 
   if ( i == m_Lookup->end() )
     {
-      const MDDEntry* mdde = GetMDDEntry(Key.Value());
-      assert(mdde);
+      if ( Entry.tag.a == 0 && Entry.tag.b == 0 )
+       {
+         Tag.a = 0xff;
+         Tag.b = m_LocalTag--;
+       }
+      else
+       {
+         Tag.a = Entry.tag.a;
+         Tag.b = Entry.tag.b;
+       }
 
       LocalTagEntry TmpEntry;
-      TmpEntry.UL = Key;
-      TmpEntry.Tag = mdde->tag;
+      TmpEntry.UL = TestUL;
+      TmpEntry.Tag = Tag;
 
       LocalTagEntryBatch.push_back(TmpEntry);
       m_Lookup->insert(std::map<UL, TagValue>::value_type(TmpEntry.UL, TmpEntry.Tag));
     }
+  else
+    {
+      Tag = (*i).second;
+    }
    
   return RESULT_OK;
 }
@@ -398,24 +561,23 @@ ASDCP::MXF::Primer::TagForKey(const ASDCP::UL& Key, ASDCP::TagValue& Tag)
 void
 ASDCP::MXF::Primer::Dump(FILE* stream)
 {
+  assert(m_Dict);
   char identbuf[IdentBufferLen];
 
   if ( stream == 0 )
     stream = stderr;
 
-  KLVPacket::Dump(stream, false);
-  fprintf(stream, "Primer: %lu %s\n",
-         LocalTagEntryBatch.ItemCount,
-         ( LocalTagEntryBatch.ItemCount == 1 ? "entry" : "entries" ));
+  KLVPacket::Dump(stream, *m_Dict, false);
+  fprintf(stream, "Primer: %u %s\n",
+         (ui32_t)LocalTagEntryBatch.size(),
+         ( LocalTagEntryBatch.size() == 1 ? "entry" : "entries" ));
   
   Batch<LocalTagEntry>::iterator i = LocalTagEntryBatch.begin();
   for ( ; i != LocalTagEntryBatch.end(); i++ )
     {
-      const MDDEntry* Entry = GetMDDEntry((*i).UL.Value());
-      fprintf(stream, "  %s %s\n", (*i).ToString(identbuf), (Entry ? Entry->name : "Unknown"));
+      const MDDEntry* Entry = m_Dict->FindUL((*i).UL.Value());
+      fprintf(stream, "  %s %s\n", (*i).EncodeString(identbuf, IdentBufferLen), (Entry ? Entry->name : "Unknown"));
     }
-
-  fputs("==========================================================================\n", stream);
 }
 
 
@@ -423,63 +585,76 @@ ASDCP::MXF::Primer::Dump(FILE* stream)
 //
 
 //
-ASDCP::Result_t
-ASDCP::MXF::Preface::InitFromBuffer(const byte_t* p, ui32_t l)
+ASDCP::MXF::Preface::Preface(const Dictionary*& d) :
+  InterchangeObject(d), m_Dict(d), Version(258), ObjectModelVersion(0)
 {
-  ASDCP_TEST_NULL(p);
-
-  Result_t result = KLVPacket::InitFromBuffer(p, l, s_MDD_Table[MDDindex_Preface].ul);
-
-  if ( ASDCP_SUCCESS(result) )
-    {
-      TLVReader MemRDR(m_ValueStart, m_ValueLength, m_Lookup);
-
-      result = MemRDR.ReadObject(OBJ_READ_ARGS(InterchangeObject, InstanceUID));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(GenerationInterchangeObject, GenerationUID));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, LastModifiedDate));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadUi16(OBJ_READ_ARGS(Preface, Version));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadUi32(OBJ_READ_ARGS(Preface, ObjectModelVersion));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, PrimaryPackage));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, Identifications));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, ContentStorage));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, OperationalPattern));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, EssenceContainers));
-      if ( ASDCP_SUCCESS(result) ) result = MemRDR.ReadObject(OBJ_READ_ARGS(Preface, DMSchemes));
-    }
+  assert(m_Dict);
+  m_UL = m_Dict->Type(MDD_Preface).ul;
+}
 
-  if ( ASDCP_FAILURE(result) )
-    DefaultLogSink().Error("Failed to initialize Preface\n");
+//
+void
+ASDCP::MXF::Preface::Copy(const Preface& rhs)
+{
+  InterchangeObject::Copy(rhs);
+
+  LastModifiedDate = rhs.LastModifiedDate;
+  Version = rhs.Version;
+  ObjectModelVersion = rhs.ObjectModelVersion;
+  PrimaryPackage = rhs.PrimaryPackage;
+  Identifications = rhs.Identifications;
+  ContentStorage = rhs.ContentStorage;
+  OperationalPattern = rhs.OperationalPattern;
+  EssenceContainers = rhs.EssenceContainers;
+  DMSchemes = rhs.DMSchemes;
+}
 
+//
+ASDCP::Result_t
+ASDCP::MXF::Preface::InitFromTLVSet(TLVReader& TLVSet)
+{
+  Result_t result = InterchangeObject::InitFromTLVSet(TLVSet);
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, LastModifiedDate));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadUi16(OBJ_READ_ARGS(Preface, Version));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadUi32(OBJ_READ_ARGS(Preface, ObjectModelVersion));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, PrimaryPackage));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, Identifications));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, ContentStorage));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, OperationalPattern));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, EssenceContainers));
+  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(Preface, DMSchemes));
   return result;
 }
 
 //
 ASDCP::Result_t
-ASDCP::MXF::Preface::WriteToBuffer(ASDCP::FrameBuffer& Buffer)
+ASDCP::MXF::Preface::WriteToTLVSet(TLVWriter& TLVSet)
 {
-  TLVWriter MemWRT(Buffer.Data() + kl_length, Buffer.Capacity() - kl_length, m_Lookup);
-  Result_t result = MemWRT.WriteObject(OBJ_WRITE_ARGS(InterchangeObject, InstanceUID));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(GenerationInterchangeObject, GenerationUID));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, LastModifiedDate));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi16(OBJ_WRITE_ARGS(Preface, Version));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteUi32(OBJ_WRITE_ARGS(Preface, ObjectModelVersion));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, PrimaryPackage));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, Identifications));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, ContentStorage));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, OperationalPattern));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, EssenceContainers));
-  if ( ASDCP_SUCCESS(result) )  result = MemWRT.WriteObject(OBJ_WRITE_ARGS(Preface, DMSchemes));
-
-  if ( ASDCP_SUCCESS(result) )
-    {
-      ui32_t packet_length = MemWRT.Size();
-      result = WriteKLToBuffer(Buffer, s_MDD_Table[MDDindex_Preface].ul, packet_length);
+  Result_t result = InterchangeObject::WriteToTLVSet(TLVSet);
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, LastModifiedDate));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteUi16(OBJ_WRITE_ARGS(Preface, Version));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteUi32(OBJ_WRITE_ARGS(Preface, ObjectModelVersion));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, PrimaryPackage));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, Identifications));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, ContentStorage));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, OperationalPattern));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, EssenceContainers));
+  if ( ASDCP_SUCCESS(result) )  result = TLVSet.WriteObject(OBJ_WRITE_ARGS(Preface, DMSchemes));
+  return result;
+}
 
-      if ( ASDCP_SUCCESS(result) )
-       Buffer.Size(Buffer.Size() + packet_length);
-    }
+//
+ASDCP::Result_t
+ASDCP::MXF::Preface::InitFromBuffer(const byte_t* p, ui32_t l)
+{
+  return InterchangeObject::InitFromBuffer(p, l);
+}
 
-  return result;
+//
+ASDCP::Result_t
+ASDCP::MXF::Preface::WriteToBuffer(ASDCP::FrameBuffer& Buffer)
+{
+  return InterchangeObject::WriteToBuffer(Buffer);
 }
 
 //
@@ -491,136 +666,108 @@ ASDCP::MXF::Preface::Dump(FILE* stream)
   if ( stream == 0 )
     stream = stderr;
 
-  KLVPacket::Dump(stream, false);
-  fprintf(stream, "  InstanceUID        = %s\n",  InstanceUID.ToString(identbuf));
-  fprintf(stream, "  GenerationUID      = %s\n",  GenerationUID.ToString(identbuf));
-  fprintf(stream, "  LastModifiedDate   = %s\n",  LastModifiedDate.ToString(identbuf));
-  fprintf(stream, "  Version            = %hu\n", Version);
-  fprintf(stream, "  ObjectModelVersion = %lu\n", ObjectModelVersion);
-  fprintf(stream, "  PrimaryPackage     = %s\n",  PrimaryPackage.ToString(identbuf));
-  fprintf(stream, "  Identifications:\n");  Identifications.Dump(stream);
-  fprintf(stream, "  ContentStorage     = %s\n",  ContentStorage.ToString(identbuf));
-  fprintf(stream, "  OperationalPattern = %s\n",  OperationalPattern.ToString(identbuf));
-  fprintf(stream, "  EssenceContainers:\n");  EssenceContainers.Dump(stream);
-  fprintf(stream, "  DMSchemes:\n");  DMSchemes.Dump(stream);
-
-  fputs("==========================================================================\n", stream);
+  InterchangeObject::Dump(stream);
+  fprintf(stream, "  %22s = %s\n",  "LastModifiedDate", LastModifiedDate.EncodeString(identbuf, IdentBufferLen));
+  fprintf(stream, "  %22s = %hu\n", "Version", Version);
+  fprintf(stream, "  %22s = %u\n",  "ObjectModelVersion", ObjectModelVersion);
+  fprintf(stream, "  %22s = %s\n",  "PrimaryPackage", PrimaryPackage.EncodeHex(identbuf, IdentBufferLen));
+  fprintf(stream, "  %22s:\n", "Identifications");  Identifications.Dump(stream);
+  fprintf(stream, "  %22s = %s\n",  "ContentStorage", ContentStorage.EncodeHex(identbuf, IdentBufferLen));
+  fprintf(stream, "  %22s = %s\n",  "OperationalPattern", OperationalPattern.EncodeString(identbuf, IdentBufferLen));
+  fprintf(stream, "  %22s:\n", "EssenceContainers");  EssenceContainers.Dump(stream);
+  fprintf(stream, "  %22s:\n", "DMSchemes");  DMSchemes.Dump(stream);
 }
 
 //------------------------------------------------------------------------------------------
 //
 
-//
-class ASDCP::MXF::h__PacketList
-{
-public:
-  std::list<InterchangeObject*> m_List;
-  std::map<UL, InterchangeObject*> m_Map;
-
-  ~h__PacketList() {
-    while ( ! m_List.empty() )
-      {
-       delete m_List.back();
-       m_List.pop_back();
-      }
-  }
-
-  //
-  void AddPacket(InterchangeObject* ThePacket)
-  {
-    assert(ThePacket);
-    m_Map.insert(std::map<UID, InterchangeObject*>::value_type(ThePacket->InstanceUID, ThePacket));
-    m_List.push_back(ThePacket);
-  }
-
-  //
-  Result_t GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object)
-  {
-    ASDCP_TEST_NULL(ObjectID);
-    ASDCP_TEST_NULL(Object);
-    std::list<InterchangeObject*>::iterator li;
-    *Object = 0;
-
-    for ( li = m_List.begin(); li != m_List.end(); li++ )
-      {
-       if ( (*li)->HasUL(ObjectID) )
-         {
-           *Object = *li;
-           return RESULT_OK;
-         }
-      }
-
-    return RESULT_FAIL;
-  }
-};
+ASDCP::MXF::OP1aHeader::OP1aHeader(const Dictionary*& d) : Partition(d), m_Dict(d), m_Primer(d), m_Preface(0) {}
+ASDCP::MXF::OP1aHeader::~OP1aHeader() {}
 
-//------------------------------------------------------------------------------------------
 //
-
-ASDCP::MXF::OPAtomHeader::OPAtomHeader() : m_Preface(0), m_HasRIP(false)
+ASDCP::Result_t
+ASDCP::MXF::OP1aHeader::InitFromFile(const Kumu::FileReader& Reader)
 {
-  m_PacketList = new h__PacketList;
-}
+  Result_t result = result = Partition::InitFromFile(Reader);
 
+  if ( ASDCP_FAILURE(result) )
+    return result;
 
-ASDCP::MXF::OPAtomHeader::~OPAtomHeader()
-{
-}
+  if ( m_Dict == &DefaultCompositeDict() )
+    {
+      // select more explicit dictionary if one is available
+      if ( OperationalPattern.ExactMatch(MXFInterop_OPAtom_Entry().ul) )
+       {
+         m_Dict = &DefaultInteropDict();
+       }
+      else if ( OperationalPattern.ExactMatch(SMPTE_390_OPAtom_Entry().ul) )
+       {
+         m_Dict = &DefaultSMPTEDict();
+       }
+    }
 
+  // slurp up the remainder of the header
+  if ( HeaderByteCount < 1024 )
+    DefaultLogSink().Warn("Improbably small HeaderByteCount value: %u\n", HeaderByteCount);
 
-ASDCP::Result_t
-ASDCP::MXF::OPAtomHeader::InitFromFile(const ASDCP::FileReader& Reader)
-{
-  m_HasRIP = false;
-  Result_t result = SeekToRIP(Reader);
+  assert (HeaderByteCount <= 0xFFFFFFFFL);
+  result = m_HeaderData.Capacity((ui32_t)HeaderByteCount);
 
   if ( ASDCP_SUCCESS(result) )
     {
-      result = m_RIP.InitFromFile(Reader);
+      ui32_t read_count;
+      result = Reader.Read(m_HeaderData.Data(), m_HeaderData.Capacity(), &read_count);
 
       if ( ASDCP_FAILURE(result) )
+        {
+         DefaultLogSink().Error("OP1aHeader::InitFromFile, Read failed\n");
+         return result;
+        }
+
+      if ( read_count != m_HeaderData.Capacity() )
        {
-         DefaultLogSink().Error("File contains no RIP\n");
-         result = RESULT_OK;
-       }
-      else
-       {
-         m_HasRIP = true;
+         DefaultLogSink().Error("Short read of OP-Atom header metadata; wanted %u, got %u\n",
+                                m_HeaderData.Capacity(), read_count);
+         return RESULT_KLV_CODING;
        }
     }
 
   if ( ASDCP_SUCCESS(result) )
-    result = Reader.Seek(0);
+    result = InitFromBuffer(m_HeaderData.RoData(), m_HeaderData.Capacity());
 
-  if ( ASDCP_SUCCESS(result) )
-    result = Partition::InitFromFile(Reader); // test UL and OP
+  return result;
+}
 
-  // slurp up the remainder of the header
-  ui32_t read_count;
+//
+ASDCP::Result_t
+ASDCP::MXF::OP1aHeader::InitFromPartitionBuffer(const byte_t* p, ui32_t l)
+{
+  Result_t result = KLVPacket::InitFromBuffer(p, l);
 
   if ( ASDCP_SUCCESS(result) )
-    {
-      ui32_t buf_len = HeaderByteCount;
-      result = m_Buffer.Capacity(buf_len);
-    }
+    result = Partition::InitFromBuffer(m_ValueStart, m_ValueLength); // test UL and OP
 
   if ( ASDCP_SUCCESS(result) )
-    result = Reader.Read(m_Buffer.Data(), m_Buffer.Capacity(), &read_count);
-
-  if ( ASDCP_SUCCESS(result) && read_count != m_Buffer.Capacity() )
     {
-      DefaultLogSink().Error("Short read of OP-Atom header metadata; wanted %lu, got %lu\n",
-                            m_Buffer.Capacity(), read_count);
-      return RESULT_FAIL;
+      ui32_t pp_len = KLVPacket::PacketLength();
+      result = InitFromBuffer(p + pp_len, l - pp_len);
     }
 
-  const byte_t* p = m_Buffer.RoData();
-  const byte_t* end_p = p + m_Buffer.Capacity();
+  return result;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::OP1aHeader::InitFromBuffer(const byte_t* p, ui32_t l)
+{
+  assert(m_Dict);
+  Result_t result = RESULT_OK;
+  const byte_t* end_p = p + l;
 
   while ( ASDCP_SUCCESS(result) && p < end_p )
     {
       // parse the packets and index them by uid, discard KLVFill items
-      InterchangeObject* object = CreateObject(p);
+      InterchangeObject* object = CreateObject(m_Dict, p);
       assert(object);
 
       object->m_Lookup = &m_Primer;
@@ -631,22 +778,26 @@ ASDCP::MXF::OPAtomHeader::InitFromFile(const ASDCP::FileReader& Reader)
 
       if ( ASDCP_SUCCESS(result) )
        {
-         if ( object->IsA(s_MDD_Table[MDDindex_KLVFill].ul) )
+         if ( object->IsA(m_Dict->ul(MDD_KLVFill)) )
            {
              delete object;
+
+             if ( p > end_p )
+               {
+                 DefaultLogSink().Error("Fill item short read: %d.\n", p - end_p);
+               }
            }
-         else if ( object->IsA(s_MDD_Table[MDDindex_Primer].ul) )
+         else if ( object->IsA(m_Dict->ul(MDD_Primer)) ) // TODO: only one primer should be found
            {
              delete object;
              result = m_Primer.InitFromBuffer(redo_p, end_p - redo_p);
            }
-         else if ( object->IsA(s_MDD_Table[MDDindex_Preface].ul) )
+         else
            {
-             m_Preface = object;
-           }
-         else  
-           {
-             m_PacketList->AddPacket(object);
+             m_PacketList->AddPacket(object); // takes ownership
+
+             if ( object->IsA(m_Dict->ul(MDD_Preface)) && m_Preface == 0 )
+               m_Preface = (Preface*)object;
            }
        }
       else
@@ -659,9 +810,15 @@ ASDCP::MXF::OPAtomHeader::InitFromFile(const ASDCP::FileReader& Reader)
   return result;
 }
 
+ASDCP::Result_t
+ASDCP::MXF::OP1aHeader::GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object)
+{
+  return m_PacketList->GetMDObjectByID(ObjectID, Object);
+}
+
 //
 ASDCP::Result_t
-ASDCP::MXF::OPAtomHeader::GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object)
+ASDCP::MXF::OP1aHeader::GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object)
 {
   InterchangeObject* TmpObject;
 
@@ -671,9 +828,16 @@ ASDCP::MXF::OPAtomHeader::GetMDObjectByType(const byte_t* ObjectID, InterchangeO
   return m_PacketList->GetMDObjectByType(ObjectID, Object);
 }
 
+//
+ASDCP::Result_t
+ASDCP::MXF::OP1aHeader::GetMDObjectsByType(const byte_t* ObjectID, std::list<InterchangeObject*>& ObjectList)
+{
+  return m_PacketList->GetMDObjectsByType(ObjectID, ObjectList);
+}
+
 //
 ASDCP::MXF::Identification*
-ASDCP::MXF::OPAtomHeader::GetIdentification()
+ASDCP::MXF::OP1aHeader::GetIdentification()
 {
   InterchangeObject* Object;
 
@@ -685,7 +849,7 @@ ASDCP::MXF::OPAtomHeader::GetIdentification()
 
 //
 ASDCP::MXF::SourcePackage*
-ASDCP::MXF::OPAtomHeader::GetSourcePackage()
+ASDCP::MXF::OP1aHeader::GetSourcePackage()
 {
   InterchangeObject* Object;
 
@@ -697,39 +861,45 @@ ASDCP::MXF::OPAtomHeader::GetSourcePackage()
 
 //
 ASDCP::Result_t
-ASDCP::MXF::OPAtomHeader::WriteToFile(ASDCP::FileWriter& Writer, ui32_t HeaderSize)
+ASDCP::MXF::OP1aHeader::WriteToFile(Kumu::FileWriter& Writer, ui32_t HeaderSize)
 {
+  assert(m_Dict);
+  if ( m_Preface == 0 )
+    return RESULT_STATE;
+
   if ( HeaderSize < 4096 ) 
     {
-      DefaultLogSink().Error("HeaderSize %lu is too small. Must be >= 4096\n");
+      DefaultLogSink().Error("HeaderSize %u is too small. Must be >= 4096\n", HeaderSize);
       return RESULT_FAIL;
     }
 
   ASDCP::FrameBuffer HeaderBuffer;
+  HeaderByteCount = HeaderSize - ArchiveSize();
+  assert (HeaderByteCount <= 0xFFFFFFFFL);
+  Result_t result = HeaderBuffer.Capacity((ui32_t) HeaderByteCount); 
+  m_Preface->m_Lookup = &m_Primer;
 
-  Result_t result = HeaderBuffer.Capacity(HeaderSize);
-  HeaderByteCount = HeaderSize;
-
-  if ( ASDCP_SUCCESS(result) )
-    {
-      assert(m_Preface);
-      m_Preface->m_Lookup = &m_Primer;
-      result = m_Preface->WriteToBuffer(HeaderBuffer);
-    }
-#if 0
   std::list<InterchangeObject*>::iterator pl_i = m_PacketList->m_List.begin();
   for ( ; pl_i != m_PacketList->m_List.end() && ASDCP_SUCCESS(result); pl_i++ )
     {
       InterchangeObject* object = *pl_i;
       object->m_Lookup = &m_Primer;
-      result = object->WriteToBuffer(HeaderBuffer);
+
+      ASDCP::FrameBuffer WriteWrapper;
+      WriteWrapper.SetData(HeaderBuffer.Data() + HeaderBuffer.Size(),
+                          HeaderBuffer.Capacity() - HeaderBuffer.Size());
+      result = object->WriteToBuffer(WriteWrapper);
+      HeaderBuffer.Size(HeaderBuffer.Size() + WriteWrapper.Size());
     }
-#endif
+
   if ( ASDCP_SUCCESS(result) )
-    result = Partition::WriteToFile(Writer);
+    {
+      UL TmpUL(m_Dict->ul(MDD_ClosedCompleteHeader));
+      result = Partition::WriteToFile(Writer, TmpUL);
+    }
 
-  //  if ( ASDCP_SUCCESS(result) )
-    //    result = m_Primer.WriteToFile(Writer);
+  if ( ASDCP_SUCCESS(result) )
+    result = m_Primer.WriteToFile(Writer);
 
   if ( ASDCP_SUCCESS(result) )
     {
@@ -741,12 +911,12 @@ ASDCP::MXF::OPAtomHeader::WriteToFile(ASDCP::FileWriter& Writer, ui32_t HeaderSi
   // KLV Fill
   if ( ASDCP_SUCCESS(result) )
     {
-      ASDCP::fpos_t pos = Writer.Tell();
+      Kumu::fpos_t pos = Writer.Tell();
 
-      if ( pos > HeaderSize )
+      if ( pos > (Kumu::fpos_t)HeaderByteCount )
        {
          char intbuf[IntBufferLen];
-         DefaultLogSink().Error("Header size %s exceeds specified value %lu\n",
+         DefaultLogSink().Error("Header size %s exceeds specified value %u\n",
                                 ui64sz(pos, intbuf),
                                 HeaderSize);
          return RESULT_FAIL;
@@ -762,7 +932,7 @@ ASDCP::MXF::OPAtomHeader::WriteToFile(ASDCP::FileWriter& Writer, ui32_t HeaderSi
        }
 
       klv_fill_length -= kl_length;
-      result = WriteKLToFile(Writer, s_MDD_Table[MDDindex_KLVFill].ul, klv_fill_length);
+      result = WriteKLToFile(Writer, m_Dict->ul(MDD_KLVFill), klv_fill_length);
 
       if ( ASDCP_SUCCESS(result) )
        result = NilBuf.Capacity(klv_fill_length);
@@ -781,18 +951,16 @@ ASDCP::MXF::OPAtomHeader::WriteToFile(ASDCP::FileWriter& Writer, ui32_t HeaderSi
 
 //
 void
-ASDCP::MXF::OPAtomHeader::Dump(FILE* stream)
+ASDCP::MXF::OP1aHeader::Dump(FILE* stream)
 {
   if ( stream == 0 )
     stream = stderr;
 
-  if ( m_HasRIP )
-    m_RIP.Dump(stream);
-
   Partition::Dump(stream);
   m_Primer.Dump(stream);
-  assert(m_Preface);
-  m_Preface->Dump(stream);
+
+  if ( m_Preface == 0 )
+    fputs("No Preface loaded\n", stream);
 
   std::list<InterchangeObject*>::iterator i = m_PacketList->m_List.begin();
   for ( ; i != m_PacketList->m_List.end(); i++ )
@@ -802,45 +970,87 @@ ASDCP::MXF::OPAtomHeader::Dump(FILE* stream)
 //------------------------------------------------------------------------------------------
 //
 
-ASDCP::MXF::OPAtomIndexFooter::OPAtomIndexFooter() : m_Lookup(0)
-{
-  m_PacketList = new h__PacketList;
-}
-
-
-ASDCP::MXF::OPAtomIndexFooter::~OPAtomIndexFooter()
+ASDCP::MXF::OPAtomIndexFooter::OPAtomIndexFooter(const Dictionary*& d) :
+  Partition(d), m_Dict(d),
+  m_CurrentSegment(0), m_BytesPerEditUnit(0), m_BodySID(0),
+  m_ECOffset(0), m_Lookup(0)
 {
+  BodySID = 0;
+  IndexSID = 129;
 }
 
+ASDCP::MXF::OPAtomIndexFooter::~OPAtomIndexFooter() {}
 
+//
 ASDCP::Result_t
-ASDCP::MXF::OPAtomIndexFooter::InitFromFile(const ASDCP::FileReader& Reader)
+ASDCP::MXF::OPAtomIndexFooter::InitFromFile(const Kumu::FileReader& Reader)
 {
   Result_t result = Partition::InitFromFile(Reader); // test UL and OP
 
   // slurp up the remainder of the footer
-  ui32_t read_count;
+  ui32_t read_count = 0;
 
-  if ( ASDCP_SUCCESS(result) )
-    result = m_Buffer.Capacity(IndexByteCount);
+  if ( ASDCP_SUCCESS(result) && IndexByteCount > 0 )
+    {
+      assert (IndexByteCount <= 0xFFFFFFFFL);
+      // At this point, m_FooterData may not have been initialized
+      // so it's capacity is zero and data pointer is NULL
+      // However, if IndexByteCount is zero then the capacity
+      // doesn't change and the data pointer is not set.
+      result = m_FooterData.Capacity((ui32_t) IndexByteCount);
+
+      if ( ASDCP_SUCCESS(result) )
+       result = Reader.Read(m_FooterData.Data(), m_FooterData.Capacity(), &read_count);
+
+      if ( ASDCP_SUCCESS(result) && read_count != m_FooterData.Capacity() )
+       {
+         DefaultLogSink().Error("Short read of footer partition: got %u, expecting %u\n",
+                                read_count, m_FooterData.Capacity());
+         return RESULT_FAIL;
+       }
+      else if( ASDCP_SUCCESS(result) && !m_FooterData.Data() )
+       {
+         DefaultLogSink().Error( "Buffer for footer partition not created: IndexByteCount = %u\n",
+                                 IndexByteCount );
+         return RESULT_FAIL;
+       }
+
+      if ( ASDCP_SUCCESS(result) )
+       result = InitFromBuffer(m_FooterData.RoData(), m_FooterData.Capacity());
+    }
+
+  return result;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::OPAtomIndexFooter::InitFromPartitionBuffer(const byte_t* p, ui32_t l)
+{
+  Result_t result = KLVPacket::InitFromBuffer(p, l);
 
   if ( ASDCP_SUCCESS(result) )
-    result = Reader.Read(m_Buffer.Data(), m_Buffer.Capacity(), &read_count);
+    result = Partition::InitFromBuffer(m_ValueStart, m_ValueLength); // test UL and OP
 
-  if ( ASDCP_SUCCESS(result) && read_count != m_Buffer.Capacity() )
+  if ( ASDCP_SUCCESS(result) )
     {
-      DefaultLogSink().Error("Short read of footer partition: got %lu, expecting %lu\n",
-                            read_count, m_Buffer.Capacity());
-      return RESULT_FAIL;
+      ui32_t pp_len = KLVPacket::PacketLength();
+      result = InitFromBuffer(p + pp_len, l - pp_len);
     }
 
-  const byte_t* p = m_Buffer.RoData();
-  const byte_t* end_p = p + m_Buffer.Capacity();
+  return result;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::OPAtomIndexFooter::InitFromBuffer(const byte_t* p, ui32_t l)
+{
+  Result_t result = RESULT_OK;
+  const byte_t* end_p = p + l;
   
   while ( ASDCP_SUCCESS(result) && p < end_p )
     {
       // parse the packets and index them by uid, discard KLVFill items
-      InterchangeObject* object = CreateObject(p);
+      InterchangeObject* object = CreateObject(m_Dict, p);
       assert(object);
 
       object->m_Lookup = m_Lookup;
@@ -849,7 +1059,7 @@ ASDCP::MXF::OPAtomIndexFooter::InitFromFile(const ASDCP::FileReader& Reader)
 
       if ( ASDCP_SUCCESS(result) )
        {
-         m_PacketList->AddPacket(object);
+         m_PacketList->AddPacket(object); // takes ownership
        }
       else
        {
@@ -866,9 +1076,61 @@ ASDCP::MXF::OPAtomIndexFooter::InitFromFile(const ASDCP::FileReader& Reader)
 
 //
 ASDCP::Result_t
-ASDCP::MXF::OPAtomIndexFooter::WriteToFile(ASDCP::FileWriter& Writer)
+ASDCP::MXF::OPAtomIndexFooter::WriteToFile(Kumu::FileWriter& Writer, ui64_t duration)
 {
-  Result_t result = WriteKLToFile(Writer, s_MDD_Table[MDDindex_CompleteFooter].ul, 0);
+  assert(m_Dict);
+  ASDCP::FrameBuffer FooterBuffer;
+  ui32_t   footer_size = m_PacketList->m_List.size() * MaxIndexSegmentSize; // segment-count * max-segment-size
+  Result_t result = FooterBuffer.Capacity(footer_size); 
+  ui32_t   iseg_count = 0;
+
+  if ( m_CurrentSegment != 0 )
+    {
+      m_CurrentSegment->IndexDuration = m_CurrentSegment->IndexEntryArray.size();
+      m_CurrentSegment = 0;
+    }
+
+  std::list<InterchangeObject*>::iterator pl_i = m_PacketList->m_List.begin();
+  for ( ; pl_i != m_PacketList->m_List.end() && ASDCP_SUCCESS(result); pl_i++ )
+    {
+      if ( (*pl_i)->IsA(OBJ_TYPE_ARGS(IndexTableSegment)) )
+       {
+         iseg_count++;
+         IndexTableSegment* Segment = (IndexTableSegment*)(*pl_i);
+
+         if ( m_BytesPerEditUnit != 0 )
+           {
+             if ( iseg_count != 1 )
+               return RESULT_STATE;
+
+             Segment->IndexDuration = duration;
+           }
+       }
+
+      InterchangeObject* object = *pl_i;
+      object->m_Lookup = m_Lookup;
+
+      ASDCP::FrameBuffer WriteWrapper;
+      WriteWrapper.SetData(FooterBuffer.Data() + FooterBuffer.Size(),
+                          FooterBuffer.Capacity() - FooterBuffer.Size());
+      result = object->WriteToBuffer(WriteWrapper);
+      FooterBuffer.Size(FooterBuffer.Size() + WriteWrapper.Size());
+    }
+
+  if ( ASDCP_SUCCESS(result) )
+    {
+      IndexByteCount = FooterBuffer.Size();
+      UL FooterUL(m_Dict->ul(MDD_CompleteFooter));
+      result = Partition::WriteToFile(Writer, FooterUL);
+    }
+
+  if ( ASDCP_SUCCESS(result) )
+    {
+      ui32_t write_count = 0;
+      result = Writer.Write(FooterBuffer.RoData(), FooterBuffer.Size(), &write_count);
+      assert(write_count == FooterBuffer.Size());
+    }
+
   return result;
 }
 
@@ -886,9 +1148,34 @@ ASDCP::MXF::OPAtomIndexFooter::Dump(FILE* stream)
     (*i)->Dump(stream);
 }
 
+ASDCP::Result_t
+ASDCP::MXF::OPAtomIndexFooter::GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object)
+{
+  return m_PacketList->GetMDObjectByID(ObjectID, Object);
+}
+
 //
 ASDCP::Result_t
-ASDCP::MXF::OPAtomIndexFooter::Lookup(ui32_t frame_num, IndexTableSegment::IndexEntry& Entry)
+ASDCP::MXF::OPAtomIndexFooter::GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object)
+{
+  InterchangeObject* TmpObject;
+
+  if ( Object == 0 )
+    Object = &TmpObject;
+
+  return m_PacketList->GetMDObjectByType(ObjectID, Object);
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::OPAtomIndexFooter::GetMDObjectsByType(const byte_t* ObjectID, std::list<InterchangeObject*>& ObjectList)
+{
+  return m_PacketList->GetMDObjectsByType(ObjectID, ObjectList);
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::OPAtomIndexFooter::Lookup(ui32_t frame_num, IndexTableSegment::IndexEntry& Entry) const
 {
   std::list<InterchangeObject*>::iterator li;
   for ( li = m_PacketList->m_List.begin(); li != m_PacketList->m_List.end(); li++ )
@@ -912,7 +1199,9 @@ ASDCP::MXF::OPAtomIndexFooter::Lookup(ui32_t frame_num, IndexTableSegment::Index
          else if ( (ui64_t)frame_num >= start_pos
                    && (ui64_t)frame_num < (start_pos + Segment->IndexDuration) )
            {
-             Entry = Segment->IndexEntryArray[frame_num-start_pos];
+             ui64_t tmp = frame_num - start_pos;
+             assert(tmp <= 0xFFFFFFFFL);
+             Entry = Segment->IndexEntryArray[(ui32_t) tmp];
              return RESULT_OK;
            }
        }
@@ -921,36 +1210,142 @@ ASDCP::MXF::OPAtomIndexFooter::Lookup(ui32_t frame_num, IndexTableSegment::Index
   return RESULT_FAIL;
 }
 
+//
+void
+ASDCP::MXF::OPAtomIndexFooter::SetIndexParamsCBR(IPrimerLookup* lookup, ui32_t size, const Rational& Rate)
+{
+  assert(lookup);
+  m_Lookup = lookup;
+  m_BytesPerEditUnit = size;
+  m_EditRate = Rate;
+
+  IndexTableSegment* Index = new IndexTableSegment(m_Dict);
+  AddChildObject(Index);
+  Index->EditUnitByteCount = m_BytesPerEditUnit;
+  Index->IndexEditRate = Rate;
+}
+
+//
+void
+ASDCP::MXF::OPAtomIndexFooter::SetIndexParamsVBR(IPrimerLookup* lookup, const Rational& Rate, Kumu::fpos_t offset)
+{
+  assert(lookup);
+  m_Lookup = lookup;
+  m_BytesPerEditUnit = 0;
+  m_EditRate = Rate;
+  m_ECOffset = offset;
+}
+
+//
+void
+ASDCP::MXF::OPAtomIndexFooter::PushIndexEntry(const IndexTableSegment::IndexEntry& Entry)
+{
+  if ( m_BytesPerEditUnit != 0 )  // are we CBR? that's bad 
+    {
+      DefaultLogSink().Error("Call to PushIndexEntry() failed: index is CBR\n");
+      return;
+    }
+
+  // do we have an available segment?
+  if ( m_CurrentSegment == 0 )
+    { // no, set up a new segment
+      m_CurrentSegment = new IndexTableSegment(m_Dict);
+      assert(m_CurrentSegment);
+      AddChildObject(m_CurrentSegment);
+      m_CurrentSegment->DeltaEntryArray.push_back(IndexTableSegment::DeltaEntry());
+      m_CurrentSegment->IndexEditRate = m_EditRate;
+      m_CurrentSegment->IndexStartPosition = 0;
+    }
+  else if ( m_CurrentSegment->IndexEntryArray.size() >= CBRIndexEntriesPerSegment )
+    { // no, this one is full, start another
+      m_CurrentSegment->IndexDuration = m_CurrentSegment->IndexEntryArray.size();
+      ui64_t StartPosition = m_CurrentSegment->IndexStartPosition + m_CurrentSegment->IndexDuration;
+
+      m_CurrentSegment = new IndexTableSegment(m_Dict);
+      assert(m_CurrentSegment);
+      AddChildObject(m_CurrentSegment);
+      m_CurrentSegment->DeltaEntryArray.push_back(IndexTableSegment::DeltaEntry());
+      m_CurrentSegment->IndexEditRate = m_EditRate;
+      m_CurrentSegment->IndexStartPosition = StartPosition;
+    }
+
+  m_CurrentSegment->IndexEntryArray.push_back(Entry);
+}
 
 //------------------------------------------------------------------------------------------
 //
 
+//
+void
+ASDCP::MXF::InterchangeObject::Copy(const InterchangeObject& rhs)
+{
+  m_UL = rhs.m_UL;
+  InstanceUID = rhs.InstanceUID;
+  GenerationUID = rhs.GenerationUID;
+}
+
 //
 ASDCP::Result_t
 ASDCP::MXF::InterchangeObject::InitFromTLVSet(TLVReader& TLVSet)
 {
   Result_t result = TLVSet.ReadObject(OBJ_READ_ARGS(InterchangeObject, InstanceUID));
-  if ( ASDCP_SUCCESS(result) ) result = TLVSet.ReadObject(OBJ_READ_ARGS(GenerationInterchangeObject, GenerationUID));
+  if ( ASDCP_SUCCESS(result) )
+    result = TLVSet.ReadObject(OBJ_READ_ARGS(GenerationInterchangeObject, GenerationUID));
   return result;
 }
 
 //
 ASDCP::Result_t
-ASDCP::MXF::InterchangeObject::WriteToBuffer(ASDCP::FrameBuffer& Buffer)
+ASDCP::MXF::InterchangeObject::WriteToTLVSet(TLVWriter& TLVSet)
+{
+  Result_t result = TLVSet.WriteObject(OBJ_WRITE_ARGS(InterchangeObject, InstanceUID));
+  if ( ASDCP_SUCCESS(result) )
+    result = TLVSet.WriteObject(OBJ_WRITE_ARGS(GenerationInterchangeObject, GenerationUID));
+  return result;
+}
+
+//
+ASDCP::Result_t
+ASDCP::MXF::InterchangeObject::InitFromBuffer(const byte_t* p, ui32_t l)
 {
-  if ( Buffer.Capacity() < (Buffer.Size() + m_KLLength + m_ValueLength) )
+  ASDCP_TEST_NULL(p);
+  Result_t result = RESULT_FALSE;
+
+  if ( m_UL.HasValue() )
     {
-      DefaultLogSink().Error("InterchangeObject::WriteToBuffer: Buffer too small\n");
-      Dump();
-      return RESULT_READFAIL;
+      result = KLVPacket::InitFromBuffer(p, l, m_UL);
+
+      if ( ASDCP_SUCCESS(result) )
+       {
+         TLVReader MemRDR(m_ValueStart, m_ValueLength, m_Lookup);
+         result = InitFromTLVSet(MemRDR);
+       }
     }
+  else
+    {
+      result = KLVPacket::InitFromBuffer(p, l);
+    }
+  
+  return result;
+}
 
-  Result_t result = WriteKLToBuffer(Buffer, m_KeyStart, m_ValueLength);
+//
+ASDCP::Result_t
+ASDCP::MXF::InterchangeObject::WriteToBuffer(ASDCP::FrameBuffer& Buffer)
+{
+  if ( ! m_UL.HasValue() )
+    return RESULT_STATE;
+
+  TLVWriter MemWRT(Buffer.Data() + kl_length, Buffer.Capacity() - kl_length, m_Lookup);
+  Result_t result = WriteToTLVSet(MemWRT);
 
   if ( ASDCP_SUCCESS(result) )
     {
-      memcpy(Buffer.Data() + Buffer.Size(), m_ValueStart, m_ValueLength);
-      Buffer.Size(Buffer.Size() + m_ValueLength);
+      ui32_t packet_length = MemWRT.Length();
+      result = WriteKLToBuffer(Buffer, packet_length);
+
+      if ( ASDCP_SUCCESS(result) )
+       Buffer.Size(Buffer.Size() + packet_length);
     }
 
   return result;
@@ -963,9 +1358,9 @@ ASDCP::MXF::InterchangeObject::Dump(FILE* stream)
   char identbuf[IdentBufferLen];
 
   fputc('\n', stream);
-  KLVPacket::Dump(stream, false);
-  fprintf(stream, "             InstanceUID = %s\n",  InstanceUID.ToString(identbuf));
-  fprintf(stream, "           GenerationUID = %s\n",  GenerationUID.ToString(identbuf));
+  KLVPacket::Dump(stream, *m_Dict, false);
+  fprintf(stream, "             InstanceUID = %s\n",  InstanceUID.EncodeHex(identbuf, IdentBufferLen));
+  fprintf(stream, "           GenerationUID = %s\n",  GenerationUID.EncodeHex(identbuf, IdentBufferLen));
 }
 
 //
@@ -979,6 +1374,313 @@ ASDCP::MXF::InterchangeObject::IsA(const byte_t* label)
 }
 
 
+//------------------------------------------------------------------------------------------
+
+
+typedef std::map<ASDCP::UL, ASDCP::MXF::MXFObjectFactory_t>FactoryMap_t;
+typedef FactoryMap_t::iterator FLi_t;
+
+//
+class FactoryList : public FactoryMap_t
+{
+  Kumu::Mutex m_Lock;
+
+public:
+  FactoryList() {}
+  ~FactoryList() {}
+
+  bool Empty() {
+    Kumu::AutoMutex BlockLock(m_Lock);
+    return empty();
+  }
+
+  FLi_t Find(const byte_t* label) {
+    Kumu::AutoMutex BlockLock(m_Lock);
+    return find(label);
+  }
+
+  FLi_t End() {
+    Kumu::AutoMutex BlockLock(m_Lock);
+    return end();
+  }
+
+  void Insert(ASDCP::UL label, ASDCP::MXF::MXFObjectFactory_t factory) {
+    Kumu::AutoMutex BlockLock(m_Lock);
+    insert(FactoryList::value_type(label, factory));
+  }
+};
+
+//
+static FactoryList s_FactoryList;
+static Kumu::Mutex s_InitLock;
+static bool        s_TypesInit = false;
+
+
+//
+void
+ASDCP::MXF::SetObjectFactory(ASDCP::UL label, ASDCP::MXF::MXFObjectFactory_t factory)
+{
+  s_FactoryList.Insert(label, factory);
+}
+
+//
+ASDCP::MXF::InterchangeObject*
+ASDCP::MXF::CreateObject(const Dictionary*& Dict, const UL& label)
+{
+  if ( ! s_TypesInit )
+    {
+      Kumu::AutoMutex BlockLock(s_InitLock);
+
+      if ( ! s_TypesInit )
+       {
+         MXF::Metadata_InitTypes(Dict);
+         s_TypesInit = true;
+       }
+    }
+
+  FLi_t i = s_FactoryList.find(label.Value());
+
+  if ( i == s_FactoryList.end() )
+    return new InterchangeObject(Dict);
+
+  return i->second(Dict);
+}
+
+
+//------------------------------------------------------------------------------------------
+
+//
+bool
+ASDCP::MXF::decode_mca_string(const std::string& s, const mca_label_map_t& labels, const Dictionary& dict, const std::string& language,
+                             InterchangeObject_list_t& descriptor_list, ui32_t& channel_count)
+{
+  const Dictionary *dictp = &dict;
+  std::string symbol_buf;
+  channel_count = 0;
+  ASDCP::MXF::SoundfieldGroupLabelSubDescriptor *current_soundfield = 0;
+  std::string::const_iterator i;
+
+  for ( i = s.begin(); i != s.end(); ++i )
+    {
+      if ( *i == '(' )
+       {
+         if ( current_soundfield != 0 )
+           {
+             fprintf(stderr, "Encountered '(', already processing a soundfield group.\n");
+             return false;
+           }
+
+         if ( symbol_buf.empty() )
+           {
+             fprintf(stderr, "Encountered '(', without leading soundfield group symbol.\n");
+             return false;
+           }
+
+         mca_label_map_t::const_iterator i = labels.find(symbol_buf);
+      
+         if ( i == labels.end() )
+           {
+             fprintf(stderr, "Unknown symbol: '%s'\n", symbol_buf.c_str());
+             return false;
+           }
+      
+         if ( i->second.Value()[10] != 2 ) // magic depends on UL "Essence Facet" byte (see ST 428-12)
+           {
+             fprintf(stderr, "Not a soundfield group symbol: '%s'\n", symbol_buf.c_str());
+             return false;
+           }
+
+         current_soundfield = new ASDCP::MXF::SoundfieldGroupLabelSubDescriptor(dictp);
+
+         GenRandomValue(current_soundfield->InstanceUID);
+         GenRandomValue(current_soundfield->MCALinkID);
+         current_soundfield->MCATagSymbol = "sg" + i->first;
+         current_soundfield->MCATagName = i->first;
+         current_soundfield->RFC5646SpokenLanguage = language;
+         current_soundfield->MCALabelDictionaryID = i->second;
+         descriptor_list.push_back(reinterpret_cast<ASDCP::MXF::InterchangeObject*>(current_soundfield));
+         symbol_buf.clear();
+       }
+      else if ( *i == ')' )
+       {
+         if ( current_soundfield == 0 )
+           {
+             fprintf(stderr, "Encountered ')', not currently processing a soundfield group.\n");
+             return false;
+           }
+
+         if ( symbol_buf.empty() )
+           {
+             fprintf(stderr, "Soundfield group description contains no channels.\n");
+             return false;
+           }
+
+         mca_label_map_t::const_iterator i = labels.find(symbol_buf);
+      
+         if ( i == labels.end() )
+           {
+             fprintf(stderr, "Unknown symbol: '%s'\n", symbol_buf.c_str());
+             return false;
+           }
+
+         ASDCP::MXF::AudioChannelLabelSubDescriptor *channel_descr =
+           new ASDCP::MXF::AudioChannelLabelSubDescriptor(dictp);
+
+         GenRandomValue(channel_descr->InstanceUID);
+         assert(current_soundfield);
+         channel_descr->MCALinkID = current_soundfield->MCALinkID;
+         channel_descr->MCAChannelID = channel_count++;
+         channel_descr->MCATagSymbol = "ch" + i->first;
+         channel_descr->MCATagName = i->first;
+         channel_descr->RFC5646SpokenLanguage = language;
+         channel_descr->MCALabelDictionaryID = i->second;
+         descriptor_list.push_back(reinterpret_cast<ASDCP::MXF::InterchangeObject*>(channel_descr));
+         symbol_buf.clear();
+         current_soundfield = 0;
+       }
+      else if ( *i == ',' )
+       {
+         if ( ! symbol_buf.empty() )
+           {
+             mca_label_map_t::const_iterator i = labels.find(symbol_buf);
+
+             if ( i == labels.end() )
+               {
+                 fprintf(stderr, "Unknown symbol: '%s'\n", symbol_buf.c_str());
+                 return false;
+               }
+
+             if ( i->second.Value()[10] != 1 ) // magic depends on UL "Essence Facet" byte (see ST 428-12)
+               {
+                 fprintf(stderr, "Not a channel symbol: '%s'\n", symbol_buf.c_str());
+                 return false;
+               }
+
+             ASDCP::MXF::AudioChannelLabelSubDescriptor *channel_descr =
+               new ASDCP::MXF::AudioChannelLabelSubDescriptor(dictp);
+
+             GenRandomValue(channel_descr->InstanceUID);
+
+             if ( current_soundfield != 0 )
+               {
+                 channel_descr->MCALinkID = current_soundfield->MCALinkID;
+               }
+
+             channel_descr->MCAChannelID = channel_count++;
+             channel_descr->MCATagSymbol = "ch" + i->first;
+             channel_descr->MCATagName = i->first;
+             channel_descr->RFC5646SpokenLanguage = language;
+             channel_descr->MCALabelDictionaryID = i->second;
+             descriptor_list.push_back(reinterpret_cast<ASDCP::MXF::InterchangeObject*>(channel_descr));
+             symbol_buf.clear();
+           }
+       }
+      else if ( isalnum(*i) )
+       {
+         symbol_buf += *i;
+       }
+      else if ( ! isspace(*i) )
+       {
+         fprintf(stderr, "Unexpected character '%c'.\n", *i);
+         return false;
+       }
+    }
+
+  if ( ! symbol_buf.empty() )
+    {
+      mca_label_map_t::const_iterator i = labels.find(symbol_buf);
+      
+      if ( i == labels.end() )
+       {
+         fprintf(stderr, "Unknown symbol: '%s'\n", symbol_buf.c_str());
+         return false;
+       }
+
+      ASDCP::MXF::AudioChannelLabelSubDescriptor *channel_descr =
+       new ASDCP::MXF::AudioChannelLabelSubDescriptor(dictp);
+
+      GenRandomValue(channel_descr->InstanceUID);
+
+      if ( current_soundfield != 0 )
+       {
+         channel_descr->MCALinkID = current_soundfield->MCALinkID;
+       }
+
+      channel_descr->MCAChannelID = channel_count++;
+      channel_descr->MCATagSymbol = "ch" + i->first;
+      channel_descr->MCATagName = i->first;
+      channel_descr->RFC5646SpokenLanguage = language;
+      channel_descr->MCALabelDictionaryID = i->second;
+      descriptor_list.push_back(reinterpret_cast<ASDCP::MXF::InterchangeObject*>(channel_descr));
+    }
+
+  return true;
+}
+
+
+ASDCP::MXF::ASDCP_MCAConfigParser::ASDCP_MCAConfigParser(const Dictionary*& d) : m_Dict(d), m_ChannelCount(0)
+{
+  m_LabelMap.insert(mca_label_map_t::value_type("L", m_Dict->ul(MDD_DCAudioChannel_L)));
+  m_LabelMap.insert(mca_label_map_t::value_type("R", m_Dict->ul(MDD_DCAudioChannel_R)));
+  m_LabelMap.insert(mca_label_map_t::value_type("C", m_Dict->ul(MDD_DCAudioChannel_C)));
+  m_LabelMap.insert(mca_label_map_t::value_type("LFE", m_Dict->ul(MDD_DCAudioChannel_LFE)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Ls", m_Dict->ul(MDD_DCAudioChannel_Ls)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rs", m_Dict->ul(MDD_DCAudioChannel_Rs)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Lss", m_Dict->ul(MDD_DCAudioChannel_Lss)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rss", m_Dict->ul(MDD_DCAudioChannel_Rss)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Lrs", m_Dict->ul(MDD_DCAudioChannel_Lrs)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rrs", m_Dict->ul(MDD_DCAudioChannel_Rrs)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Lc", m_Dict->ul(MDD_DCAudioChannel_Lc)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rc", m_Dict->ul(MDD_DCAudioChannel_Rc)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Cs", m_Dict->ul(MDD_DCAudioChannel_Cs)));
+  m_LabelMap.insert(mca_label_map_t::value_type("HI", m_Dict->ul(MDD_DCAudioChannel_HI)));
+  m_LabelMap.insert(mca_label_map_t::value_type("VIN", m_Dict->ul(MDD_DCAudioChannel_VIN)));
+  m_LabelMap.insert(mca_label_map_t::value_type("51", m_Dict->ul(MDD_DCAudioSoundfield_51)));
+  m_LabelMap.insert(mca_label_map_t::value_type("71", m_Dict->ul(MDD_DCAudioSoundfield_71)));
+  m_LabelMap.insert(mca_label_map_t::value_type("SDS", m_Dict->ul(MDD_DCAudioSoundfield_SDS)));
+  m_LabelMap.insert(mca_label_map_t::value_type("61", m_Dict->ul(MDD_DCAudioSoundfield_61)));
+  m_LabelMap.insert(mca_label_map_t::value_type("M", m_Dict->ul(MDD_DCAudioSoundfield_M)));
+}
+
+//
+ui32_t
+ASDCP::MXF::ASDCP_MCAConfigParser::ChannelCount() const
+{
+  return m_ChannelCount;
+}
+
+// 51(L,R,C,LFE,Ls,Rs),HI,VIN
+bool
+ASDCP::MXF::ASDCP_MCAConfigParser::DecodeString(const std::string& s, const std::string& language)
+{
+  return decode_mca_string(s, m_LabelMap, *m_Dict, language, *this, m_ChannelCount);
+}
+
+
+
+ASDCP::MXF::AS02_MCAConfigParser::AS02_MCAConfigParser(const Dictionary*& d) : ASDCP::MXF::ASDCP_MCAConfigParser(d)
+{
+  m_LabelMap.insert(mca_label_map_t::value_type("M1", m_Dict->ul(MDD_IMFAudioChannel_M1)));
+  m_LabelMap.insert(mca_label_map_t::value_type("M2", m_Dict->ul(MDD_IMFAudioChannel_M2)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Lt", m_Dict->ul(MDD_IMFAudioChannel_Lt)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rt", m_Dict->ul(MDD_IMFAudioChannel_Rt)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Lst", m_Dict->ul(MDD_IMFAudioChannel_Lst)));
+  m_LabelMap.insert(mca_label_map_t::value_type("Rst", m_Dict->ul(MDD_IMFAudioChannel_Rst)));
+  m_LabelMap.insert(mca_label_map_t::value_type("S", m_Dict->ul(MDD_IMFAudioChannel_S)));
+  m_LabelMap.insert(mca_label_map_t::value_type("ST", m_Dict->ul(MDD_IMFAudioSoundfield_ST)));
+  m_LabelMap.insert(mca_label_map_t::value_type("DM", m_Dict->ul(MDD_IMFAudioSoundfield_DM)));
+  m_LabelMap.insert(mca_label_map_t::value_type("DNS", m_Dict->ul(MDD_IMFAudioSoundfield_DNS)));
+  m_LabelMap.insert(mca_label_map_t::value_type("30", m_Dict->ul(MDD_IMFAudioSoundfield_30)));
+  m_LabelMap.insert(mca_label_map_t::value_type("40", m_Dict->ul(MDD_IMFAudioSoundfield_40)));
+  m_LabelMap.insert(mca_label_map_t::value_type("50", m_Dict->ul(MDD_IMFAudioSoundfield_50)));
+  m_LabelMap.insert(mca_label_map_t::value_type("60", m_Dict->ul(MDD_IMFAudioSoundfield_60)));
+  m_LabelMap.insert(mca_label_map_t::value_type("70", m_Dict->ul(MDD_IMFAudioSoundfield_70)));
+  m_LabelMap.insert(mca_label_map_t::value_type("LtRt", m_Dict->ul(MDD_IMFAudioSoundfield_LtRt)));
+  m_LabelMap.insert(mca_label_map_t::value_type("51Ex", m_Dict->ul(MDD_IMFAudioSoundfield_51Ex)));
+  m_LabelMap.insert(mca_label_map_t::value_type("HI", m_Dict->ul(MDD_IMFAudioSoundfield_HI)));
+  m_LabelMap.insert(mca_label_map_t::value_type("VIN", m_Dict->ul(MDD_IMFAudioSoundfield_VIN)));
+}
+
 //
 // end MXF.cpp
 //