ReadFileIntoString() modified to return OK when the file is empty
[asdcplib.git] / src / h__Reader.cpp
index e958e345d2249aacc5cf3e3edf456e0382686d1b..77f532e7fe20c1edd6d90a29d37b9ec9f1900c55 100755 (executable)
@@ -1,5 +1,5 @@
 /*
-Copyright (c) 2004-2006, John Hurst
+Copyright (c) 2004-2015, John Hurst
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -29,202 +29,247 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     \brief   MXF file reader base class
 */
 
+#define DEFAULT_MD_DECL
 #include "AS_DCP_internal.h"
 #include "KLV.h"
 
 using namespace ASDCP;
 using namespace ASDCP::MXF;
 
+static Kumu::Mutex sg_DefaultMDInitLock;
+static bool        sg_DefaultMDTypesInit = false;
+static const ASDCP::Dictionary *sg_dict = 0;
+
 //
-ASDCP::h__Reader::h__Reader() : m_EssenceStart(0)
+void
+ASDCP::default_md_object_init()
 {
-}
+  if ( ! sg_DefaultMDTypesInit )
+    {
+      Kumu::AutoMutex BlockLock(sg_DefaultMDInitLock);
 
-ASDCP::h__Reader::~h__Reader()
-{
-  Close();
+      if ( ! sg_DefaultMDTypesInit )
+       {
+         sg_dict = &DefaultSMPTEDict();
+         g_OP1aHeader = new ASDCP::MXF::OP1aHeader(sg_dict);
+         g_OPAtomIndexFooter = new ASDCP::MXF::OPAtomIndexFooter(sg_dict);
+         g_RIP = new ASDCP::MXF::RIP(sg_dict);
+         sg_DefaultMDTypesInit = true;
+       }
+    }
 }
 
-void
-ASDCP::h__Reader::Close()
-{
-  m_File.Close();
-}
 
 //------------------------------------------------------------------------------------------
 //
 
 //
+ASDCP::h__ASDCPReader::h__ASDCPReader(const Dictionary& d) : MXF::TrackFileReader<OP1aHeader, OPAtomIndexFooter>(d), m_BodyPart(m_Dict) {}
+ASDCP::h__ASDCPReader::~h__ASDCPReader() {}
+
+
+// AS-DCP method of opening an MXF file for read
 Result_t
-ASDCP::h__Reader::InitInfo()
+ASDCP::h__ASDCPReader::OpenMXFRead(const std::string& filename)
 {
-  InterchangeObject* Object;
+  Result_t result = ASDCP::MXF::TrackFileReader<OP1aHeader, OPAtomIndexFooter>::OpenMXFRead(filename);
 
-  m_Info.LabelSetType = LS_MXF_UNKNOWN;
-  UL OPAtomUL(Dict::ul(MDD_OPAtom));
-  UL Interop_OPAtomUL(Dict::ul(MDD_MXFInterop_OPAtom));
+  if ( KM_SUCCESS(result) )
+    result = ASDCP::MXF::TrackFileReader<OP1aHeader, OPAtomIndexFooter>::InitInfo();
 
-  if ( m_HeaderPart.OperationalPattern == Interop_OPAtomUL )
-    m_Info.LabelSetType = LS_MXF_INTEROP;
-  else if ( m_HeaderPart.OperationalPattern == OPAtomUL )
-    m_Info.LabelSetType = LS_MXF_SMPTE;
+  if( KM_SUCCESS(result) )
+    {
+      //
+      InterchangeObject* Object;
 
-  // Identification
-  Result_t result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(Identification), &Object);
+      m_Info.LabelSetType = LS_MXF_UNKNOWN;
 
-  if( ASDCP_SUCCESS(result) )
-    MD_to_WriterInfo((Identification*)Object, m_Info);
+      if ( m_HeaderPart.OperationalPattern.MatchExact(MXFInterop_OPAtom_Entry().ul) )
+       {
+         m_Info.LabelSetType = LS_MXF_INTEROP;
+       }
+      else if ( m_HeaderPart.OperationalPattern.MatchExact(SMPTE_390_OPAtom_Entry().ul) )
+       {
+         m_Info.LabelSetType = LS_MXF_SMPTE;
+       }
+      else
+       {
+         char strbuf[IdentBufferLen];
+         const MDDEntry* Entry = m_Dict->FindULExact(m_HeaderPart.OperationalPattern.Value());
 
-  // SourcePackage
-  if( ASDCP_SUCCESS(result) )
-    result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(SourcePackage), &Object);
+         if ( Entry == 0 )
+           {
+             DefaultLogSink().Warn("Operational pattern is not OP-Atom: %s\n",
+                                   m_HeaderPart.OperationalPattern.EncodeString(strbuf, IdentBufferLen));
+           }
+         else
+           {
+             DefaultLogSink().Warn("Operational pattern is not OP-Atom: %s\n", Entry->name);
+           }
+       }
 
