Click here to Skip to main content
12,628,702 members (32,345 online)
Click here to Skip to main content

Stats

255K views
4.7K downloads
105 bookmarked
Posted

Windows Media Audio compressor

, 8 Apr 2004
Managed C++ Windows Media Audio (WMA) compressor.
//
//  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
//  PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER 
//  REMAINS UNCHANGED.
//
//  Email:  yetiicb@hotmail.com
//
//  Copyright (C) 2002-2004 Idael Cardoso. 
//
#pragma once

#include "WmaWriterConfig.h"
#include "WriterSink.h"
#include "WmaWriter.h"

using namespace System;
using namespace System::IO;
using namespace System::Runtime::InteropServices;
using namespace WaveLib;
using namespace Yeti::MMedia;


namespace Yeti
{
  namespace MMedia
  {
    namespace Wmf
    {
      public __gc class WmaWriter : public AudioWriter, public IWriterSink
	      {
        protected:
          CWmaWriter* m_Writer;
          bool m_HeaderWrote;
          int m_HeaderSize;
          __int64 m_HeaderPos;
          
          void Init(WmaWriterProfile* Profile)
          {
            m_Writer = NULL;
            m_HeaderWrote = false;
            CProfile* pPrf = Profile->pProfile;
            if (pPrf != NULL)
            {
              try
              {
                CComPtr<IWMWriterSink> Sink;
                CWriterSink::Create( dynamic_cast<IWriterSink*>(this), &Sink);
                try
                {
                  GCHandle h = GCHandle::Alloc(m_InputDataFormat, GCHandleType::Pinned);
                  try
                  {
                    WAVEFORMATEX* pf = (WAVEFORMATEX*)h.AddrOfPinnedObject().ToPointer();
                    m_Writer = new CWmaWriter(pf, pPrf->m_Profile, Sink);
                  }
                  __finally
                  {
                    h.Free();
                  }
                }
                __finally
                {
                  Sink = NULL;
                }
              }
              __finally
              {
                delete pPrf;
              }
            }
            else
            {
              throw new ArgumentException("Invalid profile", "Profile");
            }
          }
        public:

          WmaWriter(System::IO::Stream*  Output, WaveLib::WaveFormat __gc* Format, WmaWriterProfile __gc* Profile)
            :AudioWriter(Output, Format)
          {
          Init(Profile);
          }
          WmaWriter(System::IO::Stream*  Output, WmaWriterConfig* Config)
            :AudioWriter(Output, Config)
          {
            Init(Config->Profile);
          }
          WmaWriter(System::IO::Stream*  Output, WaveLib::WaveFormat* Format)
            :AudioWriter(Output, Format)
          {
            Init(WmaWriterProfileManager::AudioSystemProfiles[0]);
          }
        public: //IWriterSink
          HRESULT OnHeader(/* [in] */INSSBuffer *pHeader)
          {
            try
            {
              DWORD Length = 0;
              Byte buffer[] = NULL;
              CComPtr<IManBufferRef> pManRef;
              if ( SUCCEEDED(pHeader->QueryInterface(__uuidof(IManBufferRef), (void**)&pManRef)) )
              {
                void* IntfHandle = NULL;
                pManRef->GetManBuffer(&IntfHandle);
                GCHandle h = GCHandle::op_Explicit(IntPtr(IntfHandle));
			          IManBuffer* ManBuff = static_cast<IManBuffer*>(h.Target);
                Length = ManBuff->UsedLength;
                buffer = ManBuff->Buffer;
              }
              else
              {
                BYTE* pBuffer = NULL;
                if ( SUCCEEDED(pHeader->GetBufferAndLength(&pBuffer, &Length)) )
                {
                  buffer = new Byte[Length];
                  Marshal::Copy(IntPtr(pBuffer), buffer, 0, Length);
                }
              }
              if ( !m_HeaderWrote )
              {
                if (BaseStream->CanSeek)
                {
                  m_HeaderPos = BaseStream->Position;
                }
                __super::Write(buffer, 0, Length);
                m_HeaderSize = Length;
                m_HeaderWrote = true;
              }
              else
                if ( (m_HeaderSize == Length) && (BaseStream->CanSeek) )
                {
                  __int64 pos = BaseStream->Position;
                  BaseStream->Position = m_HeaderPos;
                  __super::Write(buffer, 0, Length);
                  BaseStream->Position = pos;
                }
            }
            catch(...)
            {
            }
            return S_OK;
          }
          HRESULT AllocateDataUnit(/* [in] */DWORD cbDataUnit,/* [out] */ INSSBuffer **ppDataUnit)
          {
            IManBuffer* ManBuff = new ManBuffer(cbDataUnit);
            CBuffer::Create(ManBuff, ppDataUnit);
            return S_OK;
          }
          HRESULT IsRealTime(/* [out] */ BOOL *pfRealTime)
          {
            *pfRealTime = false;
            return S_OK;
          }
          HRESULT OnDataUnit(/* [in] */INSSBuffer *pDataUnit)
          {
          try
            {
              CComPtr<IManBufferRef> pManRef;
              if ( SUCCEEDED(pDataUnit->QueryInterface(__uuidof(IManBufferRef), (void**)&pManRef)) )
              {
                void* IntfHandle = NULL;
                pManRef->GetManBuffer(&IntfHandle);
                GCHandle h = GCHandle::op_Explicit(IntPtr(IntfHandle));
			          IManBuffer* ManBuffer = static_cast<IManBuffer*>(h.Target);
                __super::Write(ManBuffer->Buffer, 0, ManBuffer->UsedLength);
              }
              else
              {
                DWORD size = 0;
                BYTE* pBuffer = NULL;
                if ( SUCCEEDED(pDataUnit->GetBufferAndLength(&pBuffer, &size)) )
                {
                  Byte Buffer[] = new Byte[size];
                  Marshal::Copy(IntPtr(pBuffer), Buffer, 0, size);
                  __super::Write(Buffer, 0, size);
                }
              }
            }
            catch(...)
            {
            }
            return S_OK;
          }
          HRESULT OnEndWriting( void)
          {
            return S_OK;
          }
        protected:
          virtual int GetOptimalBufferSize()
          {
            return m_InputDataFormat->nAvgBytesPerSec /10;
          }
          virtual String* GetDefaultAudioFileExtension()
          {
            return S"wma";
          }
        public: //overrides
          virtual void Close()
          {
            if (m_Writer != NULL)
            {
              delete m_Writer;
              m_Writer = NULL;
            }
            __super::Close();
          }
          virtual void Write(Byte Buffer[], int index, int count)
          {
            if ( (count % m_InputDataFormat->nBlockAlign) == 0 )
            {
              if ( (index+count) > Buffer->Length )
              {
                throw new IndexOutOfRangeException();
              }
              Byte __pin* pBuffer = &Buffer[index];
              m_Writer->Write(pBuffer, count);
            }
            else
            {
              throw new ArgumentException(String::Format(S"Invalid buffer size. Buffer size must be aligned to {0} bytes.", __box(m_InputDataFormat->nBlockAlign)), String::Format(S"count={0}", __box(count)));
            }
          }
          virtual void Write(Byte Buffer[])
          {
            Write(Buffer, 0, Buffer->Length);
          }
        };
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Idael Cardoso
Web Developer
France France
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 9 Apr 2004
Article Copyright 2004 by Idael Cardoso
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid