oops
authorjhurst <jhurst@cinecert.com>
Wed, 13 Jun 2007 22:15:44 +0000 (22:15 +0000)
committerjhurst <>
Wed, 13 Jun 2007 22:15:44 +0000 (22:15 +0000)
AS_DCP_TimedText.h
src/AS_DCP_MXF.cpp
src/AS_DCP_TimedText.cpp
src/KM_fileio.cpp
src/KM_fileio.h
src/KM_xml.cpp
src/KM_xml.h
src/S12MTimecode.h [new file with mode: 0644]
src/TimedText_Parser.cpp

index b175683738caf80413637948b36ab9952241d986..9c0262ca7be5956016878803c934f0fe42fe7cab 100644 (file)
@@ -61,7 +61,7 @@ namespace ASDCP {
        Rational       EditRate;                // 
        ui32_t         ContainerDuration;
        byte_t         AssetID[UUIDlen];
-       std::string    NamespaceName; // NULL-terminated string
+       std::string    NamespaceName;
        std::string    EncodingName;
        ResourceList_t ResourceList;
 
@@ -94,6 +94,14 @@ namespace ASDCP {
        void Dump(FILE* = 0, ui32_t dump_bytes = 0) const;
       };
 
+      //
+      class IResourceResolver
+      {
+      public:
+       virtual ~IResourceResolver() {}
+       virtual Result_t ResolveRID(const byte_t* uuid, FrameBuffer&) const = 0; // return data for RID
+      };
+
       //
       class DCSubtitleParser
        {
@@ -117,8 +125,14 @@ namespace ASDCP {
          Result_t ReadTimedTextResource(std::string&) const;
 
          // Reads the Ancillary Resource having the given ID. Fails if the buffer
-         // is too small or the resource does not exist.
-         Result_t ReadAncillaryResource(const byte_t* uuid, FrameBuffer&) const;
+         // is too small or the resource does not exist. The optional Resolver
+         // argument can be provided which will be used to retrieve the resource
+         // having a particulat UUID. If a Resolver is not supplied, the default
+         // internal resolver will return the contents of the file having the UUID
+         // (with optional extension) as the filename. The filename must exist in
+         // the same directory as the XML file opened with OpenRead().
+         Result_t ReadAncillaryResource(const byte_t* uuid, FrameBuffer&,
+                                        const IResourceResolver* Resolver = 0) const;
        };
 
       //
index 9525cff2b1efd70c45753cfdf0aafd18a0b905d7..247c2dadbca4411a1075fd027ccf079cd378163d 100755 (executable)
@@ -206,7 +206,7 @@ ASDCP::RawEssenceType(const char* filename, EssenceType_t& type)
          if ( i > 1 && p[i] == 1 &&  (p[i+1] == ASDCP::MPEG2::SEQ_START || p[i+1] == ASDCP::MPEG2::PIC_START) )
            type = ESS_MPEG2_VES;
 
-         else if ( TmpElement.TestString((const char*)p, FB.Size()) )
+         else if ( Kumu::StringIsXML((const char*)p, FB.Size()) )
            type = ESS_TIMED_TEXT;
 
          else if ( ASDCP_SUCCESS(WavHeader.ReadFromBuffer(p, read_count, &data_offset)) )
index f5fcdb880d4c72056b8bd25cba4d4f815a9c5d41..5299dd1b61fa3d6af2b4dd748c1ce5ed742a2255 100644 (file)
@@ -199,7 +199,15 @@ ASDCP::TimedText::MXFReader::h__Reader::ReadTimedTextResource(FrameBuffer& Frame
   if ( ! m_File.IsOpen() )
     return RESULT_INIT;
 
-  return ReadEKLVFrame(0, FrameBuf, Dict::ul(MDD_DCTimedTextEssence), Ctx, HMAC);
+  Result_t result = ReadEKLVFrame(0, FrameBuf, Dict::ul(MDD_DCTimedTextEssence), Ctx, HMAC);
+
+ if( ASDCP_SUCCESS(result) )
+   {
+     FrameBuf.AssetID(m_TDesc.AssetID);
+     FrameBuf.MIMEType("text/xml");
+   }
+
+ return result;
 }
 
 //
@@ -215,7 +223,7 @@ ASDCP::TimedText::MXFReader::h__Reader::ReadAncillaryResource(const byte_t* uuid
     {
       char buf[64];
       DefaultLogSink().Error("No such resource: %s\n", RID.EncodeHex(buf, 64));
-      return RESULT_FORMAT;
+      return RESULT_RANGE;
     }
 
   DCTimedTextResourceDescriptor* DescObject = 0;
index 50e01d65199659394ff4f8ed5ed744832fc464cf..e94525e65934b5f1900f4e5a852741c3010cbdbc 100644 (file)
@@ -53,33 +53,33 @@ struct iovec {
 typedef struct stat     fstat_t;
 #endif
 
+//
 static void
 split(const std::string& str, char separator, std::list<std::string>& components)
 {
   const char* pstr = str.c_str();
   const char* r = strchr(pstr, separator);
 
-  while( r != NULL )
+  while ( r != 0 )
     {
-      char* cp = new char[(r-pstr)+1];
-      memcpy(cp, pstr, (r-pstr));
-      cp[(r-pstr)] = '\0';
-
-      if( strlen(cp) > 0 )
+      assert(r >= pstr);
+      if ( r > pstr )
        {
-         std::string s(cp);
-         components.push_back(s);
+         std::string tmp_str;
+         assert(r - pstr < 100);
+         tmp_str.assign(pstr, (r - pstr));
+         components.push_back(tmp_str);
        }
 
-      delete[] cp;
       pstr = r + 1;
       r = strchr(pstr, separator);
     }
 
   if( strlen(pstr) > 0 )
-      components.push_back(std::string(pstr));
+    components.push_back(std::string(pstr));
 }
 
+
 //
 static Kumu::Result_t
 do_stat(const char* path, fstat_t* stat_info)
index 43b164df2c5fc58681dfdf12222712717a5ba228..9d7cc7af0b8b5ddbc46b18517d258dfa2cc17c9a 100755 (executable)
@@ -170,7 +170,7 @@ namespace Kumu
   // Search all paths in SearchPaths for filenames matching Pattern (no directories are returned).
   // Put results in FoundPaths. Returns after first find if one_shot is true.
   PathList_t& FindInPath(const IPathMatch& Pattern, const std::string& SearchDir,
-                        PathList_t& FoundPaths, bool one_shot, char separator);
+                        PathList_t& FoundPaths, bool one_shot = false, char separator = '/');
 
   PathList_t& FindInPaths(const IPathMatch& Pattern, const PathList_t& SearchPaths,
                          PathList_t& FoundPaths, bool one_shot = false, char separator = '/');
index 03102919b664d17ce1d0ae2d8b9d56fe7d07d32b..9c41512149631d423eeee8e3a276daffe75e9b0f 100644 (file)
@@ -442,7 +442,7 @@ xph_test_start(void* p, const XML_Char* name, const XML_Char** attrs)
 
 //
 bool
-Kumu::XMLElement::TestString(const char* document, ui32_t len)
+Kumu::StringIsXML(const char* document, ui32_t len)
 {
   if ( document == 0 )
     return false;
@@ -479,9 +479,9 @@ Kumu::XMLElement::ParseString(const std::string& document)
 
 //
 bool
-Kumu::XMLElement::TestString(const char* document, ui32_t len)
+Kumu::StringIsXML(const char* document, ui32_t len)
 {
-  DefaultLogSink().Error("asdcplib compiled without XML parser support.\n");
+  DefaultLogSink().Error("Kumu compiled without XML parser support.\n");
   return false;
 }
 
index 31f506471cabacffe1e714a224e0590b1db172e9..6900dd8f6d29afd9f297b551918c201a9227ba0c 100644 (file)
@@ -41,6 +41,9 @@ namespace Kumu
 {
   class XMLElement;
 
+  // Return true if the given string contains an XML document (or the start of one).
+  bool StringIsXML(const char* document, ui32_t len = 0);
+
   //
   struct NVPair
   {
@@ -93,7 +96,6 @@ namespace Kumu
       inline void                SetNamespace(const XMLNamespace* ns) { assert(ns); m_Namespace = ns; }
 
       bool        ParseString(const std::string& document);
-      bool        TestString(const char* document, ui32_t len = 0);
 
       // building
       void        SetName(const char* name);
diff --git a/src/S12MTimecode.h b/src/S12MTimecode.h
new file mode 100644 (file)
index 0000000..23ccbb4
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+Copyright (c) 2007, John Hurst
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+   derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/*! \file    S12MTimecode.cpp
+    \version $Id$       
+    \brief   AS-DCP library, Timecode PCM essence reader and writer implementation
+*/
+
+/*
+
+  DROP-FRAME NOT SUPPORTED!
+
+*/
+
+#ifndef _S12MTIMECODE_H_
+#define _S12MTIMECODE_H_
+
+#include "KM_util.h"
+#include "KM_memio.h"
+
+namespace ASDCP {
+
+ class S12MTimecode : public Kumu::IArchive
+{
+  ui32_t m_FrameCount;
+  ui32_t m_FPS;
+
+public:
+  S12MTimecode() : m_FrameCount(0), m_FPS(0) {}
+
+  S12MTimecode(ui32_t frame_count, ui32_t fps) : m_FrameCount(frame_count), m_FPS(fps) {}
+
+  S12MTimecode(const std::string& tc, ui32_t fps) : m_FrameCount(0), m_FPS(fps)
+  {
+    DecodeString(tc);
+  }
+
+  S12MTimecode(const S12MTimecode& rhs) : m_FrameCount(0), m_FPS(0)
+  {
+    m_FPS = rhs.m_FPS;
+    m_FrameCount = rhs.m_FrameCount;
+  }
+
+  ~S12MTimecode() {}
+
+  const S12MTimecode& operator=(const S12MTimecode& rhs)
+  {
+    assert(m_FPS != 0);
+    m_FrameCount = rhs.m_FrameCount;
+    return *this;
+  }
+
+  inline void   SetFPS(ui32_t fps) { m_FPS = fps; }
+  inline ui32_t GetFPS() const { return m_FPS; }
+
+  inline void   SetFrames(ui32_t frame_count) { m_FrameCount = frame_count; }
+  inline ui32_t GetFrames() const { return m_FrameCount; }
+
+  inline bool operator==(const S12MTimecode& rhs) const { return m_FrameCount == rhs.m_FrameCount; }
+  inline bool operator<(const S12MTimecode& rhs) const { return m_FrameCount < rhs.m_FrameCount; }
+
+  inline const S12MTimecode operator+(const S12MTimecode& rhs){
+    assert(m_FPS > 0);
+    assert(m_FPS == rhs.m_FPS);
+    return S12MTimecode(m_FrameCount + rhs.m_FrameCount, m_FPS);
+  }
+
+  inline const S12MTimecode operator-(const S12MTimecode& rhs){
+    assert(m_FPS > 0);
+    assert(m_FPS == rhs.m_FPS);
+    return S12MTimecode(m_FrameCount + rhs.m_FrameCount, m_FPS);
+  }
+
+
+  void DecodeString(const std::string& tc)
+  {
+    assert(m_FPS > 0);
+    const char* p = tc.c_str();
+
+    while ( *p != 0 && ! isdigit(*p) )
+      p++;
+
+    if ( *p != 0 )
+      {
+       ui32_t hours = atoi(p);
+       ui32_t minutes = atoi(p+3);
+       ui32_t seconds = atoi(p+6);
+       ui32_t frames = atoi(p+9);
+
+       m_FrameCount = (((((hours * 60) + minutes) * 60) + seconds) * m_FPS)+ frames;
+      }
+  }
+
+  const char* EncodeString(char* buf, ui32_t buf_len)
+  {
+    assert(m_FPS > 0);
+    ui32_t frames = m_FrameCount % m_FPS;
+    m_FrameCount /= m_FPS;
+    ui32_t seconds = m_FrameCount % 60;
+    m_FrameCount /= 60;
+    ui32_t minutes = m_FrameCount % 60;
+    ui32_t hours = m_FrameCount / 60;
+
+    snprintf(buf, buf_len, "%02d:%02d:%02d:%02d", hours, minutes, seconds, frames);
+    return buf;
+  }
+
+  // IArchive
+  bool HasValue() const { return (m_FPS > 0); }
+
+  bool Archive(Kumu::MemIOWriter* Writer) const
+  {
+    if ( ! Writer->WriteUi32BE(m_FPS) ) return false;
+    if ( ! Writer->WriteUi32BE(m_FrameCount) ) return false;
+    return true;
+  }
+
+  bool Unarchive(Kumu::MemIOReader* Reader)
+  {
+    if ( ! Reader->ReadUi32BE(&m_FPS) ) return false;
+    if ( ! Reader->ReadUi32BE(&m_FrameCount) ) return false;
+    return true;
+  }
+};
+
+
+} // namespace ASDCP
+
+#endif // _S12MTIMECODE_H_
+
+//
+// end S12MTimecode.h
+//
index a2683f9ecbcf245bd363bb64cb847d33d9451db9..156c1abb093aca58966b2f28e921be292e47f196 100644 (file)
@@ -40,6 +40,53 @@ using namespace ASDCP;
 
 const char* c_dcst_namespace_name = "http://www.smpte-ra.org/schemas/428-7/2007/DCST";
 
+//------------------------------------------------------------------------------------------
+
+
+
+class FilenameResolver : public ASDCP::TimedText::IResourceResolver
+{
+  std::string m_Dirname;
+
+  FilenameResolver();
+  bool operator==(const FilenameResolver&);
+
+public:
+  FilenameResolver(const std::string& dirname)
+  {
+    if ( PathIsDirectory(dirname) )
+      {
+       m_Dirname = dirname;
+       return;
+      }
+
+    DefaultLogSink().Error("Path '%s' is not a directory, defaulting to '.'\n", dirname.c_str());
+    m_Dirname = ".";
+  }
+
+  //
+  Result_t ResolveRID(const byte_t* uuid, TimedText::FrameBuffer& FrameBuf) const
+  {
+    FileReader Reader;
+    char buf[64];
+    UUID RID(uuid);
+    std::string filename = m_Dirname + "/" + RID.EncodeHex(buf, 64);
+    DefaultLogSink().Debug("retrieving resource %s from file %s\n", buf, filename.c_str());
+
+    Result_t result = Reader.OpenRead(filename.c_str());
+
+    if ( KM_SUCCESS(result) )
+      {
+       ui32_t read_count = 0;
+       result = Reader.Read(FrameBuf.Data(), FrameBuf.Capacity(), &read_count);
+
+       if ( KM_SUCCESS(result) )
+         FrameBuf.Size(read_count);
+      }
+
+    return result;
+  }
+};
 
 //------------------------------------------------------------------------------------------
 
@@ -53,8 +100,10 @@ class ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser
   ASDCP_NO_COPY_CONSTRUCT(h__SubtitleParser);
 
 public:
+  std::string m_Filename;
   std::string m_XMLDoc;
   TimedTextDescriptor  m_TDesc;
+  mem_ptr<FilenameResolver> m_DefaultResolver;
 
   h__SubtitleParser() : m_Root("**ParserRoot**")
   {
@@ -63,8 +112,16 @@ public:
 
   ~h__SubtitleParser() {}
 
+  TimedText::IResourceResolver* GetDefaultResolver()
+  {
+    if ( m_DefaultResolver.empty() )
+      m_DefaultResolver = new FilenameResolver(PathDirname(m_Filename));
+    
+    return m_DefaultResolver;
+  }
+
   Result_t OpenRead(const char* filename);
-  Result_t ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf) const;
+  Result_t ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf, const IResourceResolver& Resolver) const;
 };
 
 //
@@ -102,22 +159,6 @@ decode_rational(const char* str_rat)
   return ASDCP::Rational(Num, Den);
 }
 
-//
-ui32_t
-CalculateSubtitleDuration(const XMLElement* begin, const XMLElement* end)
-{
-  assert(begin); assert(end);
-
-  S12MTimecode
-    beginTC(begin->GetAttrWithName("TimeIn"), 24),
-    endTC(end->GetAttrWithName("TimeOut"), 24);
-
-  if ( endTC < beginTC )
-    return 0;
-
-  return endTC.GetFrames() - beginTC.GetFrames();
-}
-
 //
 Result_t
 ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::OpenRead(const char* filename)
@@ -127,6 +168,7 @@ ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::OpenRead(const char* file
   if ( ! m_Root.ParseString(m_XMLDoc.c_str()) )
     return RESULT_FORMAT;
 
+  m_Filename = filename;
   m_TDesc.EncodingName = "UTF-8"; // the XML parser demands UTF-8
   m_TDesc.ResourceList.clear();
   m_TDesc.ContainerDuration = 0;
@@ -158,6 +200,12 @@ ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::OpenRead(const char* file
 
   m_TDesc.EditRate = decode_rational(EditRate->GetBody().c_str());
 
+  if ( m_TDesc.EditRate != EditRate_24 && m_TDesc.EditRate != EditRate_48 )
+    {
+      DefaultLogSink(). Error("EditRate must be 24/1 or 48/1\n");
+      return RESULT_FORMAT;
+    }
+
   // list of fonts
   ElementList FontList;
   m_Root.GetChildrenWithName("LoadFont", FontList);
@@ -198,10 +246,35 @@ ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::OpenRead(const char* file
       m_ResourceTypes.insert(ResourceTypeMap_t::value_type(UUID(TmpResource.ResourceID), MT_PNG));
     }
 
-  // duration
+  // Calculate the timeline duration.
+  // This is a little ugly because the last element in the file is not necessarily
+  // the last instance to be displayed, e.g., element n and element n-1 may have the
+  // same start time but n-1 may have a greater duration making it the last to be seen.
+  // We must scan the list to accumulate the latest TimeOut value.
   ElementList InstanceList;
+  ElementList::const_iterator ei;
+  ui32_t end_count = 0;
+  
   m_Root.GetChildrenWithName("Subtitle", InstanceList);
-  m_TDesc.ContainerDuration = CalculateSubtitleDuration(InstanceList.front(), InstanceList.back());
+
+  if ( InstanceList.empty() )
+    {
+      DefaultLogSink(). Error("XML document contains no Subtitle elements!\n");
+      return RESULT_FORMAT;
+    }
+
+  // assumes 24/1 or 48/1 as constrained above
+  S12MTimecode beginTC(InstanceList.front()->GetAttrWithName("TimeIn"), m_TDesc.EditRate.Numerator);
+
+  for ( ei = InstanceList.begin(); ei != InstanceList.end(); ei++ )
+    {
+      S12MTimecode tmpTC((*ei)->GetAttrWithName("TimeOut"), m_TDesc.EditRate.Numerator);
+      if ( end_count < tmpTC.GetFrames() )
+       end_count = tmpTC.GetFrames();
+    }
+
+  assert( end_count > beginTC.GetFrames() );
+  m_TDesc.ContainerDuration = end_count - beginTC.GetFrames();
 
   return RESULT_OK;
 }
@@ -209,12 +282,12 @@ ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::OpenRead(const char* file
 
 //
 Result_t
-ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf) const
+ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf,
+                                                                            const IResourceResolver& Resolver) const
 {
   FrameBuf.AssetID(uuid);
   UUID TmpID(uuid);
   char buf[64];
-  FileReader Reader;
 
   ResourceTypeMap_t::const_iterator rmi = m_ResourceTypes.find(TmpID);
 
@@ -224,30 +297,18 @@ ASDCP::TimedText::DCSubtitleParser::h__SubtitleParser::ReadAncillaryResource(con
       return RESULT_RANGE;
     }
 
-  Result_t result = Reader.OpenRead(TmpID.EncodeHex(buf, 64));
+  Result_t result = Resolver.ResolveRID(uuid, FrameBuf);
 
   if ( KM_SUCCESS(result) )
     {
-      ui32_t read_count = 0;
-      result = Reader.Read(FrameBuf.Data(), FrameBuf.Capacity(), &read_count);
-
-      if ( KM_SUCCESS(result) )
-       {
-         FrameBuf.Size(read_count);
-
-         if ( (*rmi).second == MT_PNG )
-           FrameBuf.MIMEType("image/png");
+      if ( (*rmi).second == MT_PNG )
+       FrameBuf.MIMEType("image/png");
              
-         else if ( (*rmi).second == MT_OPENTYPE )
-           FrameBuf.MIMEType("application/x-opentype");
+      else if ( (*rmi).second == MT_OPENTYPE )
+       FrameBuf.MIMEType("application/x-opentype");
 
-         else
-           FrameBuf.MIMEType("application/octet-stream");
-       }
-    }
-  else
-    {
-      DefaultLogSink(). Error("Error opening resource file %s.\n", buf);
+      else
+       FrameBuf.MIMEType("application/octet-stream");
     }
 
   return result;
@@ -302,12 +363,16 @@ ASDCP::TimedText::DCSubtitleParser::ReadTimedTextResource(std::string& s) const
 
 //
 ASDCP::Result_t
-ASDCP::TimedText::DCSubtitleParser::ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf) const
+ASDCP::TimedText::DCSubtitleParser::ReadAncillaryResource(const byte_t* uuid, FrameBuffer& FrameBuf,
+                                                         const IResourceResolver* Resolver) const
 {
- if ( m_Parser.empty() )
 if ( m_Parser.empty() )
     return RESULT_INIT;
 
- return m_Parser->ReadAncillaryResource(uuid, FrameBuf);
+  if ( Resolver == 0 )
+    Resolver = m_Parser->GetDefaultResolver();
+
+  return m_Parser->ReadAncillaryResource(uuid, FrameBuf, *Resolver);
 }