-  if( ASDCP_SUCCESS(result) )
-    {
-      SourcePackage* SP = (SourcePackage*)Object;
-      memcpy(m_Info.AssetUUID, SP->PackageUID.Value() + 16, UUIDlen);
+      if ( !m_RIP.PairArray.empty() && m_RIP.PairArray.front().ByteOffset != 0 )
+       {
+         DefaultLogSink().Error("First Partition in RIP is not at offset 0.\n");
+         result = RESULT_FORMAT;
+       }
+
+      //
+      if ( m_RIP.PairArray.size() < 2 )
+       {
+         // OP-Atom states that there will be either two or three partitions:
+         // one closed header and one closed footer with an optional body
+         // SMPTE 429-5 files may have many partitions, see SMPTE ST 410.
+         DefaultLogSink().Warn("RIP entry count is less than 2: %u\n", m_RIP.PairArray.size());
+       }
+      else if ( m_RIP.PairArray.size() > 2 )
+        {
+         // if this is a three partition file, go to the body
+         // partition and read the partition pack
+         RIP::const_pair_iterator r_i = m_RIP.PairArray.begin();
+         r_i++;
+         m_File.Seek((*r_i).ByteOffset);
+         result = m_BodyPart.InitFromFile(m_File);
+
+         if( ASDCP_FAILURE(result) )
+            {
+             DefaultLogSink().Error("ASDCP::h__ASDCPReader::OpenMXFRead, m_BodyPart.InitFromFile failed\n");
+            }
+        }
     }
 
-  // optional CryptographicContext
-  if( ASDCP_SUCCESS(result) )
+  if ( KM_SUCCESS(result) )
     {
-      Result_t cr_result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(CryptographicContext), &Object);
+      // this position will be at either
+      //     a) the spot in the header partition where essence units appear, or
+      //     b) right after the body partition header (where essence units appear)
+      m_HeaderPart.BodyOffset = m_File.Tell();
+
+      result = m_File.Seek(m_HeaderPart.FooterPartition);
 
-      if( ASDCP_SUCCESS(cr_result) )
-       MD_to_CryptoInfo((CryptographicContext*)Object, m_Info);
+      if ( ASDCP_SUCCESS(result) )
+       {
+         m_IndexAccess.m_Lookup = &m_HeaderPart.m_Primer;
+         result = m_IndexAccess.InitFromFile(m_File);
+       }
     }
 
+  m_File.Seek(m_HeaderPart.BodyOffset);
   return result;
 }
 
-
-// standard method of opening an MXF file for read
+// AS-DCP method of reading a plaintext or encrypted frame
 Result_t
-ASDCP::h__Reader::OpenMXFRead(const char* filename)
+ASDCP::h__ASDCPReader::ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
+                                    const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC)
 {
-  m_LastPosition = 0;
-  Result_t result = m_File.OpenRead(filename);
-
-  if ( ASDCP_SUCCESS(result) )
-    result = m_HeaderPart.InitFromFile(m_File);
+  return ASDCP::MXF::TrackFileReader<OP1aHeader, OPAtomIndexFooter>::ReadEKLVFrame(m_HeaderPart.BodyOffset, FrameNum, FrameBuf,
+                                                                                    EssenceUL, Ctx, HMAC);
+}
 
-  // if this is a three partition file, go to the body
-  // partition and read off the partition pack
-  if ( m_HeaderPart.m_RIP.PairArray.size() == 3 )
-    {
-      DefaultLogSink().Error("RIP count is 3: must write code...\n");
-      return RESULT_FORMAT;
-    }
-  // TODO: check the partition pack to make sure it is
-  //       really a body with a single essence container
+Result_t
+ASDCP::h__ASDCPReader::LocateFrame(ui32_t FrameNum, Kumu::fpos_t& streamOffset,
+                           i8_t& temporalOffset, i8_t& keyFrameOffset)
+{
+  return ASDCP::MXF::TrackFileReader<OP1aHeader, OPAtomIndexFooter>::LocateFrame(m_HeaderPart.BodyOffset, FrameNum,
+                                                                                   streamOffset, temporalOffset, keyFrameOffset);
+}
 
-  m_EssenceStart = m_File.Tell();
 
-  return RESULT_OK;
-}
+//------------------------------------------------------------------------------------------
+//
 
 
-// standard method of populating the in-memory index
+//
 Result_t
