From aac3cfda50b82f7b763b69b9acfcc4d63c81d98b Mon Sep 17 00:00:00 2001 From: jhurst Date: Fri, 16 Mar 2012 00:28:23 +0000 Subject: [PATCH] as-02ooooooooooo! --- src/AS_02.h | 330 ++++++++++++ src/AS_02_JP2K.cpp | 1139 +++++++++++++++++++++++++++++++++++++++++ src/AS_02_PCM.cpp | 1095 +++++++++++++++++++++++++++++++++++++++ src/AS_02_internal.h | 199 +++++++ src/AS_DCP_internal.h | 24 + src/MXF.cpp | 129 +++-- src/MXF.h | 18 +- src/Makefile.am | 10 +- src/as-02-unwrap.cpp | 508 ++++++++++++++++++ src/as-02-wrap.cpp | 653 +++++++++++++++++++++++ src/asdcp-wrap.cpp | 4 +- src/h__02_Reader.cpp | 128 +++++ src/h__02_Writer.cpp | 672 ++++++++++++++++++++++++ src/h__Writer.cpp | 25 - 14 files changed, 4837 insertions(+), 97 deletions(-) create mode 100644 src/AS_02.h create mode 100644 src/AS_02_JP2K.cpp create mode 100644 src/AS_02_PCM.cpp create mode 100644 src/AS_02_internal.h create mode 100755 src/as-02-unwrap.cpp create mode 100755 src/as-02-wrap.cpp create mode 100644 src/h__02_Reader.cpp create mode 100644 src/h__02_Writer.cpp diff --git a/src/AS_02.h b/src/AS_02.h new file mode 100644 index 0000000..355f93a --- /dev/null +++ b/src/AS_02.h @@ -0,0 +1,330 @@ +/* +Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 AS_02.h + \version $Id$ + \brief AS-02 library, public interface + +This module implements MXF AS-02 is a set of file access objects that +offer simplified access to files conforming to the standards published +by the SMPTE Media and Packaging Technology Committee 35PM. The file +format, labeled IMF Essence Component (AKA "AS-02" for historical +reasons), is described in the following document: + + o SMPTE 2067-5:201X (draft at this time) IMF Essence Component + +The following use cases are supported by the module: + + o Write essence to a plaintext or ciphertext AS-02 file: + JPEG 2000 codestreams + PCM audio streams + + o Read essence from a plaintext or ciphertext AS-02 file: + JPEG 2000 codestreams + PCM audio streams + + o Read header metadata from an AS-02 file +*/ + +#ifndef _AS_02_H_ +#define _AS_02_H_ + +#include "AS_DCP.h" +#include "MXF.h" + + +namespace ASDCP { + namespace MXF { + // #include to use these + class OPAtomHeader; + class OPAtomIndexFooter; + }; +}; + +namespace AS_02 +{ + using Kumu::Result_t; + + namespace MXF { + + // + class OP1aIndexBodyPartion : public ASDCP::MXF::Partition + { + ASDCP::MXF::IndexTableSegment* m_CurrentSegment; + ASDCP::FrameBuffer m_Buffer; + ASDCP::MXF::Rational m_EditRate; + ui32_t klv_fill_size; + + ASDCP_NO_COPY_CONSTRUCT(OP1aIndexBodyPartion); + + public: + const ASDCP::Dictionary*& m_Dict; + Kumu::fpos_t m_ECOffset; + ASDCP::IPrimerLookup* m_Lookup; + + ui32_t m_BytesPerEditUnit; + ui32_t m_FramesWritten; + + OP1aIndexBodyPartion(const ASDCP::Dictionary*&); + virtual ~OP1aIndexBodyPartion(); + virtual Result_t InitFromFile(const Kumu::FileReader& Reader); + virtual Result_t InitFromBuffer(const byte_t* p, ui32_t l); + virtual Result_t WriteToFile(Kumu::FileWriter& Writer, ASDCP::UL& PartitionLabel); + virtual void Dump(FILE* = 0); + + virtual bool Lookup(ui32_t frame_num, ASDCP::MXF::IndexTableSegment::IndexEntry&,ui32_t&) const; + virtual void PushIndexEntry(const ASDCP::MXF::IndexTableSegment::IndexEntry&); + virtual void SetIndexParamsCBR(ASDCP::IPrimerLookup* lookup, ui32_t size, const ASDCP::MXF::Rational& Rate); + virtual void SetIndexParamsVBR(ASDCP::IPrimerLookup* lookup, const ASDCP::MXF::Rational& Rate, Kumu::fpos_t offset); + + //new + virtual ui64_t Duration(); + virtual Result_t FillWriteToFile(Kumu::FileWriter& Writer, ui32_t numberOfIndexEntries); + + //new for PCM + virtual void PCMSetIndexParamsCBR(ui32_t sizeFirst, ui32_t sizeOthers); + virtual void PCMIndexLookup(ui32_t frame_num, ASDCP::MXF::IndexTableSegment::IndexEntry& Entry) const; + + }; + + // + class OP1aIndexFooter : public ASDCP::MXF::Partition + { + ASDCP::MXF::IndexTableSegment* m_CurrentSegment; + ASDCP::FrameBuffer m_Buffer; + ui32_t m_BytesPerEditUnit; + ASDCP::MXF::Rational m_EditRate; + ui32_t m_BodySID; + ASDCP_NO_COPY_CONSTRUCT(OP1aIndexFooter); + + public: + const ASDCP::Dictionary*& m_Dict; + Kumu::fpos_t m_ECOffset; + ASDCP::IPrimerLookup* m_Lookup; + + OP1aIndexFooter(const ASDCP::Dictionary*&); + virtual ~OP1aIndexFooter(); + virtual Result_t InitFromFile(const Kumu::FileReader& Reader); + virtual Result_t InitFromPartitionBuffer(const byte_t* p, ui32_t l); + virtual Result_t InitFromBuffer(const byte_t* p, ui32_t l); + virtual Result_t WriteToFile(Kumu::FileWriter& Writer, ui64_t duration); + virtual void Dump(FILE* = 0); + + virtual Result_t Lookup(ui32_t frame_num, ASDCP::MXF::IndexTableSegment::IndexEntry&) const; + virtual void PushIndexEntry(const ASDCP::MXF::IndexTableSegment::IndexEntry&); + virtual void SetIndexParamsCBR(ASDCP::IPrimerLookup* lookup, ui32_t size, const ASDCP::MXF::Rational& Rate); + virtual void SetIndexParamsVBR(ASDCP::IPrimerLookup* lookup, const ASDCP::MXF::Rational& Rate, Kumu::fpos_t offset); + }; + + } // namespace MXF + + + //--------------------------------------------------------------------------------- + // Accessors in the MXFReader and MXFWriter classes below return these types to + // provide direct access to MXF metadata structures declared in MXF.h and Metadata.h + + // See ST 2067-5 Sec. x.y.z + enum IndexStrategy_t + { + IS_LEAD, + IS_FOLLOW, + IS_FILE_SPECIFIC, + }; + + namespace JP2K + { + // + class MXFWriter + { + class h__Writer; + ASDCP::mem_ptr m_Writer; + ASDCP_NO_COPY_CONSTRUCT(MXFWriter); + + public: + MXFWriter(); + virtual ~MXFWriter(); + + // Warning: direct manipulation of MXF structures can interfere + // with the normal operation of the wrapper. Caveat emptor! + virtual ASDCP::MXF::OPAtomHeader& OPAtomHeader(); + + // Open the file for writing. The file must not exist. Returns error if + // the operation cannot be completed or if nonsensical data is discovered + // in the essence descriptor. + Result_t OpenWrite(const char* filename, const ASDCP::WriterInfo&, + const ASDCP::JP2K::PictureDescriptor&, + const IndexStrategy_t& Strategy = IS_FOLLOW, + const ui32_t& PartitionSpace = 60, /* seconds per partition */ + const ui32_t& HeaderSize = 16384); + + // Writes a frame of essence to the MXF file. If the optional AESEncContext + // argument is present, the essence is encrypted prior to writing. + // Fails if the file is not open, is finalized, or an operating system + // error occurs. + Result_t WriteFrame(const ASDCP::JP2K::FrameBuffer&, ASDCP::AESEncContext* = 0, ASDCP::HMACContext* = 0); + + // Closes the MXF file, writing the index and revised header. + Result_t Finalize(); + }; + + // + class MXFReader + { + class h__Reader; + ASDCP::mem_ptr m_Reader; + ASDCP_NO_COPY_CONSTRUCT(MXFReader); + + public: + MXFReader(); + virtual ~MXFReader(); + + // Warning: direct manipulation of MXF structures can interfere + // with the normal operation of the wrapper. Caveat emptor! + virtual ASDCP::MXF::OPAtomHeader& OPAtomHeader(); + + // Open the file for reading. The file must exist. Returns error if the + // operation cannot be completed. + Result_t OpenRead(const char* filename) const; + + // Returns RESULT_INIT if the file is not open. + Result_t Close() const; + + // Fill an AudioDescriptor struct with the values from the file's header. + // Returns RESULT_INIT if the file is not open. + Result_t FillPictureDescriptor(ASDCP::JP2K::PictureDescriptor&) const; + + // Fill a WriterInfo struct with the values from the file's header. + // Returns RESULT_INIT if the file is not open. + Result_t FillWriterInfo(ASDCP::WriterInfo&) const; + + // Reads a frame of essence from the MXF file. If the optional AESEncContext + // argument is present, the essence is decrypted after reading. If the MXF + // file is encrypted and the AESDecContext argument is NULL, the frame buffer + // will contain the ciphertext frame data. If the HMACContext argument is + // not NULL, the HMAC will be calculated (if the file supports it). + // Returns RESULT_INIT if the file is not open, failure if the frame number is + // out of range, or if optional decrypt or HAMC operations fail. + Result_t ReadFrame(ui32_t frame_number, ASDCP::JP2K::FrameBuffer&, ASDCP::AESDecContext* = 0, ASDCP::HMACContext* = 0) const; + + // Print debugging information to stream + void DumpHeaderMetadata(FILE* = 0) const; + void DumpIndex(FILE* = 0) const; + }; + + } //namespace JP2K + + + //--------------------------------------------------------------------------------- + // + namespace PCM + { + // see AS_DCP.h for related data types + + // + class MXFWriter + { + class h__Writer; + ASDCP::mem_ptr m_Writer; + ASDCP_NO_COPY_CONSTRUCT(MXFWriter); + + public: + MXFWriter(); + virtual ~MXFWriter(); + + // Warning: direct manipulation of MXF structures can interfere + // with the normal operation of the wrapper. Caveat emptor! + virtual ASDCP::MXF::OPAtomHeader& OPAtomHeader(); + + // Open the file for writing. The file must not exist. Returns error if + // the operation cannot be completed or if nonsensical data is discovered + // in the essence descriptor. + Result_t OpenWrite(const char* filename, const ASDCP::WriterInfo&, + const ASDCP::PCM::AudioDescriptor&, ui32_t HeaderSize = 16384); + + // Writes a frame of essence to the MXF file. If the optional AESEncContext + // argument is present, the essence is encrypted prior to writing. + // Fails if the file is not open, is finalized, or an operating system + // error occurs. + Result_t WriteFrame(const ASDCP::FrameBuffer&, ASDCP::AESEncContext* = 0, ASDCP::HMACContext* = 0); + + // Closes the MXF file, writing the index and revised header. + Result_t Finalize(); + }; + + // + class MXFReader + { + class h__Reader; + ASDCP::mem_ptr m_Reader; + ASDCP_NO_COPY_CONSTRUCT(MXFReader); + + public: + MXFReader(); + virtual ~MXFReader(); + + // Warning: direct manipulation of MXF structures can interfere + // with the normal operation of the wrapper. Caveat emptor! + virtual ASDCP::MXF::OPAtomHeader& OPAtomHeader(); + + // Open the file for reading. The file must exist. Returns error if the + // operation cannot be completed. + Result_t OpenRead(const char* filename) const; + + // Returns RESULT_INIT if the file is not open. + Result_t Close() const; + + // Fill an AudioDescriptor struct with the values from the file's header. + // Returns RESULT_INIT if the file is not open. + Result_t FillAudioDescriptor(ASDCP::PCM::AudioDescriptor&) const; + + // Fill a WriterInfo struct with the values from the file's header. + // Returns RESULT_INIT if the file is not open. + Result_t FillWriterInfo(ASDCP::WriterInfo&) const; + + // Reads a frame of essence from the MXF file. If the optional AESEncContext + // argument is present, the essence is decrypted after reading. If the MXF + // file is encrypted and the AESDecContext argument is NULL, the frame buffer + // will contain the ciphertext frame data. If the HMACContext argument is + // not NULL, the HMAC will be calculated (if the file supports it). + // Returns RESULT_INIT if the file is not open, failure if the frame number is + // out of range, or if optional decrypt or HAMC operations fail. + Result_t ReadFrame(ui32_t frame_number, ASDCP::PCM::FrameBuffer&, ASDCP::AESDecContext* = 0, ASDCP::HMACContext* = 0) const; + + // Print debugging information to stream + void DumpHeaderMetadata(FILE* = 0) const; + void DumpIndex(FILE* = 0) const; + }; + } // namespace PCM + + + +} // namespace AS_02 + +#endif // _AS_02_H_ + +// +// end AS_02.h +// diff --git a/src/AS_02_JP2K.cpp b/src/AS_02_JP2K.cpp new file mode 100644 index 0000000..4b1db70 --- /dev/null +++ b/src/AS_02_JP2K.cpp @@ -0,0 +1,1139 @@ +/* + Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 AS_02_JP2K.cpp + \version $Id$ + \brief AS-02 library, JPEG 2000 essence reader and writer implementation +*/ + +#include "AS_02_internal.h" + +#include +#include + +using namespace ASDCP::JP2K; +using Kumu::GenRandomValue; + +//------------------------------------------------------------------------------------------ + +static std::string JP2K_PACKAGE_LABEL = "File Package: SMPTE 429-4 frame wrapping of JPEG 2000 codestreams"; +static std::string PICT_DEF_LABEL = "Image Track"; + +//------------------------------------------------------------------------------------------ +// +// hidden, internal implementation of JPEG 2000 reader + + +class lf__Reader : public AS_02::h__Reader +{ + RGBAEssenceDescriptor* m_EssenceDescriptor; + JPEG2000PictureSubDescriptor* m_EssenceSubDescriptor; + ASDCP::Rational m_EditRate; + ASDCP::Rational m_SampleRate; + EssenceType_t m_Format; + + ASDCP_NO_COPY_CONSTRUCT(lf__Reader); + +public: + PictureDescriptor m_PDesc; // codestream parameter list + + lf__Reader(const Dictionary& d) : + AS_02::h__Reader(d), m_EssenceDescriptor(0), m_EssenceSubDescriptor(0), m_Format(ESS_UNKNOWN) {} + Result_t OpenRead(const char*, EssenceType_t); + Result_t ReadFrame(ui32_t, JP2K::FrameBuffer&, AESDecContext*, HMACContext*); + Result_t MD_to_JP2K_PDesc(JP2K::PictureDescriptor& PDesc); + + Result_t OpenMXFRead(const char* filename); + // positions file before reading + Result_t ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC); + + // reads from current position + Result_t ReadEKLVPacket(ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC); + +}; + +// +ASDCP::Result_t +lf__Reader::MD_to_JP2K_PDesc(ASDCP::JP2K::PictureDescriptor& PDesc) +{ + memset(&PDesc, 0, sizeof(PDesc)); + MXF::RGBAEssenceDescriptor* PDescObj = (MXF::RGBAEssenceDescriptor*)m_EssenceDescriptor; + + PDesc.EditRate = m_EditRate; + PDesc.SampleRate = m_SampleRate; + assert(PDescObj->ContainerDuration <= 0xFFFFFFFFL); + PDesc.ContainerDuration = (ui32_t) PDescObj->ContainerDuration; + PDesc.StoredWidth = PDescObj->StoredWidth; + PDesc.StoredHeight = PDescObj->StoredHeight; + PDesc.AspectRatio = PDescObj->AspectRatio; + + if ( m_EssenceSubDescriptor != 0 ) + { + PDesc.Rsize = m_EssenceSubDescriptor->Rsize; + PDesc.Xsize = m_EssenceSubDescriptor->Xsize; + PDesc.Ysize = m_EssenceSubDescriptor->Ysize; + PDesc.XOsize = m_EssenceSubDescriptor->XOsize; + PDesc.YOsize = m_EssenceSubDescriptor->YOsize; + PDesc.XTsize = m_EssenceSubDescriptor->XTsize; + PDesc.YTsize = m_EssenceSubDescriptor->YTsize; + PDesc.XTOsize = m_EssenceSubDescriptor->XTOsize; + PDesc.YTOsize = m_EssenceSubDescriptor->YTOsize; + PDesc.Csize = m_EssenceSubDescriptor->Csize; + + // PictureComponentSizing + ui32_t tmp_size = m_EssenceSubDescriptor->PictureComponentSizing.Length(); + + if ( tmp_size == 17 ) // ( 2 * sizeof(ui32_t) ) + 3 components * 3 byte each + memcpy(&PDesc.ImageComponents, m_EssenceSubDescriptor->PictureComponentSizing.RoData() + 8, tmp_size - 8); + + else + DefaultLogSink().Error("Unexpected PictureComponentSizing size: %u, should be 17\n", tmp_size); + + // CodingStyleDefault + memset(&PDesc.CodingStyleDefault, 0, sizeof(CodingStyleDefault_t)); + memcpy(&PDesc.CodingStyleDefault, + m_EssenceSubDescriptor->CodingStyleDefault.RoData(), + m_EssenceSubDescriptor->CodingStyleDefault.Length()); + + // QuantizationDefault + memset(&PDesc.QuantizationDefault, 0, sizeof(QuantizationDefault_t)); + memcpy(&PDesc.QuantizationDefault, + m_EssenceSubDescriptor->QuantizationDefault.RoData(), + m_EssenceSubDescriptor->QuantizationDefault.Length()); + + PDesc.QuantizationDefault.SPqcdLength = m_EssenceSubDescriptor->QuantizationDefault.Length() - 1; + } + + return RESULT_OK; +} + +// +// +ASDCP::Result_t +lf__Reader::OpenRead(const char* filename, ASDCP::EssenceType_t type) +{ + Result_t result = OpenMXFRead(filename); + + if( ASDCP_SUCCESS(result) ) + { + InterchangeObject* tmp_iobj = 0; + m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(RGBAEssenceDescriptor), &tmp_iobj); + m_EssenceDescriptor = static_cast(tmp_iobj); + + m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(JPEG2000PictureSubDescriptor), &tmp_iobj); + m_EssenceSubDescriptor = static_cast(tmp_iobj); + + std::list ObjectList; + m_HeaderPart.GetMDObjectsByType(OBJ_TYPE_ARGS(Track), ObjectList); + + if ( ObjectList.empty() ) + { + DefaultLogSink().Error("MXF Metadata contains no Track Sets.\n"); + return RESULT_FORMAT; + } + + m_EditRate = ((Track*)ObjectList.front())->EditRate; + m_SampleRate = m_EssenceDescriptor->SampleRate; + + if ( type == ASDCP::ESS_JPEG_2000 ) + { + if ( m_EditRate != m_SampleRate ) + { + DefaultLogSink().Warn("EditRate and SampleRate do not match (%.03f, %.03f).\n", + m_EditRate.Quotient(), m_SampleRate.Quotient()); + + if ( m_EditRate == EditRate_24 && m_SampleRate == EditRate_48 ) + { + DefaultLogSink().Debug("File may contain JPEG Interop stereoscopic images.\n"); + return RESULT_SFORMAT; + } + + return RESULT_FORMAT; + } + } + else if ( type == ASDCP::ESS_JPEG_2000_S ) + { + if ( m_EditRate == EditRate_24 ) + { + if ( m_SampleRate != EditRate_48 ) + { + DefaultLogSink().Error("EditRate and SampleRate not correct for 24/48 stereoscopic essence.\n"); + return RESULT_FORMAT; + } + } + else if ( m_EditRate == EditRate_25 ) + { + if ( m_SampleRate != EditRate_50 ) + { + DefaultLogSink().Error("EditRate and SampleRate not correct for 25/50 stereoscopic essence.\n"); + return RESULT_FORMAT; + } + } + else if ( m_EditRate == EditRate_30 ) + { + if ( m_SampleRate != EditRate_60 ) + { + DefaultLogSink().Error("EditRate and SampleRate not correct for 30/60 stereoscopic essence.\n"); + return RESULT_FORMAT; + } + } + else + { + DefaultLogSink().Error("EditRate not correct for stereoscopic essence: %d/%d.\n", + m_EditRate.Numerator, m_EditRate.Denominator); + return RESULT_FORMAT; + } + } + else + { + DefaultLogSink().Error("'type' argument unexpected: %x\n", type); + return RESULT_STATE; + } + + result = MD_to_JP2K_PDesc(m_PDesc); + } + + if( ASDCP_SUCCESS(result) ) + result = InitMXFIndex(); + + if( ASDCP_SUCCESS(result) ) + result = InitInfo(); + + return result; +} + +// +// +ASDCP::Result_t +lf__Reader::ReadFrame(ui32_t FrameNum, JP2K::FrameBuffer& FrameBuf, + AESDecContext* Ctx, HMACContext* HMAC) +{ + if ( ! m_File.IsOpen() ) + return RESULT_INIT; + + assert(m_Dict); + return ReadEKLVFrame(FrameNum, FrameBuf, m_Dict->ul(MDD_JPEG2000Essence), Ctx, HMAC); +} + + +// +class AS_02::JP2K::MXFReader::h__Reader : public lf__Reader +{ + ASDCP_NO_COPY_CONSTRUCT(h__Reader); + h__Reader(); + +public: + h__Reader(const Dictionary& d) : lf__Reader(d) {} +}; + +AS_02::JP2K::MXFReader::MXFReader() +{ + m_Reader = new h__Reader(DefaultCompositeDict()); +} + + +AS_02::JP2K::MXFReader::~MXFReader() +{ +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +ASDCP::MXF::OPAtomHeader& +AS_02::JP2K::MXFReader::OPAtomHeader() +{ + if ( m_Reader.empty() ) + { + assert(g_OPAtomHeader); + return *g_OPAtomHeader; + } + + return m_Reader->m_HeaderPart; +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +/* +ASDCP::MXF::OPAtomIndexFooter& +AS_02::JP2K::MXFReader::OPAtomIndexFooter() +{ + if ( m_Reader.empty() ) + { + assert(g_OPAtomIndexFooter); + return *g_OPAtomIndexFooter; + } + + return m_Reader->m_FooterPart; +} +*/ + +// Open the file for reading. The file must exist. Returns error if the +// operation cannot be completed. +Result_t AS_02::JP2K::MXFReader::OpenRead(const char* filename) const +{ + return m_Reader->OpenRead(filename, ASDCP::ESS_JPEG_2000); +} + +// +Result_t AS_02::JP2K::MXFReader::ReadFrame(ui32_t FrameNum, ASDCP::JP2K::FrameBuffer& FrameBuf, + ASDCP::AESDecContext* Ctx, ASDCP::HMACContext* HMAC) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + return m_Reader->ReadFrame(FrameNum, FrameBuf, Ctx, HMAC); + + return RESULT_INIT; +} + + +// Fill the struct with the values from the file's header. +// Returns RESULT_INIT if the file is not open. +ASDCP::Result_t AS_02::JP2K::MXFReader::FillPictureDescriptor(PictureDescriptor& PDesc) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + { + PDesc = m_Reader->m_PDesc; + return RESULT_OK; + } + + return RESULT_INIT; +} + + +// Fill the struct with the values from the file's header. +// Returns RESULT_INIT if the file is not open. +ASDCP::Result_t AS_02::JP2K::MXFReader::FillWriterInfo(WriterInfo& Info) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + { + Info = m_Reader->m_Info; + return RESULT_OK; + } + + return RESULT_INIT; +} + +// +void +AS_02::JP2K::MXFReader::DumpHeaderMetadata(FILE* stream) const +{ + if ( m_Reader->m_File.IsOpen() ) + m_Reader->m_HeaderPart.Dump(stream); +} + + +// +void +AS_02::JP2K::MXFReader::DumpIndex(FILE* stream) const +{ + if ( m_Reader->m_File.IsOpen() ) + m_Reader->m_FooterPart.Dump(stream); +} + +// standard method of opening an MXF file for read +Result_t +lf__Reader::OpenMXFRead(const char* filename) +{ + m_LastPosition = 0; + AS_02::MXF::OP1aIndexBodyPartion* pCurrentBodyPartIndex = NULL; + Partition* pPart = NULL; + ui64_t EssenceStart = 0; + Result_t result = m_File.OpenRead(filename); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.InitFromFile(m_File); + + if ( ASDCP_SUCCESS(result) ) + { + ui32_t partition_size = m_HeaderPart.m_RIP.PairArray.size(); + + if ( partition_size > 3 ) + { + //for all entry except the first and the last(header&footer) + Array::iterator r_i = m_HeaderPart.m_RIP.PairArray.begin(); + r_i++; + ui32_t i=2; + + while(r_i != m_HeaderPart.m_RIP.PairArray.end() && im_Dict); + result = pPart->InitFromFile(m_File); + + if(pPart->BodySID != 0 && pPart->IndexSID == 0) + { // AS_02::IS_FOLLOW + r_i++; i++; + EssenceStart = m_File.Tell(); + + m_File.Seek((*r_i).ByteOffset); + pCurrentBodyPartIndex = new AS_02::MXF::OP1aIndexBodyPartion(this->m_Dict); + pCurrentBodyPartIndex->m_Lookup = &m_HeaderPart.m_Primer; + result = pCurrentBodyPartIndex->InitFromFile(m_File); + } + else + { // AS_02::IS_LEAD + delete pPart; + m_File.Seek((*r_i).ByteOffset); + pCurrentBodyPartIndex = new AS_02::MXF::OP1aIndexBodyPartion(this->m_Dict); + pCurrentBodyPartIndex->m_Lookup = &m_HeaderPart.m_Primer; + result = pCurrentBodyPartIndex->InitFromFile(m_File); + + if ( ASDCP_FAILURE(result) ) + { + break; + } + + r_i++; i++; + m_File.Seek((*r_i).ByteOffset); + pPart = new Partition(this->m_Dict); + result = pPart->InitFromFile(m_File); + EssenceStart = m_File.Tell(); + } + + if ( ASDCP_FAILURE(result) ) + { + break; + } + + if(i==3) + { + this->m_EssenceStart = EssenceStart; + this->m_pCurrentBodyPartition = pPart; + this->m_pCurrentIndexPartition = pCurrentBodyPartIndex; + } + + this->m_BodyPartList.push_back(pCurrentBodyPartIndex); + this->m_BodyPartList.push_back(pPart); + r_i++; i++; + } + } + } + + return result; +} + +// +class lf__Writer : public AS_02::h__Writer +{ + ASDCP_NO_COPY_CONSTRUCT(lf__Writer); + lf__Writer(); + + JPEG2000PictureSubDescriptor* m_EssenceSubDescriptor; + +public: + PictureDescriptor m_PDesc; + byte_t m_EssenceUL[SMPTE_UL_LENGTH]; + + //new attributes for AS-02 support + AS_02::IndexStrategy_t m_IndexStrategy; //Shim parameter index_strategy_frame/clip + ui32_t m_PartitionSpace; //Shim parameter partition_spacing + + lf__Writer(const Dictionary& d) : h__Writer(d), m_EssenceSubDescriptor(0), m_IndexStrategy(AS_02::IS_FOLLOW), m_PartitionSpace(60) { + memset(m_EssenceUL, 0, SMPTE_UL_LENGTH); + } + + ~lf__Writer(){} + + Result_t OpenWrite(const char*, EssenceType_t type, const AS_02::IndexStrategy_t& IndexStrategy, + const ui32_t& PartitionSpace, const ui32_t& HeaderSize); + Result_t SetSourceStream(const PictureDescriptor&, const std::string& label, + ASDCP::Rational LocalEditRate = ASDCP::Rational(0,0)); + Result_t WriteFrame(const JP2K::FrameBuffer&, bool add_index, AESEncContext*, HMACContext*); + Result_t Finalize(); + Result_t JP2K_PDesc_to_MD(JP2K::PictureDescriptor& PDesc); + + //void AddSourceClip(const MXF::Rational& EditRate, ui32_t TCFrameRate, + // const std::string& TrackName, const UL& EssenceUL, + // const UL& DataDefinition, const std::string& PackageLabel); + //void AddDMSegment(const MXF::Rational& EditRate, ui32_t TCFrameRate, + // const std::string& TrackName, const UL& DataDefinition, + // const std::string& PackageLabel); + //void AddEssenceDescriptor(const UL& WrappingUL); + //Result_t CreateBodyPart(const MXF::Rational& EditRate, ui32_t BytesPerEditUnit = 0); + + ////new method to create BodyPartition for essence and index + //Result_t CreateBodyPartPair(); + ////new method to finalize BodyPartion(index) + //Result_t CompleteIndexBodyPart(); + + // reimplement these functions in AS_02_PCM to support modifications for AS-02 + //Result_t WriteEKLVPacket(const ASDCP::FrameBuffer& FrameBuf, + // const byte_t* EssenceUL, AESEncContext* Ctx, HMACContext* HMAC); + Result_t WriteMXFFooter(); + + +}; + +const int VideoLineMapSize = 16; // See SMPTE 377M D.2.1 +const int PixelLayoutSize = 8*2; // See SMPTE 377M D.2.3 +static const byte_t s_PixelLayoutXYZ[PixelLayoutSize] = { 0xd8, 0x0c, 0xd9, 0x0c, 0xda, 0x0c, 0x00 }; + +// +ASDCP::Result_t +lf__Writer::JP2K_PDesc_to_MD(JP2K::PictureDescriptor& PDesc) +{ + assert(m_EssenceDescriptor); + assert(m_EssenceSubDescriptor); + MXF::RGBAEssenceDescriptor* PDescObj = (MXF::RGBAEssenceDescriptor*)m_EssenceDescriptor; + + PDescObj->ContainerDuration = PDesc.ContainerDuration; + PDescObj->SampleRate = PDesc.EditRate; + PDescObj->FrameLayout = 0; + PDescObj->StoredWidth = PDesc.StoredWidth; + PDescObj->StoredHeight = PDesc.StoredHeight; + PDescObj->AspectRatio = PDesc.AspectRatio; + + // if ( m_Info.LabelSetType == LS_MXF_SMPTE ) + // { + // PictureEssenceCoding UL = + // Video Line Map ui32_t[VideoLineMapSize] = { 2, 4, 0, 0 } + // CaptureGamma UL = + // ComponentMaxRef ui32_t = 4095 + // ComponentMinRef ui32_t = 0 + // PixelLayout byte_t[PixelLayoutSize] = s_PixelLayoutXYZ + // } + + assert(m_Dict); + if ( PDesc.StoredWidth < 2049 ) + { + PDescObj->PictureEssenceCoding.Set(m_Dict->ul(MDD_JP2KEssenceCompression_2K)); + m_EssenceSubDescriptor->Rsize = 3; + } + else + { + PDescObj->PictureEssenceCoding.Set(m_Dict->ul(MDD_JP2KEssenceCompression_4K)); + m_EssenceSubDescriptor->Rsize = 4; + } + + m_EssenceSubDescriptor->Xsize = PDesc.Xsize; + m_EssenceSubDescriptor->Ysize = PDesc.Ysize; + m_EssenceSubDescriptor->XOsize = PDesc.XOsize; + m_EssenceSubDescriptor->YOsize = PDesc.YOsize; + m_EssenceSubDescriptor->XTsize = PDesc.XTsize; + m_EssenceSubDescriptor->YTsize = PDesc.YTsize; + m_EssenceSubDescriptor->XTOsize = PDesc.XTOsize; + m_EssenceSubDescriptor->YTOsize = PDesc.YTOsize; + m_EssenceSubDescriptor->Csize = PDesc.Csize; + + const ui32_t tmp_buffer_len = 1024; + byte_t tmp_buffer[tmp_buffer_len]; + + // slh: this has to be done dynamically since the number of components is not always 3 + *(ui32_t*)tmp_buffer = KM_i32_BE(m_EssenceSubDescriptor->Csize); + *(ui32_t*)(tmp_buffer+4) = KM_i32_BE(sizeof(ASDCP::JP2K::ImageComponent_t)); + memcpy(tmp_buffer + 8, &PDesc.ImageComponents, sizeof(ASDCP::JP2K::ImageComponent_t) * m_EssenceSubDescriptor->Csize); + const ui32_t pcomp_size = (sizeof(int) * 2) + (sizeof(ASDCP::JP2K::ImageComponent_t) * m_EssenceSubDescriptor->Csize); + + /* + *(ui32_t*)tmp_buffer = KM_i32_BE(MaxComponents); // three components + *(ui32_t*)(tmp_buffer+4) = KM_i32_BE(sizeof(ASDCP::JP2K::ImageComponent_t)); + memcpy(tmp_buffer + 8, &PDesc.ImageComponents, sizeof(ASDCP::JP2K::ImageComponent_t) * MaxComponents); + const ui32_t pcomp_size = (sizeof(int) * 2) + (sizeof(ASDCP::JP2K::ImageComponent_t) * MaxComponents); + */ + + memcpy(m_EssenceSubDescriptor->PictureComponentSizing.Data(), tmp_buffer, pcomp_size); + m_EssenceSubDescriptor->PictureComponentSizing.Length(pcomp_size); + + ui32_t precinct_set_size = 0, i; + for ( i = 0; PDesc.CodingStyleDefault.SPcod.PrecinctSize[i] != 0 && i < MaxPrecincts; i++ ) + precinct_set_size++; + + ui32_t csd_size = sizeof(CodingStyleDefault_t) - MaxPrecincts + precinct_set_size; + memcpy(m_EssenceSubDescriptor->CodingStyleDefault.Data(), &PDesc.CodingStyleDefault, csd_size); + m_EssenceSubDescriptor->CodingStyleDefault.Length(csd_size); + + ui32_t qdflt_size = PDesc.QuantizationDefault.SPqcdLength + 1; + memcpy(m_EssenceSubDescriptor->QuantizationDefault.Data(), &PDesc.QuantizationDefault, qdflt_size); + m_EssenceSubDescriptor->QuantizationDefault.Length(qdflt_size); + + return RESULT_OK; +} + + +// Open the file for writing. The file must not exist. Returns error if +// the operation cannot be completed. +ASDCP::Result_t +lf__Writer::OpenWrite(const char* filename, EssenceType_t type, const AS_02::IndexStrategy_t& IndexStrategy, + const ui32_t& PartitionSpace, const ui32_t& HeaderSize) +{ + if ( ! m_State.Test_BEGIN() ) + return RESULT_STATE; + + ASDCP::Result_t result = m_File.OpenWrite(filename); + + if ( ASDCP_SUCCESS(result) ) + { + m_IndexStrategy = IndexStrategy; + m_PartitionSpace = PartitionSpace; + m_HeaderSize = HeaderSize; + RGBAEssenceDescriptor* tmp_rgba = new RGBAEssenceDescriptor(m_Dict); + tmp_rgba->ComponentMaxRef = 4095; + tmp_rgba->ComponentMinRef = 0; + + m_EssenceDescriptor = tmp_rgba; + m_EssenceSubDescriptor = new JPEG2000PictureSubDescriptor(m_Dict); + m_EssenceSubDescriptorList.push_back((InterchangeObject*)m_EssenceSubDescriptor); + + GenRandomValue(m_EssenceSubDescriptor->InstanceUID); + m_EssenceDescriptor->SubDescriptors.push_back(m_EssenceSubDescriptor->InstanceUID); + result = m_State.Goto_INIT(); + } + + return result; +} + +// Automatically sets the MXF file's metadata from the first jpeg codestream stream. +ASDCP::Result_t +lf__Writer::SetSourceStream(const PictureDescriptor& PDesc, const std::string& label, ASDCP::Rational LocalEditRate) +{ + assert(m_Dict); + if ( ! m_State.Test_INIT() ) + return RESULT_STATE; + + if ( LocalEditRate == ASDCP::Rational(0,0) ) + LocalEditRate = PDesc.EditRate; + + m_PDesc = PDesc; + Result_t result = JP2K_PDesc_to_MD(m_PDesc); + + if ( ASDCP_SUCCESS(result) ) + { + memcpy(m_EssenceUL, m_Dict->ul(MDD_JPEG2000Essence), SMPTE_UL_LENGTH); + m_EssenceUL[SMPTE_UL_LENGTH-1] = 1; // first (and only) essence container + result = m_State.Goto_READY(); + } + + if ( ASDCP_SUCCESS(result) ) + { + ui32_t TCFrameRate = ( m_PDesc.EditRate == EditRate_23_98 ) ? 24 : m_PDesc.EditRate.Numerator; + + result = WriteMXFHeader(label, UL(m_Dict->ul(MDD_JPEG_2000Wrapping)), + PICT_DEF_LABEL, UL(m_EssenceUL), UL(m_Dict->ul(MDD_PictureDataDef)), + LocalEditRate, TCFrameRate); + } + + return result; +} + +// Writes a frame of essence to the MXF file. If the optional AESEncContext +// argument is present, the essence is encrypted prior to writing. +// Fails if the file is not open, is finalized, or an operating system +// error occurs. +// +ASDCP::Result_t +lf__Writer::WriteFrame(const ASDCP::JP2K::FrameBuffer& FrameBuf, bool add_index, + AESEncContext* Ctx, HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + + if ( m_State.Test_READY() ){ + result = m_State.Goto_RUNNING(); // first time through + } + ui64_t StreamOffset = m_StreamOffset; + + if ( ASDCP_SUCCESS(result) ) + result = WriteEKLVPacket(FrameBuf, m_EssenceUL, Ctx, HMAC); + + if ( ASDCP_SUCCESS(result) && add_index ) + { + //create new Index and add it to the IndexTableSegment in the IndexPartition + IndexTableSegment::IndexEntry Entry; + Entry.StreamOffset = StreamOffset; + m_CurrentIndexBodyPartition->m_FramesWritten = m_FramesWritten; + m_CurrentIndexBodyPartition->PushIndexEntry(Entry); + + //here we must check if the number of frames per partition are reached + if(m_FramesWritten!=0 &&((m_FramesWritten+1) % m_PartitionSpace) == 0){ + this->m_BodyOffset += m_StreamOffset; + //StreamOffset - Offset in bytes from the start of the Essence + //Container of first Essence Element in this Edit Unit of + //stored Essence within the Essence Container Stream + //this->m_StreamOffset = 0; ??? + + //Complete the Index-BodyPartion + result = CompleteIndexBodyPart(); + //Create new BodyPartions for Essence and Index + result = CreateBodyPartPair(); + } + //else do nothing, we must only insert the current frame + //else{} + } + m_FramesWritten++; + return result; +} + + +// Closes the MXF file, writing the index and other closing information. +// +ASDCP::Result_t +lf__Writer::Finalize() +{ + Result_t result = RESULT_OK; + + if ( ! m_State.Test_RUNNING() ) + return RESULT_STATE; + + m_State.Goto_FINAL(); + + //the last Frame was written, complete the BodyPartion(Index), after that write the MXF-Footer + result = CompleteIndexBodyPart(); + + if ( ASDCP_FAILURE(result) ){ + return result; + } + return WriteMXFFooter(); +} + + +// +class AS_02::JP2K::MXFWriter::h__Writer : public lf__Writer +{ + ASDCP_NO_COPY_CONSTRUCT(h__Writer); + h__Writer(); + +public: + h__Writer(const Dictionary& d) : lf__Writer(d) {} +}; + + +//------------------------------------------------------------------------------------------ + + + +AS_02::JP2K::MXFWriter::MXFWriter() +{ +} + +AS_02::JP2K::MXFWriter::~MXFWriter() +{ +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +ASDCP::MXF::OPAtomHeader& +AS_02::JP2K::MXFWriter::OPAtomHeader() +{ + if ( m_Writer.empty() ) + { + assert(g_OPAtomHeader); + return *g_OPAtomHeader; + } + + return m_Writer->m_HeaderPart; +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +/* +ASDCP::MXF::OPAtomIndexFooter& +AS_02::JP2K::MXFWriter::OPAtomIndexFooter() +{ + if ( m_Writer.empty() ) + { + assert(g_OPAtomIndexFooter); + return *g_OPAtomIndexFooter; + } + + return m_Writer->m_FooterPart; +} +*/ + +// Open the file for writing. The file must not exist. Returns error if +// the operation cannot be completed. +ASDCP::Result_t +AS_02::JP2K::MXFWriter::OpenWrite(const char* filename, const ASDCP::WriterInfo& Info, + const ASDCP::JP2K::PictureDescriptor& PDesc, + const IndexStrategy_t& Strategy, + const ui32_t& PartitionSpace, + const ui32_t& HeaderSize) +{ + m_Writer = new AS_02::JP2K::MXFWriter::h__Writer(DefaultSMPTEDict()); + m_Writer->m_Info = Info; + + ASDCP::Result_t result = m_Writer->OpenWrite(filename, ASDCP::ESS_JPEG_2000, Strategy, PartitionSpace, HeaderSize); + + if ( ASDCP_SUCCESS(result) ) + result = m_Writer->SetSourceStream(PDesc, JP2K_PACKAGE_LABEL); + + if ( ASDCP_FAILURE(result) ) + m_Writer.release(); + + return result; +} + + +// Writes a frame of essence to the MXF file. If the optional AESEncContext +// argument is present, the essence is encrypted prior to writing. +// Fails if the file is not open, is finalized, or an operating system +// error occurs. +ASDCP::Result_t +AS_02::JP2K::MXFWriter::WriteFrame(const ASDCP::JP2K::FrameBuffer& FrameBuf, AESEncContext* Ctx, HMACContext* HMAC) +{ + if ( m_Writer.empty() ) + return RESULT_INIT; + + return m_Writer->WriteFrame(FrameBuf, true, Ctx, HMAC); +} + +// Closes the MXF file, writing the index and other closing information. +ASDCP::Result_t +AS_02::JP2K::MXFWriter::Finalize() +{ + if ( m_Writer.empty() ) + return RESULT_INIT; + + return m_Writer->Finalize(); +} + + +//------------------------------------------------------------------------------------------ + +// standard method of reading a plaintext or encrypted frame +Result_t +lf__Reader::ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + IndexTableSegment::IndexEntry TmpEntry; + + assert(m_pCurrentIndexPartition != NULL); + + if( m_pCurrentIndexPartition->Lookup(FrameNum, TmpEntry, m_start_pos) == false) + { + m_start_pos = 0; + + //compute new indexPartition for this FrameNum + for (ui32_t i = 0; i < m_BodyPartList.size(); i+=2 ) + { + if( m_IndexStrategy == AS_02::IS_FOLLOW ) + { + m_pCurrentBodyPartition = m_BodyPartList.at(i); + m_pCurrentIndexPartition = dynamic_cast (m_BodyPartList.at(i+1)); + } + else if( m_IndexStrategy == AS_02::IS_LEAD ) + { + m_pCurrentIndexPartition = dynamic_cast (m_BodyPartList.at(i)); + m_pCurrentBodyPartition = m_BodyPartList.at(i+1); + } + else + { + return RESULT_FORMAT; //return error + } + + if( m_pCurrentIndexPartition == 0 ) + return RESULT_FORMAT; + + if(m_pCurrentIndexPartition->Lookup(FrameNum, TmpEntry, m_start_pos)) + { + if ( FrameNum % m_PartitionSpace == 0 ) + { + ui64_t offset = m_pCurrentBodyPartition->ThisPartition - m_pCurrentBodyPartition->PreviousPartition; + offset += m_pCurrentBodyPartition->ArchiveSize();//Offset for the BodyPartitionHeader - Partition::ArchiveSize(); + m_EssenceStart += offset; + } + break; + } + } + } + + // get frame position and go read the frame's key and length + Kumu::fpos_t FilePosition = this->m_EssenceStart + TmpEntry.StreamOffset; + + if ( FilePosition != m_LastPosition ) + { + m_LastPosition = FilePosition; + result = m_File.Seek(FilePosition); + } + + if( ASDCP_SUCCESS(result) ) + result = ReadEKLVPacket(FrameNum, FrameNum + 1, FrameBuf, EssenceUL, Ctx, HMAC); + + return result; +} + +// +Result_t +lf__Reader::ReadEKLVPacket(ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) +{ + KLReader Reader; + Result_t result = Reader.ReadKLFromFile(m_File); + + if ( ASDCP_FAILURE(result) ) + return result; + + UL Key(Reader.Key()); + ui64_t PacketLength = Reader.Length(); + m_LastPosition = m_LastPosition + Reader.KLLength() + PacketLength; + assert(m_Dict); + + if ( memcmp(Key.Value(), m_Dict->ul(MDD_CryptEssence), Key.Size() - 1) == 0 ) // ignore the stream numbers + { + if ( ! m_Info.EncryptedEssence ) + { + DefaultLogSink().Error("EKLV packet found, no Cryptographic Context in header.\n"); + return RESULT_FORMAT; + } + + // read encrypted triplet value into internal buffer + assert(PacketLength <= 0xFFFFFFFFL); + m_CtFrameBuf.Capacity((ui32_t) PacketLength); + ui32_t read_count; + result = m_File.Read(m_CtFrameBuf.Data(), (ui32_t) PacketLength, + &read_count); + + if ( ASDCP_FAILURE(result) ) + return result; + + if ( read_count != PacketLength ) + { + DefaultLogSink().Error("read length is smaller than EKLV packet length.\n"); + return RESULT_FORMAT; + } + + m_CtFrameBuf.Size((ui32_t) PacketLength); + + // should be const but mxflib::ReadBER is not + byte_t* ess_p = m_CtFrameBuf.Data(); + + // read context ID length + if ( ! Kumu::read_test_BER(&ess_p, UUIDlen) ) + return RESULT_FORMAT; + + // test the context ID + if ( memcmp(ess_p, m_Info.ContextID, UUIDlen) != 0 ) + { + DefaultLogSink().Error("Packet's Cryptographic Context ID does not match the header.\n"); + return RESULT_FORMAT; + } + ess_p += UUIDlen; + + // read PlaintextOffset length + if ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) ) + return RESULT_FORMAT; + + ui32_t PlaintextOffset = (ui32_t)KM_i64_BE(Kumu::cp2i(ess_p)); + ess_p += sizeof(ui64_t); + + // read essence UL length + if ( ! Kumu::read_test_BER(&ess_p, SMPTE_UL_LENGTH) ) + return RESULT_FORMAT; + + // test essence UL + if ( memcmp(ess_p, EssenceUL, SMPTE_UL_LENGTH - 1) != 0 ) // ignore the stream number + { + char strbuf[IntBufferLen]; + const MDDEntry* Entry = m_Dict->FindUL(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 ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) ) + return RESULT_FORMAT; + + ui32_t SourceLength = (ui32_t)KM_i64_BE(Kumu::cp2i(ess_p)); + ess_p += sizeof(ui64_t); + assert(SourceLength); + + if ( 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 ( ! Kumu::read_test_BER(&ess_p, 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); + + if ( PacketLength < tmp_len ) + { + DefaultLogSink().Error("Frame length is larger than EKLV packet length.\n"); + return RESULT_FORMAT; + } + + if ( Ctx ) + { + // wrap the pointer and length as a FrameBuffer for use by + // DecryptFrameBuffer() and TestValues() + ASDCP::FrameBuffer TmpWrapper; + TmpWrapper.SetData(ess_p, tmp_len); + TmpWrapper.Size(tmp_len); + TmpWrapper.SourceLength(SourceLength); + TmpWrapper.PlaintextOffset(PlaintextOffset); + + result = DecryptFrameBuffer(TmpWrapper, FrameBuf, Ctx); + FrameBuf.FrameNumber(FrameNum); + + // detect and test integrity pack + if ( ASDCP_SUCCESS(result) && m_Info.UsesHMAC && HMAC ) + { + IntegrityPack IntPack; + result = IntPack.TestValues(TmpWrapper, m_Info.AssetUUID, SequenceNum, HMAC); + } + } + else // return ciphertext to caller + { + if ( FrameBuf.Capacity() < tmp_len ) + { + 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 ( memcmp(Key.Value(), EssenceUL, Key.Size() - 1) == 0 ) // ignore the stream number + { // read plaintext frame + if ( FrameBuf.Capacity() < PacketLength ) + { + char intbuf[IntBufferLen]; + 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; + assert(PacketLength <= 0xFFFFFFFFL); + result = m_File.Read(FrameBuf.Data(), (ui32_t) PacketLength, &read_count); + + if ( ASDCP_FAILURE(result) ) + return result; + + if ( read_count != PacketLength ) + { + char intbuf1[IntBufferLen]; + char intbuf2[IntBufferLen]; + DefaultLogSink().Error("read_count: %s != FrameLength: %s\n", + ui64sz(read_count, intbuf1), + ui64sz(PacketLength, intbuf2) ); + + return RESULT_READFAIL; + } + + FrameBuf.FrameNumber(FrameNum); + FrameBuf.Size(read_count); + } + else + { + char strbuf[IntBufferLen]; + const MDDEntry* Entry = m_Dict->FindUL(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; + } + + return result; +} + + +// standard method of writing the header and footer of a completed MXF file +// +Result_t +lf__Writer::WriteMXFFooter() +{ + // Set top-level file package correctly for OP-Atom + + // m_MPTCSequence->Duration = m_MPTimecode->Duration = m_MPClSequence->Duration = m_MPClip->Duration = + // m_FPTCSequence->Duration = m_FPTimecode->Duration = m_FPClSequence->Duration = m_FPClip->Duration = + + DurationElementList_t::iterator dli = m_DurationUpdateList.begin(); + + for (; dli != m_DurationUpdateList.end(); dli++ ) + **dli = m_FramesWritten; + + m_EssenceDescriptor->ContainerDuration = m_FramesWritten; + m_FooterPart.PreviousPartition = m_HeaderPart.m_RIP.PairArray.back().ByteOffset; + + Kumu::fpos_t here = m_File.Tell(); + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(0, here)); // Last RIP Entry + m_HeaderPart.FooterPartition = here; + + assert(m_Dict); + // re-label the partition + UL OPAtomUL(m_Dict->ul(MDD_OP1a)); + m_HeaderPart.OperationalPattern = OPAtomUL; + m_HeaderPart.m_Preface->OperationalPattern = m_HeaderPart.OperationalPattern; + + m_FooterPart.OperationalPattern = m_HeaderPart.OperationalPattern; + m_FooterPart.EssenceContainers = m_HeaderPart.EssenceContainers; + m_FooterPart.FooterPartition = here; + m_FooterPart.ThisPartition = here; + + Result_t result = m_FooterPart.WriteToFile(m_File, m_FramesWritten); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.m_RIP.WriteToFile(m_File); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Seek(0); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.WriteToFile(m_File, m_HeaderSize); + + //update the value of FooterPartition in all Partitions + std::vector::iterator iter = this->m_BodyPartList.begin(); + for (; iter != this->m_BodyPartList.end(); iter++ ){ + (*iter)->FooterPartition = m_FooterPart.ThisPartition; + if ( ASDCP_SUCCESS(result) ) + result = m_File.Seek((*iter)->ThisPartition); + if ( ASDCP_SUCCESS(result) ){ + UL BodyUL(m_Dict->ul(MDD_ClosedCompleteBodyPartition)); + result = (*iter)->WriteToFile(m_File, BodyUL); + } + } + + m_File.Close(); + return result; +} + +// +// end AS_02_JP2K.cpp +// diff --git a/src/AS_02_PCM.cpp b/src/AS_02_PCM.cpp new file mode 100644 index 0000000..cf8995e --- /dev/null +++ b/src/AS_02_PCM.cpp @@ -0,0 +1,1095 @@ +/* + Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 AS_02_PCM.cpp + \version $Id$ + \brief AS-02 library, PCM essence reader and writer implementation +*/ + +#include "AS_02_internal.h" + +#include +#include +#include + +//------------------------------------------------------------------------------------------ + +static std::string PCM_PACKAGE_LABEL = "File Package: SMPTE 382M clip wrapping of wave audio"; +static std::string SOUND_DEF_LABEL = "Sound Track"; + +static byte_t SNDFMT_CFG_1_UL[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0b, + 0x04, 0x02, 0x02, 0x10, 0x03, 0x01, 0x01, 0x00 }; + +static byte_t SNDFMT_CFG_2_UL[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0b, + 0x04, 0x02, 0x02, 0x10, 0x03, 0x01, 0x02, 0x00 }; + +static byte_t SNDFMT_CFG_3_UL[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0b, + 0x04, 0x02, 0x02, 0x10, 0x03, 0x01, 0x03, 0x00 }; + +//this must be changed because the CBR_frame_size is only +// +static ui32_t +calc_CBR_frame_size(ASDCP::WriterInfo& Info, const ASDCP::PCM::AudioDescriptor& ADesc) +{ + ui32_t CBR_frame_size = 0; + + if ( Info.EncryptedEssence ) + { + CBR_frame_size = + //TODO: correct? + /*SMPTE_UL_LENGTH + + MXF_BER_LENGTH + + */klv_cryptinfo_size + + calc_esv_length(ASDCP::PCM::CalcFrameBufferSize(ADesc), 0) + + ( Info.UsesHMAC ? klv_intpack_size : (MXF_BER_LENGTH * 3) ); + } + else + { + CBR_frame_size = ASDCP::PCM::CalcFrameBufferSize(ADesc); + } + + return CBR_frame_size; +} + + +//------------------------------------------------------------------------------------------ + + +class AS_02::PCM::MXFReader::h__Reader : public AS_02::h__Reader +{ + ASDCP_NO_COPY_CONSTRUCT(h__Reader); + h__Reader(); + +public: + ASDCP::PCM::AudioDescriptor m_ADesc; + + h__Reader(const Dictionary& d) : AS_02::h__Reader(d) {} + ~h__Reader() {} + ASDCP::Result_t OpenRead(const char*); + ASDCP::Result_t ReadFrame(ui32_t, ASDCP::PCM::FrameBuffer&, ASDCP::AESDecContext*, ASDCP::HMACContext*); + + + Result_t OpenMXFRead(const char* filename); + // positions file before reading + Result_t ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC); + + // reads from current position + Result_t ReadEKLVPacket(ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC); + + +}; + + +// +// +ASDCP::Result_t +AS_02::PCM::MXFReader::h__Reader::OpenRead(const char* filename) +{ + Result_t result = OpenMXFRead(filename); + + if( ASDCP_SUCCESS(result) ) + { + InterchangeObject* Object; + if ( ASDCP_SUCCESS(m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(WaveAudioDescriptor), &Object)) ) + { + assert(Object); + result = MD_to_PCM_ADesc((ASDCP::MXF::WaveAudioDescriptor*)Object, m_ADesc); + } + } + + // check for sample/frame rate sanity + if ( ASDCP_SUCCESS(result) + && m_ADesc.EditRate != EditRate_24 + && m_ADesc.EditRate != EditRate_25 + && m_ADesc.EditRate != EditRate_30 + && m_ADesc.EditRate != EditRate_48 + && m_ADesc.EditRate != EditRate_50 + && m_ADesc.EditRate != EditRate_60 + && m_ADesc.EditRate != EditRate_23_98 ) + { + DefaultLogSink().Error("PCM file EditRate is not a supported value: %d/%d\n", // lu + m_ADesc.EditRate.Numerator, m_ADesc.EditRate.Denominator); + + // oh, they gave us the audio sampling rate instead, assume 24/1 + if ( m_ADesc.EditRate == SampleRate_48k ) + { + DefaultLogSink().Warn("adjusting EditRate to 24/1\n"); + m_ADesc.EditRate = EditRate_24; + } + else + { + // or we just drop the hammer + return RESULT_FORMAT; + } + } + + if( ASDCP_SUCCESS(result) ) + result = InitMXFIndex(); + + if( ASDCP_SUCCESS(result) ) + result = InitInfo(); + + // TODO: test file for sane CBR index BytesPerEditUnit + + return result; +} + + +// +// +ASDCP::Result_t +AS_02::PCM::MXFReader::h__Reader::ReadFrame(ui32_t FrameNum, ASDCP::PCM::FrameBuffer& FrameBuf, + ASDCP::AESDecContext* Ctx, ASDCP::HMACContext* HMAC) +{ + if ( ! m_File.IsOpen() ) + return RESULT_INIT; + + assert(m_Dict); + return ReadEKLVFrame(FrameNum, FrameBuf, m_Dict->ul(MDD_WAVEssence), Ctx, HMAC); +} + + +AS_02::PCM::MXFReader::MXFReader() +{ + m_Reader = new h__Reader(DefaultCompositeDict()); +} + + +AS_02::PCM::MXFReader::~MXFReader() +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + m_Reader->Close(); +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +ASDCP::MXF::OPAtomHeader& +AS_02::PCM::MXFReader::OPAtomHeader() +{ + if ( m_Reader.empty() ) + { + assert(g_OPAtomHeader); + return *g_OPAtomHeader; + } + + return m_Reader->m_HeaderPart; +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +/* +ASDCP::MXF::OPAtomIndexFooter& +AS_02::PCM::MXFReader::OPAtomIndexFooter() +{ + if ( m_Reader.empty() ) + { + assert(g_OPAtomIndexFooter); + return *g_OPAtomIndexFooter; + } + + return m_Reader->m_FooterPart; +} +*/ + +// Open the file for reading. The file must exist. Returns error if the +// operation cannot be completed. +ASDCP::Result_t +AS_02::PCM::MXFReader::OpenRead(const char* filename) const +{ + return m_Reader->OpenRead(filename); +} + +// Reads a frame of essence from the MXF file. If the optional AESEncContext +// argument is present, the essence is decrypted after reading. If the MXF +// file is encrypted and the AESDecContext argument is NULL, the frame buffer +// will contain the ciphertext frame data. +ASDCP::Result_t +AS_02::PCM::MXFReader::ReadFrame(ui32_t FrameNum, ASDCP::PCM::FrameBuffer& FrameBuf, + ASDCP::AESDecContext* Ctx, ASDCP::HMACContext* HMAC) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + return m_Reader->ReadFrame(FrameNum, FrameBuf, Ctx, HMAC); + + return RESULT_INIT; +} + + +// Fill the struct with the values from the file's header. +// Returns RESULT_INIT if the file is not open. +ASDCP::Result_t +AS_02::PCM::MXFReader::FillAudioDescriptor(ASDCP::PCM::AudioDescriptor& ADesc) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + { + ADesc = m_Reader->m_ADesc; + return RESULT_OK; + } + + return RESULT_INIT; +} + +// Fill the struct with the values from the file's header. +// Returns RESULT_INIT if the file is not open. +ASDCP::Result_t +AS_02::PCM::MXFReader::FillWriterInfo(WriterInfo& Info) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + { + Info = m_Reader->m_Info; + return RESULT_OK; + } + + return RESULT_INIT; +} + +// +void +AS_02::PCM::MXFReader::DumpHeaderMetadata(FILE* stream) const +{ + if ( m_Reader && m_Reader->m_File.IsOpen() ) + m_Reader->m_HeaderPart.Dump(stream); +} + + +// +void +AS_02::PCM::MXFReader::DumpIndex(FILE* stream) const +{ + if ( m_Reader->m_File.IsOpen() ) + m_Reader->m_FooterPart.Dump(stream); +} + + +//------------------------------------------------------------------------------------------ + +// +class AS_02::PCM::MXFWriter::h__Writer : public AS_02::h__Writer +{ + ASDCP_NO_COPY_CONSTRUCT(h__Writer); + h__Writer(); + +public: + ASDCP::PCM::AudioDescriptor m_ADesc; + byte_t m_EssenceUL[SMPTE_UL_LENGTH]; + ui64_t m_KLV_start; + + h__Writer(const Dictionary& d) : AS_02::h__Writer(d), m_KLV_start(0){ + memset(m_EssenceUL, 0, SMPTE_UL_LENGTH); + + } + + ~h__Writer(){} + + Result_t OpenWrite(const char*, ui32_t HeaderSize); + Result_t SetSourceStream(const ASDCP::PCM::AudioDescriptor&); + Result_t WriteFrame(const FrameBuffer&, ASDCP::AESEncContext* = 0, ASDCP::HMACContext* = 0); + + Result_t Finalize(); + + //void AddSourceClip(const MXF::Rational& EditRate, ui32_t TCFrameRate, + // const std::string& TrackName, const UL& EssenceUL, + // const UL& DataDefinition, const std::string& PackageLabel); + //void AddDMSegment(const MXF::Rational& EditRate, ui32_t TCFrameRate, + // const std::string& TrackName, const UL& DataDefinition, + // const std::string& PackageLabel); + //void AddEssenceDescriptor(const UL& WrappingUL); + //Result_t CreateBodyPart(const MXF::Rational& EditRate, ui32_t BytesPerEditUnit = 0); + + ////new method to create BodyPartition for essence and index + //Result_t CreateBodyPartPair(); + ////new method to finalize BodyPartion(index) + //Result_t CompleteIndexBodyPart(); + + // reimplement these functions in AS_02_PCM to support modifications for AS-02 + Result_t WriteEKLVPacket(const ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESEncContext* Ctx, HMACContext* HMAC); + Result_t WriteMXFFooter(); + +}; + +// Open the file for writing. The file must not exist. Returns error if +// the operation cannot be completed. +ASDCP::Result_t +AS_02::PCM::MXFWriter::h__Writer::OpenWrite(const char* filename, ui32_t HeaderSize) +{ + if ( ! m_State.Test_BEGIN() ) + return RESULT_STATE; + + Result_t result = m_File.OpenWrite(filename); + + if ( ASDCP_SUCCESS(result) ) + { + m_HeaderSize = HeaderSize; + m_EssenceDescriptor = new WaveAudioDescriptor(m_Dict); + result = m_State.Goto_INIT(); + } + + return result; +} + + +// Automatically sets the MXF file's metadata from the WAV parser info. +ASDCP::Result_t +AS_02::PCM::MXFWriter::h__Writer::SetSourceStream(const ASDCP::PCM::AudioDescriptor& ADesc) +{ + if ( ! m_State.Test_INIT() ) + return RESULT_STATE; + + if ( ADesc.EditRate != EditRate_24 + && ADesc.EditRate != EditRate_25 + && ADesc.EditRate != EditRate_30 + && ADesc.EditRate != EditRate_48 + && ADesc.EditRate != EditRate_50 + && ADesc.EditRate != EditRate_60 + && ADesc.EditRate != EditRate_23_98 ) + { + DefaultLogSink().Error("AudioDescriptor.EditRate is not a supported value: %d/%d\n", + ADesc.EditRate.Numerator, ADesc.EditRate.Denominator); + return RESULT_RAW_FORMAT; + } + + if ( ADesc.AudioSamplingRate != SampleRate_48k && ADesc.AudioSamplingRate != SampleRate_96k ) + { + DefaultLogSink().Error("AudioDescriptor.AudioSamplingRate is not 48000/1 or 96000/1: %d/%d\n", + ADesc.AudioSamplingRate.Numerator, ADesc.AudioSamplingRate.Denominator); + return RESULT_RAW_FORMAT; + } + + assert(m_Dict); + m_ADesc = ADesc; + + Result_t result = PCM_ADesc_to_MD(m_ADesc, (WaveAudioDescriptor*)m_EssenceDescriptor); + + if ( ASDCP_SUCCESS(result) ) + { + memcpy(m_EssenceUL, m_Dict->ul(MDD_WAVEssence), SMPTE_UL_LENGTH); + //SMPTE 382M-2007: ByteNo. 15 - 02h - Wave Clip-Wrapped Element + m_EssenceUL[SMPTE_UL_LENGTH-2] = 2; // 02h - Wave Clip-Wrapped Element + m_EssenceUL[SMPTE_UL_LENGTH-1] = 1; // first (and only) essence container + result = m_State.Goto_READY(); + } + + if ( ASDCP_SUCCESS(result) ) + { + ui32_t TCFrameRate = ( m_ADesc.EditRate == EditRate_23_98 ) ? 24 : m_ADesc.EditRate.Numerator; + + result = WriteMXFHeader(PCM_PACKAGE_LABEL, UL(m_Dict->ul(MDD_WAVWrapping)), + SOUND_DEF_LABEL, UL(m_EssenceUL), UL(m_Dict->ul(MDD_SoundDataDef)), + m_ADesc.EditRate, TCFrameRate, calc_CBR_frame_size(m_Info, m_ADesc)); + } + + return result; +} + + +// +// +ASDCP::Result_t +AS_02::PCM::MXFWriter::h__Writer::WriteFrame(const FrameBuffer& FrameBuf, AESEncContext* Ctx, + HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + + if ( m_State.Test_READY() ) + result = m_State.Goto_RUNNING(); // first time through + + if ( ASDCP_SUCCESS(result) ) + result = WriteEKLVPacket(FrameBuf, m_EssenceUL, Ctx, HMAC); + + if ( ASDCP_SUCCESS(result) ) + m_FramesWritten++; + + return result; +} + +// Closes the MXF file, writing the index and other closing information. +// +ASDCP::Result_t +AS_02::PCM::MXFWriter::h__Writer::Finalize() +{ + if ( ! m_State.Test_RUNNING() ) + return RESULT_STATE; + + m_State.Goto_FINAL(); + + return WriteMXFFooter(); +} + + +//------------------------------------------------------------------------------------------ +// + + + +AS_02::PCM::MXFWriter::MXFWriter() +{ +} + +AS_02::PCM::MXFWriter::~MXFWriter() +{ +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +ASDCP::MXF::OPAtomHeader& +AS_02::PCM::MXFWriter::OPAtomHeader() +{ + if ( m_Writer.empty() ) + { + assert(g_OPAtomHeader); + return *g_OPAtomHeader; + } + + return m_Writer->m_HeaderPart; +} + +// Warning: direct manipulation of MXF structures can interfere +// with the normal operation of the wrapper. Caveat emptor! +// +/* +ASDCP::MXF::OPAtomIndexFooter& +AS_02::PCM::MXFWriter::OPAtomIndexFooter() +{ + if ( m_Writer.empty() ) + { + assert(g_OPAtomIndexFooter); + return *g_OPAtomIndexFooter; + } + + return m_Writer->m_FooterPart; +} +*/ + +// Open the file for writing. The file must not exist. Returns error if +// the operation cannot be completed. +ASDCP::Result_t +AS_02::PCM::MXFWriter::OpenWrite(const char* filename, const WriterInfo& Info, + const ASDCP::PCM::AudioDescriptor& ADesc, ui32_t HeaderSize) +{ + m_Writer = new h__Writer(DefaultSMPTEDict()); + m_Writer->m_Info = Info; + + Result_t result = m_Writer->OpenWrite(filename, HeaderSize); + + if ( ASDCP_SUCCESS(result) ) + result = m_Writer->SetSourceStream(ADesc); + + if ( ASDCP_FAILURE(result) ) + m_Writer.release(); + + return result; +} + +// Writes a frame of essence to the MXF file. If the optional AESEncContext +// argument is present, the essence is encrypted prior to writing. +// Fails if the file is not open, is finalized, or an operating system +// error occurs. +ASDCP::Result_t +AS_02::PCM::MXFWriter::WriteFrame(const FrameBuffer& FrameBuf, AESEncContext* Ctx, HMACContext* HMAC) +{ + if ( m_Writer.empty() ) + return RESULT_INIT; + + return m_Writer->WriteFrame(FrameBuf, Ctx, HMAC); +} + +// Closes the MXF file, writing the index and other closing information. +ASDCP::Result_t +AS_02::PCM::MXFWriter::Finalize() +{ + if ( m_Writer.empty() ) + return RESULT_INIT; + + return m_Writer->Finalize(); +} + +// standard method of opening an MXF file for read +Result_t +AS_02::PCM::MXFReader::h__Reader::OpenMXFRead(const char* filename) +{ + m_LastPosition = 0; + AS_02::MXF::OP1aIndexBodyPartion* pCurrentBodyPartIndex = NULL; + Partition* pPart = NULL; + ui64_t EssenceStart = 0; + Result_t result = m_File.OpenRead(filename); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.InitFromFile(m_File); + + if ( ASDCP_SUCCESS(result) ) + { + ui32_t partition_size = m_HeaderPart.m_RIP.PairArray.size(); + + if ( partition_size > 3 ) + { + //for all entry except the first and the last(header&footer) + Array::iterator r_i = m_HeaderPart.m_RIP.PairArray.begin(); + r_i++; + ui32_t i=2; + + while ( r_i != m_HeaderPart.m_RIP.PairArray.end() && i < partition_size ) + { + m_File.Seek((*r_i).ByteOffset); + pPart = new Partition(this->m_Dict); + result = pPart->InitFromFile(m_File); + + // TODO:: expect Index partition + delete pPart; + m_File.Seek((*r_i).ByteOffset); + pCurrentBodyPartIndex = new AS_02::MXF::OP1aIndexBodyPartion(this->m_Dict); + pCurrentBodyPartIndex->m_Lookup = &m_HeaderPart.m_Primer; + result = pCurrentBodyPartIndex->InitFromFile(m_File); + + if ( ASDCP_FAILURE(result) ) + { + break; + } + + r_i++; i++; + + m_File.Seek((*r_i).ByteOffset); + pPart = new Partition(this->m_Dict); + result = pPart->InitFromFile(m_File); + EssenceStart = m_File.Tell(); + + if ( ASDCP_FAILURE(result) ) + { + break; + } + + if(i==3) + { + m_EssenceStart = EssenceStart; + m_pCurrentBodyPartition = pPart; + m_pCurrentIndexPartition = pCurrentBodyPartIndex; + } + + m_BodyPartList.push_back(pCurrentBodyPartIndex); + m_BodyPartList.push_back(pPart); + r_i++; i++; + } + } + } + + return result; +} + +// standard method of reading a plaintext or encrypted frame +Result_t +AS_02::PCM::MXFReader::h__Reader::ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + // look up frame index node + IndexTableSegment::IndexEntry TmpEntry; + ui32_t i = 0; + + if(m_pCurrentIndexPartition == NULL) + { + m_pCurrentIndexPartition = dynamic_cast (m_BodyPartList.at(i)); + m_pCurrentBodyPartition = m_BodyPartList.at(i+1); + } + else + { + return RESULT_FORMAT; //return error + } + + if(m_pCurrentIndexPartition == NULL) + { + return RESULT_FORMAT; //return error + } + + m_pCurrentIndexPartition->PCMIndexLookup(FrameNum,TmpEntry); + // get frame position and go read the frame's key and length + Kumu::fpos_t FilePosition = this->m_EssenceStart + TmpEntry.StreamOffset; + + if ( FilePosition != m_LastPosition ) + { + m_LastPosition = FilePosition; + result = m_File.Seek(FilePosition); + } + + if( ASDCP_SUCCESS(result) ) + result = ReadEKLVPacket(FrameNum, FrameNum + 1, FrameBuf, EssenceUL, Ctx, HMAC); + + return result; +} + +Result_t +AS_02::PCM::MXFReader::h__Reader::ReadEKLVPacket(ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) +{ + KLReader Reader; + + //save position to read KLV packet + Kumu::fpos_t SaveFilePosition = m_File.Tell(); + //Seek backward to KLV start + m_File.Seek(this->m_EssenceStart); + Result_t result = Reader.ReadKLFromFile(m_File); + //set old position + m_File.Seek(SaveFilePosition); + + if ( ASDCP_FAILURE(result) ) + return result; + + UL Key(Reader.Key()); + ui64_t PacketLength = Reader.Length(); + m_LastPosition = m_LastPosition + PacketLength; + if(FrameNum = 0){ + m_LastPosition+= Reader.KLLength(); + } + assert(m_Dict); + + //TODO: for AS_02 PCM - not in the dictionary + + static const byte_t WaveClipEssenceUL_Data[SMPTE_UL_LENGTH] = + { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x02, 0x01, 0x01, + 0x0d, 0x01, 0x03, 0x01, 0x16, 0x01, 0x02, 0x01 }; + + + if( memcmp(Key.Value(), WaveClipEssenceUL_Data, SMPTE_UL_LENGTH) == 0 ){ + byte_t WaveFrameEssenceUL_Data[SMPTE_UL_LENGTH] = + { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x02, 0x01, 0x01, + 0x0d, 0x01, 0x03, 0x01, 0x16, 0x01, 0x01, 0x01 }; + + Key.Set(WaveFrameEssenceUL_Data); + } + + + if ( memcmp(Key.Value(), m_Dict->ul(MDD_CryptEssence), Key.Size() - 1) == 0 ) // ignore the stream numbers + { + if ( ! m_Info.EncryptedEssence ) + { + DefaultLogSink().Error("EKLV packet found, no Cryptographic Context in header.\n"); + return RESULT_FORMAT; + } + + // read encrypted triplet value into internal buffer + assert(PacketLength <= 0xFFFFFFFFL); + m_CtFrameBuf.Capacity((ui32_t) PacketLength); + ui32_t read_count; + result = m_File.Read(m_CtFrameBuf.Data(), (ui32_t) PacketLength, + &read_count); + + if ( ASDCP_FAILURE(result) ) + return result; + + if ( read_count != PacketLength ) + { + DefaultLogSink().Error("read length is smaller than EKLV packet length.\n"); + return RESULT_FORMAT; + } + + m_CtFrameBuf.Size((ui32_t) PacketLength); + + // should be const but mxflib::ReadBER is not + byte_t* ess_p = m_CtFrameBuf.Data(); + + // read context ID length + if ( ! Kumu::read_test_BER(&ess_p, UUIDlen) ) + return RESULT_FORMAT; + + // test the context ID + if ( memcmp(ess_p, m_Info.ContextID, UUIDlen) != 0 ) + { + DefaultLogSink().Error("Packet's Cryptographic Context ID does not match the header.\n"); + return RESULT_FORMAT; + } + ess_p += UUIDlen; + + // read PlaintextOffset length + if ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) ) + return RESULT_FORMAT; + + ui32_t PlaintextOffset = (ui32_t)KM_i64_BE(Kumu::cp2i(ess_p)); + ess_p += sizeof(ui64_t); + + // read essence UL length + if ( ! Kumu::read_test_BER(&ess_p, SMPTE_UL_LENGTH) ) + return RESULT_FORMAT; + + // test essence UL + if ( memcmp(ess_p, EssenceUL, SMPTE_UL_LENGTH - 1) != 0 ) // ignore the stream number + { + char strbuf[IntBufferLen]; + const MDDEntry* Entry = m_Dict->FindUL(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 ( ! Kumu::read_test_BER(&ess_p, sizeof(ui64_t)) ) + return RESULT_FORMAT; + + ui32_t SourceLength = (ui32_t)KM_i64_BE(Kumu::cp2i(ess_p)); + ess_p += sizeof(ui64_t); + assert(SourceLength); + + if ( 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 ( ! Kumu::read_test_BER(&ess_p, 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); + + if ( PacketLength < tmp_len ) + { + DefaultLogSink().Error("Frame length is larger than EKLV packet length.\n"); + return RESULT_FORMAT; + } + + if ( Ctx ) + { + // wrap the pointer and length as a FrameBuffer for use by + // DecryptFrameBuffer() and TestValues() + FrameBuffer TmpWrapper; + TmpWrapper.SetData(ess_p, tmp_len); + TmpWrapper.Size(tmp_len); + TmpWrapper.SourceLength(SourceLength); + TmpWrapper.PlaintextOffset(PlaintextOffset); + + result = DecryptFrameBuffer(TmpWrapper, FrameBuf, Ctx); + FrameBuf.FrameNumber(FrameNum); + + // detect and test integrity pack + if ( ASDCP_SUCCESS(result) && m_Info.UsesHMAC && HMAC ) + { + IntegrityPack IntPack; + result = IntPack.TestValues(TmpWrapper, m_Info.AssetUUID, SequenceNum, HMAC); + } + } + else // return ciphertext to caller + { + if ( FrameBuf.Capacity() < tmp_len ) + { + 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 ( memcmp(Key.Value(), EssenceUL, Key.Size() - 1) == 0 ) // ignore the stream number + { // read plaintext frame + if ( FrameBuf.Capacity() < PacketLength ) + { + char intbuf[IntBufferLen]; + 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; + assert(PacketLength <= 0xFFFFFFFFL); + result = m_File.Read(FrameBuf.Data(), (ui32_t) PacketLength, &read_count); + + if ( ASDCP_FAILURE(result) ) + return result; + + if ( read_count != PacketLength ) + { + char intbuf1[IntBufferLen]; + char intbuf2[IntBufferLen]; + DefaultLogSink().Error("read_count: %s != FrameLength: %s\n", + ui64sz(read_count, intbuf1), + ui64sz(PacketLength, intbuf2) ); + + return RESULT_READFAIL; + } + + FrameBuf.FrameNumber(FrameNum); + FrameBuf.Size(read_count); + } + else + { + char strbuf[IntBufferLen]; + const MDDEntry* Entry = m_Dict->FindUL(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; + } + + return result; +} + +// standard method of writing the header and footer of a completed MXF file +// +Result_t +AS_02::PCM::MXFWriter::h__Writer::WriteMXFFooter() +{ + // Set top-level file package correctly for OP-Atom + + // m_MPTCSequence->Duration = m_MPTimecode->Duration = m_MPClSequence->Duration = m_MPClip->Duration = + // m_FPTCSequence->Duration = m_FPTimecode->Duration = m_FPClSequence->Duration = m_FPClip->Duration = + + // + m_CurrentIndexBodyPartition->m_FramesWritten = m_FramesWritten; + m_CurrentIndexBodyPartition->PCMSetIndexParamsCBR(m_CurrentIndexBodyPartition->m_BytesPerEditUnit+24,m_CurrentIndexBodyPartition->m_BytesPerEditUnit); + CompleteIndexBodyPart(); + + DurationElementList_t::iterator dli = m_DurationUpdateList.begin(); + + for (; dli != m_DurationUpdateList.end(); dli++ ) + **dli = m_FramesWritten; + + m_EssenceDescriptor->ContainerDuration = m_FramesWritten; + m_FooterPart.PreviousPartition = m_HeaderPart.m_RIP.PairArray.back().ByteOffset; + + Kumu::fpos_t here = m_File.Tell(); + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(0, here)); // Last RIP Entry + m_HeaderPart.FooterPartition = here; + + assert(m_Dict); + // re-label the partition + UL OP1aUL(m_Dict->ul(MDD_OP1a)); + m_HeaderPart.OperationalPattern = OP1aUL; + m_HeaderPart.m_Preface->OperationalPattern = m_HeaderPart.OperationalPattern; + + m_FooterPart.OperationalPattern = m_HeaderPart.OperationalPattern; + m_FooterPart.EssenceContainers = m_HeaderPart.EssenceContainers; + m_FooterPart.FooterPartition = here; + m_FooterPart.ThisPartition = here; + + Result_t result = m_FooterPart.WriteToFile(m_File, m_FramesWritten); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.m_RIP.WriteToFile(m_File); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Seek(0); + + if ( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.WriteToFile(m_File, m_HeaderSize); + + //update the value of FooterPartition in all Partitions + std::vector::iterator bl_i = this->m_BodyPartList.begin(); + for (; bl_i != m_BodyPartList.end(); bl_i++ ){ + (*bl_i)->FooterPartition = m_FooterPart.ThisPartition; + if ( ASDCP_SUCCESS(result) ) + result = m_File.Seek((*bl_i)->ThisPartition); + if ( ASDCP_SUCCESS(result) ){ + UL BodyUL(m_Dict->ul(MDD_ClosedCompleteBodyPartition)); + result = (*bl_i)->WriteToFile(m_File, BodyUL); + } + } + + m_File.Close(); + return result; +} + +// standard method of writing a plaintext or encrypted frame +Result_t +AS_02::PCM::MXFWriter::h__Writer::WriteEKLVPacket(const ASDCP::FrameBuffer& FrameBuf, const byte_t* EssenceUL, + AESEncContext* Ctx, HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + IntegrityPack IntPack; + + const ui32_t AS_02_PCM_MXF_BER_LENGTH = 8; + //TODO: AS_02_PCM_MXF_BER_LENGTH - customize for EncryptedEssence + + byte_t overhead[128]; + Kumu::MemIOWriter Overhead(overhead, 128); + assert(m_Dict); + + if ( FrameBuf.Size() == 0 ) + { + DefaultLogSink().Error("Cannot write empty frame buffer\n"); + return RESULT_EMPTY_FB; + } + + if ( m_Info.EncryptedEssence ) + { + if ( ! Ctx ) + return RESULT_CRYPT_CTX; + + if ( m_Info.UsesHMAC && ! HMAC ) + return RESULT_HMAC_CTX; + + if ( FrameBuf.PlaintextOffset() > FrameBuf.Size() ) + return RESULT_LARGE_PTO; + + // encrypt the essence data (create encrypted source value) + result = EncryptFrameBuffer(FrameBuf, m_CtFrameBuf, Ctx); + + // create HMAC + if ( ASDCP_SUCCESS(result) && m_Info.UsesHMAC ) + result = IntPack.CalcValues(m_CtFrameBuf, m_Info.AssetUUID, m_FramesWritten + 1, HMAC); + + if ( ASDCP_SUCCESS(result) ) + { // write UL + Overhead.WriteRaw(m_Dict->ul(MDD_CryptEssence), SMPTE_UL_LENGTH); + + // construct encrypted triplet header + ui32_t ETLength = klv_cryptinfo_size + m_CtFrameBuf.Size(); + ui32_t BER_length = MXF_BER_LENGTH; + + if ( m_Info.UsesHMAC ) + ETLength += klv_intpack_size; + else + ETLength += (MXF_BER_LENGTH * 3); // for empty intpack + + if ( ETLength > 0x00ffffff ) // Need BER integer longer than MXF_BER_LENGTH bytes + { + BER_length = Kumu::get_BER_length_for_value(ETLength); + + // the packet is longer by the difference in expected vs. actual BER length + ETLength += BER_length - MXF_BER_LENGTH; + + if ( BER_length == 0 ) + result = RESULT_KLV_CODING; + } + + if ( ASDCP_SUCCESS(result) ) + { + if ( ! ( Overhead.WriteBER(ETLength, BER_length) // write encrypted triplet length + && Overhead.WriteBER(UUIDlen, MXF_BER_LENGTH) // write ContextID length + && Overhead.WriteRaw(m_Info.ContextID, UUIDlen) // write ContextID + && Overhead.WriteBER(sizeof(ui64_t), MXF_BER_LENGTH) // write PlaintextOffset length + && Overhead.WriteUi64BE(FrameBuf.PlaintextOffset()) // write PlaintextOffset + && Overhead.WriteBER(SMPTE_UL_LENGTH, MXF_BER_LENGTH) // write essence UL length + && Overhead.WriteRaw((byte_t*)EssenceUL, SMPTE_UL_LENGTH) // write the essence UL + && Overhead.WriteBER(sizeof(ui64_t), MXF_BER_LENGTH) // write SourceLength length + && Overhead.WriteUi64BE(FrameBuf.Size()) // write SourceLength + && Overhead.WriteBER(m_CtFrameBuf.Size(), BER_length) ) ) // write ESV length + { + result = RESULT_KLV_CODING; + } + } + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(Overhead.Data(), Overhead.Length()); + } + + if ( ASDCP_SUCCESS(result) ) + { + m_StreamOffset += Overhead.Length(); + // write encrypted source value + result = m_File.Writev((byte_t*)m_CtFrameBuf.RoData(), m_CtFrameBuf.Size()); + } + + if ( ASDCP_SUCCESS(result) ) + { + m_StreamOffset += m_CtFrameBuf.Size(); + + byte_t hmoverhead[512]; + Kumu::MemIOWriter HMACOverhead(hmoverhead, 512); + + // write the HMAC + if ( m_Info.UsesHMAC ) + { + HMACOverhead.WriteRaw(IntPack.Data, klv_intpack_size); + } + else + { // we still need the var-pack length values if the intpack is empty + for ( ui32_t i = 0; i < 3 ; i++ ) + HMACOverhead.WriteBER(0, MXF_BER_LENGTH); + } + + // write HMAC + result = m_File.Writev(HMACOverhead.Data(), HMACOverhead.Length()); + m_StreamOffset += HMACOverhead.Length(); + } + } + else + { + if(m_FramesWritten == 0){ + ui32_t BER_length = AS_02_PCM_MXF_BER_LENGTH; //MXF_BER_LENGTH; + + if ( FrameBuf.Size() > 0x00ffffff ) // Need BER integer longer than MXF_BER_LENGTH bytes + { + BER_length = Kumu::get_BER_length_for_value(FrameBuf.Size()); + + if ( BER_length == 0 ) + result = RESULT_KLV_CODING; + } + + Overhead.WriteRaw((byte_t*)EssenceUL, SMPTE_UL_LENGTH); + Overhead.WriteBER(FrameBuf.Size(), BER_length); + + //position of the KLV start + m_KLV_start = m_File.Tell(); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(Overhead.Data(), Overhead.Length()); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev((byte_t*)FrameBuf.RoData(), FrameBuf.Size()); + + if ( ASDCP_SUCCESS(result) ) + m_StreamOffset += Overhead.Length() + FrameBuf.Size(); + } + else{ + //update the KLV - length; new value plus old value from length field + //necessary to know position of length field -> bodyPartition + 8 + //update every time when writing new essence or at the end of writing + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev((byte_t*)FrameBuf.RoData(), FrameBuf.Size()); + + if ( ASDCP_SUCCESS(result) ) + m_StreamOffset += FrameBuf.Size(); + } + } + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(); + + return result; +} + +// +// end AS_02_PCM.cpp +// + diff --git a/src/AS_02_internal.h b/src/AS_02_internal.h new file mode 100644 index 0000000..15f4486 --- /dev/null +++ b/src/AS_02_internal.h @@ -0,0 +1,199 @@ +/* + Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 AS_02_internal.h + \version $Id: AS_02_internal.h *** + \brief AS-02 library, non-public common elements +*/ + +#ifndef _AS_02_INTERNAL_H_ +#define _AS_02_INTERNAL_H_ + +#include +#include +#include +#include "Metadata.h" +#include "AS_DCP_internal.h" +#include "AS_02.h" + +using Kumu::DefaultLogSink; + +using namespace ASDCP; +using namespace ASDCP::MXF; + +namespace AS_02 +{ + static void CalculateIndexPartitionSize(ui32_t& size,ui32_t numberOfIndexEntries) + { + if(numberOfIndexEntries){ + //Partition::ArchiveSize(); HeaderSize = 124 bytes + //KLV-Item = 20 bytes + //ItemSize IndexEntry = 11 bytes + //number of IndexEntries - parameter + //IndexEntryArray = 12 bytes + //size for other Elements(PosTableCount etc.) = 108 bytes + //see Index.cpp ASDCP::MXF::IndexTableSegment::WriteToTLVSet(TLVWriter& TLVSet) how this is computed + size = 124 + 20 + 11 * numberOfIndexEntries + 12 +108; + size += 20;//because maybe we must fill the last partition, minimum required space for KLV-Item + } + else{ + //Partition HeaderSize = 124 bytes + //KLV-Item = 20 bytes + //244 for 2 IndexTableSegments + size = 124 + 20 + 244; + } + } + + // + class h__Reader + { + ASDCP_NO_COPY_CONSTRUCT(h__Reader); + h__Reader(); + + public: + const Dictionary* m_Dict; + Kumu::FileReader m_File; + OPAtomHeader m_HeaderPart; + //more than one Body-Partition use a list + std::vector m_BodyPartList; + OPAtomIndexFooter m_FooterPart; + ui64_t m_EssenceStart; + WriterInfo m_Info; + ASDCP::FrameBuffer m_CtFrameBuf; + Kumu::fpos_t m_LastPosition; + + IndexStrategy_t m_IndexStrategy; //Shim parameter index_strategy_frame/clip + ui32_t m_PartitionSpace; + + ////new elements for AS-02 + Partition* m_pCurrentBodyPartition; + AS_02::MXF::OP1aIndexBodyPartion* m_pCurrentIndexPartition; + ui32_t m_start_pos; + + h__Reader(const Dictionary&); + virtual ~h__Reader(); + + Result_t InitInfo(); + virtual Result_t OpenMXFRead(const char* filename) = 0; + Result_t InitMXFIndex(); + + // positions file before reading + virtual Result_t ReadEKLVFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) = 0; + + // reads from current position + virtual Result_t ReadEKLVPacket(ui32_t FrameNum, ui32_t SequenceNum, ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESDecContext* Ctx, HMACContext* HMAC) = 0; + void Close(); + }; + + // + class h__Writer + { + ASDCP_NO_COPY_CONSTRUCT(h__Writer); + h__Writer(); + + public: + const Dictionary* m_Dict; + Kumu::FileWriter m_File; + ui32_t m_HeaderSize; + OPAtomHeader m_HeaderPart; + //more than one Body-Partition -> use a list of Partitions + std::vector m_BodyPartList; + //we don't use the footer like in the dcps but we need also a footer + AS_02::MXF::OP1aIndexFooter m_FooterPart; + ui64_t m_EssenceStart; + + MaterialPackage* m_MaterialPackage; + SourcePackage* m_FilePackage; + + FileDescriptor* m_EssenceDescriptor; + std::list m_EssenceSubDescriptorList; + + ui32_t m_FramesWritten; + ui64_t m_StreamOffset; + ASDCP::FrameBuffer m_CtFrameBuf; + h__WriterState m_State; + WriterInfo m_Info; + DurationElementList_t m_DurationUpdateList; + + //new elements for AS-02 + ui64_t m_BodyOffset; + //TODO: Currently not used, delete if not necessary + // Counter values for BodySID and IndexSID + ui32_t m_CurrentBodySID; + ui32_t m_CurrentIndexSID; + //TODO: maybe set this to the lf__Writer class because this is only in JP2K creation necessary + //our computed PartitionSpace + ui32_t m_PartitionSpace; + IndexStrategy_t m_IndexStrategy; //Shim parameter index_strategy_frame/clip + + //the EditRate + ASDCP::MXF::Rational m_EditRate; + //the BytesPerEditUnit + ui32_t m_BytesPerEditUnit; + //pointer to the current Body Partition(Index) + AS_02::MXF::OP1aIndexBodyPartion* m_CurrentIndexBodyPartition; + + h__Writer(const Dictionary&); + virtual ~h__Writer(); + + //virtual methods, implementation details for JP2K or PCM are in the MXFWriter::h__Writer classes if they are different + virtual void InitHeader(); + /*virtual*/ void AddSourceClip(const ASDCP::MXF::Rational& EditRate, ui32_t TCFrameRate, + const std::string& TrackName, const UL& EssenceUL, + const UL& DataDefinition, const std::string& PackageLabel); + /*virtual*/ void AddDMSegment(const ASDCP::MXF::Rational& EditRate, ui32_t TCFrameRate, + const std::string& TrackName, const UL& DataDefinition, + const std::string& PackageLabel); + /*virtual*/ void AddEssenceDescriptor(const ASDCP::UL& WrappingUL); + virtual Result_t CreateBodyPart(const ASDCP::MXF::Rational& EditRate, ui32_t BytesPerEditUnit = 0); + + //new method to create BodyPartition for essence and index + virtual Result_t CreateBodyPartPair(); + //new method to finalize BodyPartion(index) + virtual Result_t CompleteIndexBodyPart(); + + // all the above for a single source clip + virtual Result_t WriteMXFHeader(const std::string& PackageLabel, const UL& WrappingUL, + const std::string& TrackName, const UL& EssenceUL, + const UL& DataDefinition, const ASDCP::MXF::Rational& EditRate, + ui32_t TCFrameRate, ui32_t BytesPerEditUnit = 0); + + virtual Result_t WriteEKLVPacket(const ASDCP::FrameBuffer& FrameBuf, + const byte_t* EssenceUL, AESEncContext* Ctx, HMACContext* HMAC); + + virtual Result_t WriteMXFFooter() = 0; + + }; + +} // namespace AS_02 + +#endif // _AS_02_INTERNAL_H_ + +// +// end AS_02_internal.h +// diff --git a/src/AS_DCP_internal.h b/src/AS_DCP_internal.h index dd21f0d..082cd83 100755 --- a/src/AS_DCP_internal.h +++ b/src/AS_DCP_internal.h @@ -55,6 +55,30 @@ namespace ASDCP { void default_md_object_init(); + // + static std::vector + version_split(const char* str) + { + std::vector result; + const char* pstr = str; + const char* r = strchr(pstr, '.'); + + while ( r != 0 ) + { + assert(r >= pstr); + if ( r > pstr ) + result.push_back(atoi(pstr)); + + pstr = r + 1; + r = strchr(pstr, '.'); + } + + if( strlen(pstr) > 0 ) + result.push_back(atoi(pstr)); + + assert(result.size() == 3); + return result; + } // constant values used to calculate KLV and EKLV packet sizes static const ui32_t klv_cryptinfo_size = diff --git a/src/MXF.cpp b/src/MXF.cpp index bc7bec2..6bc3fcb 100755 --- a/src/MXF.cpp +++ b/src/MXF.cpp @@ -43,8 +43,6 @@ const ui32_t CBRIndexEntriesPerSegment = 5000; //------------------------------------------------------------------------------------------ // -const ui32_t kl_length = ASDCP::SMPTE_UL_LENGTH + ASDCP::MXF_BER_LENGTH; - // ASDCP::Result_t ASDCP::MXF::SeekToRIP(const Kumu::FileReader& Reader) @@ -174,80 +172,77 @@ ASDCP::MXF::RIP::Dump(FILE* stream) // // -class ASDCP::MXF::Partition::h__PacketList -{ -public: - std::list m_List; - std::map m_Map; - - ~h__PacketList() { - while ( ! m_List.empty() ) - { - delete m_List.back(); - m_List.pop_back(); - } - } +ASDCP::MXF::Partition::PacketList::~PacketList() { + while ( ! m_List.empty() ) + { + delete m_List.back(); + m_List.pop_back(); + } +} - // - void AddPacket(InterchangeObject* ThePacket) // takes ownership - { - assert(ThePacket); - m_Map.insert(std::map::value_type(ThePacket->InstanceUID, ThePacket)); - m_List.push_back(ThePacket); - } +// +void +ASDCP::MXF::Partition::PacketList::AddPacket(InterchangeObject* ThePacket) // takes ownership +{ + assert(ThePacket); + m_Map.insert(std::map::value_type(ThePacket->InstanceUID, ThePacket)); + m_List.push_back(ThePacket); +} - // - Result_t GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object) - { - ASDCP_TEST_NULL(Object); +// +ASDCP::Result_t +ASDCP::MXF::Partition::PacketList::GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object) +{ + ASDCP_TEST_NULL(Object); - std::map::iterator mi = m_Map.find(ObjectID); + std::map::iterator mi = m_Map.find(ObjectID); + + if ( mi == m_Map.end() ) + { + *Object = 0; + return RESULT_FAIL; + } - if ( mi == m_Map.end() ) - { - *Object = 0; - return RESULT_FAIL; - } + *Object = (*mi).second; + return RESULT_OK; +} - *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::iterator li; + *Object = 0; - // - Result_t GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object) - { - ASDCP_TEST_NULL(ObjectID); - ASDCP_TEST_NULL(Object); - std::list::iterator li; - *Object = 0; - - for ( li = m_List.begin(); li != m_List.end(); li++ ) - { - if ( (*li)->HasUL(ObjectID) ) - { - *Object = *li; - return RESULT_OK; - } - } + for ( li = m_List.begin(); li != m_List.end(); li++ ) + { + if ( (*li)->HasUL(ObjectID) ) + { + *Object = *li; + return RESULT_OK; + } + } - return RESULT_FAIL; - } + return RESULT_FAIL; +} - // - Result_t GetMDObjectsByType(const byte_t* ObjectID, std::list& ObjectList) - { - ASDCP_TEST_NULL(ObjectID); - std::list::iterator li; +// +ASDCP::Result_t +ASDCP::MXF::Partition::PacketList::GetMDObjectsByType(const byte_t* ObjectID, std::list& ObjectList) +{ + ASDCP_TEST_NULL(ObjectID); + std::list::iterator li; - for ( li = m_List.begin(); li != m_List.end(); li++ ) - { - if ( (*li)->HasUL(ObjectID) ) - ObjectList.push_back(*li); - } + for ( li = m_List.begin(); li != m_List.end(); li++ ) + { + if ( (*li)->HasUL(ObjectID) ) + ObjectList.push_back(*li); + } - return ObjectList.empty() ? RESULT_FAIL : RESULT_OK; - } -}; + return ObjectList.empty() ? RESULT_FAIL : RESULT_OK; +} //------------------------------------------------------------------------------------------ // @@ -260,7 +255,7 @@ ASDCP::MXF::Partition::Partition(const Dictionary*& d) : FooterPartition(0), HeaderByteCount(0), IndexByteCount(0), IndexSID(0), BodyOffset(0), BodySID(0) { - m_PacketList = new h__PacketList; + m_PacketList = new PacketList; } ASDCP::MXF::Partition::~Partition() diff --git a/src/MXF.h b/src/MXF.h index 3d0264c..9c7b592 100755 --- a/src/MXF.h +++ b/src/MXF.h @@ -40,6 +40,8 @@ namespace ASDCP { class InterchangeObject; + const ui32_t kl_length = ASDCP::SMPTE_UL_LENGTH + ASDCP::MXF_BER_LENGTH; + // typedef ASDCP::MXF::InterchangeObject* (*MXFObjectFactory_t)(const Dictionary*&); @@ -114,8 +116,20 @@ namespace ASDCP Partition(); protected: - class h__PacketList; - mem_ptr m_PacketList; + class PacketList + { + public: + std::list m_List; + std::map m_Map; + + ~PacketList(); + void AddPacket(InterchangeObject* ThePacket); // takes ownership + Result_t GetMDObjectByID(const UUID& ObjectID, InterchangeObject** Object); + Result_t GetMDObjectByType(const byte_t* ObjectID, InterchangeObject** Object); + Result_t GetMDObjectsByType(const byte_t* ObjectID, std::list& ObjectList); + }; + + mem_ptr m_PacketList; public: const Dictionary*& m_Dict; diff --git a/src/Makefile.am b/src/Makefile.am index 7947d99..43623f9 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -69,7 +69,8 @@ libasdcp_la_SOURCES = MPEG2_Parser.cpp MPEG.cpp JP2K_Codestream_Parser.cpp \ AS_DCP_PCM.cpp AS_DCP_TimedText.cpp PCMParserList.cpp \ Wav.h WavFileWriter.h MXF.h Metadata.h \ JP2K.h AS_DCP.h AS_DCP_internal.h KLV.h MPEG.h MXFTypes.h MDD.h \ - PCMParserList.h S12MTimecode.h MDD.cpp + PCMParserList.h S12MTimecode.h MDD.cpp \ + AS_02_MXF.cpp AS_02_JP2K.cpp AS_02_PCM.cpp h__02_Reader.cpp h__02_Writer.cpp if DEV_HEADERS nodist_libasdcp_la_SOURCES += TimedText_Transform.h TimedText_Transform.cpp @@ -135,6 +136,7 @@ endif # list of programs to be built and installed bin_PROGRAMS = \ asdcp-wrap asdcp-unwrap asdcp-util asdcp-info asdcp-test \ + as-02-wrap as-02-unwrap \ j2c-test blackwave klvwalk wavesplit \ kmfilegen kmrandgen kmuuidgen @@ -142,6 +144,12 @@ bin_PROGRAMS = \ asdcp_test_SOURCES = asdcp-test.cpp asdcp_test_LDADD = libasdcp.la +as_02_wrap_SOURCES = as-02-wrap.cpp +as_02_wrap_LDADD = libasdcp.la + +as_02_unwrap_SOURCES = as-02-unwrap.cpp +as_02_unwrap_LDADD = libasdcp.la + asdcp_wrap_SOURCES = asdcp-wrap.cpp asdcp_wrap_LDADD = libasdcp.la diff --git a/src/as-02-unwrap.cpp b/src/as-02-unwrap.cpp new file mode 100755 index 0000000..6cb90e2 --- /dev/null +++ b/src/as-02-unwrap.cpp @@ -0,0 +1,508 @@ +/* +Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 as-02-unwrap.cpp + \version $Id$ + \brief AS-02 file manipulation utility + + This program extracts picture and sound from AS-02 files. + + For more information about AS-02, please refer to the header file AS_02.h + For more information about asdcplib, please refer to the header file AS_DCP.h +*/ + +#include +#include +#include + +using namespace ASDCP; + +const ui32_t FRAME_BUFFER_SIZE = 4 * Kumu::Megabyte; + +//------------------------------------------------------------------------------------------ +// +// command line option parser class + +static const char* PROGRAM_NAME = "as-02-unwrap"; // program name for messages + +// Increment the iterator, test for an additional non-option command line argument. +// Causes the caller to return if there are no remaining arguments or if the next +// argument begins with '-'. +#define TEST_EXTRA_ARG(i,c) \ + if ( ++i >= argc || argv[(i)][0] == '-' ) { \ + fprintf(stderr, "Argument not found for option -%c.\n", (c)); \ + return; \ + } + +// +void +banner(FILE* stream = stdout) +{ + fprintf(stream, "\n\ +%s (asdcplib %s)\n\n\ +Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, John Hurst\n\n\ +asdcplib may be copied only under the terms of the license found at\n\ +the top of every file in the asdcplib distribution kit.\n\n\ +Specify the -h (help) option for further information about %s\n\n", + PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME); +} + +// +void +usage(FILE* stream = stdout) +{ + fprintf(stream, "\ +USAGE: %s [-h|-help] [-V]\n\ +\n\ + %s [-1|-2] [-b ] [-d ]\n\ + [-f ] [-m] [-p ] [-R] [-s ] [-v] [-W]\n\ + [-w] []\n\n", + PROGRAM_NAME, PROGRAM_NAME, PROGRAM_NAME); + + fprintf(stream, "\ +Options:\n\ + -1 - Split Wave essence to mono WAV files during extract.\n\ + Default is multichannel WAV\n\ + -2 - Split Wave essence to stereo WAV files during extract.\n\ + Default is multichannel WAV\n\ + -b - Specify size in bytes of picture frame buffer\n\ + Defaults to 4,194,304 (4MB)\n\ + -d - Number of frames to process, default all\n\ + -f - Starting frame number, default 0\n\ + -h | -help - Show help\n\ + -k - Use key for ciphertext operations\n\ + -m - verify HMAC values when reading\n\ + -s - Number of bytes to dump to output when -v is given\n\ + -V - Show version information\n\ + -v - Verbose, prints informative messages to stderr\n\ + -W - Read input file only, do not write destination file\n\ + -w - Width of numeric element in a series of frame file names\n\ + (default 6)\n\ + -z - Fail if j2c inputs have unequal parameters (default)\n\ + -Z - Ignore unequal parameters in j2c inputs\n\ +\n\ + NOTES: o There is no option grouping, all options must be distinct arguments.\n\ + o All option arguments must be separated from the option by whitespace.\n\n"); +} + +// +class CommandOptions +{ + CommandOptions(); + +public: + bool error_flag; // true if the given options are in error or not complete + bool key_flag; // true if an encryption key was given + bool read_hmac; // true if HMAC values are to be validated + bool split_wav; // true if PCM is to be extracted to stereo WAV files + bool mono_wav; // true if PCM is to be extracted to mono WAV files + bool verbose_flag; // true if the verbose option was selected + ui32_t fb_dump_size; // number of bytes of frame buffer to dump + bool no_write_flag; // true if no output files are to be written + bool version_flag; // true if the version display option was selected + bool help_flag; // true if the help display option was selected + bool stereo_image_flag; // if true, expect stereoscopic JP2K input (left eye first) + ui32_t number_width; // number of digits in a serialized filename (for JPEG extract) + ui32_t start_frame; // frame number to begin processing + ui32_t duration; // number of frames to be processed + bool duration_flag; // true if duration argument given + bool j2c_pedantic; // passed to JP2K::SequenceParser::OpenRead + ui32_t picture_rate; // fps of picture when wrapping PCM + ui32_t fb_size; // size of picture frame buffer + const char* file_prefix; // filename pre for files written by the extract mode + byte_t key_value[KeyLen]; // value of given encryption key (when key_flag is true) + byte_t key_id_value[UUIDlen];// value of given key ID (when key_id_flag is true) + PCM::ChannelFormat_t channel_fmt; // audio channel arrangement + const char* input_filename; + std::string prefix_buffer; + + // + CommandOptions(int argc, const char** argv) : + error_flag(true), key_flag(false), read_hmac(false), split_wav(false), + mono_wav(false), verbose_flag(false), fb_dump_size(0), no_write_flag(false), + version_flag(false), help_flag(false), number_width(6), + start_frame(0), duration(0xffffffff), duration_flag(false), j2c_pedantic(true), + picture_rate(24), fb_size(FRAME_BUFFER_SIZE), file_prefix(0), + input_filename(0) + { + memset(key_value, 0, KeyLen); + memset(key_id_value, 0, UUIDlen); + + for ( int i = 1; i < argc; ++i ) + { + + if ( (strcmp( argv[i], "-help") == 0) ) + { + help_flag = true; + continue; + } + + if ( argv[i][0] == '-' + && ( isalpha(argv[i][1]) || isdigit(argv[i][1]) ) + && argv[i][2] == 0 ) + { + switch ( argv[i][1] ) + { + case '1': mono_wav = true; break; + case '2': split_wav = true; break; + + case 'b': + TEST_EXTRA_ARG(i, 'b'); + fb_size = abs(atoi(argv[i])); + + if ( verbose_flag ) + fprintf(stderr, "Frame Buffer size: %u bytes.\n", fb_size); + + break; + + case 'd': + TEST_EXTRA_ARG(i, 'd'); + duration_flag = true; + duration = abs(atoi(argv[i])); + break; + + case 'f': + TEST_EXTRA_ARG(i, 'f'); + start_frame = abs(atoi(argv[i])); + break; + + case 'h': help_flag = true; break; + case 'm': read_hmac = true; break; + + case 'p': + TEST_EXTRA_ARG(i, 'p'); + picture_rate = abs(atoi(argv[i])); + break; + + case 's': + TEST_EXTRA_ARG(i, 's'); + fb_dump_size = abs(atoi(argv[i])); + break; + + case 'V': version_flag = true; break; + case 'v': verbose_flag = true; break; + case 'W': no_write_flag = true; break; + + case 'w': + TEST_EXTRA_ARG(i, 'w'); + number_width = abs(atoi(argv[i])); + break; + + case 'Z': j2c_pedantic = false; break; + case 'z': j2c_pedantic = true; break; + + default: + fprintf(stderr, "Unrecognized option: %s\n", argv[i]); + return; + } + } + else + { + if ( argv[i][0] != '-' ) + { + if ( input_filename == 0 ) + { + input_filename = argv[i]; + } + else if ( file_prefix == 0 ) + { + file_prefix = argv[i]; + } + } + else + { + fprintf(stderr, "Unrecognized argument: %s\n", argv[i]); + return; + } + } + } + + if ( help_flag || version_flag ) + return; + + if ( input_filename == 0 ) + { + fputs("At least one filename argument is required.\n", stderr); + return; + } + + if ( file_prefix == 0 ) + { + prefix_buffer = Kumu::PathSetExtension(input_filename, "") + "_"; + file_prefix = prefix_buffer.c_str(); + } + + error_flag = false; + } +}; + + +//------------------------------------------------------------------------------------------ +// JPEG 2000 essence + + +// Read one or more plaintext JPEG 2000 codestreams from a plaintext ASDCP file +// Read one or more plaintext JPEG 2000 codestreams from a ciphertext ASDCP file +// Read one or more ciphertext JPEG 2000 codestreams from a ciphertext ASDCP file +// +Result_t +read_JP2K_file(CommandOptions& Options) +{ + AESDecContext* Context = 0; + HMACContext* HMAC = 0; + JP2K::MXFReader Reader; + JP2K::FrameBuffer FrameBuffer(Options.fb_size); + ui32_t frame_count = 0; + + Result_t result = Reader.OpenRead(Options.input_filename); + + if ( ASDCP_SUCCESS(result) ) + { + JP2K::PictureDescriptor PDesc; + Reader.FillPictureDescriptor(PDesc); + + frame_count = PDesc.ContainerDuration; + + if ( Options.verbose_flag ) + { + fprintf(stderr, "Frame Buffer size: %u\n", Options.fb_size); + JP2K::PictureDescriptorDump(PDesc); + } + } + + if ( ASDCP_SUCCESS(result) && Options.key_flag ) + { + Context = new AESDecContext; + result = Context->InitKey(Options.key_value); + + if ( ASDCP_SUCCESS(result) && Options.read_hmac ) + { + WriterInfo Info; + Reader.FillWriterInfo(Info); + + if ( Info.UsesHMAC ) + { + HMAC = new HMACContext; + result = HMAC->InitKey(Options.key_value, Info.LabelSetType); + } + else + { + fputs("File does not contain HMAC values, ignoring -m option.\n", stderr); + } + } + } + + ui32_t last_frame = Options.start_frame + ( Options.duration ? Options.duration : frame_count); + if ( last_frame > frame_count ) + last_frame = frame_count; + + char name_format[64]; + snprintf(name_format, 64, "%%s%%0%du.j2c", Options.number_width); + + for ( ui32_t i = Options.start_frame; ASDCP_SUCCESS(result) && i < last_frame; i++ ) + { + result = Reader.ReadFrame(i, FrameBuffer, Context, HMAC); + + if ( ASDCP_SUCCESS(result) ) + { + Kumu::FileWriter OutFile; + char filename[256]; + ui32_t write_count; + snprintf(filename, 256, name_format, Options.file_prefix, i); + result = OutFile.OpenWrite(filename); + + if ( ASDCP_SUCCESS(result) ) + result = OutFile.Write(FrameBuffer.Data(), FrameBuffer.Size(), &write_count); + + if ( Options.verbose_flag ) + FrameBuffer.Dump(stderr, Options.fb_dump_size); + } + } + + return result; +} + +//------------------------------------------------------------------------------------------ +// PCM essence + +// Read one or more plaintext PCM audio streams from a plaintext ASDCP file +// Read one or more plaintext PCM audio streams from a ciphertext ASDCP file +// Read one or more ciphertext PCM audio streams from a ciphertext ASDCP file +// +Result_t +read_PCM_file(CommandOptions& Options) +{ + AESDecContext* Context = 0; + HMACContext* HMAC = 0; + PCM::MXFReader Reader; + PCM::FrameBuffer FrameBuffer; + WavFileWriter OutWave; + PCM::AudioDescriptor ADesc; + ui32_t last_frame = 0; + + Result_t result = Reader.OpenRead(Options.input_filename); + + if ( ASDCP_SUCCESS(result) ) + { + Reader.FillAudioDescriptor(ADesc); + ADesc.EditRate = Rational(1, 1); + FrameBuffer.Capacity(PCM::CalcFrameBufferSize(ADesc)); + + if ( Options.verbose_flag ) + PCM::AudioDescriptorDump(ADesc); + } + + if ( ASDCP_SUCCESS(result) ) + { + last_frame = ADesc.ContainerDuration; + + if ( Options.duration > 0 && Options.duration < last_frame ) + last_frame = Options.duration; + + if ( Options.start_frame > 0 ) + { + if ( Options.start_frame > ADesc.ContainerDuration ) + { + fprintf(stderr, "Start value greater than file duration.\n"); + return RESULT_FAIL; + } + + last_frame = Kumu::xmin(Options.start_frame + last_frame, ADesc.ContainerDuration); + } + + ADesc.ContainerDuration = last_frame - Options.start_frame; + OutWave.OpenWrite(ADesc, Options.file_prefix, + ( Options.split_wav ? WavFileWriter::ST_STEREO : + ( Options.mono_wav ? WavFileWriter::ST_MONO : WavFileWriter::ST_NONE ) )); + } + + if ( ASDCP_SUCCESS(result) && Options.key_flag ) + { + Context = new AESDecContext; + result = Context->InitKey(Options.key_value); + + if ( ASDCP_SUCCESS(result) && Options.read_hmac ) + { + WriterInfo Info; + Reader.FillWriterInfo(Info); + + if ( Info.UsesHMAC ) + { + HMAC = new HMACContext; + result = HMAC->InitKey(Options.key_value, Info.LabelSetType); + } + else + { + fputs("File does not contain HMAC values, ignoring -m option.\n", stderr); + } + } + } + + for ( ui32_t i = Options.start_frame; ASDCP_SUCCESS(result) && i < last_frame; i++ ) + { + result = Reader.ReadFrame(i, FrameBuffer, Context, HMAC); + + if ( ASDCP_SUCCESS(result) ) + { + if ( Options.verbose_flag ) + FrameBuffer.Dump(stderr, Options.fb_dump_size); + + result = OutWave.WriteFrame(FrameBuffer); + } + } + + return result; +} + + +// +int +main(int argc, const char** argv) +{ + char str_buf[64]; + CommandOptions Options(argc, argv); + + if ( Options.version_flag ) + banner(); + + if ( Options.help_flag ) + usage(); + + if ( Options.version_flag || Options.help_flag ) + return 0; + + if ( Options.error_flag ) + { + fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME); + return 3; + } + + EssenceType_t EssenceType; + Result_t result = ASDCP::EssenceType(Options.input_filename, EssenceType); + + if ( ASDCP_SUCCESS(result) ) + { + switch ( EssenceType ) + { + case ESS_JPEG_2000: + result = read_JP2K_file(Options); + break; + + case ESS_PCM_24b_48k: + case ESS_PCM_24b_96k: + result = read_PCM_file(Options); + break; + + default: + fprintf(stderr, "%s: Unknown file type, not ASDCP essence.\n", Options.input_filename); + return 5; + } + } + + if ( ASDCP_FAILURE(result) ) + { + fputs("Program stopped on error.\n", stderr); + + if ( result == RESULT_SFORMAT ) + { + fputs("Use option '-3' to force stereoscopic mode.\n", stderr); + } + else if ( result != RESULT_FAIL ) + { + fputs(result, stderr); + fputc('\n', stderr); + } + + return 1; + } + + return 0; +} + + +// +// end as-02-unwrap.cpp +// diff --git a/src/as-02-wrap.cpp b/src/as-02-wrap.cpp new file mode 100755 index 0000000..b6a2cdd --- /dev/null +++ b/src/as-02-wrap.cpp @@ -0,0 +1,653 @@ +/* +Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 as-02-wrap.cpp + \version $Id$ + \brief AS-02 file manipulation utility + + This program wraps IMF essence (picture or sound) in to an AS-02 MXF file. + + For more information about AS-02, please refer to the header file AS_02.h + For more information about asdcplib, please refer to the header file AS_DCP.h +*/ + +#include +#include +#include +#include +#include + +using namespace ASDCP; + +const ui32_t FRAME_BUFFER_SIZE = 4 * Kumu::Megabyte; + + +const char* +RationalToString(const ASDCP::Rational& r, char* buf, const ui32_t& len) +{ + snprintf(buf, len, "%d/%d", r.Numerator, r.Denominator); + return buf; +} + +//------------------------------------------------------------------------------------------ +// +// command line option parser class + +static const char* PROGRAM_NAME = "as-02-wrap"; // program name for messages + +// local program identification info written to file headers +class MyInfo : public WriterInfo +{ +public: + MyInfo() + { + static byte_t default_ProductUUID_Data[UUIDlen] = + { 0x7d, 0x83, 0x6e, 0x16, 0x37, 0xc7, 0x4c, 0x22, + 0xb2, 0xe0, 0x46, 0xa7, 0x17, 0xe8, 0x4f, 0x42 }; + + memcpy(ProductUUID, default_ProductUUID_Data, UUIDlen); + CompanyName = "WidgetCo"; + ProductName = "as-02-wrap"; + ProductVersion = ASDCP::Version(); + } +} s_MyInfo; + + + +// Increment the iterator, test for an additional non-option command line argument. +// Causes the caller to return if there are no remaining arguments or if the next +// argument begins with '-'. +#define TEST_EXTRA_ARG(i,c) \ + if ( ++i >= argc || argv[(i)][0] == '-' ) { \ + fprintf(stderr, "Argument not found for option -%c.\n", (c)); \ + return; \ + } + +// +void +banner(FILE* stream = stdout) +{ + fprintf(stream, "\n\ +%s (asdcplib %s)\n\n\ +Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, John Hurst\n\n\ +asdcplib may be copied only under the terms of the license found at\n\ +the top of every file in the asdcplib distribution kit.\n\n\ +Specify the -h (help) option for further information about %s\n\n", + PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME); +} + +// +void +usage(FILE* stream = stdout) +{ + fprintf(stream, "\ +USAGE: %s [-h|-help] [-V]\n\ +\n\ + %s [-a ] [-b ] [-C
    ] [-d ]\n\ + [-e|-E] [-f ] [-j ] [-k ]\n\ + [-M] [-p /] [-v] [-W]\n\ + [-z|-Z] + \n\n", + PROGRAM_NAME, PROGRAM_NAME); + + fprintf(stream, "\ +Options:\n\ + -C
      - Set ChannelAssignment UL value\n\ + -h | -help - Show help\n\ + -V - Show version information\n\ + -e - Encrypt JP2K headers (default)\n\ + -E - Do not encrypt JP2K headers\n\ + -j - Write key ID instead of creating a random value\n\ + -k - Use key for ciphertext operations\n\ + -M - Do not create HMAC values when writing\n\ + -a - Specify the Asset ID of the file\n\ + -b - Specify size in bytes of picture frame buffer\n\ + Defaults to 4,194,304 (4MB)\n\ + -d - Number of frames to process, default all\n\ + -f - Starting frame number, default 0\n\ + -p / - Edit Rate of the output file. 24/1 is the default\n\ + -v - Verbose, prints informative messages to stderr\n\ + -W - Read input file only, do not write source file\n\ + -z - Fail if j2c inputs have unequal parameters (default)\n\ + -Z - Ignore unequal parameters in j2c inputs\n\ +\n\ + NOTES: o There is no option grouping, all options must be distinct arguments.\n\ + o All option arguments must be separated from the option by whitespace.\n\n"); +} + +// +// +class CommandOptions +{ + CommandOptions(); + +public: + bool error_flag; // true if the given options are in error or not complete + bool key_flag; // true if an encryption key was given + bool asset_id_flag; // true if an asset ID was given + bool encrypt_header_flag; // true if j2c headers are to be encrypted + bool write_hmac; // true if HMAC values are to be generated and written + bool verbose_flag; // true if the verbose option was selected + ui32_t fb_dump_size; // number of bytes of frame buffer to dump + bool no_write_flag; // true if no output files are to be written + bool version_flag; // true if the version display option was selected + bool help_flag; // true if the help display option was selected + ui32_t start_frame; // frame number to begin processing + ui32_t duration; // number of frames to be processed + bool j2c_pedantic; // passed to JP2K::SequenceParser::OpenRead + Rational edit_rate; // edit rate of JP2K sequence + ui32_t fb_size; // size of picture frame buffer + byte_t key_value[KeyLen]; // value of given encryption key (when key_flag is true) + bool key_id_flag; // true if a key ID was given + byte_t key_id_value[UUIDlen];// value of given key ID (when key_id_flag is true) + byte_t asset_id_value[UUIDlen];// value of asset ID (when asset_id_flag is true) + std::string out_file; // + bool show_ul_values; /// if true, dump the UL table before going tp work. + Kumu::PathList_t filenames; // list of filenames to be processed + UL channel_assignment; + + //new attributes for AS-02 support + AS_02::IndexStrategy_t index_strategy; //Shim parameter index_strategy_frame/clip + ui32_t partition_space; //Shim parameter partition_spacing + + // + CommandOptions(int argc, const char** argv) : + error_flag(true), key_flag(false), key_id_flag(false), asset_id_flag(false), + encrypt_header_flag(true), write_hmac(true), verbose_flag(false), fb_dump_size(0), + no_write_flag(false), version_flag(false), help_flag(false), start_frame(0), + duration(0xffffffff), j2c_pedantic(true), fb_size(FRAME_BUFFER_SIZE), + show_ul_values(false), index_strategy(AS_02::IS_FOLLOW), partition_space(60) + { + memset(key_value, 0, KeyLen); + memset(key_id_value, 0, UUIDlen); + + for ( int i = 1; i < argc; i++ ) + { + + if ( (strcmp( argv[i], "-help") == 0) ) + { + help_flag = true; + continue; + } + + if ( argv[i][0] == '-' + && ( isalpha(argv[i][1]) || isdigit(argv[i][1]) ) + && argv[i][2] == 0 ) + { + switch ( argv[i][1] ) + { + case 'a': + asset_id_flag = true; + TEST_EXTRA_ARG(i, 'a'); + { + ui32_t length; + Kumu::hex2bin(argv[i], asset_id_value, UUIDlen, &length); + + if ( length != UUIDlen ) + { + fprintf(stderr, "Unexpected asset ID length: %u, expecting %u characters.\n", length, UUIDlen); + return; + } + } + break; + + case 'b': + TEST_EXTRA_ARG(i, 'b'); + fb_size = abs(atoi(argv[i])); + + if ( verbose_flag ) + fprintf(stderr, "Frame Buffer size: %u bytes.\n", fb_size); + + break; + + case 'C': + TEST_EXTRA_ARG(i, 'U'); + if ( ! channel_assignment.DecodeHex(argv[i]) ) + { + fprintf(stderr, "Error decoding UL value: %s\n", argv[i]); + return; + } + break; + + case 'd': + TEST_EXTRA_ARG(i, 'd'); + duration = abs(atoi(argv[i])); + break; + + case 'E': encrypt_header_flag = false; break; + case 'e': encrypt_header_flag = true; break; + + case 'f': + TEST_EXTRA_ARG(i, 'f'); + start_frame = abs(atoi(argv[i])); + break; + + case 'h': help_flag = true; break; + + case 'j': key_id_flag = true; + TEST_EXTRA_ARG(i, 'j'); + { + ui32_t length; + Kumu::hex2bin(argv[i], key_id_value, UUIDlen, &length); + + if ( length != UUIDlen ) + { + fprintf(stderr, "Unexpected key ID length: %u, expecting %u characters.\n", length, UUIDlen); + return; + } + } + break; + + case 'k': key_flag = true; + TEST_EXTRA_ARG(i, 'k'); + { + ui32_t length; + Kumu::hex2bin(argv[i], key_value, KeyLen, &length); + + if ( length != KeyLen ) + { + fprintf(stderr, "Unexpected key length: %u, expecting %u characters.\n", length, KeyLen); + return; + } + } + break; + + case 'M': write_hmac = false; break; + + case 'p': + TEST_EXTRA_ARG(i, 'p'); + /// TODO: VERY BROKEN, WANT RATIONAL + edit_rate.Numerator = abs(atoi(argv[i])); + edit_rate.Denominator = 1; + break; + + case 'V': version_flag = true; break; + case 'v': verbose_flag = true; break; + case 'W': no_write_flag = true; break; + case 'Z': j2c_pedantic = false; break; + case 'z': j2c_pedantic = true; break; + + default: + fprintf(stderr, "Unrecognized option: %s\n", argv[i]); + return; + } + } + else + { + + if ( argv[i][0] != '-' ) + { + filenames.push_back(argv[i]); + } + else + { + fprintf(stderr, "Unrecognized argument: %s\n", argv[i]); + return; + } + } + } + + if ( help_flag || version_flag ) + return; + + if ( filenames.size() < 2 ) + { + fputs("Option requires at least two filename arguments: \n", stderr); + return; + } + + out_file = filenames.back(); + filenames.pop_back(); + error_flag = false; + } +}; + + +//------------------------------------------------------------------------------------------ +// JPEG 2000 essence + +// Write one or more plaintext JPEG 2000 codestreams to a plaintext AS-02 file +// Write one or more plaintext JPEG 2000 codestreams to a ciphertext AS-02 file +// +Result_t +write_JP2K_file(CommandOptions& Options) +{ + AESEncContext* Context = 0; + HMACContext* HMAC = 0; + AS_02::JP2K::MXFWriter Writer; + JP2K::FrameBuffer FrameBuffer(Options.fb_size); + JP2K::PictureDescriptor PDesc; + JP2K::SequenceParser Parser; + byte_t IV_buf[CBC_BLOCK_SIZE]; + Kumu::FortunaRNG RNG; + + // set up essence parser + Result_t result = Parser.OpenRead(Options.filenames.front().c_str(), Options.j2c_pedantic); + + // set up MXF writer + if ( ASDCP_SUCCESS(result) ) + { + Parser.FillPictureDescriptor(PDesc); + PDesc.EditRate = Options.edit_rate; + + if ( Options.verbose_flag ) + { + fprintf(stderr, "JPEG 2000 pictures\n"); + fputs("PictureDescriptor:\n", stderr); + fprintf(stderr, "Frame Buffer size: %u\n", Options.fb_size); + JP2K::PictureDescriptorDump(PDesc); + } + } + + if ( ASDCP_SUCCESS(result) && ! Options.no_write_flag ) + { + WriterInfo Info = s_MyInfo; // fill in your favorite identifiers here + Info.LabelSetType = LS_MXF_SMPTE; + + if ( Options.asset_id_flag ) + memcpy(Info.AssetUUID, Options.asset_id_value, UUIDlen); + else + Kumu::GenRandomUUID(Info.AssetUUID); + + // configure encryption + if( Options.key_flag ) + { + Kumu::GenRandomUUID(Info.ContextID); + Info.EncryptedEssence = true; + + if ( Options.key_id_flag ) + memcpy(Info.CryptographicKeyID, Options.key_id_value, UUIDlen); + else + RNG.FillRandom(Info.CryptographicKeyID, UUIDlen); + + Context = new AESEncContext; + result = Context->InitKey(Options.key_value); + + if ( ASDCP_SUCCESS(result) ) + result = Context->SetIVec(RNG.FillRandom(IV_buf, CBC_BLOCK_SIZE)); + + if ( ASDCP_SUCCESS(result) && Options.write_hmac ) + { + Info.UsesHMAC = true; + HMAC = new HMACContext; + result = HMAC->InitKey(Options.key_value, Info.LabelSetType); + } + } + + if ( ASDCP_SUCCESS(result) ) + result = Writer.OpenWrite(Options.out_file.c_str(), Info, PDesc, Options.index_strategy, Options.partition_space); + } + + if ( ASDCP_SUCCESS(result) ) + { + ui32_t duration = 0; + result = Parser.Reset(); + + while ( ASDCP_SUCCESS(result) && duration++ < Options.duration ) + { + if ( duration == 1 ) + { + result = Parser.ReadFrame(FrameBuffer); + + if ( ASDCP_SUCCESS(result) ) + { + if ( Options.verbose_flag ) + FrameBuffer.Dump(stderr, Options.fb_dump_size); + + if ( Options.encrypt_header_flag ) + FrameBuffer.PlaintextOffset(0); + } + } + + if ( ASDCP_SUCCESS(result) && ! Options.no_write_flag ) + { + result = Writer.WriteFrame(FrameBuffer, Context, HMAC); + + // The Writer class will forward the last block of ciphertext + // to the encryption context for use as the IV for the next + // frame. If you want to use non-sequitur IV values, un-comment + // the following line of code. + // if ( ASDCP_SUCCESS(result) && Options.key_flag ) + // Context->SetIVec(RNG.FillRandom(IV_buf, CBC_BLOCK_SIZE)); + } + } + + if ( result == RESULT_ENDOFFILE ) + result = RESULT_OK; + } + + if ( ASDCP_SUCCESS(result) && ! Options.no_write_flag ) + result = Writer.Finalize(); + + return result; +} + +//------------------------------------------------------------------------------------------ +// PCM essence + + +// Write one or more plaintext PCM audio streams to a plaintext ASDCP file +// Write one or more plaintext PCM audio streams to a ciphertext ASDCP file +// +Result_t +write_PCM_file(CommandOptions& Options) +{ + AESEncContext* Context = 0; + HMACContext* HMAC = 0; + PCMParserList Parser; + PCM::MXFWriter Writer; + PCM::FrameBuffer FrameBuffer; + PCM::AudioDescriptor ADesc; + byte_t IV_buf[CBC_BLOCK_SIZE]; + Kumu::FortunaRNG RNG; + + // set up essence parser + Result_t result = Parser.OpenRead(Options.filenames, Rational(1, 1)); + + // set up MXF writer + if ( ASDCP_SUCCESS(result) ) + { + Parser.FillAudioDescriptor(ADesc); + + ADesc.EditRate = Options.edit_rate; + FrameBuffer.Capacity(PCM::CalcFrameBufferSize(ADesc)); + + if ( Options.verbose_flag ) + { + char buf[64]; + fprintf(stderr, "%.1fkHz PCM Audio, %s fps (%u spf)\n", + ADesc.AudioSamplingRate.Quotient() / 1000.0, + RationalToString(Options.edit_rate, buf, 64), + PCM::CalcSamplesPerFrame(ADesc)); + fputs("AudioDescriptor:\n", stderr); + PCM::AudioDescriptorDump(ADesc); + } + } + + if ( ASDCP_SUCCESS(result) && ! Options.no_write_flag ) + { + WriterInfo Info = s_MyInfo; // fill in your favorite identifiers here + Info.LabelSetType = LS_MXF_SMPTE; + + if ( Options.asset_id_flag ) + memcpy(Info.AssetUUID, Options.asset_id_value, UUIDlen); + else + Kumu::GenRandomUUID(Info.AssetUUID); + + // configure encryption + if( Options.key_flag ) + { + Kumu::GenRandomUUID(Info.ContextID); + Info.EncryptedEssence = true; + + if ( Options.key_id_flag ) + memcpy(Info.CryptographicKeyID, Options.key_id_value, UUIDlen); + else + RNG.FillRandom(Info.CryptographicKeyID, UUIDlen); + + Context = new AESEncContext; + result = Context->InitKey(Options.key_value); + + if ( ASDCP_SUCCESS(result) ) + result = Context->SetIVec(RNG.FillRandom(IV_buf, CBC_BLOCK_SIZE)); + + if ( ASDCP_SUCCESS(result) && Options.write_hmac ) + { + Info.UsesHMAC = true; + HMAC = new HMACContext; + result = HMAC->InitKey(Options.key_value, Info.LabelSetType); + } + } + + if ( ASDCP_SUCCESS(result) ) + result = Writer.OpenWrite(Options.out_file.c_str(), Info, ADesc); + + if ( ASDCP_SUCCESS(result) && Options.channel_assignment.HasValue() ) + { + MXF::WaveAudioDescriptor *descriptor = 0; + Writer.OPAtomHeader().GetMDObjectByType(DefaultSMPTEDict().ul(MDD_WaveAudioDescriptor), + reinterpret_cast(&descriptor)); + descriptor->ChannelAssignment = Options.channel_assignment; + } + } + + if ( ASDCP_SUCCESS(result) ) + { + result = Parser.Reset(); + ui32_t duration = 0; + + while ( ASDCP_SUCCESS(result) && duration++ < Options.duration ) + { + result = Parser.ReadFrame(FrameBuffer); + + if ( ASDCP_SUCCESS(result) ) + { + if ( FrameBuffer.Size() != FrameBuffer.Capacity() ) + { + fprintf(stderr, "WARNING: Last frame read was short, PCM input is possibly not frame aligned.\n"); + fprintf(stderr, "Expecting %u bytes, got %u.\n", FrameBuffer.Capacity(), FrameBuffer.Size()); + result = RESULT_ENDOFFILE; + continue; + } + + if ( Options.verbose_flag ) + FrameBuffer.Dump(stderr, Options.fb_dump_size); + + if ( ! Options.no_write_flag ) + { + result = Writer.WriteFrame(FrameBuffer, Context, HMAC); + + // The Writer class will forward the last block of ciphertext + // to the encryption context for use as the IV for the next + // frame. If you want to use non-sequitur IV values, un-comment + // the following line of code. + // if ( ASDCP_SUCCESS(result) && Options.key_flag ) + // Context->SetIVec(RNG.FillRandom(IV_buf, CBC_BLOCK_SIZE)); + } + } + } + + if ( result == RESULT_ENDOFFILE ) + result = RESULT_OK; + } + + if ( ASDCP_SUCCESS(result) && ! Options.no_write_flag ) + result = Writer.Finalize(); + + return result; +} + + +// +int +main(int argc, const char** argv) +{ + Result_t result = RESULT_OK; + char str_buf[64]; + CommandOptions Options(argc, argv); + + if ( Options.version_flag ) + banner(); + + if ( Options.help_flag ) + usage(); + + if ( Options.version_flag || Options.help_flag ) + return 0; + + if ( Options.error_flag ) + { + fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME); + return 3; + } + + if ( Options.show_ul_values ) + { + DefaultSMPTEDict().Dump(stdout); + } + + EssenceType_t EssenceType; + result = ASDCP::RawEssenceType(Options.filenames.front().c_str(), EssenceType); + + if ( ASDCP_SUCCESS(result) ) + { + switch ( EssenceType ) + { + case ESS_JPEG_2000: + result = write_JP2K_file(Options); + break; + + case ESS_PCM_24b_48k: + case ESS_PCM_24b_96k: + result = write_PCM_file(Options); + break; + + default: + fprintf(stderr, "%s: Unknown file type, not ASDCP-compatible essence.\n", + Options.filenames.front().c_str()); + return 5; + } + } + + if ( ASDCP_FAILURE(result) ) + { + fputs("Program stopped on error.\n", stderr); + + if ( result != RESULT_FAIL ) + { + fputs(result, stderr); + fputc('\n', stderr); + } + + return 1; + } + + return 0; +} + + +// +// end as-02-wrap.cpp +// diff --git a/src/asdcp-wrap.cpp b/src/asdcp-wrap.cpp index a704552..b6880ac 100755 --- a/src/asdcp-wrap.cpp +++ b/src/asdcp-wrap.cpp @@ -28,7 +28,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \version $Id$ \brief AS-DCP file manipulation utility - This program wraps d-cinema essence (picture, sound or text) in t an AS-DCP + This program wraps d-cinema essence (picture, sound or text) into an AS-DCP MXF file. For more information about asdcplib, please refer to the header file AS_DCP.h @@ -129,7 +129,7 @@ Options:\n\ -j - Write key ID instead of creating a random value\n\ -k - Use key for ciphertext operations\n\ -M - Do not create HMAC values when writing\n\ - -a - Specify the Asset ID of a file\n\ + -a - Specify the Asset ID of the file\n\ -b - Specify size in bytes of picture frame buffer\n\ Defaults to 4,194,304 (4MB)\n\ -d - Number of frames to process, default all\n\ diff --git a/src/h__02_Reader.cpp b/src/h__02_Reader.cpp new file mode 100644 index 0000000..2a21165 --- /dev/null +++ b/src/h__02_Reader.cpp @@ -0,0 +1,128 @@ +/* + Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 h__02_Reader.cpp + \version $Id$ + \brief MXF file reader base class +*/ + +#include "AS_02_internal.h" + +using namespace ASDCP; +using namespace ASDCP::MXF; + +// +AS_02::h__Reader::h__Reader(const Dictionary& d) : + m_HeaderPart(m_Dict), m_FooterPart(m_Dict), m_Dict(&d), m_EssenceStart(0) +{ + m_pCurrentIndexPartition = 0; + //// start_pos = 0; +} + +AS_02::h__Reader::~h__Reader() +{ + std::vector::iterator bli = m_BodyPartList.begin(); + for ( ; bli != m_BodyPartList.end(); bli++ ){ + delete(*bli); + *bli = 0; + } + Close(); +} + +void +AS_02::h__Reader::Close() +{ + m_File.Close(); +} + +//------------------------------------------------------------------------------------------ +// + +// +Result_t +AS_02::h__Reader::InitInfo() +{ + assert(m_Dict); + InterchangeObject* Object; + + UL OPAtomUL(SMPTE_390_OPAtom_Entry().ul); + UL Interop_OPAtomUL(MXFInterop_OPAtom_Entry().ul); + m_Info.LabelSetType = LS_MXF_SMPTE; + + // Identification + Result_t result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(Identification), &Object); + + if( ASDCP_SUCCESS(result) ) + MD_to_WriterInfo((Identification*)Object, m_Info); + + // SourcePackage + if( ASDCP_SUCCESS(result) ) + result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(SourcePackage), &Object); + + if( ASDCP_SUCCESS(result) ) + { + SourcePackage* SP = (SourcePackage*)Object; + memcpy(m_Info.AssetUUID, SP->PackageUID.Value() + 16, UUIDlen); + } + + // optional CryptographicContext + if( ASDCP_SUCCESS(result) ) + { + Result_t cr_result = m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(CryptographicContext), &Object); + + if( ASDCP_SUCCESS(cr_result) ) + MD_to_CryptoInfo((CryptographicContext*)Object, m_Info, *m_Dict); + } + + return result; +} + +// standard method of populating the in-memory index +Result_t +AS_02::h__Reader::InitMXFIndex() +{ + if ( ! m_File.IsOpen() ) + return RESULT_INIT; + + Result_t result = m_File.Seek(m_HeaderPart.FooterPartition); + + if ( ASDCP_SUCCESS(result) ) + { + m_FooterPart.m_Lookup = &m_HeaderPart.m_Primer; + //Footer don't need to be initialized because there is no index table in the footer + //result = m_FooterPart.InitFromFile(m_File); + } + + if ( ASDCP_SUCCESS(result) ) + m_File.Seek(m_EssenceStart); + + return result; +} + + +// +// end h__02_Reader.cpp +// diff --git a/src/h__02_Writer.cpp b/src/h__02_Writer.cpp new file mode 100644 index 0000000..0ff0660 --- /dev/null +++ b/src/h__02_Writer.cpp @@ -0,0 +1,672 @@ +/* + Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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 h__02_Writer.cpp + \version $Id$ + \brief MXF file writer base class +*/ + +#include "AS_02_internal.h" + +using namespace ASDCP; +using namespace ASDCP::MXF; + +// a magic number identifying asdcplib +#ifndef ASDCP_BUILD_NUMBER +#define ASDCP_BUILD_NUMBER 0x6A68 +#endif + +// +AS_02::h__Writer::h__Writer(const Dictionary& d) : + m_HeaderPart(m_Dict), m_FooterPart(m_Dict), m_Dict(&d), + m_HeaderSize(0), m_EssenceStart(0), + m_EssenceDescriptor(0), m_FramesWritten(0), + m_StreamOffset(0), m_BodyOffset(0), + m_CurrentBodySID(0), m_CurrentIndexSID(0), + m_PartitionSpace(60), m_IndexStrategy(AS_02::IS_FOLLOW) +{ +} + +AS_02::h__Writer::~h__Writer() +{ + while (! m_BodyPartList.empty() ) + { + delete m_BodyPartList.back(); + m_BodyPartList.pop_back(); + } +} + +// +void +AS_02::h__Writer::InitHeader() +{ + assert(m_Dict); + assert(m_EssenceDescriptor); + + m_HeaderPart.m_Primer.ClearTagList(); + m_HeaderPart.m_Preface = new Preface(m_Dict); + m_HeaderPart.AddChildObject(m_HeaderPart.m_Preface); + + // Set the Operational Pattern label -- we're just starting and have no RIP or index, + // so we tell the world by using OP1a + m_HeaderPart.m_Preface->OperationalPattern = UL(m_Dict->ul(MDD_OP1a)); + m_HeaderPart.OperationalPattern = m_HeaderPart.m_Preface->OperationalPattern; + + //always more than 3 partition in AS-02; essence is not permitted to be existent in the header + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(0, 0)); // no essence in header + + // + // Identification + // + Identification* Ident = new Identification(m_Dict); + m_HeaderPart.AddChildObject(Ident); + m_HeaderPart.m_Preface->Identifications.push_back(Ident->InstanceUID); + + Kumu::GenRandomValue(Ident->ThisGenerationUID); + Ident->CompanyName = m_Info.CompanyName.c_str(); + Ident->ProductName = m_Info.ProductName.c_str(); + Ident->VersionString = m_Info.ProductVersion.c_str(); + Ident->ProductUID.Set(m_Info.ProductUUID); + Ident->Platform = ASDCP_PLATFORM; + + std::vector version = version_split(Version()); + + Ident->ToolkitVersion.Major = version[0]; + Ident->ToolkitVersion.Minor = version[1]; + Ident->ToolkitVersion.Patch = version[2]; + Ident->ToolkitVersion.Build = ASDCP_BUILD_NUMBER; + Ident->ToolkitVersion.Release = VersionType::RL_RELEASE; +} + +template +struct TrackSet +{ + MXF::Track* Track; + MXF::Sequence* Sequence; + ClipT* Clip; + + TrackSet() : Track(0), Sequence(0), Clip(0) {} +}; + +// +template +TrackSet +CreateTrackAndSequence(OPAtomHeader& Header, PackageT& Package, const std::string TrackName, + const MXF::Rational& EditRate, const UL& Definition, ui32_t TrackID, const Dictionary*& Dict) +{ + TrackSet NewTrack; + + NewTrack.Track = new Track(Dict); + Header.AddChildObject(NewTrack.Track); + NewTrack.Track->EditRate = EditRate; + Package.Tracks.push_back(NewTrack.Track->InstanceUID); + NewTrack.Track->TrackID = TrackID; + NewTrack.Track->TrackName = TrackName.c_str(); + + NewTrack.Sequence = new Sequence(Dict); + Header.AddChildObject(NewTrack.Sequence); + NewTrack.Track->Sequence = NewTrack.Sequence->InstanceUID; + NewTrack.Sequence->DataDefinition = Definition; + + return NewTrack; +} + +// +template +TrackSet +CreateTimecodeTrack(OPAtomHeader& Header, PackageT& Package, + const MXF::Rational& EditRate, ui32_t TCFrameRate, ui64_t TCStart, const Dictionary*& Dict) +{ + assert(Dict); + UL TCUL(Dict->ul(MDD_TimecodeDataDef)); + + TrackSet NewTrack = CreateTrackAndSequence(Header, Package, "Timecode Track", EditRate, TCUL, 1, Dict); + + NewTrack.Clip = new TimecodeComponent(Dict); + Header.AddChildObject(NewTrack.Clip); + NewTrack.Sequence->StructuralComponents.push_back(NewTrack.Clip->InstanceUID); + NewTrack.Clip->RoundedTimecodeBase = TCFrameRate; + NewTrack.Clip->StartTimecode = TCStart; + NewTrack.Clip->DataDefinition = TCUL; + + return NewTrack; +} + + +// +void +AS_02::h__Writer::AddSourceClip(const ASDCP::MXF::Rational& EditRate, ui32_t TCFrameRate, + const std::string& TrackName, const UL& EssenceUL, + const UL& DataDefinition, const std::string& PackageLabel) +{ + // + ContentStorage* Storage = new ContentStorage(m_Dict); + m_HeaderPart.AddChildObject(Storage); + m_HeaderPart.m_Preface->ContentStorage = Storage->InstanceUID; + + EssenceContainerData* ECD = new EssenceContainerData(m_Dict); + m_HeaderPart.AddChildObject(ECD); + Storage->EssenceContainerData.push_back(ECD->InstanceUID); + ECD->IndexSID = 129; + ECD->BodySID = 1; + + UUID assetUUID(m_Info.AssetUUID); + UMID SourcePackageUMID, MaterialPackageUMID; + SourcePackageUMID.MakeUMID(0x0f, assetUUID); + MaterialPackageUMID.MakeUMID(0x0f); // unidentified essence + + // + // Material Package + // + m_MaterialPackage = new MaterialPackage(m_Dict); + m_MaterialPackage->Name = "AS_02 Material Package"; + m_MaterialPackage->PackageUID = MaterialPackageUMID; + m_HeaderPart.AddChildObject(m_MaterialPackage); + Storage->Packages.push_back(m_MaterialPackage->InstanceUID); + + TrackSet MPTCTrack = + CreateTimecodeTrack(m_HeaderPart, *m_MaterialPackage, + EditRate, TCFrameRate, 0, m_Dict); + m_DurationUpdateList.push_back(&(MPTCTrack.Sequence->Duration)); + m_DurationUpdateList.push_back(&(MPTCTrack.Clip->Duration)); + + TrackSet MPTrack = + CreateTrackAndSequence(m_HeaderPart, *m_MaterialPackage, + TrackName, EditRate, DataDefinition, + 2, m_Dict); + m_DurationUpdateList.push_back(&(MPTrack.Sequence->Duration)); + + MPTrack.Clip = new SourceClip(m_Dict); + m_HeaderPart.AddChildObject(MPTrack.Clip); + MPTrack.Sequence->StructuralComponents.push_back(MPTrack.Clip->InstanceUID); + MPTrack.Clip->DataDefinition = DataDefinition; + MPTrack.Clip->SourcePackageID = SourcePackageUMID; + MPTrack.Clip->SourceTrackID = 2; + m_DurationUpdateList.push_back(&(MPTrack.Clip->Duration)); + + + // + // File (Source) Package + // + m_FilePackage = new SourcePackage(m_Dict); + m_FilePackage->Name = PackageLabel.c_str(); + m_FilePackage->PackageUID = SourcePackageUMID; + ECD->LinkedPackageUID = SourcePackageUMID; + + m_HeaderPart.AddChildObject(m_FilePackage); + Storage->Packages.push_back(m_FilePackage->InstanceUID); + + TrackSet FPTCTrack = + CreateTimecodeTrack(m_HeaderPart, *m_FilePackage, + EditRate, TCFrameRate, + ui64_C(3600) * TCFrameRate, m_Dict); + m_DurationUpdateList.push_back(&(FPTCTrack.Sequence->Duration)); + m_DurationUpdateList.push_back(&(FPTCTrack.Clip->Duration)); + TrackSet FPTrack = + CreateTrackAndSequence(m_HeaderPart, *m_FilePackage, + TrackName, EditRate, DataDefinition, + 2, m_Dict); + m_DurationUpdateList.push_back(&(FPTrack.Sequence->Duration)); + + // Consult ST 379:2004 Sec. 6.3, "Element to track relationship" to see where "12" comes from. + FPTrack.Track->TrackNumber = KM_i32_BE(Kumu::cp2i((EssenceUL.Value() + 12))); + + FPTrack.Clip = new SourceClip(m_Dict); + m_HeaderPart.AddChildObject(FPTrack.Clip); + FPTrack.Sequence->StructuralComponents.push_back(FPTrack.Clip->InstanceUID); + FPTrack.Clip->DataDefinition = DataDefinition; + + // for now we do not allow setting this value, so all files will be 'original' + FPTrack.Clip->SourceTrackID = 0; + FPTrack.Clip->SourcePackageID = NilUMID; + m_DurationUpdateList.push_back(&(FPTrack.Clip->Duration)); + + m_EssenceDescriptor->LinkedTrackID = FPTrack.Track->TrackID; +} + +// +void +AS_02::h__Writer::AddDMSegment(const ASDCP::MXF::Rational& EditRate, ui32_t TCFrameRate, + const std::string& TrackName, const UL& DataDefinition, + const std::string& PackageLabel) +{ + // + ContentStorage* Storage = new ContentStorage(m_Dict); + m_HeaderPart.AddChildObject(Storage); + m_HeaderPart.m_Preface->ContentStorage = Storage->InstanceUID; + + EssenceContainerData* ECD = new EssenceContainerData(m_Dict); + m_HeaderPart.AddChildObject(ECD); + Storage->EssenceContainerData.push_back(ECD->InstanceUID); + ECD->IndexSID = 129; + ECD->BodySID = 1; + + UUID assetUUID(m_Info.AssetUUID); + UMID SourcePackageUMID, MaterialPackageUMID; + SourcePackageUMID.MakeUMID(0x0f, assetUUID); + MaterialPackageUMID.MakeUMID(0x0f); // unidentified essence + + // + // Material Package + // + m_MaterialPackage = new MaterialPackage(m_Dict); + m_MaterialPackage->Name = "AS_02 Material Package"; + m_MaterialPackage->PackageUID = MaterialPackageUMID; + m_HeaderPart.AddChildObject(m_MaterialPackage); + Storage->Packages.push_back(m_MaterialPackage->InstanceUID); + + TrackSet MPTCTrack = + CreateTimecodeTrack(m_HeaderPart, *m_MaterialPackage, + EditRate, TCFrameRate, 0, m_Dict); + m_DurationUpdateList.push_back(&(MPTCTrack.Sequence->Duration)); + m_DurationUpdateList.push_back(&(MPTCTrack.Clip->Duration)); + + TrackSet MPTrack = + CreateTrackAndSequence(m_HeaderPart, *m_MaterialPackage, + TrackName, EditRate, DataDefinition, + 2, m_Dict); + m_DurationUpdateList.push_back(&(MPTrack.Sequence->Duration)); + + MPTrack.Clip = new DMSegment(m_Dict); + m_HeaderPart.AddChildObject(MPTrack.Clip); + MPTrack.Sequence->StructuralComponents.push_back(MPTrack.Clip->InstanceUID); + MPTrack.Clip->DataDefinition = DataDefinition; + // MPTrack.Clip->SourcePackageID = SourcePackageUMID; + // MPTrack.Clip->SourceTrackID = 2; + m_DurationUpdateList.push_back(&(MPTrack.Clip->Duration)); + + + // + // File (Source) Package + // + m_FilePackage = new SourcePackage(m_Dict); + m_FilePackage->Name = PackageLabel.c_str(); + m_FilePackage->PackageUID = SourcePackageUMID; + ECD->LinkedPackageUID = SourcePackageUMID; + + m_HeaderPart.AddChildObject(m_FilePackage); + Storage->Packages.push_back(m_FilePackage->InstanceUID); + + TrackSet FPTCTrack = + CreateTimecodeTrack(m_HeaderPart, *m_FilePackage, + EditRate, TCFrameRate, + ui64_C(3600) * TCFrameRate, m_Dict); + m_DurationUpdateList.push_back(&(FPTCTrack.Sequence->Duration)); + m_DurationUpdateList.push_back(&(FPTCTrack.Clip->Duration)); + + TrackSet FPTrack = + CreateTrackAndSequence(m_HeaderPart, *m_FilePackage, + TrackName, EditRate, DataDefinition, + 2, m_Dict); + m_DurationUpdateList.push_back(&(FPTrack.Sequence->Duration)); + + FPTrack.Clip = new DMSegment(m_Dict); + m_HeaderPart.AddChildObject(FPTrack.Clip); + FPTrack.Sequence->StructuralComponents.push_back(FPTrack.Clip->InstanceUID); + FPTrack.Clip->DataDefinition = DataDefinition; + FPTrack.Clip->EventComment = "D-Cinema Timed Text"; + + m_DurationUpdateList.push_back(&(FPTrack.Clip->Duration)); + m_EssenceDescriptor->LinkedTrackID = FPTrack.Track->TrackID; +} + +// +void +AS_02::h__Writer::AddEssenceDescriptor(const UL& WrappingUL) +{ + // + // Essence Descriptor + // + m_EssenceDescriptor->EssenceContainer = WrappingUL; + m_HeaderPart.m_Preface->PrimaryPackage = m_FilePackage->InstanceUID; + + // + // Essence Descriptors + // + assert(m_Dict); + //TODO: Mono Essence, only one GenericContainer ? + //UL GenericContainerUL(m_Dict->ul(MDD_GCMulti)); + //m_HeaderPart.EssenceContainers.push_back(GenericContainerUL); + + if ( m_Info.EncryptedEssence ) + { + UL CryptEssenceUL(m_Dict->ul(MDD_EncryptedContainerLabel)); + m_HeaderPart.EssenceContainers.push_back(CryptEssenceUL); + m_HeaderPart.m_Preface->DMSchemes.push_back(UL(m_Dict->ul(MDD_CryptographicFrameworkLabel))); + AddDMScrypt(m_HeaderPart, *m_FilePackage, m_Info, WrappingUL, m_Dict); + } + else + { + m_HeaderPart.EssenceContainers.push_back(WrappingUL); + } + + m_HeaderPart.m_Preface->EssenceContainers = m_HeaderPart.EssenceContainers; + m_HeaderPart.AddChildObject(m_EssenceDescriptor); + + std::list::iterator sdli = m_EssenceSubDescriptorList.begin(); + for ( ; sdli != m_EssenceSubDescriptorList.end(); sdli++ ) + m_HeaderPart.AddChildObject(*sdli); + + m_FilePackage->Descriptor = m_EssenceDescriptor->InstanceUID; +} + +// +Result_t +AS_02::h__Writer::CreateBodyPart(const ASDCP::MXF::Rational& EditRate, ui32_t BytesPerEditUnit) +{ + assert(m_Dict); + Result_t result = RESULT_OK; + m_EditRate = EditRate; + m_BytesPerEditUnit = BytesPerEditUnit; + + result = CreateBodyPartPair(); + + //TODO: no IndexTables in the footer -> The spec is silent on that topic + m_FooterPart.IndexSID = 0;//129; + + return result; +} + +// standard method of creating a new BodyPartition Pair for Essence and IndexTables +Result_t AS_02::h__Writer::CreateBodyPartPair() +{ + Result_t result = RESULT_OK; + + if ( m_IndexStrategy == AS_02::IS_FILE_SPECIFIC ){ + result = RESULT_FAIL; + } + + //similar to both index strategies + + Partition *m_BodyPartEssence = new ASDCP::MXF::Partition(m_Dict); + m_BodyPartEssence->EssenceContainers = m_HeaderPart.EssenceContainers; + //necessary? - here we must increment the BodySID, when a new BodyPartion is created + m_BodyPartEssence->BodySID = 1;//++m_CurrentBodySID; + UL OperationalPattern(m_Dict->ul(MDD_OP1a)); + m_BodyPartEssence->OperationalPattern = OperationalPattern; + + m_BodyPartEssence->FooterPartition = 0; + m_BodyPartEssence->IndexSID = 0; + m_BodyPartEssence->BodyOffset = m_BodyOffset; + + m_CurrentIndexBodyPartition = new AS_02::MXF::OP1aIndexBodyPartion(this->m_Dict); + m_CurrentIndexBodyPartition->EssenceContainers = m_HeaderPart.EssenceContainers; + m_CurrentIndexBodyPartition->BodySID = 0; + m_CurrentIndexBodyPartition->OperationalPattern = OperationalPattern; + m_CurrentIndexBodyPartition->FooterPartition = 0; + m_CurrentIndexBodyPartition->IndexSID = 129;//++m_CurrentIndexSID; + + //we must differentiate between index_strategy "lead" and "follow" + if ( m_IndexStrategy == AS_02::IS_FOLLOW ) + { + if(m_BodyPartList.size()>0){ + m_BodyPartEssence->PreviousPartition = m_BodyPartList.back()->ThisPartition; + } + else{ + m_BodyPartEssence->PreviousPartition = m_HeaderPart.ThisPartition; + } + /* Write partition header for the body partition and create IndexBodyPartition. + When "all" essence packets are written, write out index table. */ + m_CurrentIndexBodyPartition->ThisPartition = 0; + m_BodyPartEssence->ThisPartition = m_File.Tell(); + m_CurrentIndexBodyPartition->PreviousPartition = m_BodyPartEssence->ThisPartition; + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(m_CurrentIndexBodyPartition->BodySID, m_CurrentIndexBodyPartition->ThisPartition)); + + this->m_BodyPartList.push_back(m_CurrentIndexBodyPartition); + this->m_BodyPartList.push_back(m_BodyPartEssence); + } + else if ( m_IndexStrategy == AS_02::IS_LEAD ) + { + /* Write KLVFill packet large enough to hold the completed index data */ + m_CurrentIndexBodyPartition->ThisPartition = m_File.Tell(); + m_CurrentIndexBodyPartition->FillWriteToFile(m_File,m_PartitionSpace); + m_BodyPartEssence->ThisPartition = m_File.Tell(); + m_BodyPartEssence->PreviousPartition = m_CurrentIndexBodyPartition->ThisPartition; + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(m_CurrentIndexBodyPartition->BodySID, m_CurrentIndexBodyPartition->ThisPartition)); + + if(m_BodyPartList.size()>0){ + m_CurrentIndexBodyPartition->PreviousPartition = m_BodyPartList.back()->ThisPartition; + } + else{ + m_CurrentIndexBodyPartition->PreviousPartition = m_HeaderPart.ThisPartition; + } + + //necessary to traverse across all of the body partition packs and update the FooterPartition entries at the end of writing + this->m_BodyPartList.push_back(m_CurrentIndexBodyPartition); + this->m_BodyPartList.push_back(m_BodyPartEssence); + + } + + /* similar to both index strategies */ + + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(m_BodyPartEssence->BodySID, m_BodyPartEssence->ThisPartition)); + UL BodyUL(m_Dict->ul(MDD_ClosedCompleteBodyPartition)); + result = m_BodyPartEssence->WriteToFile(m_File, BodyUL); + + if ( ASDCP_SUCCESS(result) ) + { + //TODO: Is this necessary?What means ECoffset?Never used in the code? If necessary check if it is set correctly. + + // Index setup + Kumu::fpos_t ECoffset = m_File.Tell(); + + if(m_BytesPerEditUnit == 0){ + m_CurrentIndexBodyPartition->SetIndexParamsVBR(&m_HeaderPart.m_Primer, m_EditRate, ECoffset); + } + else{ + m_CurrentIndexBodyPartition->SetIndexParamsCBR(&m_HeaderPart.m_Primer, m_BytesPerEditUnit, m_EditRate); + } + } + + return result; +} + +Result_t AS_02::h__Writer::CompleteIndexBodyPart() +{ + Result_t result = RESULT_OK; + if ( m_IndexStrategy == AS_02::IS_FOLLOW ) + { + m_CurrentIndexBodyPartition->ThisPartition = m_File.Tell(); + m_HeaderPart.m_RIP.PairArray.push_back(RIP::Pair(m_CurrentIndexBodyPartition->BodySID, m_CurrentIndexBodyPartition->ThisPartition)); + } + + UL BodyUL(m_Dict->ul(MDD_ClosedCompleteBodyPartition)); + ui64_t cur_pos = m_File.Tell(); + m_File.Seek(m_CurrentIndexBodyPartition->ThisPartition); + result = m_CurrentIndexBodyPartition->WriteToFile(m_File, BodyUL); + m_File.Seek(cur_pos); + return result; +} + +// +Result_t +AS_02::h__Writer::WriteMXFHeader(const std::string& PackageLabel, const UL& WrappingUL, + const std::string& TrackName, const UL& EssenceUL, const UL& DataDefinition, + const ASDCP::MXF::Rational& EditRate, ui32_t TCFrameRate, ui32_t BytesPerEditUnit) +{ + InitHeader(); + AddSourceClip(EditRate, TCFrameRate, TrackName, EssenceUL, DataDefinition, PackageLabel); + AddEssenceDescriptor(WrappingUL); + + Result_t result = m_HeaderPart.WriteToFile(m_File, m_HeaderSize); + + //use the FrameRate for the indexing; initialize the SID counters + m_CurrentBodySID = 0; + m_CurrentIndexSID = 0; + m_PartitionSpace = m_PartitionSpace * TCFrameRate; ///// TODO ???? + + if ( KM_SUCCESS(result) ) + result = CreateBodyPart(EditRate, BytesPerEditUnit); + + return result; +} + + +// standard method of writing a plaintext or encrypted frame +Result_t +AS_02::h__Writer::WriteEKLVPacket(const ASDCP::FrameBuffer& FrameBuf, const byte_t* EssenceUL, + AESEncContext* Ctx, HMACContext* HMAC) +{ + Result_t result = RESULT_OK; + IntegrityPack IntPack; + + byte_t overhead[128]; + Kumu::MemIOWriter Overhead(overhead, 128); + assert(m_Dict); + + if ( FrameBuf.Size() == 0 ) + { + DefaultLogSink().Error("Cannot write empty frame buffer\n"); + return RESULT_EMPTY_FB; + } + + if ( m_Info.EncryptedEssence ) + { + if ( ! Ctx ) + return RESULT_CRYPT_CTX; + + if ( m_Info.UsesHMAC && ! HMAC ) + return RESULT_HMAC_CTX; + + if ( FrameBuf.PlaintextOffset() > FrameBuf.Size() ) + return RESULT_LARGE_PTO; + + // encrypt the essence data (create encrypted source value) + result = EncryptFrameBuffer(FrameBuf, m_CtFrameBuf, Ctx); + + // create HMAC + if ( ASDCP_SUCCESS(result) && m_Info.UsesHMAC ) + result = IntPack.CalcValues(m_CtFrameBuf, m_Info.AssetUUID, m_FramesWritten + 1, HMAC); + + if ( ASDCP_SUCCESS(result) ) + { // write UL + Overhead.WriteRaw(m_Dict->ul(MDD_CryptEssence), SMPTE_UL_LENGTH); + + // construct encrypted triplet header + ui32_t ETLength = klv_cryptinfo_size + m_CtFrameBuf.Size(); + ui32_t BER_length = MXF_BER_LENGTH; + + if ( m_Info.UsesHMAC ) + ETLength += klv_intpack_size; + else + ETLength += (MXF_BER_LENGTH * 3); // for empty intpack + + if ( ETLength > 0x00ffffff ) // Need BER integer longer than MXF_BER_LENGTH bytes + { + BER_length = Kumu::get_BER_length_for_value(ETLength); + + // the packet is longer by the difference in expected vs. actual BER length + ETLength += BER_length - MXF_BER_LENGTH; + + if ( BER_length == 0 ) + result = RESULT_KLV_CODING; + } + + if ( ASDCP_SUCCESS(result) ) + { + if ( ! ( Overhead.WriteBER(ETLength, BER_length) // write encrypted triplet length + && Overhead.WriteBER(UUIDlen, MXF_BER_LENGTH) // write ContextID length + && Overhead.WriteRaw(m_Info.ContextID, UUIDlen) // write ContextID + && Overhead.WriteBER(sizeof(ui64_t), MXF_BER_LENGTH) // write PlaintextOffset length + && Overhead.WriteUi64BE(FrameBuf.PlaintextOffset()) // write PlaintextOffset + && Overhead.WriteBER(SMPTE_UL_LENGTH, MXF_BER_LENGTH) // write essence UL length + && Overhead.WriteRaw((byte_t*)EssenceUL, SMPTE_UL_LENGTH) // write the essence UL + && Overhead.WriteBER(sizeof(ui64_t), MXF_BER_LENGTH) // write SourceLength length + && Overhead.WriteUi64BE(FrameBuf.Size()) // write SourceLength + && Overhead.WriteBER(m_CtFrameBuf.Size(), BER_length) ) ) // write ESV length + { + result = RESULT_KLV_CODING; + } + } + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(Overhead.Data(), Overhead.Length()); + } + + if ( ASDCP_SUCCESS(result) ) + { + m_StreamOffset += Overhead.Length(); + // write encrypted source value + result = m_File.Writev((byte_t*)m_CtFrameBuf.RoData(), m_CtFrameBuf.Size()); + } + + if ( ASDCP_SUCCESS(result) ) + { + m_StreamOffset += m_CtFrameBuf.Size(); + + byte_t hmoverhead[512]; + Kumu::MemIOWriter HMACOverhead(hmoverhead, 512); + + // write the HMAC + if ( m_Info.UsesHMAC ) + { + HMACOverhead.WriteRaw(IntPack.Data, klv_intpack_size); + } + else + { // we still need the var-pack length values if the intpack is empty + for ( ui32_t i = 0; i < 3 ; i++ ) + HMACOverhead.WriteBER(0, MXF_BER_LENGTH); + } + + // write HMAC + result = m_File.Writev(HMACOverhead.Data(), HMACOverhead.Length()); + m_StreamOffset += HMACOverhead.Length(); + } + } + else + { + ui32_t BER_length = MXF_BER_LENGTH; + + if ( FrameBuf.Size() > 0x00ffffff ) // Need BER integer longer than MXF_BER_LENGTH bytes + { + BER_length = Kumu::get_BER_length_for_value(FrameBuf.Size()); + + if ( BER_length == 0 ) + result = RESULT_KLV_CODING; + } + + Overhead.WriteRaw((byte_t*)EssenceUL, SMPTE_UL_LENGTH); + Overhead.WriteBER(FrameBuf.Size(), BER_length); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(Overhead.Data(), Overhead.Length()); + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev((byte_t*)FrameBuf.RoData(), FrameBuf.Size()); + + if ( ASDCP_SUCCESS(result) ) + m_StreamOffset += Overhead.Length() + FrameBuf.Size(); + } + + if ( ASDCP_SUCCESS(result) ) + result = m_File.Writev(); + + return result; +} + +// +// end h__02_Writer.cpp +// diff --git a/src/h__Writer.cpp b/src/h__Writer.cpp index f21b165..48b3486 100755 --- a/src/h__Writer.cpp +++ b/src/h__Writer.cpp @@ -41,31 +41,6 @@ using namespace ASDCP::MXF; #endif -static std::vector -version_split(const char* str) -{ - std::vector result; - - const char* pstr = str; - const char* r = strchr(pstr, '.'); - - while ( r != 0 ) - { - assert(r >= pstr); - if ( r > pstr ) - result.push_back(atoi(pstr)); - - pstr = r + 1; - r = strchr(pstr, '.'); - } - - if( strlen(pstr) > 0 ) - result.push_back(atoi(pstr)); - - assert(result.size() == 3); - return result; -} - // ASDCP::h__Writer::h__Writer(const Dictionary& d) : -- 2.30.2