Copying ltmmMediaSample Attributes and Data for C++

The following code demonstrates how to copy a media sample's attributes and data to another media sample.

// include the LEAD Multimedia TOOLKIT header
#include "ltmm.h"

/////////////////////////////////////////////////////////////////
//CopyMediaSampleAttributes
// copies data and attributes from one sample to another
// pDest - destination sample interface
// pSource - source sample interface
HRESULT CopyMediaSampleAttributes(IltmmMediaSampleDisp* pDest, IltmmMediaSampleDisp* pSource)
{
   HRESULT hr;
   VARIANT_BOOL f;
   LARGE_INTEGER starttime;
   LARGE_INTEGER stoptime;
   VARIANT var;
   long cbData;
   long cbBuffer;
   IltmmMediaTypeDisp* pMediaType;

   // return error if NULL
   if(!pSource || !pDest)
      return E_POINTER;

   // get the source actual data length
   hr = pSource->get_ActualDataLength(&cbData);
   if(FAILED(hr))
      return hr;

   // now the dest maximum buffer size
   hr = pDest->get_BufferSize(&cbBuffer);
   if(FAILED(hr))
      return hr;

   // if no room for the data, return an error
   if(cbData > cbBuffer)
      return E_OUTOFMEMORY;

   // any data to copy?
   if(cbData)
   {
      // yes, then copy away
      hr = pSource->GetData(cbData, &var);
      if(FAILED(hr))
         return hr;
      hr = pDest->SetData(cbData, var);
      VariantClear(&var);
      if(FAILED(hr))
         return hr;
   }
   else
   {
      // no, just set the dest data length to 0
      pDest->put_ActualDataLength(0);
   }

   // copy the the media type, if there is one
   pMediaType = NULL;
   pSource->GetMediaType(&pMediaType);
   if(pMediaType)
   {
      pDest->SetMediaType(pMediaType);
      pMediaType->Release();
   }

   // copy discontinuity
   f = VARIANT_FALSE;
   pSource->get_Discontinuity(&f);
   pDest->put_Discontinuity(f);

   // copy preroll
   f = VARIANT_FALSE;
   pSource->get_Preroll(&f);
   pDest->put_Preroll(f);

   // copy syncpoint
   f = VARIANT_FALSE;
   pSource->get_SyncPoint(&f);
   pDest->put_SyncPoint(f);

   // is the time available?
   hr = pSource->GetTime(&starttime.HighPart, (long*) &starttime.LowPart, &stoptime.HighPart, (long*) &stoptime.LowPart);
   if(FAILED(hr))
   {
      // no, then reset the dest time
      pDest->ResetTime();
   }
   else
   {
      // yes, copy to the dest
      pDest->SetTime(starttime.HighPart, starttime.LowPart, stoptime.HighPart, stoptime.LowPart);
   }

   // is the media time available?
   hr = pSource->GetMediaTime(&starttime.HighPart, (long*) &starttime.LowPart, &stoptime.HighPart, (long*) &stoptime.LowPart);
   if(FAILED(hr))
   {
      // no, then reset the dest media time
      pDest->ResetMediaTime();
   }
   else
   {
      // yes, copy to the dest
      pDest->SetMediaTime(starttime.HighPart, starttime.LowPart, stoptime.HighPart, stoptime.LowPart);
   }
   return S_OK;
}