-ASDCP::h__Reader::InitMXFIndex()
+ASDCP::KLReader::ReadKLFromFile(Kumu::FileReader& Reader)
 {
-  if ( ! m_File.IsOpen() )
-    return RESULT_INIT;
+  ui32_t read_count;
+  ui32_t header_length = SMPTE_UL_LENGTH + MXF_BER_LENGTH;
+  Result_t result = Reader.Read(m_KeyBuf, header_length, &read_count);
+
+  if ( ASDCP_FAILURE(result) )
+    return result;
 
-  Result_t result = m_File.Seek(m_HeaderPart.FooterPartition);
+  if ( read_count != header_length )
+    return RESULT_READFAIL;
 
-  if ( ASDCP_SUCCESS(result) )
+  const byte_t* ber_start = m_KeyBuf + SMPTE_UL_LENGTH;
+
+  if ( ( *ber_start & 0x80 ) == 0 )
     {
-      m_FooterPart.m_Lookup = &m_HeaderPart.m_Primer;
-      result = m_FooterPart.InitFromFile(m_File);
+      DefaultLogSink().Error("BER encoding error.\n");
+      return RESULT_FORMAT;
     }
 
-  if ( ASDCP_SUCCESS(result) )
-    m_File.Seek(m_EssenceStart);
+  ui8_t ber_size = ( *ber_start & 0x0f ) + 1;
 
-  return result;
-}
+  if ( ber_size > 9 )
+    {
+      DefaultLogSink().Error("BER size encoding error.\n");
+      return RESULT_FORMAT;
+    }
 
-//
-class KLReader : public ASDCP::KLVPacket
-{
-  ASDCP_NO_COPY_CONSTRUCT(KLReader);
-  byte_t m_KeyBuf[32];
+  if ( ber_size < MXF_BER_LENGTH )
+    {
+      DefaultLogSink().Error("BER size %d shorter than AS-DCP/AS-02 minimum %d.\n",
+                            ber_size, MXF_BER_LENGTH);
+      return RESULT_FORMAT;
+    }
 
-public:
-  KLReader() {}
-  ~KLReader() {}
+  if ( ber_size > MXF_BER_LENGTH )
+    {
+      ui32_t diff = ber_size - MXF_BER_LENGTH;
+      assert((SMPTE_UL_LENGTH + MXF_BER_LENGTH + diff) <= (SMPTE_UL_LENGTH * 2));
+      result = Reader.Read(m_KeyBuf + SMPTE_UL_LENGTH + MXF_BER_LENGTH, diff, &read_count);
 
-  inline const byte_t* Key() { return m_KeyBuf; }
-  inline const ui64_t  Length() { return m_ValueLength; }
-  inline const ui64_t  KLLength() { return m_KLLength; }
+      if ( ASDCP_FAILURE(result) )
+       return result;
 
-  Result_t ReadKLFromFile(ASDCP::FileReader& Reader)
-  {
-    ui32_t read_count;
-    ui32_t header_length = SMPTE_UL_LENGTH + MXF_BER_LENGTH;
-    Result_t result = Reader.Read(m_KeyBuf, header_length, &read_count);
+      if ( read_count != diff )
+       return RESULT_READFAIL;
 
-    if ( read_count != header_length )
-      return RESULT_READFAIL;
-  
-    if ( ASDCP_SUCCESS(result) )
-      result = InitFromBuffer(m_KeyBuf, header_length);
+      header_length += diff;
+    }
 
-    return result;
-  }
-};
+  return InitFromBuffer(m_KeyBuf, header_length);
+}
 
 
-// standard method of reading a plaintext or encrypted frame
-Result_t
-ASDCP::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
-                                const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC)
-{
-  // look up frame index node
-  IndexTableSegment::IndexEntry TmpEntry;
+//------------------------------------------------------------------------------------------
+//
 
-  if ( ASDCP_FAILURE(m_FooterPart.Lookup(FrameNum, TmpEntry)) )
-    {
-      DefaultLogSink().Error("Frame value out of range: %lu\n", FrameNum);
-      return RESULT_RANGE;
-    }
 
-  // get frame position and go read the frame's key and length
-  Result_t result = RESULT_OK;
+// base subroutine for reading a KLV packet, assumes file position is at the first byte of the packet
+Result_t
+ASDCP::Read_EKLV_Packet(Kumu::FileReader& File, const ASDCP::Dictionary& Dict,
+                       const ASDCP::WriterInfo& Info, Kumu::fpos_t& LastPosition, ASDCP::FrameBuffer& CtFrameBuf,
+                       ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf,
+                       const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC)
+{
   KLReader Reader;
-  ASDCP::fpos_t FilePosition = m_EssenceStart + TmpEntry.StreamOffset;
-
-  if ( FilePosition != m_LastPosition )
-    {
-      m_LastPosition = FilePosition;
-      result = m_File.Seek(FilePosition);
-    }
+  Result_t result = Reader.ReadKLFromFile(File);
 
-  if ( ASDCP_SUCCESS(result) )
-    result = Reader.ReadKLFromFile(m_File);
-
-  if ( ASDCP_FAILURE(result) )
+  if ( KM_FAILURE(result) )
     return result;
 
   UL Key(Reader.Key());
-  UL CryptEssenceUL(Dict::ul(MDD_CryptEssence));
-  UL InteropCryptEssenceUL(Dict::ul(MDD_MXFInterop_CryptEssence));
   ui64_t PacketLength = Reader.Length();
-  m_LastPosition = m_LastPosition + Reader.KLLength() + PacketLength;
+  LastPosition = LastPosition + Reader.KLLength() + PacketLength;
 
-  if ( Key == InteropCryptEssenceUL || Key == CryptEssenceUL )
+  if ( Key.MatchIgnoreStream(Dict.ul(MDD_CryptEssence)) )  // ignore the stream numbers
     {
-      if ( ! m_Info.EncryptedEssence )
+      if ( ! Info.EncryptedEssence )
        {
          DefaultLogSink().Error("EKLV packet found, no Cryptographic Context in header.\n");
          return RESULT_FORMAT;
        }
 
       // read encrypted triplet value into internal buffer
-      m_CtFrameBuf.Capacity(PacketLength);
+      assert(PacketLength <= 0xFFFFFFFFL);
+      CtFrameBuf.Capacity((ui32_t) PacketLength);
       ui32_t read_count;
-      result = m_File.Read(m_CtFrameBuf.Data(), PacketLength, &read_count);
+      result = File.Read(CtFrameBuf.Data(), (ui32_t) PacketLength, &read_count);
 
       if ( ASDCP_FAILURE(result) )
        return result;
@@ -235,17 +280,17 @@ ASDCP::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
           return RESULT_FORMAT;
         }
 
-      m_CtFrameBuf.Size(PacketLength);
+      CtFrameBuf.Size((ui32_t) PacketLength);
 
       // should be const but mxflib::ReadBER is not
-      byte_t* ess_p = m_CtFrameBuf.Data();
+      byte_t* ess_p = CtFrameBuf.Data();
 
       // read context ID length
-      if ( ! read_test_BER(&ess_p, UUIDlen) )
+      if ( ! Kumu::read_test_BER(&ess_p, UUIDlen) )
        return RESULT_FORMAT;
 
       // test the context ID
-      if ( memcmp(ess_p, m_Info.ContextID, UUIDlen) != 0 )
+      if ( memcmp(ess_p, Info.ContextID, UUIDlen) != 0 )
        {
          DefaultLogSink().Error("Packet's Cryptographic Context ID does not match the header.\n");
          return RESULT_FORMAT;
@@ -253,43 +298,60 @@ ASDCP::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
       ess_p += UUIDlen;
 
       // read PlaintextOffset length
-      if ( ! read_test_BER(&ess_p, sizeof(ui64_t)) )
+      if ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) )
        return RESULT_FORMAT;
 
-      ui32_t PlaintextOffset = (ui32_t)ASDCP_i64_BE(cp2i<ui64_t>(ess_p));
+      ui32_t PlaintextOffset = (ui32_t)KM_i64_BE(Kumu::cp2i<ui64_t>(ess_p));
       ess_p += sizeof(ui64_t);
 
       // read essence UL length
-      if ( ! read_test_BER(&ess_p, SMPTE_UL_LENGTH) )
+      if ( ! Kumu::read_test_BER(&ess_p, SMPTE_UL_LENGTH) )
        return RESULT_FORMAT;
 
-      // TODO: test essence UL
+      // test essence UL
+      if ( ! UL(ess_p).MatchIgnoreStream(EssenceUL) ) // ignore the stream number
+       {
+         char strbuf[IntBufferLen];
+         const MDDEntry* Entry = Dict.FindULAnyVersion(Key.Value());
+
+         if ( Entry == 0 )
+           {
+             DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Key.EncodeString(strbuf, IntBufferLen));
+           }
+         else
+           {
+             DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Entry->name);
+           }
+
+         return RESULT_FORMAT;
+       }
+
       ess_p += SMPTE_UL_LENGTH;
 
       // read SourceLength length
-      if ( ! read_test_BER(&ess_p, sizeof(ui64_t)) )
+      if ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) )
        return RESULT_FORMAT;
 
-      ui32_t SourceLength = (ui32_t)ASDCP_i64_BE(cp2i<ui64_t>(ess_p));
+      ui32_t SourceLength = (ui32_t)KM_i64_BE(Kumu::cp2i<ui64_t>(ess_p));
       ess_p += sizeof(ui64_t);
       assert(SourceLength);
          
       if ( FrameBuf.Capacity() < SourceLength )
        {
-         DefaultLogSink().Error("FrameBuf.Capacity: %lu SourceLength: %lu\n", FrameBuf.Capacity(), SourceLength);
+         DefaultLogSink().Error("FrameBuf.Capacity: %u SourceLength: %u\n", FrameBuf.Capacity(), SourceLength);
          return RESULT_SMALLBUF;
        }
 
       ui32_t esv_length = calc_esv_length(SourceLength, PlaintextOffset);
 
       // read ESV length
-      if ( ! read_test_BER(&ess_p, esv_length) )
+      if ( ! Kumu::read_test_BER(&ess_p, esv_length) )
        {
-         DefaultLogSink().Error("read_test_BER did not return %lu\n", esv_length);
+         DefaultLogSink().Error("read_test_BER did not return %u\n", esv_length);
          return RESULT_FORMAT;
        }
 
-      ui32_t tmp_len = esv_length + (m_Info.UsesHMAC ? klv_intpack_size : 0);
+      ui32_t tmp_len = esv_length + (Info.UsesHMAC ? klv_intpack_size : 0);
 
       if ( PacketLength < tmp_len )
        {
@@ -311,36 +373,43 @@ ASDCP::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
          FrameBuf.FrameNumber(FrameNum);
   
          // detect and test integrity pack
-         if ( ASDCP_SUCCESS(result) && m_Info.UsesHMAC && HMAC )
+         if ( ASDCP_SUCCESS(result) && Info.UsesHMAC && HMAC )
            {
              IntegrityPack IntPack;
-             result = IntPack.TestValues(TmpWrapper, m_Info.AssetUUID, FrameNum + 1, HMAC);
+             result = IntPack.TestValues(TmpWrapper, Info.AssetUUID, SequenceNum, HMAC);
            }
        }
       else // return ciphertext to caller
        {
          if ( FrameBuf.Capacity() < tmp_len )
-           return RESULT_SMALLBUF;
+           {
+             char intbuf[IntBufferLen];
+             DefaultLogSink().Error("FrameBuf.Capacity: %u FrameLength: %s\n",
+                                    FrameBuf.Capacity(), ui64sz(PacketLength, intbuf));
+             return RESULT_SMALLBUF;
+           }
 
          memcpy(FrameBuf.Data(), ess_p, tmp_len);
          FrameBuf.Size(tmp_len);
+         FrameBuf.FrameNumber(FrameNum);
          FrameBuf.SourceLength(SourceLength);
          FrameBuf.PlaintextOffset(PlaintextOffset);
        }
     }
-  else if ( Key == EssenceUL )
+  else if ( Key.MatchIgnoreStream(EssenceUL) ) // ignore the stream number
     { // read plaintext frame
        if ( FrameBuf.Capacity() < PacketLength )
        {
          char intbuf[IntBufferLen];
-         DefaultLogSink().Error("FrameBuf.Capacity: %lu FrameLength: %s\n",
+         DefaultLogSink().Error("FrameBuf.Capacity: %u FrameLength: %s\n",
                                 FrameBuf.Capacity(), ui64sz(PacketLength, intbuf));
          return RESULT_SMALLBUF;
        }
 
       // read the data into the supplied buffer
       ui32_t read_count;
-      result = m_File.Read(FrameBuf.Data(), PacketLength, &read_count);
+      assert(PacketLength <= 0xFFFFFFFFL);
+      result = File.Read(FrameBuf.Data(), (ui32_t) PacketLength, &read_count);
          
       if ( ASDCP_FAILURE(result) )
        return result;
@@ -362,11 +431,17 @@ ASDCP::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
   else
     {
       char strbuf[IntBufferLen];
-      const MDDEntry* Entry = Dict::FindUL(Key.Value());
+      const MDDEntry* Entry = Dict.FindULAnyVersion(Key.Value());
+
       if ( Entry == 0 )
-        DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Key.ToString(strbuf));
+       {
+         DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Key.EncodeString(strbuf, IntBufferLen));
+       }
       else
-        DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Entry->name);
+       {
+         DefaultLogSink().Warn("Unexpected Essence UL found: %s.\n", Entry->name);
+       }
+
       return RESULT_FORMAT;
     }