diff --git a/APEDotNet/APEDotNet.h b/APEDotNet/APEDotNet.h new file mode 100644 index 0000000..e69de29 diff --git a/APEDotNet/APEDotNet.vcproj b/APEDotNet/APEDotNet.vcproj new file mode 100644 index 0000000..634179d --- /dev/null +++ b/APEDotNet/APEDotNet.vcproj @@ -0,0 +1,422 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/APEDotNet/AssemblyInfo.cpp b/APEDotNet/AssemblyInfo.cpp new file mode 100644 index 0000000..c369569 --- /dev/null +++ b/APEDotNet/AssemblyInfo.cpp @@ -0,0 +1,40 @@ +#include "stdafx.h" + +using namespace System; +using namespace System::Reflection; +using namespace System::Runtime::CompilerServices; +using namespace System::Runtime::InteropServices; +using namespace System::Security::Permissions; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly:AssemblyTitleAttribute("APEDotNet")]; +[assembly:AssemblyDescriptionAttribute("")]; +[assembly:AssemblyConfigurationAttribute("")]; +[assembly:AssemblyCompanyAttribute("")]; +[assembly:AssemblyProductAttribute("APEDotNet")]; +[assembly:AssemblyCopyrightAttribute("Copyright (c) Greg Chudov 2008")]; +[assembly:AssemblyTrademarkAttribute("")]; +[assembly:AssemblyCultureAttribute("")]; + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the value or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly:AssemblyVersionAttribute("1.0.*")]; + +[assembly:ComVisible(false)]; + +[assembly:CLSCompliantAttribute(true)]; + +[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/APEDotNet/ReadMe.txt b/APEDotNet/ReadMe.txt new file mode 100644 index 0000000..7b4d3de --- /dev/null +++ b/APEDotNet/ReadMe.txt @@ -0,0 +1,31 @@ +======================================================================== + DYNAMIC LINK LIBRARY : APEDotNet Project Overview +======================================================================== + +AppWizard has created this APEDotNet DLL for you. + +This file contains a summary of what you will find in each of the files that +make up your APEDotNet application. + +APEDotNet.vcproj + This is the main project file for VC++ projects generated using an Application Wizard. + It contains information about the version of Visual C++ that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +APEDotNet.cpp + This is the main DLL source file. + +APEDotNet.h + This file contains a class declaration. + +AssemblyInfo.cpp + Contains custom attributes for modifying assembly metadata. + +///////////////////////////////////////////////////////////////////////////// +Other notes: + +AppWizard uses "TODO:" to indicate parts of the source code you +should add to or customize. + +///////////////////////////////////////////////////////////////////////////// diff --git a/APEDotNet/Stdafx.cpp b/APEDotNet/Stdafx.cpp new file mode 100644 index 0000000..a9bcc4f --- /dev/null +++ b/APEDotNet/Stdafx.cpp @@ -0,0 +1,5 @@ +// stdafx.cpp : source file that includes just the standard includes +// APEDotNet.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" diff --git a/APEDotNet/Stdafx.h b/APEDotNet/Stdafx.h new file mode 100644 index 0000000..2e525d4 --- /dev/null +++ b/APEDotNet/Stdafx.h @@ -0,0 +1,7 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, +// but are changed infrequently + +#pragma once + + diff --git a/APEDotNet/apedotnet.cpp b/APEDotNet/apedotnet.cpp new file mode 100644 index 0000000..783aaf7 --- /dev/null +++ b/APEDotNet/apedotnet.cpp @@ -0,0 +1,233 @@ +// This is the main DLL file. + +using namespace System; +using namespace System::Text; +using namespace System::Collections::Generic; +using namespace System::Collections::Specialized; +using namespace System::Runtime::InteropServices; + +#ifndef _WAVEFORMATEX_ +#define _WAVEFORMATEX_ + +#define BOOL int +#define TRUE 1 +#define FALSE 0 +#define HWND long + +/* + * extended waveform format structure used for all non-PCM formats. this + * structure is common to all non-PCM formats. + */ +typedef struct tWAVEFORMATEX +{ + Int16 wFormatTag; /* format type */ + Int16 nChannels; /* number of channels (i.e. mono, stereo...) */ + Int32 nSamplesPerSec; /* sample rate */ + Int32 nAvgBytesPerSec; /* for buffer estimation */ + Int16 nBlockAlign; /* block size of data */ + Int16 wBitsPerSample; /* number of bits per sample of mono data */ + Int16 cbSize; /* the count in bytes of the size of */ + /* extra information (after cbSize) */ +} WAVEFORMATEX, *PWAVEFORMATEX, *NPWAVEFORMATEX, *LPWAVEFORMATEX; + +#endif /* _WAVEFORMATEX_ */ + +#include "All.h" +#include "MACLib.h" +#include "APETag.h" + +namespace APEDotNet { + + public ref class APEReader { + public: + APEReader(String^ path) { + IntPtr pathChars; + + pAPEDecompress = NULL; + _sampleOffset = 0; + _samplesWaiting = false; + _path = NULL; + pBuffer = NULL; + + int nRetVal = 0; + + pathChars = Marshal::StringToHGlobalUni(path); + size_t pathLen = wcslen ((const wchar_t*)pathChars.ToPointer())+1; + _path = new wchar_t[pathLen]; + memcpy ((void*) _path, (const wchar_t*)pathChars.ToPointer(), pathLen*sizeof(wchar_t)); + Marshal::FreeHGlobal(pathChars); + + pAPEDecompress = CreateIAPEDecompress (_path, &nRetVal); + if (!pAPEDecompress) { + throw gcnew Exception("Unable to open file."); + } + + _sampleRate = pAPEDecompress->GetInfo (APE_INFO_SAMPLE_RATE, 0, 0); + _bitsPerSample = pAPEDecompress->GetInfo (APE_INFO_BITS_PER_SAMPLE, 0, 0); + _channelCount = pAPEDecompress->GetInfo (APE_INFO_CHANNELS, 0, 0); + + // make a buffer to hold 16384 blocks of audio data + nBlockAlign = pAPEDecompress->GetInfo (APE_INFO_BLOCK_ALIGN, 0, 0); + pBuffer = new unsigned char [16384 * nBlockAlign]; + + // loop through the whole file + _sampleCount = pAPEDecompress->GetInfo (APE_DECOMPRESS_TOTAL_BLOCKS, 0, 0); // * ? + } + + ~APEReader () + { + if (pBuffer) delete [] pBuffer; + if (_path) delete [] _path; + } + + property Int32 BitsPerSample { + Int32 get() { + return _bitsPerSample; + } + } + + property Int32 ChannelCount { + Int32 get() { + return _channelCount; + } + } + + property Int32 SampleRate { + Int32 get() { + return _sampleRate; + } + } + + property Int64 Length { + Int64 get() { + return _sampleCount; + } + } + + property Int64 Position { + Int64 get() { + return _sampleOffset; + } + void set(Int64 offset) { + _sampleOffset = offset; + _samplesWaiting = false; + if (pAPEDecompress->Seek ((int) offset /*? */)) + throw gcnew Exception("Unable to seek."); + } + } + + property Int64 Remaining { + Int64 get() { + return _sampleCount - _sampleOffset; + } + } + + void Close() { + if (pAPEDecompress) delete pAPEDecompress; + pAPEDecompress = NULL; + } + + property NameValueCollection^ Tags { + NameValueCollection^ get () { + if (!_tags) GetTags (); + return _tags; + } + void set (NameValueCollection ^tags) { + _tags = tags; + } + } + + Int32 Read([Out] array^% sampleBuffer) { + int sampleCount; + + int nBlocksRetrieved; + if (pAPEDecompress->GetData ((char *) pBuffer, 16384, &nBlocksRetrieved)) + throw gcnew Exception("An error occurred while decoding."); + + sampleCount = nBlocksRetrieved; + array^ _sampleBuffer = gcnew array (nBlocksRetrieved, 2); + + { + interior_ptr pMyBuffer = &_sampleBuffer[0, 0]; + unsigned short * pAPEBuffer = (unsigned short *) pBuffer; + unsigned short * pAPEBufferEnd = (unsigned short *) pBuffer + 2 * nBlocksRetrieved; + + while (pAPEBuffer < pAPEBufferEnd) { + *(pMyBuffer++) = *(pAPEBuffer++); + *(pMyBuffer++) = *(pAPEBuffer++); + } + } +#if 0 + for (int i = 0; i < nBlocksRetrieved; i++) + { + _sampleBuffer[i,0] = pBuffer[i*4] + (pBuffer[i*4+1] << 8); + _sampleBuffer[i,1] = pBuffer[i*4+2] + (pBuffer[i*4+3] << 8); + } +#endif + sampleBuffer = _sampleBuffer; + _sampleOffset += nBlocksRetrieved; + _samplesWaiting = false; + + return sampleCount; + } + + private: + IAPEDecompress * pAPEDecompress; + + NameValueCollection^ _tags; + Int64 _sampleCount, _sampleOffset; + Int32 _bitsPerSample, _channelCount, _sampleRate; + int nBlockAlign; + bool _samplesWaiting; + unsigned char * pBuffer; + const wchar_t * _path; + + void GetTags (void) + { + _tags = gcnew NameValueCollection(); + CAPETag apeTag (_path, TRUE); + for (int i = 0; ; i++) + { + CAPETagField * field = apeTag.GetTagField (i); + if (!field) + break; + if (field->GetIsUTF8Text()) + { + int valueSize = field->GetFieldValueSize(); + while (valueSize && field->GetFieldValue()[valueSize-1]=='\0') + valueSize --; + const wchar_t * fieldName = field->GetFieldName (); + if (!wcsicmp (fieldName, L"YEAR")) + fieldName = L"DATE"; + if (!wcsicmp (fieldName, L"TRACK")) + fieldName = L"TRACKNUMBER"; + _tags->Add (gcnew String (fieldName), + gcnew String (field->GetFieldValue(), 0, valueSize, System::Text::Encoding::UTF8)); + } + } + } + +#if 0 + APE__StreamDecoderWriteStatus WriteCallback(const APE__StreamDecoder *decoder, + const APE__Frame *frame, const APE__int32 * const buffer[], void *client_data) + { + if ((_sampleBuffer == nullptr) || (_sampleBuffer->GetLength(0) != sampleCount)) { + _sampleBuffer = gcnew array(sampleCount, _channelCount); + } + + for (Int32 iChan = 0; iChan < _channelCount; iChan++) { + interior_ptr pMyBuffer = &_sampleBuffer[0, iChan]; + const APE__int32 *pAPEBuffer = buffer[iChan]; + const APE__int32 *pAPEBufferEnd = pAPEBuffer + sampleCount; + + while (pAPEBuffer < pAPEBufferEnd) { + *pMyBuffer = *pAPEBuffer; + pMyBuffer += _channelCount; + pAPEBuffer++; + } + } + } +#endif + }; + +} diff --git a/APEDotNet/app.ico b/APEDotNet/app.ico new file mode 100644 index 0000000..3a5525f Binary files /dev/null and b/APEDotNet/app.ico differ diff --git a/APEDotNet/app.rc b/APEDotNet/app.rc new file mode 100644 index 0000000..bb5fb6f --- /dev/null +++ b/APEDotNet/app.rc @@ -0,0 +1,63 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon placed first or with lowest ID value becomes application icon + +LANGUAGE 25, 1 +#pragma code_page(1251) +1 ICON "app.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" + "\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/APEDotNet/resource.h b/APEDotNet/resource.h new file mode 100644 index 0000000..1f2251c --- /dev/null +++ b/APEDotNet/resource.h @@ -0,0 +1,3 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by app.rc diff --git a/APETagsDotNet/APETagsDotNet.cpp b/APETagsDotNet/APETagsDotNet.cpp new file mode 100644 index 0000000..e10211d --- /dev/null +++ b/APETagsDotNet/APETagsDotNet.cpp @@ -0,0 +1,6 @@ +// This is the main DLL file. + +#include "stdafx.h" + +#include "APETagsDotNet.h" + diff --git a/APETagsDotNet/APETagsDotNet.h b/APETagsDotNet/APETagsDotNet.h new file mode 100644 index 0000000..bd87926 --- /dev/null +++ b/APETagsDotNet/APETagsDotNet.h @@ -0,0 +1,158 @@ +// APETagsDotNet.h + +#pragma once + +using namespace System; +using namespace System::Runtime::InteropServices; + +#include + +/***************************************************************************************** +The version of the APE tag +*****************************************************************************************/ +#define CURRENT_APE_TAG_VERSION 2000 + +/***************************************************************************************** +Footer (and header) flags +*****************************************************************************************/ +#define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31) +#define APE_TAG_FLAG_CONTAINS_FOOTER (1 << 30) +#define APE_TAG_FLAG_IS_HEADER (1 << 29) + +#define APE_TAG_FLAGS_DEFAULT (APE_TAG_FLAG_CONTAINS_FOOTER) + +/***************************************************************************************** +Tag field flags +*****************************************************************************************/ +#define TAG_FIELD_FLAG_READ_ONLY (1 << 0) + +#define TAG_FIELD_FLAG_DATA_TYPE_MASK (6) +#define TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8 (0 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_BINARY (1 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_EXTERNAL_INFO (2 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_RESERVED (3 << 1) + +/***************************************************************************************** +The footer at the end of APE tagged files (can also optionally be at the front of the tag) +*****************************************************************************************/ +#define APE_TAG_FOOTER_BYTES 32 + +namespace APETagsDotNet { + + ref class APE_TAG_FOOTER + { + protected: + + String^ m_cID; // should equal 'APETAGEX' + int m_nVersion; // equals CURRENT_APE_TAG_VERSION + int m_nSize; // the complete size of the tag, including this footer (excludes header) + int m_nFields; // the number of fields in the tag + int m_nFlags; // the tag flags + array^ m_cReserved; // reserved for later use (must be zero) + + public: + + APE_TAG_FOOTER(int nFields, int nFieldBytes) + { + //TODO + //m_cID = gcnew array (8); + //Marshal::Copy (m_cID, 0, (IntPtr) "APETAGEX", 8); + m_cID = gcnew String ("APETAGEX"); + m_cReserved = gcnew array (8); + //TODO + //memset(m_cReserved, 0, 8); + m_nFields = nFields; + m_nFlags = APE_TAG_FLAGS_DEFAULT; + m_nSize = nFieldBytes + APE_TAG_FOOTER_BYTES; + m_nVersion = CURRENT_APE_TAG_VERSION; + } + + property Int32 TotalTagBytes { Int32 get() { return m_nSize + (HasHeader ? APE_TAG_FOOTER_BYTES : 0); } } + property Int32 FieldBytes { Int32 get() { return m_nSize - APE_TAG_FOOTER_BYTES; } } + property Int32 FieldsOffset { Int32 get() { return HasHeader ? APE_TAG_FOOTER_BYTES : 0; } } + property Int32 NumberFields { Int32 get() { return m_nFields; } } + property bool HasHeader { bool get() { return (m_nFlags & APE_TAG_FLAG_CONTAINS_HEADER) != 0; } } + property bool IsHeader { bool get() { return (m_nFlags & APE_TAG_FLAG_IS_HEADER) != 0; } } + property Int32 Version { Int32 get() { return m_nVersion; } } + + bool GetIsValid (bool bAllowHeader) + { + //TODO + return //(strncmp(m_cID, "APETAGEX", 8) == 0) && + (m_nVersion <= CURRENT_APE_TAG_VERSION) && + (m_nFields <= 65536) && + (FieldBytes <= (1024 * 1024 * 16)) && + (bAllowHeader || !IsHeader); + } + }; + + + public ref class APETagField + { + public: + // create a tag field (use nFieldBytes = -1 for null-terminated strings) + APETagField (String^ fieldName, array^ fieldValue, int fieldFlags) { + _fieldName = fieldName; + _fieldValue = fieldValue; + _fieldFlags = fieldFlags; + } + + // destructor + ~APETagField() { + } + + // gets the size of the entire field in bytes (name, value, and metadata) + int GetFieldSize() + { + return _fieldName->Length + 1 + _fieldValue->Length + 4 + 4; + } + + // get the name of the field + property String^ FieldName { + String ^ get() { return _fieldName; } + } + + // get the value of the field + property array^ FieldValue { + array^ get() { return _fieldValue; } + } + + // output the entire field to a buffer (GetFieldSize() bytes) + int SaveField(char * pBuffer) + { + //TODO + //*((int *) pBuffer) = m_nFieldValueBytes; + //pBuffer += 4; + //*((int *) pBuffer) = m_nFieldFlags; + //pBuffer += 4; + // + //CSmartPtr spFieldNameANSI((char *) GetANSIFromUTF16(m_spFieldNameUTF16), TRUE); + //strcpy(pBuffer, spFieldNameANSI); + //pBuffer += strlen(spFieldNameANSI) + 1; + + //memcpy(pBuffer, m_spFieldValue, m_nFieldValueBytes); + + return GetFieldSize(); + } + + // checks to see if the field is read-only + property bool IsReadOnly { bool get() { return (_fieldFlags & TAG_FIELD_FLAG_READ_ONLY) != 0; } } + property bool IsUTF8Text { bool get() { return (_fieldFlags & TAG_FIELD_FLAG_DATA_TYPE_MASK) == TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8; } } + + // set helpers (use with EXTREME caution) + property Int32 FieldFlags { + Int32 get() { return _fieldFlags; } + void set(Int32 fieldFlags) { _fieldFlags = fieldFlags; } + } + + private: + String^ _fieldName; + array^ _fieldValue; + int _fieldFlags; + int _fieldValueBytes; + }; + + public ref class APETagsDotNet + { + }; +} diff --git a/APETagsDotNet/APETagsDotNet.vcproj b/APETagsDotNet/APETagsDotNet.vcproj new file mode 100644 index 0000000..b2eaf26 --- /dev/null +++ b/APETagsDotNet/APETagsDotNet.vcproj @@ -0,0 +1,422 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/APETagsDotNet/AssemblyInfo.cpp b/APETagsDotNet/AssemblyInfo.cpp new file mode 100644 index 0000000..74164b1 --- /dev/null +++ b/APETagsDotNet/AssemblyInfo.cpp @@ -0,0 +1,40 @@ +#include "stdafx.h" + +using namespace System; +using namespace System::Reflection; +using namespace System::Runtime::CompilerServices; +using namespace System::Runtime::InteropServices; +using namespace System::Security::Permissions; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly:AssemblyTitleAttribute("APETagsDotNet")]; +[assembly:AssemblyDescriptionAttribute("")]; +[assembly:AssemblyConfigurationAttribute("")]; +[assembly:AssemblyCompanyAttribute("Microsoft")]; +[assembly:AssemblyProductAttribute("APETagsDotNet")]; +[assembly:AssemblyCopyrightAttribute("Copyright (c) Microsoft 2008")]; +[assembly:AssemblyTrademarkAttribute("")]; +[assembly:AssemblyCultureAttribute("")]; + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the value or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly:AssemblyVersionAttribute("1.0.*")]; + +[assembly:ComVisible(false)]; + +[assembly:CLSCompliantAttribute(true)]; + +[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/APETagsDotNet/ReadMe.txt b/APETagsDotNet/ReadMe.txt new file mode 100644 index 0000000..a7a9a18 --- /dev/null +++ b/APETagsDotNet/ReadMe.txt @@ -0,0 +1,31 @@ +======================================================================== + DYNAMIC LINK LIBRARY : APETagsDotNet Project Overview +======================================================================== + +AppWizard has created this APETagsDotNet DLL for you. + +This file contains a summary of what you will find in each of the files that +make up your APETagsDotNet application. + +APETagsDotNet.vcproj + This is the main project file for VC++ projects generated using an Application Wizard. + It contains information about the version of Visual C++ that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +APETagsDotNet.cpp + This is the main DLL source file. + +APETagsDotNet.h + This file contains a class declaration. + +AssemblyInfo.cpp + Contains custom attributes for modifying assembly metadata. + +///////////////////////////////////////////////////////////////////////////// +Other notes: + +AppWizard uses "TODO:" to indicate parts of the source code you +should add to or customize. + +///////////////////////////////////////////////////////////////////////////// diff --git a/APETagsDotNet/Stdafx.cpp b/APETagsDotNet/Stdafx.cpp new file mode 100644 index 0000000..8d546b7 --- /dev/null +++ b/APETagsDotNet/Stdafx.cpp @@ -0,0 +1,5 @@ +// stdafx.cpp : source file that includes just the standard includes +// APETagsDotNet.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" diff --git a/APETagsDotNet/Stdafx.h b/APETagsDotNet/Stdafx.h new file mode 100644 index 0000000..2e525d4 --- /dev/null +++ b/APETagsDotNet/Stdafx.h @@ -0,0 +1,7 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, +// but are changed infrequently + +#pragma once + + diff --git a/APETagsDotNet/app.ico b/APETagsDotNet/app.ico new file mode 100644 index 0000000..3a5525f Binary files /dev/null and b/APETagsDotNet/app.ico differ diff --git a/APETagsDotNet/app.rc b/APETagsDotNet/app.rc new file mode 100644 index 0000000..bb5fb6f --- /dev/null +++ b/APETagsDotNet/app.rc @@ -0,0 +1,63 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon placed first or with lowest ID value becomes application icon + +LANGUAGE 25, 1 +#pragma code_page(1251) +1 ICON "app.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" + "\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/APETagsDotNet/resource.h b/APETagsDotNet/resource.h new file mode 100644 index 0000000..1f2251c --- /dev/null +++ b/APETagsDotNet/resource.h @@ -0,0 +1,3 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by app.rc diff --git a/CUETools/AudioReadWrite.cs b/CUETools/AudioReadWrite.cs new file mode 100644 index 0000000..dd7eeae --- /dev/null +++ b/CUETools/AudioReadWrite.cs @@ -0,0 +1,874 @@ +using System; +using System.IO; +using FLACDotNet; +using WavPackDotNet; +using APEDotNet; +using System.Collections.Generic; +using System.Collections.Specialized; + +namespace JDP { + public interface IAudioSource { + uint Read(byte[] buff, uint sampleCount); + ulong Length { get; } + ulong Position { get; set; } + NameValueCollection Tags { get; set; } + ulong Remaining { get; } + void Close(); + int BitsPerSample { get; } + int ChannelCount { get; } + int SampleRate { get; } + } + + public interface IAudioDest { + void Write(byte[] buff, uint sampleCount); + void Close(); + long FinalSampleCount { set; } + } + + public static class AudioReadWrite { + public static IAudioSource GetAudioSource(string path) { + switch (Path.GetExtension(path).ToLower()) { + case ".wav": + return new WAVReader(path); + case ".flac": + return new FLACReader(path); + case ".wv": + return new WavPackReader(path); + case ".ape": + return new APEReader(path); + default: + throw new Exception("Unsupported audio type."); + } + } + + public static IAudioDest GetAudioDest(string path, int bitsPerSample, int channelCount, int sampleRate, long finalSampleCount) { + IAudioDest dest; + switch (Path.GetExtension(path).ToLower()) { + case ".wav": + dest = new WAVWriter(path, bitsPerSample, channelCount, sampleRate); break; + case ".flac": + dest = new FLACWriter(path, bitsPerSample, channelCount, sampleRate); break; + case ".wv": + dest = new WavPackWriter(path, bitsPerSample, channelCount, sampleRate); break; + case ".dummy": + dest = new DummyWriter(path, bitsPerSample, channelCount, sampleRate); break; + default: + throw new Exception("Unsupported audio type."); + } + dest.FinalSampleCount = finalSampleCount; + return dest; + } + } + + public class DummyWriter : IAudioDest { + + public DummyWriter (string path, int bitsPerSample, int channelCount, int sampleRate) { + } + + + public void Close() { + } + + public long FinalSampleCount { + set { + } + } + + public void Write(byte[] buff, uint sampleCount) { + } + } + + public class WAVReader : IAudioSource { + FileStream _fs; + BinaryReader _br; + ulong _dataOffset, _dataLen; + ulong _samplePos, _sampleLen; + int _bitsPerSample, _channelCount, _sampleRate, _blockAlign; + bool _largeFile; + + public WAVReader(string path) { + _fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + _br = new BinaryReader(_fs); + + ParseHeaders(); + + _sampleLen = _dataLen / (uint)_blockAlign; + Position = 0; + } + + public void Close() { + _br.Close(); + + _br = null; + _fs = null; + } + + private void ParseHeaders() { + const long maxFileSize = 0x7FFFFFFEL; + const uint fccRIFF = 0x46464952; + const uint fccWAVE = 0x45564157; + const uint fccFormat = 0x20746D66; + const uint fccData = 0x61746164; + + uint lenRIFF; + long fileEnd; + bool foundFormat, foundData; + + if (_br.ReadUInt32() != fccRIFF) { + throw new Exception("Not a valid RIFF file."); + } + + lenRIFF = _br.ReadUInt32(); + fileEnd = (long)lenRIFF + 8; + + if (_br.ReadUInt32() != fccWAVE) { + throw new Exception("Not a valid WAVE file."); + } + + _largeFile = false; + foundFormat = false; + foundData = false; + + while (_fs.Position < fileEnd) { + uint ckID, ckSize, ckSizePadded; + long ckEnd; + + ckID = _br.ReadUInt32(); + ckSize = _br.ReadUInt32(); + ckSizePadded = (ckSize + 1U) & ~1U; + ckEnd = _fs.Position + (long)ckSizePadded; + + if (ckID == fccFormat) { + foundFormat = true; + + if (_br.ReadUInt16() != 1) { + throw new Exception("WAVE must be PCM format."); + } + _channelCount = _br.ReadInt16(); + _sampleRate = _br.ReadInt32(); + _br.ReadInt32(); + _blockAlign = _br.ReadInt16(); + _bitsPerSample = _br.ReadInt16(); + } + else if (ckID == fccData) { + foundData = true; + + _dataOffset = (ulong) _fs.Position; + if (_fs.Length <= maxFileSize) { + _dataLen = ckSize; + } + else { + _largeFile = true; + _dataLen = ((ulong)_fs.Length) - _dataOffset; + } + } + + if ((foundFormat & foundData) || _largeFile) { + break; + } + + _fs.Seek(ckEnd, SeekOrigin.Begin); + } + + if ((foundFormat & foundData) == false) { + throw new Exception("Format or data chunk not found."); + } + + if (_channelCount <= 0) { + throw new Exception("Channel count is invalid."); + } + if (_sampleRate <= 0) { + throw new Exception("Sample rate is invalid."); + } + if (_blockAlign != (_channelCount * ((_bitsPerSample + 7) / 8))) { + throw new Exception("Block align is invalid."); + } + if ((_bitsPerSample <= 0) || (_bitsPerSample > 32)) { + throw new Exception("Bits per sample is invalid."); + } + } + + public ulong Position { + get { + return _samplePos; + } + set { + ulong seekPos; + + if (value > _sampleLen) { + _samplePos = _sampleLen; + } + else { + _samplePos = value; + } + + seekPos = _dataOffset + (_samplePos * (uint)_blockAlign); + _fs.Seek((long) seekPos, SeekOrigin.Begin); + } + } + + public ulong Length { + get { + return _sampleLen; + } + } + + public ulong Remaining { + get { + return _sampleLen - _samplePos; + } + } + + public int ChannelCount { + get { + return _channelCount; + } + } + + public int SampleRate { + get { + return _sampleRate; + } + } + + public int BitsPerSample { + get { + return _bitsPerSample; + } + } + + public int BlockAlign { + get { + return _blockAlign; + } + } + + public NameValueCollection Tags { + get { + return new NameValueCollection(); + } + set { + } + } + + public void GetTags(out List names, out List values) + { + names = new List(); + values = new List(); + } + + public uint Read(byte[] buff, uint sampleCount) { + if (sampleCount > Remaining) + sampleCount = (uint) Remaining; + + uint byteCount = sampleCount * (uint) _blockAlign; + + if (sampleCount != 0) { + if (_fs.Read(buff, 0, (int) byteCount) != byteCount) { + throw new Exception("Incomplete file read."); + } + _samplePos += sampleCount; + } + + return sampleCount; + } + } + + public class WAVWriter : IAudioDest { + FileStream _fs; + BinaryWriter _bw; + int _bitsPerSample, _channelCount, _sampleRate, _blockAlign; + long _sampleLen; + + public WAVWriter(string path, int bitsPerSample, int channelCount, int sampleRate) { + _bitsPerSample = bitsPerSample; + _channelCount = channelCount; + _sampleRate = sampleRate; + _blockAlign = _channelCount * ((_bitsPerSample + 7) / 8); + + _fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); + _bw = new BinaryWriter(_fs); + + WriteHeaders(); + } + + private void WriteHeaders() { + const uint fccRIFF = 0x46464952; + const uint fccWAVE = 0x45564157; + const uint fccFormat = 0x20746D66; + const uint fccData = 0x61746164; + + _bw.Write(fccRIFF); + _bw.Write((uint)0); + _bw.Write(fccWAVE); + + _bw.Write(fccFormat); + _bw.Write((uint)16); + _bw.Write((ushort)1); + _bw.Write((ushort)_channelCount); + _bw.Write((uint)_sampleRate); + _bw.Write((uint)(_sampleRate * _blockAlign)); + _bw.Write((ushort)_blockAlign); + _bw.Write((ushort)_bitsPerSample); + + _bw.Write(fccData); + _bw.Write((uint)0); + } + + public void Close() { + const long maxFileSize = 0x7FFFFFFEL; + long dataLen, dataLenPadded; + + dataLen = _sampleLen * _blockAlign; + + if ((dataLen & 1) == 1) { + _bw.Write((byte)0); + } + + if ((dataLen + 44) > maxFileSize) { + dataLen = ((maxFileSize - 44) / _blockAlign) * _blockAlign; + } + + dataLenPadded = ((dataLen & 1) == 1) ? (dataLen + 1) : dataLen; + + _bw.Seek(4, SeekOrigin.Begin); + _bw.Write((uint)(dataLenPadded + 36)); + + _bw.Seek(40, SeekOrigin.Begin); + _bw.Write((uint)dataLen); + + _bw.Close(); + + _bw = null; + _fs = null; + } + + public long Position { + get { + return _sampleLen; + } + } + + public long FinalSampleCount { + set { + } + } + + public void Write(byte[] buff, uint sampleCount) { + if (sampleCount < 0) { + sampleCount = 0; + } + + if (sampleCount != 0) { + _fs.Write(buff, 0, (int) sampleCount * _blockAlign); + _sampleLen += sampleCount; + } + } + } + + class FLACReader : IAudioSource { + FLACDotNet.FLACReader _flacReader; + int[,] _sampleBuffer; + uint _bufferOffset, _bufferLength; + + public FLACReader(string path) { + _flacReader = new FLACDotNet.FLACReader(path); + _bufferOffset = 0; + _bufferLength = 0; + } + + public void Close() { + _flacReader.Close(); + } + + public NameValueCollection Tags + { + get { return _flacReader.Tags; } + set { _flacReader.Tags = value; } + } + + public bool UpdateTags() + { + return _flacReader.UpdateTags(); + } + + public ulong Length { + get { + return (ulong) _flacReader.Length; + } + } + + public ulong Remaining { + get { + return (ulong) _flacReader.Remaining + SamplesInBuffer; + } + } + + public ulong Position { + get { + return (ulong) _flacReader.Position - SamplesInBuffer; + } + set { + _flacReader.Position = (long) value; + _bufferOffset = 0; + _bufferLength = 0; + } + } + + private uint SamplesInBuffer { + get { + return (uint) (_bufferLength - _bufferOffset); + } + } + + public int BitsPerSample { + get { + return _flacReader.BitsPerSample; + } + } + + public int ChannelCount { + get { + return _flacReader.ChannelCount; + } + } + + public int SampleRate { + get { + return _flacReader.SampleRate; + } + } + + private unsafe void FLACSamplesToBytes_16(int[,] inSamples, uint inSampleOffset, + byte[] outSamples, uint outByteOffset, uint sampleCount, int channelCount) + { + uint loopCount = sampleCount * (uint) channelCount; + + if ((inSamples.GetLength(0) - inSampleOffset < sampleCount) || + (outSamples.Length - outByteOffset < loopCount * 2)) + { + throw new IndexOutOfRangeException(); + } + + fixed (int* pInSamplesFixed = &inSamples[inSampleOffset, 0]) { + fixed (byte* pOutSamplesFixed = &outSamples[outByteOffset]) { + int* pInSamples = pInSamplesFixed; + short* pOutSamples = (short*)pOutSamplesFixed; + + for (int i = 0; i < loopCount; i++) { + *(pOutSamples++) = (short)*(pInSamples++); + } + } + } + } + + public uint Read(byte[] buff, uint sampleCount) { + if (_flacReader.BitsPerSample != 16) { + throw new Exception("Reading is only supported for 16 bit sample depth."); + } + int chanCount = _flacReader.ChannelCount; + uint copyCount; + uint buffOffset = 0; + uint samplesNeeded = sampleCount; + + while (samplesNeeded != 0) { + if (SamplesInBuffer == 0) { + _bufferOffset = 0; + _bufferLength = (uint) _flacReader.Read(out _sampleBuffer); + } + + copyCount = Math.Min(samplesNeeded, SamplesInBuffer); + + FLACSamplesToBytes_16(_sampleBuffer, _bufferOffset, buff, buffOffset, + copyCount, chanCount); + + samplesNeeded -= copyCount; + buffOffset += copyCount * (uint) chanCount * 2; + _bufferOffset += copyCount; + } + + return sampleCount; + } + } + + class FLACWriter : IAudioDest { + FLACDotNet.FLACWriter _flacWriter; + int[,] _sampleBuffer; + int _bitsPerSample; + int _channelCount; + int _sampleRate; + + public FLACWriter(string path, int bitsPerSample, int channelCount, int sampleRate) { + if (bitsPerSample != 16) { + throw new Exception("Bits per sample must be 16."); + } + _bitsPerSample = bitsPerSample; + _channelCount = channelCount; + _sampleRate = sampleRate; + _flacWriter = new FLACDotNet.FLACWriter(path, bitsPerSample, channelCount, sampleRate); + } + + public long FinalSampleCount { + get { + return _flacWriter.FinalSampleCount; + } + set { + _flacWriter.FinalSampleCount = value; + } + } + + public int CompressionLevel { + get { + return _flacWriter.CompressionLevel; + } + set { + _flacWriter.CompressionLevel = value; + } + } + + public bool Verify { + get { + return _flacWriter.Verify; + } + set { + _flacWriter.Verify = value; + } + } + + public void SetTags(NameValueCollection tags) + { + _flacWriter.SetTags (tags); + } + + public void Close() { + _flacWriter.Close(); + } + + private unsafe void BytesToFLACSamples_16(byte[] inSamples, int inByteOffset, + int[,] outSamples, int outSampleOffset, uint sampleCount, int channelCount) + { + uint loopCount = sampleCount * (uint) channelCount; + + if ((inSamples.Length - inByteOffset < loopCount * 2) || + (outSamples.GetLength(0) - outSampleOffset < sampleCount)) + { + throw new IndexOutOfRangeException(); + } + + fixed (byte* pInSamplesFixed = &inSamples[inByteOffset]) { + fixed (int* pOutSamplesFixed = &outSamples[outSampleOffset, 0]) { + short* pInSamples = (short*)pInSamplesFixed; + int* pOutSamples = pOutSamplesFixed; + + for (int i = 0; i < loopCount; i++) { + *(pOutSamples++) = (int)*(pInSamples++); + } + } + } + } + + public void Write(byte[] buff, uint sampleCount) { + if ((_sampleBuffer == null) || (_sampleBuffer.GetLength(0) < sampleCount)) { + _sampleBuffer = new int[sampleCount, _channelCount]; + } + BytesToFLACSamples_16(buff, 0, _sampleBuffer, 0, sampleCount, _channelCount); + _flacWriter.Write(_sampleBuffer, (int) sampleCount); + } + } + + class APEReader : IAudioSource { + APEDotNet.APEReader _apeReader; + int[,] _sampleBuffer; + uint _bufferOffset, _bufferLength; + + public APEReader(string path) { + _apeReader = new APEDotNet.APEReader(path); + _bufferOffset = 0; + _bufferLength = 0; + } + + public void Close() { + _apeReader.Close(); + } + + public ulong Length { + get { + return (ulong) _apeReader.Length; + } + } + + public ulong Remaining { + get { + return (ulong) _apeReader.Remaining + SamplesInBuffer; + } + } + + public ulong Position { + get { + return (ulong) _apeReader.Position - SamplesInBuffer; + } + set { + _apeReader.Position = (long) value; + _bufferOffset = 0; + _bufferLength = 0; + } + } + + private uint SamplesInBuffer { + get { + return (uint) (_bufferLength - _bufferOffset); + } + } + + public int BitsPerSample { + get { + return _apeReader.BitsPerSample; + } + } + + public int ChannelCount { + get { + return _apeReader.ChannelCount; + } + } + + public int SampleRate { + get { + return _apeReader.SampleRate; + } + } + + public NameValueCollection Tags + { + get { return _apeReader.Tags; } + set { _apeReader.Tags = value; } + } + + private unsafe void APESamplesToBytes_16(int[,] inSamples, uint inSampleOffset, + byte[] outSamples, uint outByteOffset, uint sampleCount, int channelCount) + { + uint loopCount = sampleCount * (uint) channelCount; + + if ((inSamples.GetLength(0) - inSampleOffset < sampleCount) || + (outSamples.Length - outByteOffset < loopCount * 2)) + { + throw new IndexOutOfRangeException(); + } + + fixed (int* pInSamplesFixed = &inSamples[inSampleOffset, 0]) { + fixed (byte* pOutSamplesFixed = &outSamples[outByteOffset]) { + int* pInSamples = pInSamplesFixed; + short* pOutSamples = (short*)pOutSamplesFixed; + + for (int i = 0; i < loopCount; i++) { + *(pOutSamples++) = (short)*(pInSamples++); + } + } + } + } + + public uint Read(byte[] buff, uint sampleCount) { + if (_apeReader.BitsPerSample != 16) { + throw new Exception("Reading is only supported for 16 bit sample depth."); + } + int chanCount = _apeReader.ChannelCount; + uint samplesNeeded, copyCount, buffOffset; + + buffOffset = 0; + samplesNeeded = sampleCount; + + while (samplesNeeded != 0) { + if (SamplesInBuffer == 0) { + _bufferOffset = 0; + _bufferLength = (uint) _apeReader.Read(out _sampleBuffer); + } + + copyCount = Math.Min(samplesNeeded, SamplesInBuffer); + + APESamplesToBytes_16(_sampleBuffer, _bufferOffset, buff, buffOffset, + copyCount, chanCount); + + samplesNeeded -= copyCount; + buffOffset += copyCount * (uint) chanCount * 2; + _bufferOffset += copyCount; + } + + return sampleCount; + } + } + + + class WavPackReader : IAudioSource { + WavPackDotNet.WavPackReader _wavPackReader; + + public WavPackReader(string path) { + _wavPackReader = new WavPackDotNet.WavPackReader(path); + } + + public void Close() { + _wavPackReader.Close(); + } + + public ulong Length { + get { + return (ulong) _wavPackReader.Length; + } + } + + public ulong Remaining { + get { + return (ulong) _wavPackReader.Remaining; + } + } + + public ulong Position { + get { + return (ulong) _wavPackReader.Position; + } + set { + _wavPackReader.Position = (int) value; + } + } + + public int BitsPerSample { + get { + return _wavPackReader.BitsPerSample; + } + } + + public int ChannelCount { + get { + return _wavPackReader.ChannelCount; + } + } + + public int SampleRate { + get { + return _wavPackReader.SampleRate; + } + } + + public NameValueCollection Tags + { + get { return _wavPackReader.Tags; } + set { _wavPackReader.Tags = value; } + } + + private unsafe void WavPackSamplesToBytes_16(int[,] inSamples, uint inSampleOffset, + byte[] outSamples, uint outByteOffset, uint sampleCount, int channelCount) + { + uint loopCount = sampleCount * (uint) channelCount; + + if ((inSamples.GetLength(0) - inSampleOffset < sampleCount) || + (outSamples.Length - outByteOffset < loopCount * 2)) + { + throw new IndexOutOfRangeException(); + } + + fixed (int* pInSamplesFixed = &inSamples[inSampleOffset, 0]) { + fixed (byte* pOutSamplesFixed = &outSamples[outByteOffset]) { + int* pInSamples = pInSamplesFixed; + short* pOutSamples = (short*)pOutSamplesFixed; + + for (int i = 0; i < loopCount; i++) { + *(pOutSamples++) = (short)*(pInSamples++); + } + } + } + } + + public uint Read(byte[] buff, uint sampleCount) { + if (_wavPackReader.BitsPerSample != 16) { + throw new Exception("Reading is only supported for 16 bit sample depth."); + } + int chanCount = _wavPackReader.ChannelCount; + int[,] sampleBuffer; + + sampleBuffer = new int[sampleCount * 2, chanCount]; + _wavPackReader.Read(sampleBuffer, (int) sampleCount); + WavPackSamplesToBytes_16(sampleBuffer, 0, buff, 0, sampleCount, chanCount); + + return sampleCount; + } + } + + class WavPackWriter : IAudioDest { + WavPackDotNet.WavPackWriter _wavPackWriter; + int[,] _sampleBuffer; + int _bitsPerSample; + int _channelCount; + int _sampleRate; + + public WavPackWriter(string path, int bitsPerSample, int channelCount, int sampleRate) { + if (bitsPerSample != 16) { + throw new Exception("Bits per sample must be 16."); + } + _bitsPerSample = bitsPerSample; + _channelCount = channelCount; + _sampleRate = sampleRate; + _wavPackWriter = new WavPackDotNet.WavPackWriter(path, bitsPerSample, channelCount, sampleRate); + } + + public long FinalSampleCount { + get { + return _wavPackWriter.FinalSampleCount; + } + set { + _wavPackWriter.FinalSampleCount = (int)value; + } + } + + public int CompressionMode { + get { + return _wavPackWriter.CompressionMode; + } + set { + _wavPackWriter.CompressionMode = value; + } + } + + public int ExtraMode { + get { + return _wavPackWriter.ExtraMode; + } + set { + _wavPackWriter.ExtraMode = value; + } + } + + public void Close() { + _wavPackWriter.Close(); + } + + private unsafe void BytesToWavPackSamples_16(byte[] inSamples, int inByteOffset, + int[,] outSamples, int outSampleOffset, uint sampleCount, int channelCount) + { + uint loopCount = sampleCount * (uint) channelCount; + + if ((inSamples.Length - inByteOffset < loopCount * 2) || + (outSamples.GetLength(0) - outSampleOffset < sampleCount)) + { + throw new IndexOutOfRangeException(); + } + + fixed (byte* pInSamplesFixed = &inSamples[inByteOffset]) { + fixed (int* pOutSamplesFixed = &outSamples[outSampleOffset, 0]) { + short* pInSamples = (short*)pInSamplesFixed; + int* pOutSamples = pOutSamplesFixed; + + for (int i = 0; i < loopCount; i++) { + *(pOutSamples++) = (int)*(pInSamples++); + } + } + } + } + + public void Write(byte[] buff, uint sampleCount) { + if ((_sampleBuffer == null) || (_sampleBuffer.GetLength(0) < sampleCount)) { + _sampleBuffer = new int[sampleCount, _channelCount]; + } + BytesToWavPackSamples_16(buff, 0, _sampleBuffer, 0, sampleCount, _channelCount); + _wavPackWriter.Write(_sampleBuffer, (int) sampleCount); + } + } +} \ No newline at end of file diff --git a/CUETools/CUETools.csproj b/CUETools/CUETools.csproj new file mode 100644 index 0000000..df44dc1 --- /dev/null +++ b/CUETools/CUETools.csproj @@ -0,0 +1,176 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {EF351583-A9CD-4530-92C3-20AC02136BC2} + WinExe + Properties + JDP + CUETools + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AnyCPU + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + AnyCPU + + + true + ..\bin\win32\Debug\ + DEBUG;TRACE + true + full + x86 + prompt + + + ..\bin\win32\Release\ + TRACE + true + true + pdbonly + x86 + prompt + + + true + ..\bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + + + ..\bin\x64\Release\ + TRACE + true + true + pdbonly + x64 + prompt + + + + + + + + + + + + Form + + + frmBatch.cs + + + Form + + + frmFilenameCorrector.cs + + + Form + + + frmReport.cs + + + Form + + + frmSettings.cs + + + + Form + + + frmCUETools.cs + + + + + Designer + frmBatch.cs + + + Designer + frmCUETools.cs + + + Designer + frmFilenameCorrector.cs + + + Designer + frmReport.cs + + + Designer + frmSettings.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + {9AE965C4-301E-4C01-B90F-297AF341ACC6} + APEDotNet + + + {E70FA90A-7012-4A52-86B5-362B699D1540} + FLACDotNet + + + {CC2E74B6-534A-43D8-9F16-AC03FE955000} + WavPackDotNet + + + + + \ No newline at end of file diff --git a/CUETools/CUETools.sln b/CUETools/CUETools.sln new file mode 100644 index 0000000..90c5f7f --- /dev/null +++ b/CUETools/CUETools.sln @@ -0,0 +1,158 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CUETools", "CUETools.csproj", "{EF351583-A9CD-4530-92C3-20AC02136BC2}" + ProjectSection(ProjectDependencies) = postProject + {9AE965C4-301E-4C01-B90F-297AF341ACC6} = {9AE965C4-301E-4C01-B90F-297AF341ACC6} + {E70FA90A-7012-4A52-86B5-362B699D1540} = {E70FA90A-7012-4A52-86B5-362B699D1540} + {CC2E74B6-534A-43D8-9F16-AC03FE955000} = {CC2E74B6-534A-43D8-9F16-AC03FE955000} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FLACDotNet", "..\FLACDotNet\FLACDotNet.vcproj", "{E70FA90A-7012-4A52-86B5-362B699D1540}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "APEDotNet", "..\APEDotNet\APEDotNet.vcproj", "{9AE965C4-301E-4C01-B90F-297AF341ACC6}" + ProjectSection(ProjectDependencies) = postProject + {0B9C97D4-61B8-4294-A1DF-BA90752A1779} = {0B9C97D4-61B8-4294-A1DF-BA90752A1779} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CodecLibs", "CodecLibs", "{8B179853-B7D6-479C-B8B2-6CBCE835D040}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WavPackDotNet", "..\WavPackDotNet\WavPackDotNet.vcproj", "{CC2E74B6-534A-43D8-9F16-AC03FE955000}" + ProjectSection(ProjectDependencies) = postProject + {0B9C97D4-61B8-4294-A1DF-BA90752A1779} = {0B9C97D4-61B8-4294-A1DF-BA90752A1779} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MACLib", "..\MAC_SDK\Source\MACLib\MACLib.vcproj", "{0B9C97D4-61B8-4294-A1DF-BA90752A1779}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CodecWrappers", "CodecWrappers", "{85F88959-C9E9-4989-ACB1-67BA9D1BEFE7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libFLAC_static", "..\flac\src\libFLAC\libFLAC_static.vcproj", "{4CEFBC84-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "APETagsDotNet", "..\APETagsDotNet\APETagsDotNet.vcproj", "{A8662B81-5B09-487E-B8F6-28251A8C46AF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|Win32.ActiveCfg = Debug|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|Win32.Build.0 = Debug|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|x64.ActiveCfg = Debug|x64 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|x64.Build.0 = Debug|x64 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|x86.ActiveCfg = Debug|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Debug|x86.Build.0 = Debug|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|Any CPU.Build.0 = Release|Any CPU + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|Win32.ActiveCfg = Release|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|Win32.Build.0 = Release|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|x64.ActiveCfg = Release|x64 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|x64.Build.0 = Release|x64 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|x86.ActiveCfg = Release|x86 + {EF351583-A9CD-4530-92C3-20AC02136BC2}.Release|x86.Build.0 = Release|x86 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|Any CPU.ActiveCfg = Debug|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|Win32.ActiveCfg = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|Win32.Build.0 = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x64.ActiveCfg = Debug|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x64.Build.0 = Debug|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x86.ActiveCfg = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x86.Build.0 = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|Any CPU.ActiveCfg = Release|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|Win32.ActiveCfg = Release|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|Win32.Build.0 = Release|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x64.ActiveCfg = Release|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x64.Build.0 = Release|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x86.ActiveCfg = Release|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x86.Build.0 = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|Any CPU.ActiveCfg = Debug|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|Win32.ActiveCfg = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|Win32.Build.0 = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x64.ActiveCfg = Debug|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x64.Build.0 = Debug|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x86.ActiveCfg = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x86.Build.0 = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|Any CPU.ActiveCfg = Release|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|Win32.ActiveCfg = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|Win32.Build.0 = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x64.ActiveCfg = Release|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x64.Build.0 = Release|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x86.ActiveCfg = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x86.Build.0 = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|Win32.ActiveCfg = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|Win32.Build.0 = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|x64.ActiveCfg = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|x86.ActiveCfg = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|x86.Build.0 = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|Any CPU.ActiveCfg = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|Win32.ActiveCfg = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|Win32.Build.0 = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|x64.ActiveCfg = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|x86.ActiveCfg = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|x86.Build.0 = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|Any CPU.ActiveCfg = Debug|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|Win32.ActiveCfg = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|Win32.Build.0 = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x64.ActiveCfg = Debug|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x64.Build.0 = Debug|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x86.ActiveCfg = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x86.Build.0 = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|Any CPU.ActiveCfg = Release|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|Win32.ActiveCfg = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|Win32.Build.0 = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x64.ActiveCfg = Release|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x64.Build.0 = Release|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x86.ActiveCfg = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x86.Build.0 = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|Any CPU.ActiveCfg = Debug|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x86.ActiveCfg = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x86.Build.0 = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|Any CPU.ActiveCfg = Release|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x86.ActiveCfg = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x86.Build.0 = Release|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|Win32.ActiveCfg = Debug|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|Win32.Build.0 = Debug|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|x64.ActiveCfg = Debug|x64 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|x64.Build.0 = Debug|x64 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|x86.ActiveCfg = Debug|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Debug|x86.Build.0 = Debug|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|Any CPU.ActiveCfg = Release|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|Win32.ActiveCfg = Release|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|Win32.Build.0 = Release|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|x64.ActiveCfg = Release|x64 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|x64.Build.0 = Release|x64 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|x86.ActiveCfg = Release|Win32 + {A8662B81-5B09-487E-B8F6-28251A8C46AF}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {9AE965C4-301E-4C01-B90F-297AF341ACC6} = {85F88959-C9E9-4989-ACB1-67BA9D1BEFE7} + {CC2E74B6-534A-43D8-9F16-AC03FE955000} = {85F88959-C9E9-4989-ACB1-67BA9D1BEFE7} + {E70FA90A-7012-4A52-86B5-362B699D1540} = {85F88959-C9E9-4989-ACB1-67BA9D1BEFE7} + {A8662B81-5B09-487E-B8F6-28251A8C46AF} = {85F88959-C9E9-4989-ACB1-67BA9D1BEFE7} + {0B9C97D4-61B8-4294-A1DF-BA90752A1779} = {8B179853-B7D6-479C-B8B2-6CBCE835D040} + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {8B179853-B7D6-479C-B8B2-6CBCE835D040} + EndGlobalSection +EndGlobal diff --git a/CUETools/GPL.txt b/CUETools/GPL.txt new file mode 100644 index 0000000..45645b4 --- /dev/null +++ b/CUETools/GPL.txt @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/CUETools/Main.cs b/CUETools/Main.cs new file mode 100644 index 0000000..8edd270 --- /dev/null +++ b/CUETools/Main.cs @@ -0,0 +1,2404 @@ +// **************************************************************************** +// +// CUE Tools +// Copyright (C) 2006-2007 Moitah (moitah@yahoo.com) +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// **************************************************************************** + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Text; +using System.Globalization; +using System.IO; +using System.Net; + +namespace JDP { + + public enum OutputAudioFormat + { + WAV, + FLAC, + WavPack, + NoAudio + } + + static class General { + public static string FormatExtension(OutputAudioFormat value) + { + switch (value) + { + case OutputAudioFormat.FLAC: return ".flac"; + case OutputAudioFormat.WavPack: return ".wv"; + case OutputAudioFormat.WAV: return ".wav"; + case OutputAudioFormat.NoAudio: return ".dummy"; + } + return ".wav"; + } + + public static int TimeFromString(string s) { + string[] n = s.Split(':'); + if (n.Length != 3) { + throw new Exception("Invalid timestamp."); + } + int min, sec, frame; + + min = Int32.Parse(n[0]); + sec = Int32.Parse(n[1]); + frame = Int32.Parse(n[2]); + + return frame + (sec * 75) + (min * 60 * 75); + } + + public static string TimeToString(uint t) { + uint min, sec, frame; + + frame = t % 75; + t /= 75; + sec = t % 60; + t /= 60; + min = t; + + return String.Format("{0:00}:{1:00}:{2:00}", min, sec, frame); + } + + public static CUELine FindCUELine(List list, string command) { + command = command.ToUpper(); + foreach (CUELine line in list) { + if (line.Params[0].ToUpper() == command) { + return line; + } + } + return null; + } + + public static CUELine FindCUELine(List list, string command, string command2) + { + command = command.ToUpper(); + command2 = command2.ToUpper(); + foreach (CUELine line in list) + { + if (line.Params.Count > 1 && line.Params[0].ToUpper() == command && line.Params[1].ToUpper() == command2) + { + return line; + } + } + return null; + } + + public static void SetCUELine(List list, string command, string value, bool quoted) + { + CUELine line = General.FindCUELine(list, command); + if (line == null) + { + line = new CUELine(); + line.Params.Add(command); line.IsQuoted.Add(false); + line.Params.Add(value); line.IsQuoted.Add(true); + list.Add(line); + } + else + { + line.Params[1] = value; + line.IsQuoted[1] = quoted; + } + } + + public static void SetCUELine(List list, string command, string command2, string value, bool quoted) + { + CUELine line = General.FindCUELine(list, command, command2); + if (line == null) + { + line = new CUELine(); + line.Params.Add(command); line.IsQuoted.Add(false); + line.Params.Add(command2); line.IsQuoted.Add(false); + line.Params.Add(value); line.IsQuoted.Add(true); + list.Add(line); + } + else + { + line.Params[2] = value; + line.IsQuoted[2] = quoted; + } + } + + public static string ReplaceMultiple(string s, List find, List replace) + { + if (find.Count != replace.Count) + { + throw new ArgumentException(); + } + StringBuilder sb; + int iChar, iFind; + string f; + bool found; + + sb = new StringBuilder(); + + for (iChar = 0; iChar < s.Length; iChar++) + { + found = false; + for (iFind = 0; iFind < find.Count; iFind++) + { + f = find[iFind]; + if ((f.Length <= (s.Length - iChar)) && (s.Substring(iChar, f.Length) == f)) + { + if (replace[iFind] == null) + { + return null; + } + sb.Append(replace[iFind]); + iChar += f.Length - 1; + found = true; + break; + } + } + + if (!found) + { + sb.Append(s[iChar]); + } + } + + return sb.ToString(); + } + + public static string EmptyStringToNull(string s) + { + return ((s != null) && (s.Length == 0)) ? null : s; + } + } + + delegate void SetStatus(string status, uint percentTrack, double percentDisk); + + enum CUEStyle { + SingleFileWithCUE, + SingleFile, + GapsPrepended, + GapsAppended, + GapsLeftOut + } + + public class CUEConfig { + public uint fixWhenConfidence; + public uint fixWhenPercent; + public uint encodeWhenConfidence; + public uint encodeWhenPercent; + public bool writeCRC; + public bool writeArLog; + public bool fixOffset; + public bool noUnverifiedOutput; + public bool autoCorrectFilenames; + public bool flacVerify; + public uint flacCompressionLevel; + public bool preserveHTOA; + public int wvCompressionMode; + public int wvExtraMode; + public bool keepOriginalFilenames; + public string trackFilenameFormat; + public string singleFilenameFormat; + public bool removeSpecial; + public string specialExceptions; + public bool replaceSpaces; + public bool embedLog; + + private string[] _charMap; + + public CUEConfig() + { + fixWhenConfidence = 1; + fixWhenPercent = 51; + encodeWhenConfidence = 1; + encodeWhenPercent = 100; + fixOffset = true; + noUnverifiedOutput = false; + writeCRC = true; + writeArLog = true; + + autoCorrectFilenames = true; + flacVerify = false; + flacCompressionLevel = 5; + preserveHTOA = false; + wvCompressionMode = 1; + wvExtraMode = 0; + keepOriginalFilenames = true; + trackFilenameFormat = "%N-%A-%T"; + singleFilenameFormat = "%F"; + removeSpecial = true; + specialExceptions = "-()"; + replaceSpaces = true; + embedLog = true; + BuildCharMap(); + } + + public void Save (SettingsWriter sw) + { + sw.Save("ArFixWhenConfidence", fixWhenConfidence.ToString()); + sw.Save("ArFixWhenPercent", fixWhenPercent.ToString()); + sw.Save("ArEncodeWhenConfidence", encodeWhenConfidence.ToString()); + sw.Save("ArEncodeWhenPercent", encodeWhenPercent.ToString()); + sw.Save("ArNoUnverifiedOutput", noUnverifiedOutput ? "1" : "0"); + sw.Save("ArFixOffset", fixOffset ? "1" : "0"); + sw.Save("ArWriteCRC", writeCRC ? "1" : "0"); + sw.Save("ArWriteLog", writeArLog ? "1" : "0"); + + sw.Save("AutoCorrectFilenames", autoCorrectFilenames ? "1" : "0"); + sw.Save("FLACVerify", flacVerify ? "1" : "0"); + sw.Save("FLACCompressionLevel", flacCompressionLevel.ToString()); + sw.Save("PreserveHTOA", preserveHTOA ? "1" : "0"); + sw.Save("WVCompressionMode", wvCompressionMode.ToString()); + sw.Save("WVExtraMode", wvExtraMode.ToString()); + sw.Save("KeepOriginalFilenames", keepOriginalFilenames ? "1" : "0"); + sw.Save("SingleFilenameFormat", singleFilenameFormat); + sw.Save("TrackFilenameFormat", trackFilenameFormat); + sw.Save("RemoveSpecialCharacters", removeSpecial ? "1" : "0"); + sw.Save("SpecialCharactersExceptions", specialExceptions); + sw.Save("ReplaceSpaces", replaceSpaces ? "1" : "0"); + sw.Save("EmbedLog", embedLog ? "1" : "0"); + } + + public void Load(SettingsReader sr) + { + string val; + + val = sr.Load("ArFixWhenConfidence"); + if ((val == null) || !UInt32.TryParse(val, out fixWhenConfidence) || + fixWhenConfidence <= 0 || fixWhenConfidence > 1000) + fixWhenConfidence = 1; + + val = sr.Load("ArFixWhenPercent"); + if ((val == null) || !UInt32.TryParse(val, out fixWhenPercent) || + fixWhenPercent <= 0 || fixWhenPercent > 100) + fixWhenPercent = 50; + + val = sr.Load("ArEncodeWhenConfidence"); + if ((val == null) || !UInt32.TryParse(val, out encodeWhenConfidence) || + encodeWhenConfidence <= 0 || encodeWhenConfidence > 1000) + encodeWhenConfidence = 1; + + val = sr.Load("ArEncodeWhenPercent"); + if ((val == null) || !UInt32.TryParse(val, out encodeWhenPercent) || + encodeWhenPercent <= 0 || encodeWhenPercent > 100) + encodeWhenPercent = 50; + + val = sr.Load("ArNoUnverifiedOutput"); + noUnverifiedOutput = (val != null) ? (val != "0") : true; + + val = sr.Load("ArFixOffset"); + fixOffset = (val != null) ? (val != "0") : true; + + val = sr.Load("ArWriteCRC"); + writeCRC = (val != null) ? (val != "0") : true; + + val = sr.Load("ArWriteLog"); + writeArLog = (val != null) ? (val != "0") : true; + + val = sr.Load("PreserveHTOA"); + preserveHTOA = (val != null) ? (val != "0") : true; + + val = sr.Load("AutoCorrectFilenames"); + autoCorrectFilenames = (val != null) ? (val != "0") : false; + + val = sr.Load("FLACCompressionLevel"); + if ((val == null) || !UInt32.TryParse(val, out flacCompressionLevel) || + flacCompressionLevel > 8) + flacCompressionLevel = 5; + + val = sr.Load("FLACVerify"); + flacVerify = (val != null) ? (val != "0") : false; + + val = sr.Load("WVCompressionMode"); + if ((val == null) || !Int32.TryParse(val, out wvCompressionMode) || + (wvCompressionMode < 0) || (wvCompressionMode > 3)) + wvCompressionMode = 1; + + val = sr.Load("WVExtraMode"); + if ((val == null) || !Int32.TryParse(val, out wvExtraMode) || + (wvExtraMode < 0) || (wvExtraMode > 6)) + wvExtraMode = 0; + + val = sr.Load("KeepOriginalFilenames"); + keepOriginalFilenames = (val != null) ? (val != "0") : true; + + val = sr.Load("SingleFilenameFormat"); + singleFilenameFormat = (val != null) ? val : "%F"; + + val = sr.Load("TrackFilenameFormat"); + trackFilenameFormat = (val != null) ? val : "%N-%A-%T"; + + val = sr.Load("RemoveSpecialCharacters"); + removeSpecial = (val != null) ? (val != "0") : true; + + val = sr.Load("SpecialCharactersExceptions"); + specialExceptions = (val != null) ? val : "-()"; + + val = sr.Load("ReplaceSpaces"); + replaceSpaces = (val != null) ? (val != "0") : true; + + val = sr.Load("EmbedLog"); + embedLog = (val != null) ? (val != "0") : true; + + BuildCharMap(); + } + + public void BuildCharMap() + { + System.Collections.BitArray allowed = new System.Collections.BitArray(256, true); + char[] invalid = Path.GetInvalidFileNameChars(); + int i; + + if (removeSpecial) + { + byte[] exceptions = CUESheet.Encoding.GetBytes(specialExceptions); + + for (i = 0; i <= 255; i++) + { + allowed[i] = ((i >= 'a') && (i <= 'z')) || + ((i >= 'A') && (i <= 'Z')) || + ((i >= '0') && (i <= '9')) || + (i == ' ') || (i == '_'); + } + + for (i = 0; i < exceptions.Length; i++) + { + allowed[exceptions[i]] = true; + } + } + + for (i = 0; i < invalid.Length; i++) + { + allowed[invalid[i]] = false; + } + + _charMap = new string[256]; + for (i = 0; i <= 255; i++) + { + if (allowed[i]) + { + _charMap[i] = CUESheet.Encoding.GetString(new byte[] { (byte)i }); + } + else + { + _charMap[i] = String.Empty; + } + } + } + public string CleanseString (string s) + { + StringBuilder sb = new StringBuilder(); + byte[] b = CUESheet.Encoding.GetBytes(s); + + for (int i = 0; i < b.Length; i++) + { + sb.Append(_charMap[b[i]]); + } + + return sb.ToString(); + } + } + + class CUESheet { + private bool _stop; + private List _attributes; + private List _tracks; + private List _sources; + private List _sourcePaths, _trackFilenames; + private string _htoaFilename, _singleFilename; + private bool _hasHTOAFilename, _hasTrackFilenames, _hasSingleFilename, _appliedWriteOffset; + private bool _hasEmbeddedCUESheet; + private bool _paddedToFrame, _usePregapForFirstTrackInSingleFile; + private int _writeOffset; + private bool _accurateRip, _accurateOffset; + private uint? _dataTrackLength; + private string _accurateRipId; + private string _eacLog; + private string _cuePath; + private NameValueCollection _albumTags; + private List accDisks; + private HttpStatusCode accResult; + private const int _arOffsetRange = 5 * 588 - 1; + CUEConfig _config; + + public CUESheet(string pathIn, CUEConfig config) + { + _config = config; + + string cueDir, lineStr, command, pathAudio, fileType; + CUELine line; + TrackInfo trackInfo; + int tempTimeLength, timeRelativeToFileStart, absoluteFileStartTime; + int fileTimeLengthSamples, fileTimeLengthFrames, i, trackNumber; + bool seenFirstFileIndex, seenDataTrack; + List indexes; + IndexInfo indexInfo; + SourceInfo sourceInfo; + NameValueCollection _trackTags = null; + + _stop = false; + _attributes = new List(); + _tracks = new List(); + _sources = new List(); + _sourcePaths = new List(); + _cuePath = null; + _paddedToFrame = false; + _usePregapForFirstTrackInSingleFile = false; + _accurateRip = false; + _accurateOffset = false; + _appliedWriteOffset = false; + _dataTrackLength = null; + _albumTags = new NameValueCollection(); + cueDir = Path.GetDirectoryName(pathIn); + pathAudio = null; + indexes = new List(); + trackInfo = null; + absoluteFileStartTime = 0; + fileTimeLengthSamples = 0; + fileTimeLengthFrames = 0; + trackNumber = 0; + seenFirstFileIndex = false; + seenDataTrack = false; + accDisks = new List(); + _hasEmbeddedCUESheet = false; + + _config.BuildCharMap(); + + TextReader sr; + + if (Path.GetExtension(pathIn).ToLower() != ".cue") + { + IAudioSource audioSource; + NameValueCollection tags; + string cuesheetTag = null; + + audioSource = AudioReadWrite.GetAudioSource(pathIn); + tags = audioSource.Tags; + cuesheetTag = tags.Get("CUESHEET"); + _accurateRipId = tags.Get("ACCURATERIPID"); + _eacLog = tags.Get("LOG"); + if (_eacLog == null) _eacLog = tags.Get("LOGFILE"); + if (_eacLog == null) _eacLog = tags.Get("EACLOG"); + audioSource.Close(); + if (cuesheetTag == null) + throw new Exception("Input file does not contain a .cue sheet."); + sr = new StringReader (cuesheetTag); + pathAudio = pathIn; + _hasEmbeddedCUESheet = true; + } else + { + if (_config.autoCorrectFilenames) + sr = new StringReader (CorrectAudioFilenames(pathIn, false)); + else + sr = new StreamReader (pathIn, CUESheet.Encoding); + + try + { + StreamReader logReader = new StreamReader(Path.ChangeExtension(pathIn, ".log"), CUESheet.Encoding); + _eacLog = logReader.ReadToEnd(); + } + catch { } + } + + using (sr) { + while ((lineStr = sr.ReadLine()) != null) { + line = new CUELine(lineStr); + if (line.Params.Count > 0) { + command = line.Params[0].ToUpper(); + + if (command == "FILE") { + fileType = line.Params[2].ToUpper(); + if ((fileType == "BINARY") || (fileType == "MOTOROLA")) { + seenDataTrack = true; + } + else if (seenDataTrack) { + throw new Exception("Audio tracks cannot appear after data tracks."); + } + else { + if (!_hasEmbeddedCUESheet) + { + pathAudio = LocateFile(cueDir, line.Params[1]); + if (pathAudio == null) + { + throw new Exception("Unable to locate file \"" + line.Params[1] + "\"."); + } + } else + { + if (_sourcePaths.Count > 0 ) + throw new Exception("Extra file in embedded CUE sheet: \"" + line.Params[1] + "\"."); + } + _sourcePaths.Add(pathAudio); + absoluteFileStartTime += fileTimeLengthFrames; + NameValueCollection tags; + fileTimeLengthSamples = GetSampleLength(pathAudio, out tags); + if (_hasEmbeddedCUESheet) + _albumTags = tags; + else + _trackTags = tags; + fileTimeLengthFrames = (int)((fileTimeLengthSamples + 587) / 588); + seenFirstFileIndex = false; + } + } + else if (command == "TRACK") { + if (line.Params[2].ToUpper() != "AUDIO") { + seenDataTrack = true; + } + else if (seenDataTrack) { + throw new Exception("Audio tracks cannot appear after data tracks."); + } + else { + trackNumber = Int32.Parse(line.Params[1]); + if (trackNumber != _tracks.Count + 1) { + throw new Exception("Invalid track number."); + } + trackInfo = new TrackInfo(); + _tracks.Add(trackInfo); + } + } + else if (seenDataTrack) { + // Ignore lines belonging to data tracks + } + else if (command == "INDEX") { + timeRelativeToFileStart = General.TimeFromString(line.Params[2]); + if (!seenFirstFileIndex) + { + if (timeRelativeToFileStart != 0) + { + throw new Exception("First index must start at file beginning."); + } + if (trackNumber > 0 && _trackTags != null && _trackTags.Count != 0) + _tracks[trackNumber-1]._trackTags = _trackTags; + seenFirstFileIndex = true; + sourceInfo.Path = pathAudio; + sourceInfo.Offset = 0; + sourceInfo.Length = (uint)fileTimeLengthSamples; + _sources.Add(sourceInfo); + if ((fileTimeLengthSamples % 588) != 0) + { + sourceInfo.Path = null; + sourceInfo.Offset = 0; + sourceInfo.Length = (uint)((fileTimeLengthFrames * 588) - fileTimeLengthSamples); + _sources.Add(sourceInfo); + _paddedToFrame = true; + } + } + indexInfo.Track = trackNumber; + indexInfo.Index = Int32.Parse(line.Params[1]); + indexInfo.Time = absoluteFileStartTime + timeRelativeToFileStart; + indexes.Add(indexInfo); + } + else if (command == "PREGAP") { + if (seenFirstFileIndex) { + throw new Exception("Pregap must occur at the beginning of a file."); + } + tempTimeLength = General.TimeFromString(line.Params[1]); + indexInfo.Track = trackNumber; + indexInfo.Index = 0; + indexInfo.Time = absoluteFileStartTime; + indexes.Add(indexInfo); + sourceInfo.Path = null; + sourceInfo.Offset = 0; + sourceInfo.Length = (uint) tempTimeLength * 588; + _sources.Add(sourceInfo); + absoluteFileStartTime += tempTimeLength; + } + else if (command == "POSTGAP") { + throw new Exception("POSTGAP command isn't supported."); + } + else if ((command == "REM") && + (line.Params.Count >= 3) && + (line.Params[1].Length >= 10) && + (line.Params[1].Substring(0, 10).ToUpper() == "REPLAYGAIN")) + { + // Remove ReplayGain lines + } + else if ((command == "REM") && + (line.Params.Count == 3) && + (line.Params[1].ToUpper() == "DATATRACKLENGTH")) + { + _dataTrackLength = (uint)General.TimeFromString(line.Params[2]); + } + else if ((command == "REM") && + (line.Params.Count == 3) && + (line.Params[1].ToUpper() == "ACCURATERIPID")) + { + _accurateRipId = line.Params[2]; + } + else + { + if (trackInfo != null) + { + trackInfo.Attributes.Add(line); + } + else + { + _attributes.Add(line); + } + } + } + } + } + + if (trackNumber == 0) { + throw new Exception("File must contain at least one audio track."); + } + + // Add dummy track for calculation purposes + indexInfo.Track = trackNumber + 1; + indexInfo.Index = 1; + indexInfo.Time = absoluteFileStartTime + fileTimeLengthFrames; + indexes.Add(indexInfo); + + // Calculate the length of each index + for (i = 0; i < indexes.Count - 1; i++) { + indexInfo = indexes[i]; + + tempTimeLength = indexes[i + 1].Time - indexInfo.Time; + if (tempTimeLength > 0) { + _tracks[indexInfo.Track - 1].AddIndex((indexInfo.Index == 0), (uint) tempTimeLength); + } + else if (tempTimeLength < 0) { + throw new Exception("Indexes must be in chronological order."); + } + } + + for (i = 0; i < TrackCount; i++) { + if (_tracks[i].LastIndex < 1) { + throw new Exception("Track must have an INDEX 01."); + } + } + + // Store the audio filenames, generating generic names if necessary + _hasSingleFilename = (_sourcePaths.Count == 1); + _singleFilename = _hasSingleFilename ? Path.GetFileName(_sourcePaths[0]) : + "Range.wav"; + + _hasHTOAFilename = (_sourcePaths.Count == (TrackCount + 1)); + _htoaFilename = _hasHTOAFilename ? Path.GetFileName(_sourcePaths[0]) : "01.00.wav"; + + _hasTrackFilenames = (_sourcePaths.Count == TrackCount) || _hasHTOAFilename; + _trackFilenames = new List(); + for (i = 0; i < TrackCount; i++) { + _trackFilenames.Add( _hasTrackFilenames ? Path.GetFileName( + _sourcePaths[i + (_hasHTOAFilename ? 1 : 0)]) : String.Format("{0:00}.wav", i + 1) ); + } + + if (_hasTrackFilenames) + for (i = 0; i < TrackCount; i++) + { + TrackInfo track = _tracks[i]; + string artist = track._trackTags.Get("ARTIST"); + string title = track._trackTags.Get("TITLE"); + if (track.Artist == "" && artist != null) + track.Artist = artist; + if (track.Title == "" && title != null) + track.Title = title; + } + if (!_hasEmbeddedCUESheet && _hasSingleFilename) + { + _albumTags = _tracks[0]._trackTags; + _tracks[0]._trackTags = new NameValueCollection(); + } + if (General.FindCUELine(_attributes, "PERFORMER") == null && GetCommonTag("ALBUM ARTIST") != null) + General.SetCUELine(_attributes, "PERFORMER", GetCommonTag("ALBUM ARTIST"), true); + if (General.FindCUELine(_attributes, "PERFORMER") == null && GetCommonTag("ARTIST") != null) + General.SetCUELine(_attributes, "PERFORMER", GetCommonTag("ARTIST"), true); + if (General.FindCUELine(_attributes, "TITLE") == null && GetCommonTag("ALBUM") != null) + General.SetCUELine(_attributes, "TITLE", GetCommonTag("ALBUM"), true); + if (General.FindCUELine(_attributes, "REM", "DATE") == null && GetCommonTag("DATE") != null) + General.SetCUELine(_attributes, "REM", "DATE", GetCommonTag("DATE"), false); + if (General.FindCUELine(_attributes, "REM", "DATE") == null && GetCommonTag("YEAR") != null) + General.SetCUELine(_attributes, "REM", "DATE", GetCommonTag("YEAR"), false); + if (General.FindCUELine(_attributes, "REM", "GENRE") == null && GetCommonTag("GENRE") != null) + General.SetCUELine(_attributes, "REM", "GENRE", GetCommonTag("GENRE"), true); + if (_accurateRipId == null) + _accurateRipId = GetCommonTag("ACCURATERIPID"); + + if (_accurateRipId == null && _dataTrackLength == null && _eacLog != null) + { + sr = new StringReader(_eacLog); + int lastAudioSector = -1; + bool isEACLog = false; + while ((lineStr = sr.ReadLine()) != null) + { + if (!isEACLog) + { + if (!lineStr.StartsWith("Exact Audio Copy")) + break; + isEACLog = true; + } + string[] n = lineStr.Split('|'); + if (n.Length == 5) + try + { + int trNo = Int32.Parse(n[0]); + int trStart = Int32.Parse(n[3]); + int trEnd = Int32.Parse(n[4]); + if (trNo == TrackCount && trEnd > 0) + lastAudioSector = trEnd; + if (trNo == TrackCount + 1 && lastAudioSector != -1 && trEnd > lastAudioSector + (90 + 60) * 75 + 150) + { + _dataTrackLength = (uint)(trEnd - lastAudioSector - (90 + 60) * 75 - 150); + break; + } + } + catch { } + } + } + if (_accurateRipId == null && _dataTrackLength != null) + CalculateAccurateRipId(); + } + + public static Encoding Encoding { + get { + return Encoding.GetEncoding(1252); + } + } + + public string GetCommonTag(string tagName) + { + if (_hasEmbeddedCUESheet || _hasSingleFilename) + return _albumTags.Get(tagName); + if (_hasTrackFilenames) + { + string tagValue = null; + bool commonValue = true; + for (int i = 0; i < TrackCount; i++) + { + TrackInfo track = _tracks[i]; + string newValue = track._trackTags.Get (tagName); + if (tagValue == null) + tagValue = newValue; + else + commonValue = (newValue == null || tagValue == newValue); + } + return commonValue ? tagValue : null; + } + return null; + } + + private static string LocateFile(string dir, string file) { + List dirList, fileList; + string altDir, path; + + dirList = new List(); + fileList = new List(); + altDir = Path.GetDirectoryName(file); + file = Path.GetFileName(file); + + dirList.Add(dir); + if (altDir.Length != 0) { + dirList.Add(Path.IsPathRooted(altDir) ? altDir : Path.Combine(dir, altDir)); + } + + fileList.Add(file); + fileList.Add(file.Replace(' ', '_')); + fileList.Add(file.Replace('_', ' ')); + + for (int iDir = 0; iDir < dirList.Count; iDir++) { + for (int iFile = 0; iFile < fileList.Count; iFile++) { + path = Path.Combine(dirList[iDir], fileList[iFile]); + + if (File.Exists(path)) { + return path; + } + } + } + + return null; + } + + public void GenerateFilenames (OutputAudioFormat format, string outputPath) + { + _cuePath = outputPath; + + string extension = General.FormatExtension(format); + List find, replace; + string filename; + int iTrack; + + find = new List(); + replace = new List(); + + find.Add("%D"); // 0: Album artist + find.Add("%C"); // 1: Album title + find.Add("%N"); // 2: Track number + find.Add("%A"); // 3: Track artist + find.Add("%T"); // 4: Track title + find.Add("%F"); // 5: Input filename + + replace.Add(General.EmptyStringToNull(_config.CleanseString(Artist))); + replace.Add(General.EmptyStringToNull(_config.CleanseString(Title))); + replace.Add(null); + replace.Add(null); + replace.Add(null); + replace.Add(Path.GetFileNameWithoutExtension(outputPath)); + + if (_config.keepOriginalFilenames && HasSingleFilename) + { + SingleFilename = Path.ChangeExtension(SingleFilename, extension); + } + else + { + filename = General.ReplaceMultiple(_config.singleFilenameFormat, find, replace); + if (filename == null) + { + filename = "Range"; + } + if (_config.replaceSpaces) + { + filename = filename.Replace(' ', '_'); + } + filename += extension; + + SingleFilename = filename; + } + + for (iTrack = -1; iTrack < TrackCount; iTrack++) + { + bool htoa = (iTrack == -1); + + if (_config.keepOriginalFilenames && htoa && HasHTOAFilename) + { + HTOAFilename = Path.ChangeExtension(HTOAFilename, extension); + } + else if (_config.keepOriginalFilenames && !htoa && HasTrackFilenames) + { + TrackFilenames[iTrack] = Path.ChangeExtension( + TrackFilenames[iTrack], extension); + } + else + { + string trackStr = htoa ? "01.00" : String.Format("{0:00}", iTrack + 1); + string artist = Tracks[htoa ? 0 : iTrack].Artist; + string title = htoa ? "(HTOA)" : Tracks[iTrack].Title; + + replace[2] = trackStr; + replace[3] = General.EmptyStringToNull(_config.CleanseString(artist==""?Artist:artist)); + replace[4] = General.EmptyStringToNull(_config.CleanseString(title)); + + filename = General.ReplaceMultiple(_config.trackFilenameFormat, find, replace); + if (filename == null) + { + filename = replace[2]; + } + if (_config.replaceSpaces) + { + filename = filename.Replace(' ', '_'); + } + filename += extension; + + if (htoa) + { + HTOAFilename = filename; + } + else + { + TrackFilenames[iTrack] = filename; + } + } + } + } + + private int GetSampleLength(string path, out NameValueCollection tags) + { + IAudioSource audioSource; + + audioSource = AudioReadWrite.GetAudioSource(path); + + if ((audioSource.BitsPerSample != 16) || + (audioSource.ChannelCount != 2) || + (audioSource.SampleRate != 44100) || + (audioSource.Length > Int32.MaxValue)) + { + audioSource.Close(); + throw new Exception("Audio format is invalid."); + } + + tags = audioSource.Tags; + audioSource.Close(); + return (int)audioSource.Length; + } + + public void Write(string path, CUEStyle style) { + StreamWriter sw = new StreamWriter(path, false, CUESheet.Encoding); + Write (sw, style); + } + + public void Write(TextWriter sw, CUEStyle style) { + int i, iTrack, iIndex; + TrackInfo track; + bool htoaToFile = ((style == CUEStyle.GapsAppended) && _config.preserveHTOA && + (_tracks[0].IndexLengths[0] != 0)); + + uint timeRelativeToFileStart = 0; + + using (sw) { + if (_accurateRipId != null) + WriteLine(sw, 0, "REM ACCURATERIPID " + + _accurateRipId); + + for (i = 0; i < _attributes.Count; i++) { + WriteLine(sw, 0, _attributes[i]); + } + + if (style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE) { + WriteLine(sw, 0, String.Format("FILE \"{0}\" WAVE", _singleFilename)); + } + if (htoaToFile) { + WriteLine(sw, 0, String.Format("FILE \"{0}\" WAVE", _htoaFilename)); + } + + for (iTrack = 0; iTrack < TrackCount; iTrack++) { + track = _tracks[iTrack]; + + if ((style == CUEStyle.GapsPrepended) || + (style == CUEStyle.GapsLeftOut) || + ((style == CUEStyle.GapsAppended) && + ((track.IndexLengths[0] == 0) || ((iTrack == 0) && !htoaToFile))) ) + { + WriteLine(sw, 0, String.Format("FILE \"{0}\" WAVE", _trackFilenames[iTrack])); + timeRelativeToFileStart = 0; + } + + WriteLine(sw, 1, String.Format("TRACK {0:00} AUDIO", iTrack + 1)); + for (i = 0; i < track.Attributes.Count; i++) { + WriteLine(sw, 2, track.Attributes[i]); + } + + for (iIndex = 0; iIndex <= track.LastIndex; iIndex++) { + if (track.IndexLengths[iIndex] != 0) { + if ((iIndex == 0) && + ((style == CUEStyle.GapsLeftOut) || + ((style == CUEStyle.GapsAppended) && (iTrack == 0) && !htoaToFile) || + ((style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE) && (iTrack == 0) && _usePregapForFirstTrackInSingleFile))) + { + WriteLine(sw, 2, "PREGAP " + General.TimeToString(track.IndexLengths[iIndex])); + } + else { + WriteLine(sw, 2, String.Format( "INDEX {0:00} {1}", iIndex, + General.TimeToString(timeRelativeToFileStart) )); + timeRelativeToFileStart += track.IndexLengths[iIndex]; + + if ((style == CUEStyle.GapsAppended) && (iIndex == 0)) { + WriteLine(sw, 0, String.Format("FILE \"{0}\" WAVE", _trackFilenames[iTrack])); + timeRelativeToFileStart = 0; + } + } + } + } + } + } + } + + private uint sumDigits(uint n) + { + uint r = 0; + while (n > 0) + { + r = r + (n % 10); + n = n / 10; + } + return r; + } + private uint readIntLE(byte[] data, int pos) + { + return (uint) (data[pos] + ( data[pos+1] << 8 ) + ( data[pos+2] << 16 ) + ( data[pos+3] << 24) ); + } + + private void CalculateAccurateRipId () + { + // Calculate the three disc ids used by AR + uint discId1 = 0; + uint discId2 = 0; + uint cddbDiscId = 0; + uint trackOffset = 0; + + for (int iTrack = 0; iTrack < TrackCount; iTrack++) + { + TrackInfo track = _tracks[iTrack]; + + trackOffset += track.IndexLengths[0]; + discId1 += trackOffset; + discId2 += (trackOffset == 0 ? 1 : trackOffset) * ((uint)iTrack + 1); + cddbDiscId += sumDigits((uint)(trackOffset / 75) + 2); + + for (int iIndex = 1; iIndex <= track.LastIndex; iIndex++) + trackOffset += track.IndexLengths[iIndex]; + } + if (_dataTrackLength.HasValue) + { + trackOffset += ((90 + 60) * 75) + 150; // 90 second lead-out, 60 second lead-in, 150 sector gap + cddbDiscId += sumDigits((uint)(trackOffset / 75) + 2); + trackOffset += _dataTrackLength.Value; + } + discId1 += trackOffset; + discId2 += (trackOffset == 0 ? 1 : trackOffset) * ((uint)TrackCount + 1); + + cddbDiscId = ((cddbDiscId % 255) << 24) + + (((uint)(trackOffset / 75) - (uint)(_tracks[0].IndexLengths[0] / 75)) << 8) + + (uint)(TrackCount + (_dataTrackLength.HasValue ? 1 : 0)); + + discId1 &= 0xFFFFFFFF; + discId2 &= 0xFFFFFFFF; + cddbDiscId &= 0xFFFFFFFF; + + _accurateRipId = String.Format("{0:x8}-{1:x8}-{2:x8}", discId1, discId2, cddbDiscId); + } + + public void ContactAccurateRip() + { + // Calculate the three disc ids used by AR + uint discId1 = 0; + uint discId2 = 0; + uint cddbDiscId = 0; + + if (_accurateRipId == null) + CalculateAccurateRipId (); + + string[] n = _accurateRipId.Split('-'); + if (n.Length != 3) { + throw new Exception("Invalid accurateRipId."); + } + discId1 = UInt32.Parse(n[0], NumberStyles.HexNumber); + discId2 = UInt32.Parse(n[1], NumberStyles.HexNumber); + cddbDiscId = UInt32.Parse(n[2], NumberStyles.HexNumber); + + string url = String.Format("http://www.accuraterip.com/accuraterip/{0:x}/{1:x}/{2:x}/dBAR-{3:d3}-{4:x8}-{5:x8}-{6:x8}.bin", + discId1 & 0xF, discId1>>4 & 0xF, discId1>>8 & 0xF, TrackCount, discId1, discId2, cddbDiscId); + + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "GET"; + + try + { + HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); + accResult = resp.StatusCode; + + if (accResult == HttpStatusCode.OK) + { + // Retrieve response stream and wrap in StreamReader + Stream respStream = resp.GetResponseStream(); + + // Allocate byte buffer to hold stream contents + byte [] urlData = new byte[13]; + long urlDataLen; + + accDisks.Clear(); + while ( 0 != (urlDataLen = respStream.Read(urlData, 0, 13)) ) + { + if (urlDataLen < 13) + { + accResult = HttpStatusCode.PartialContent; + return; + } + AccDisk dsk = new AccDisk(); + dsk.count = urlData[0]; + dsk.discId1 = readIntLE(urlData, 1); + dsk.discId2 = readIntLE(urlData, 5); + dsk.cddbDiscId = readIntLE(urlData, 9); + + for (int i = 0; i < dsk.count; i++) + { + urlDataLen = respStream.Read(urlData, 0, 9); + if (urlDataLen < 9) + { + accResult = HttpStatusCode.PartialContent; + return; + } + AccTrack trk = new AccTrack(); + trk.count = urlData[0]; + trk.CRC = readIntLE(urlData, 1); + trk.Frame450CRC = readIntLE(urlData, 5); + dsk.tracks.Add(trk); + } + accDisks.Add(dsk); + } + respStream.Close(); + } + } + catch (WebException ex) + { + if (ex.Status == WebExceptionStatus.ProtocolError) + accResult = ((HttpWebResponse)ex.Response).StatusCode; + else + accResult = HttpStatusCode.BadRequest; + } + } + + unsafe private void CalculateAccurateRipCRCsSemifast(UInt32* samples, uint count, int iTrack, uint currentOffset, uint previousOffset, uint trackLength) + { + fixed (uint* CRCsA = iTrack != 0 ? _tracks[iTrack - 1].OffsetedCRC : null, + CRCsB = _tracks[iTrack].OffsetedCRC, + CRCsC = iTrack != TrackCount - 1 ? _tracks[iTrack + 1].OffsetedCRC : null) + { + for (uint si = 0; si < count; si++) + { + uint sampleValue = samples[si]; + int i; + int iB = Math.Max(0, _arOffsetRange - (int)(currentOffset + si)); + int iC = Math.Min(2 * _arOffsetRange + 1, _arOffsetRange + (int)trackLength - (int)(currentOffset + si)); + + uint baseSumA = sampleValue * (uint)(previousOffset + 1 - iB); + for (i = 0; i < iB; i++) + { + CRCsA[i] += baseSumA; + baseSumA += sampleValue; + } + uint baseSumB = sampleValue * (uint)Math.Max(1, (int)(currentOffset + si) - _arOffsetRange + 1); + for (i = iB; i < iC; i++) + { + CRCsB[i] += baseSumB; + baseSumB += sampleValue; + } + uint baseSumC = sampleValue; + for (i = iC; i <= 2 * _arOffsetRange; i++) + { + CRCsC[i] += baseSumC; + baseSumC += sampleValue; + } + } + return; + } + } + + unsafe private void CalculateAccurateRipCRCs(UInt32* samples, uint count, int iTrack, uint currentOffset, uint previousOffset, uint trackLength) + { + for (int si = 0; si < count; si++) + for (int oi = -_arOffsetRange; oi <= _arOffsetRange; oi++) + { + int iTrack2 = iTrack; + int currentOffset2 = (int) currentOffset + si - oi; + + if (currentOffset2 < 5 * 588 - 1 && iTrack == 0) + // we are in the skipped area at the start of the disk + { + continue; + } + else if (currentOffset2 < 0) + // offset takes us to previous track + { + iTrack2--; + currentOffset2 += (int) previousOffset; + } + else if (currentOffset2 >= trackLength - 5 * 588 && iTrack == TrackCount - 1) + // we are in the skipped area at the end of the disc + { + continue; + } + else if (currentOffset2 >= trackLength) + // offset takes us to the next track + { + iTrack2++; + currentOffset2 -= (int) trackLength; + } + _tracks[iTrack2].OffsetedCRC[_arOffsetRange - oi] += (uint)(samples [si] * (currentOffset2 + 1)); + } + } + + unsafe private void CalculateAccurateRipCRCsFast(UInt32* samples, uint count, int iTrack, uint currentOffset) + { + int s1 = (int) Math.Min(count, Math.Max(0, 450 * 588 - _arOffsetRange - (int)currentOffset)); + int s2 = (int) Math.Min(count, Math.Max(0, 451 * 588 + _arOffsetRange - (int)currentOffset)); + if ( s1 < s2 ) + fixed (uint* FrameCRCs = _tracks[iTrack].OffsetedFrame450CRC) + for (int sj = s1; sj < s2; sj++) + { + int magicFrameOffset = (int)currentOffset + sj - 450 * 588 + 1; + int firstOffset = Math.Max(-_arOffsetRange, magicFrameOffset - 588); + int lastOffset = Math.Min(magicFrameOffset - 1, _arOffsetRange); + for (int oi = firstOffset; oi <= lastOffset; oi++) + FrameCRCs[_arOffsetRange - oi] += (uint)(samples[sj] * (magicFrameOffset - oi)); + } + fixed (uint* CRCs = _tracks[iTrack].OffsetedCRC) + { + uint baseSum = 0, stepSum = 0; + currentOffset += (uint) _arOffsetRange + 1; + for (uint si = 0; si < count; si++) + { + uint sampleValue = samples[si]; + stepSum += sampleValue; + baseSum += sampleValue * (uint)(currentOffset + si); + } + for (int i = 2 * _arOffsetRange; i >= 0; i--) + { + CRCs[i] += baseSum; + baseSum -= stepSum; + } + } + } + + public void GenerateAccurateRipLog(TextWriter sw, int oi) + { + for (int iTrack = 0; iTrack < TrackCount; iTrack++) + { + uint count = 0; + uint partials = 0; + uint conf = 0; + string pressings = ""; + string partpressings = ""; + for (int di = 0; di < (int)accDisks.Count; di++) + { + count += accDisks[di].tracks[iTrack].count; + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - oi] == accDisks[di].tracks[iTrack].CRC) + { + conf += accDisks[di].tracks[iTrack].count; + if (pressings != "") + pressings = pressings + ","; + pressings = pressings + (di + 1).ToString(); + } + if (_tracks[iTrack].OffsetedFrame450CRC[_arOffsetRange - oi] == accDisks[di].tracks[iTrack].Frame450CRC) + { + partials += accDisks[di].tracks[iTrack].count; + if (partpressings != "") + partpressings = partpressings + ","; + partpressings = partpressings + (di + 1).ToString(); + } + } + if (conf > 0) + sw.WriteLine(String.Format(" {0:00}\t[{1:x8}] ({3:00}/{2:00}) Accurately ripped as in pressing(s) #{4}", iTrack + 1, _tracks[iTrack].OffsetedCRC[_arOffsetRange - oi], count, conf, pressings)); + else if (partials > 0) + sw.WriteLine(String.Format(" {0:00}\t[{1:x8}] ({3:00}/{2:00}) Partial match to pressing(s) #{4} ", iTrack + 1, _tracks[iTrack].OffsetedCRC[_arOffsetRange - oi], count, partials, partpressings)); + else + sw.WriteLine(String.Format(" {0:00}\t[{1:x8}] (00/{2:00}) No matches", iTrack + 1, _tracks[iTrack].OffsetedCRC[_arOffsetRange - oi], count)); + } + } + + public void GenerateAccurateRipLog(TextWriter sw) + { + int iTrack; + sw.WriteLine (String.Format("[Disc ID: {0}]", _accurateRipId)); + if (0 != _writeOffset) + sw.WriteLine(String.Format("Offset applied: {0}", _writeOffset)); + sw.WriteLine(String.Format("Track\t[ CRC ] Status")); + if (accResult == HttpStatusCode.NotFound) + { + for (iTrack = 0; iTrack < TrackCount; iTrack++) + sw.WriteLine(String.Format(" {0:00}\t[{1:x8}] Disk not present in database", iTrack + 1, _tracks[iTrack].CRC)); + } + else if (accResult != HttpStatusCode.OK) + { + for (iTrack = 0; iTrack < TrackCount; iTrack++) + sw.WriteLine(String.Format(" {0:00}\t[{1:x8}] Database access error {2}", iTrack + 1, _tracks[iTrack].CRC, accResult.ToString())); + } + else + { + GenerateAccurateRipLog(sw, _writeOffset); + uint offsets_match = 0; + for (int oi = -_arOffsetRange; oi <= _arOffsetRange; oi++) + { + uint matches = 0; + for (iTrack = 0; iTrack < TrackCount; iTrack++) + for (int di = 0; di < (int)accDisks.Count; di++) + if ( (_tracks[iTrack].OffsetedCRC[_arOffsetRange - oi] == accDisks[di].tracks[iTrack].CRC && accDisks[di].tracks[iTrack].CRC != 0) || + (_tracks[iTrack].OffsetedFrame450CRC[_arOffsetRange - oi] == accDisks[di].tracks[iTrack].Frame450CRC && accDisks[di].tracks[iTrack].Frame450CRC != 0) ) + matches++; + if (matches != 0 && oi != _writeOffset) + { + if (offsets_match++ > 10) + { + sw.WriteLine("More than 10 offsets match!"); + break; + } + sw.WriteLine(String.Format("Offsetted by {0}:", oi)); + GenerateAccurateRipLog(sw, oi); + } + } + } + } + + public void GenerateAccurateRipTagsForTrack(NameValueCollection tags, int offset, int bestOffset, int iTrack, string prefix) + { + uint total = 0; + uint matching = 0; + uint matching2 = 0; + uint matching3 = 0; + for (int iDisk = 0; iDisk < accDisks.Count; iDisk++) + { + total += accDisks[iDisk].tracks[iTrack].count; + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - offset] == + accDisks[iDisk].tracks[iTrack].CRC) + matching += accDisks[iDisk].tracks[iTrack].count; + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - bestOffset] == + accDisks[iDisk].tracks[iTrack].CRC) + matching2 += accDisks[iDisk].tracks[iTrack].count; + for (int oi = -_arOffsetRange; oi <= _arOffsetRange; oi++) + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - oi] == + accDisks[iDisk].tracks[iTrack].CRC) + matching3 += accDisks[iDisk].tracks[iTrack].count; + } + tags.Add(String.Format("{0}ACCURATERIPCRC", prefix), String.Format("{0:x8}", _tracks[iTrack].OffsetedCRC[_arOffsetRange - offset])); + tags.Add(String.Format("{0}ACCURATERIPCOUNT", prefix), String.Format("{0}", matching)); + tags.Add(String.Format("{0}ACCURATERIPCOUNTALLOFFSETS", prefix), String.Format("{0}", matching3)); + tags.Add(String.Format("{0}ACCURATERIPTOTAL", prefix), String.Format("{0}", total)); + if (bestOffset != offset) + tags.Add(String.Format("{0}ACCURATERIPCOUNTWITHOFFSET", prefix), String.Format("{0}", matching2)); + } + + public void GenerateAccurateRipTags(NameValueCollection tags, int offset, int bestOffset, int iTrack) + { + tags.Add("ACCURATERIPID", _accurateRipId); + if (bestOffset != offset) + tags.Add("ACCURATERIPOFFSET", String.Format("{1}{0}", bestOffset - offset, bestOffset > offset ? "+" : "")); + if (iTrack != -1) + GenerateAccurateRipTagsForTrack(tags, offset, bestOffset, iTrack, ""); + else + for (iTrack = 0; iTrack < TrackCount; iTrack++) + { + GenerateAccurateRipTagsForTrack(tags, offset, bestOffset, iTrack, + String.Format("cue_track{0:00}_", iTrack + 1)); + } + } + + public void CleanupTags (NameValueCollection tags, string substring) + { + string [] keys = tags.AllKeys; + for (int i = 0; i < keys.Length; i++) + if (keys[i].ToUpper().Contains(substring)) + tags.Remove (keys[i]); + } + + private void FindBestOffset(uint minConfidence, bool optimizeConfidence, out uint outTracksMatch, out int outBestOffset) + { + uint bestTracksMatch = 0; + uint bestConfidence = 0; + int bestOffset = 0; + + for (int offset = -_arOffsetRange; offset <= _arOffsetRange; offset++) + { + uint tracksMatch = 0; + uint sumConfidence = 0; + + for (int iTrack = 0; iTrack < TrackCount; iTrack++) + { + uint confidence = 0; + + for (int di = 0; di < (int)accDisks.Count; di++) + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - offset] == accDisks[di].tracks[iTrack].CRC) + confidence += accDisks[di].tracks[iTrack].count; + + if (confidence >= minConfidence) + tracksMatch++; + + sumConfidence += confidence; + } + + if (tracksMatch > bestTracksMatch + || (tracksMatch == bestTracksMatch && optimizeConfidence && sumConfidence > bestConfidence) + || (tracksMatch == bestTracksMatch && optimizeConfidence && sumConfidence == bestConfidence && Math.Abs(offset) < Math.Abs(bestOffset)) + || (tracksMatch == bestTracksMatch && !optimizeConfidence && Math.Abs(offset) < Math.Abs(bestOffset)) + ) + { + bestTracksMatch = tracksMatch; + bestConfidence = sumConfidence; + bestOffset = offset; + } + } + outBestOffset = bestOffset; + outTracksMatch = bestTracksMatch; + } + + public void WriteAudioFiles(string dir, CUEStyle style, SetStatus statusDel) { + string[] destPaths; + int[] destLengths; + bool htoaToFile = ((style == CUEStyle.GapsAppended) && _config.preserveHTOA && + (_tracks[0].IndexLengths[0] != 0)); + + if (_usePregapForFirstTrackInSingleFile) { + throw new Exception("UsePregapForFirstTrackInSingleFile is not supported for writing audio files."); + } + + if (style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE) { + destPaths = new string[1]; + destPaths[0] = Path.Combine(dir, _singleFilename); + } + else { + destPaths = new string[TrackCount + (htoaToFile ? 1 : 0)]; + if (htoaToFile) { + destPaths[0] = Path.Combine(dir, _htoaFilename); + } + for (int i = 0; i < TrackCount; i++) { + destPaths[i + (htoaToFile ? 1 : 0)] = Path.Combine(dir, _trackFilenames[i]); + } + } + + if ( !_accurateRip || _accurateOffset ) + for (int i = 0; i < destPaths.Length; i++) { + for (int j = 0; j < _sourcePaths.Count; j++) { + if (destPaths[i].ToLower() == _sourcePaths[j].ToLower()) { + throw new Exception("Source and destination audio file paths cannot be the same."); + } + } + } + + destLengths = CalculateAudioFileLengths(style); + + bool SkipOutput = false; + + if (_accurateRip) { + statusDel((string)"Contacting AccurateRip database...", 0, 0); + ContactAccurateRip(); + + if (accResult != HttpStatusCode.OK) + { + if (!_accurateOffset) + return; + if (_config.noUnverifiedOutput) + return; + } + else if (_accurateOffset) + { + _writeOffset = 0; + WriteAudioFilesPass(dir, style, statusDel, destPaths, destLengths, htoaToFile, true); + + uint tracksMatch; + int bestOffset; + + if (_config.noUnverifiedOutput) + { + FindBestOffset(_config.encodeWhenConfidence, false, out tracksMatch, out bestOffset); + if (tracksMatch * 100 < _config.encodeWhenPercent * TrackCount) + SkipOutput = true; + } + + if (!SkipOutput && _config.fixOffset) + { + FindBestOffset(_config.fixWhenConfidence, false, out tracksMatch, out bestOffset); + if (tracksMatch * 100 >= _config.fixWhenPercent * TrackCount) + _writeOffset = bestOffset; + } + } + } + + if (!SkipOutput) + { + bool verifyOnly = _accurateRip && !_accurateOffset; + if (!verifyOnly && style != CUEStyle.SingleFileWithCUE) + { + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + Write(_cuePath, style); + } + WriteAudioFilesPass(dir, style, statusDel, destPaths, destLengths, htoaToFile, verifyOnly); + } + + if (_accurateRip) + { + statusDel((string)"Generating AccurateRip report...", 0, 0); + if (!_accurateOffset && _config.writeCRC && _writeOffset == 0) + { + uint tracksMatch; + int bestOffset; + FindBestOffset(1, true, out tracksMatch, out bestOffset); + + if (_hasEmbeddedCUESheet) + { + IAudioSource audioSource = AudioReadWrite.GetAudioSource(_sourcePaths[0]); + NameValueCollection tags = audioSource.Tags; + CleanupTags(tags, "ACCURATERIP"); + GenerateAccurateRipTags (tags, 0, bestOffset, -1); + if (audioSource is FLACReader) + ((FLACReader)audioSource).UpdateTags(); + audioSource.Close(); + audioSource = null; + } else if (_hasTrackFilenames) + { + for (int iTrack = 0; iTrack < TrackCount; iTrack++) + { + string src = _sourcePaths[iTrack + (_hasHTOAFilename ? 1 : 0)]; + IAudioSource audioSource = AudioReadWrite.GetAudioSource(src); + if (audioSource is FLACReader) + { + NameValueCollection tags = audioSource.Tags; + CleanupTags(tags, "ACCURATERIP"); + GenerateAccurateRipTags (tags, 0, bestOffset, iTrack); + ((FLACReader)audioSource).UpdateTags(); + } + audioSource.Close(); + audioSource = null; + } + } + } + + if (_config.writeArLog) + { + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + StreamWriter sw = new StreamWriter(Path.ChangeExtension(_cuePath, ".accurip"), + false, CUESheet.Encoding); + GenerateAccurateRipLog(sw); + sw.Close(); + } + } + } + + public void WriteAudioFilesPass(string dir, CUEStyle style, SetStatus statusDel, string[] destPaths, int[] destLengths, bool htoaToFile, bool noOutput) + { + const int buffLen = 16384; + int iTrack, iIndex; + byte[] buff = new byte[buffLen * 2 * 2]; + TrackInfo track; + IAudioSource audioSource = null; + IAudioDest audioDest = null; + bool discardOutput; + int iSource = -1; + int iDest = -1; + uint samplesRemSource = 0; + + if (_writeOffset != 0) + { + uint absOffset = (uint)Math.Abs(_writeOffset); + SourceInfo sourceInfo; + + sourceInfo.Path = null; + sourceInfo.Offset = 0; + sourceInfo.Length = absOffset; + + if (_writeOffset < 0) + { + _sources.Insert(0, sourceInfo); + + int last = _sources.Count - 1; + while (absOffset >= _sources[last].Length) + { + absOffset -= _sources[last].Length; + _sources.RemoveAt(last--); + } + sourceInfo = _sources[last]; + sourceInfo.Length -= absOffset; + _sources[last] = sourceInfo; + } + else + { + _sources.Add(sourceInfo); + + while (absOffset >= _sources[0].Length) + { + absOffset -= _sources[0].Length; + _sources.RemoveAt(0); + } + sourceInfo = _sources[0]; + sourceInfo.Offset += absOffset; + sourceInfo.Length -= absOffset; + _sources[0] = sourceInfo; + } + + _appliedWriteOffset = true; + } + + if (style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE) + { + iDest++; + audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest], noOutput); + if (audioDest is FLACWriter) + { + FLACWriter w = (FLACWriter)audioDest; + NameValueCollection destTags = new NameValueCollection(); + + if (_hasEmbeddedCUESheet || _hasSingleFilename) + destTags.Add(_albumTags); + else if (_hasTrackFilenames) + { + // TODO + } + + destTags.Remove ("CUESHEET"); + destTags.Remove ("LOG"); + destTags.Remove ("LOGFILE"); + destTags.Remove ("EACLOG"); + CleanupTags(destTags, "ACCURATERIP"); + CleanupTags(destTags, "REPLAYGAIN"); + + if (style == CUEStyle.SingleFileWithCUE) + { + StringWriter sw = new StringWriter(); + Write(sw, style); + destTags.Add("CUESHEET", sw.ToString()); + sw.Close(); + } + if (_eacLog != null) + destTags.Add("LOG", _eacLog); + + if (_accurateRipId != null && _config.writeCRC) + { + if (style == CUEStyle.SingleFileWithCUE && _accurateOffset && accResult == HttpStatusCode.OK) + GenerateAccurateRipTags(destTags, _writeOffset, _writeOffset, -1); + else + destTags.Add("ACCURATERIPID", _accurateRipId); + } + w.SetTags(destTags); + } + } + + if (_accurateRip && noOutput) + for (iTrack = 0; iTrack < TrackCount; iTrack++) + for (int iCRC = 0; iCRC < 10 * 588; iCRC++) + { + _tracks[iTrack].OffsetedCRC[iCRC] = 0; + _tracks[iTrack].OffsetedFrame450CRC[iCRC] = 0; + } + + uint currentOffset = 0, previousOffset = 0; + uint trackLength = _tracks[0].IndexLengths[0] * 588; + uint diskLength = 0, diskOffset = 0; + + for (iTrack = 0; iTrack < TrackCount; iTrack++) + for (iIndex = 0; iIndex <= _tracks[iTrack].LastIndex; iIndex++) + diskLength += _tracks[iTrack].IndexLengths[iIndex] * 588; + + + statusDel(String.Format("{2} track {0:00} ({1:00}%)...", 0, 0, noOutput ? "Verifying" : "Writing"), 0, 0.0); + + for (iTrack = 0; iTrack < TrackCount; iTrack++) { + track = _tracks[iTrack]; + + if ((style == CUEStyle.GapsPrepended) || (style == CUEStyle.GapsLeftOut)) { + if (audioDest != null) audioDest.Close(); + iDest++; + audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest], noOutput); + } + + for (iIndex = 0; iIndex <= track.LastIndex; iIndex++) { + uint trackPercent= 0, lastTrackPercent= 101; + uint samplesRemIndex = track.IndexLengths[iIndex] * 588; + + if (iIndex == 1) + { + previousOffset = currentOffset; + currentOffset = 0; + trackLength = 0; + for (int iIndex2 = 1; iIndex2 <= track.LastIndex; iIndex2++) + trackLength += _tracks[iTrack].IndexLengths[iIndex2] * 588; + if (iTrack != TrackCount -1) + trackLength += _tracks[iTrack + 1].IndexLengths[0] * 588; + } + + if ((style == CUEStyle.GapsAppended) && (iIndex == 1)) { + if (audioDest != null) audioDest.Close(); + iDest++; + audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest], noOutput); + if (audioDest is FLACWriter) + { + NameValueCollection destTags = new NameValueCollection(); + + if (_hasEmbeddedCUESheet) + { + string trackPrefix = String.Format ("cue_track{0:00}_", iTrack + 1); + string[] keys = _albumTags.AllKeys; + for (int i = 0; i < keys.Length; i++) + { + if (keys[i].ToLower().StartsWith(trackPrefix) + || !keys[i].ToLower().StartsWith("cue_track")) + { + string name = keys[i].ToLower().StartsWith(trackPrefix) ? + keys[i].Substring(trackPrefix.Length) : keys[i]; + string[] values = _albumTags.GetValues(keys[i]); + for (int j = 0; j < values.Length; j++) + destTags.Add(name, values[j]); + } + } + } + else if (_hasTrackFilenames) + destTags.Add(track._trackTags); + else if (_hasSingleFilename) + { + // TODO? + } + + destTags.Remove("CUESHEET"); + destTags.Remove("TRACKNUMBER"); + destTags.Remove("LOG"); + destTags.Remove("LOGFILE"); + destTags.Remove("EACLOG"); + CleanupTags(destTags, "ACCURATERIP"); + CleanupTags(destTags, "REPLAYGAIN"); + + if (destTags.Get("TITLE") == null && "" != track.Title) + destTags.Add("TITLE", track.Title); + if (destTags.Get("ARTIST") == null && "" != track.Artist) + destTags.Add("ARTIST", track.Artist); + destTags.Add("TRACKNUMBER", iTrack.ToString()); + if (_accurateRipId != null && _config.writeCRC) + { + if (_accurateOffset && accResult == HttpStatusCode.OK) + GenerateAccurateRipTags(destTags, _writeOffset, _writeOffset, iTrack); + else + destTags.Add("ACCURATERIPID", _accurateRipId); + } + ((FLACWriter)audioDest).SetTags(destTags); + } + } + + if ((style == CUEStyle.GapsAppended) && (iIndex == 0) && (iTrack == 0)) { + discardOutput = !htoaToFile; + if (htoaToFile) { + iDest++; + audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest], noOutput); + } + } + else if ((style == CUEStyle.GapsLeftOut) && (iIndex == 0)) { + discardOutput = true; + } + else { + discardOutput = false; + } + + while (samplesRemIndex != 0) { + if (samplesRemSource == 0) { + if (audioSource != null) audioSource.Close(); + audioSource = GetAudioSource(++iSource); + samplesRemSource = (uint) _sources[iSource].Length; + } + + uint copyCount = (uint) Math.Min(Math.Min(samplesRemIndex, samplesRemSource), buffLen); + + if ( trackLength > 0 ) + { + trackPercent = (uint)(currentOffset / 0.01 / trackLength); + double diskPercent = ((float)diskOffset) / diskLength; + if (trackPercent != lastTrackPercent) + statusDel(String.Format("{2} track {0:00} ({1:00}%)...", iIndex > 0 ? iTrack + 1 : iTrack, trackPercent, + noOutput?"Verifying":"Writing"), trackPercent, diskPercent); + lastTrackPercent = trackPercent; + } + + audioSource.Read(buff, copyCount); + if (!discardOutput) audioDest.Write(buff, copyCount); + if (_accurateRip && noOutput && (iTrack != 0 || iIndex != 0)) + unsafe { + fixed (byte * pBuff = &buff[0]) + { + UInt32 * samples = (UInt32*) pBuff; + int iTrack2 = iTrack - (iIndex == 0 ? 1 : 0); + + uint si1 = (uint) Math.Min(copyCount, Math.Max(0, 588*(iTrack2 == 0?10:5) - (int) currentOffset)); + uint si2 = (uint) Math.Min(copyCount, Math.Max(si1, trackLength - (int) currentOffset - 588 * (iTrack2 == TrackCount - 1?10:5))); + if (iTrack2 == 0) + CalculateAccurateRipCRCs (samples, si1, iTrack2, currentOffset, previousOffset, trackLength); + else + CalculateAccurateRipCRCsSemifast (samples, si1, iTrack2, currentOffset, previousOffset, trackLength); + if (si2 > si1) + CalculateAccurateRipCRCsFast (samples+si1, (uint)(si2 - si1), iTrack2, currentOffset + si1); + if (iTrack2 == TrackCount - 1) + CalculateAccurateRipCRCs (samples+si2, copyCount-si2, iTrack2, currentOffset+si2, previousOffset, trackLength); + else + CalculateAccurateRipCRCsSemifast (samples + si2, copyCount - si2, iTrack2, currentOffset + si2, previousOffset, trackLength); + } + } + currentOffset += copyCount; + diskOffset += copyCount; + samplesRemIndex -= copyCount; + samplesRemSource -= copyCount; + + lock (this) { + if (_stop) { + audioSource.Close(); + try { audioDest.Close(); } catch {} + throw new StopException(); + } + } + } + } + } + + if (audioSource != null) audioSource.Close(); + audioDest.Close(); + } + + public static string CorrectAudioFilenames(string path, bool always) { + string[] audioExts = new string[] { "*.wav", "*.flac", "*.wv", "*.ape" }; + List lines = new List(); + List filePos = new List(); + List origFiles = new List(); + bool foundAll = true; + string[] audioFiles = null; + string lineStr; + CUELine line; + string dir; + int i; + + dir = Path.GetDirectoryName(path); + + using (StreamReader sr = new StreamReader(path, CUESheet.Encoding)) { + while ((lineStr = sr.ReadLine()) != null) { + lines.Add(lineStr); + line = new CUELine(lineStr); + if ((line.Params.Count == 3) && (line.Params[0].ToUpper() == "FILE")) { + string fileType = line.Params[2].ToUpper(); + if ((fileType != "BINARY") && (fileType != "MOTOROLA")) { + filePos.Add(lines.Count - 1); + origFiles.Add(line.Params[1]); + foundAll &= (LocateFile(dir, line.Params[1]) != null); + } + } + } + } + + if (!foundAll || always) + { + for (i = 0; i < audioExts.Length; i++) + { + foundAll = true; + List newFiles = new List(); + for (int j = 0; j < origFiles.Count; j++) + { + string newFilename = Path.ChangeExtension(Path.GetFileName(origFiles[j]), audioExts[i].Substring(1)); + foundAll &= LocateFile(dir, newFilename) != null; + newFiles.Add (newFilename); + } + if (foundAll) + { + audioFiles = newFiles.ToArray(); + break; + } + audioFiles = Directory.GetFiles(dir, audioExts[i]); + if (audioFiles.Length == filePos.Count) + { + break; + } + } + if (i == audioExts.Length) + { + throw new Exception("Unable to locate the audio files."); + } + Array.Sort(audioFiles); + + for (i = 0; i < filePos.Count; i++) + { + lines[filePos[i]] = "FILE \"" + Path.GetFileName(audioFiles[i]) + "\" WAVE"; + } + } + + using (StringWriter sw = new StringWriter()) { + for (i = 0; i < lines.Count; i++) { + sw.WriteLine(lines[i]); + } + return sw.ToString (); + } + } + + private int[] CalculateAudioFileLengths(CUEStyle style) { + int iTrack, iIndex, iFile; + TrackInfo track; + int[] fileLengths; + bool htoaToFile = ((style == CUEStyle.GapsAppended) && _config.preserveHTOA && + (_tracks[0].IndexLengths[0] != 0)); + bool discardOutput; + + if (style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE) { + fileLengths = new int[1]; + iFile = 0; + } + else { + fileLengths = new int[TrackCount + (htoaToFile ? 1 : 0)]; + iFile = -1; + } + + for (iTrack = 0; iTrack < TrackCount; iTrack++) { + track = _tracks[iTrack]; + + if ((style == CUEStyle.GapsPrepended) || (style == CUEStyle.GapsLeftOut)) { + iFile++; + } + + for (iIndex = 0; iIndex <= track.LastIndex; iIndex++) { + if ((style == CUEStyle.GapsAppended) && (iIndex == 1)) { + iFile++; + } + + if ((style == CUEStyle.GapsAppended) && (iIndex == 0) && (iTrack == 0)) { + discardOutput = !htoaToFile; + if (htoaToFile) { + iFile++; + } + } + else if ((style == CUEStyle.GapsLeftOut) && (iIndex == 0)) { + discardOutput = true; + } + else { + discardOutput = false; + } + + if (!discardOutput) { + fileLengths[iFile] += (int) track.IndexLengths[iIndex] * 588; + } + } + } + + return fileLengths; + } + + public void Stop() { + lock (this) { + _stop = true; + } + } + + public int TrackCount { + get { + return _tracks.Count; + } + } + + private IAudioDest GetAudioDest(string path, int finalSampleCount, bool noOutput) { + if (noOutput) + return new DummyWriter(path, 16, 2, 44100); + + IAudioDest dest = AudioReadWrite.GetAudioDest(path, 16, 2, 44100, finalSampleCount); + + if (dest is FLACWriter) { + FLACWriter w = (FLACWriter)dest; + w.CompressionLevel = (int) _config.flacCompressionLevel; + w.Verify = _config.flacVerify; + } + if (dest is WavPackWriter) { + WavPackWriter w = (WavPackWriter)dest; + w.CompressionMode = _config.wvCompressionMode; + w.ExtraMode = _config.wvExtraMode; + } + + return dest; + } + + private IAudioSource GetAudioSource(int sourceIndex) { + SourceInfo sourceInfo = _sources[sourceIndex]; + IAudioSource audioSource; + + if (sourceInfo.Path == null) { + audioSource = new SilenceGenerator(sourceInfo.Offset + sourceInfo.Length); + } + else { + audioSource = AudioReadWrite.GetAudioSource(sourceInfo.Path); + } + + audioSource.Position = sourceInfo.Offset; + + return audioSource; + } + + private void WriteLine(TextWriter sw, int level, CUELine line) { + WriteLine(sw, level, line.ToString()); + } + + private void WriteLine(TextWriter sw, int level, string line) { + sw.Write(new string(' ', level * 2)); + sw.WriteLine(line); + } + + public List Attributes { + get { + return _attributes; + } + } + + public List Tracks { + get { + return _tracks; + } + } + + public bool HasHTOAFilename { + get { + return _hasHTOAFilename; + } + } + + public string HTOAFilename { + get { + return _htoaFilename; + } + set { + _htoaFilename = value; + } + } + + public bool HasTrackFilenames { + get { + return _hasTrackFilenames; + } + } + + public List TrackFilenames { + get { + return _trackFilenames; + } + } + + public bool HasSingleFilename { + get { + return _hasSingleFilename; + } + } + + public string SingleFilename { + get { + return _singleFilename; + } + set { + _singleFilename = value; + } + } + + public string Artist { + get { + CUELine line = General.FindCUELine(_attributes, "PERFORMER"); + return (line == null) ? String.Empty : line.Params[1]; + } + } + + public string Title { + get { + CUELine line = General.FindCUELine(_attributes, "TITLE"); + return (line == null) ? String.Empty : line.Params[1]; + } + } + + public int WriteOffset { + get { + return _writeOffset; + } + set { + if (_appliedWriteOffset) { + throw new Exception("Cannot change write offset after audio files have been written."); + } + _writeOffset = value; + } + } + + public bool PaddedToFrame { + get { + return _paddedToFrame; + } + } + + public string DataTrackLength + { + get + { + return General.TimeToString(_dataTrackLength.HasValue ? _dataTrackLength.Value : 0); + } + set + { + uint dtl = (uint) General.TimeFromString(value); + if (dtl != 0) + { + _dataTrackLength = dtl; + if (_accurateRip && _accurateRipId == null) + CalculateAccurateRipId (); + } + } + } + + public bool UsePregapForFirstTrackInSingleFile { + get { + return _usePregapForFirstTrackInSingleFile; + } + set{ + _usePregapForFirstTrackInSingleFile = value; + } + } + + public CUEConfig Config { + get { + return _config; + } + } + + public bool AccurateRip { + get { + return _accurateRip; + } + set { + _accurateRip = value; + } + } + + public bool AccurateOffset { + get { + return _accurateOffset; + } + set { + _accurateOffset = value; + } + } + } + + class CUELine { + private List _params; + private List _quoted; + + public CUELine() { + _params = new List(); + _quoted = new List(); + } + + public CUELine(string line) { + int start, end, lineLen; + bool isQuoted; + + _params = new List(); + _quoted = new List(); + + start = 0; + lineLen = line.Length; + + while (true) { + while ((start < lineLen) && (line[start] == ' ')) { + start++; + } + if (start >= lineLen) { + break; + } + + isQuoted = (line[start] == '"'); + if (isQuoted) { + start++; + } + + end = line.IndexOf(isQuoted ? '"' : ' ', start); + if (end == -1) { + end = lineLen; + } + + _params.Add(line.Substring(start, end - start)); + _quoted.Add(isQuoted); + + start = isQuoted ? end + 1 : end; + } + } + + public List Params { + get { + return _params; + } + } + + public List IsQuoted { + get { + return _quoted; + } + } + + public override string ToString() { + if (_params.Count != _quoted.Count) { + throw new Exception("Parameter and IsQuoted lists must match."); + } + + StringBuilder sb = new StringBuilder(); + int last = _params.Count - 1; + + for (int i = 0; i <= last; i++) { + if (_quoted[i]) sb.Append('"'); + sb.Append(_params[i]); + if (_quoted[i]) sb.Append('"'); + if (i < last) sb.Append(' '); + } + + return sb.ToString(); + } + } + + class TrackInfo { + private List _indexLengths; + private List _attributes; + public uint[] OffsetedCRC; + public uint[] OffsetedFrame450CRC; + public NameValueCollection _trackTags; + + public TrackInfo() { + _indexLengths = new List(); + _attributes = new List(); + _trackTags = new NameValueCollection(); + OffsetedCRC = new uint[10 * 588]; + OffsetedFrame450CRC = new uint[10 * 588]; + + _indexLengths.Add(0); + } + + public uint CRC + { + get + { + return OffsetedCRC[5 * 588 - 1]; + } + } + + public int LastIndex { + get { + return _indexLengths.Count - 1; + } + } + + public List IndexLengths { + get { + return _indexLengths; + } + } + + public void AddIndex(bool isGap, uint length) { + if (isGap) { + _indexLengths[0] = length; + } + else { + _indexLengths.Add(length); + } + } + + public List Attributes { + get { + return _attributes; + } + } + + public string Artist { + get { + CUELine line = General.FindCUELine(_attributes, "PERFORMER"); + return (line == null) ? String.Empty : line.Params[1]; + } + set + { + General.SetCUELine(_attributes, "PERFORMER", value, true); + } + } + + public string Title { + get { + CUELine line = General.FindCUELine(_attributes, "TITLE"); + return (line == null) ? String.Empty : line.Params[1]; + } + set + { + General.SetCUELine(_attributes, "TITLE", value, true); + } + } + } + + struct IndexInfo { + public int Track; + public int Index; + public int Time; + } + + struct SourceInfo { + public string Path; + public uint Offset; + public uint Length; + } + + struct AccTrack + { + public uint count; + public uint CRC; + public uint Frame450CRC; + } + + class AccDisk + { + public uint count; + public uint discId1; + public uint discId2; + public uint cddbDiscId; + public List tracks; + + public AccDisk() { + tracks = new List(); + } + } + + + class StopException : Exception { + public StopException() : base() { + } + } + + class SilenceGenerator : IAudioSource { + private ulong _sampleOffset, _sampleCount; + + public SilenceGenerator(uint sampleCount) { + _sampleOffset = 0; + _sampleCount = sampleCount; + } + + public ulong Length { + get { + return _sampleCount; + } + } + + public ulong Remaining { + get { + return _sampleCount - _sampleOffset; + } + } + + public ulong Position { + get { + return _sampleOffset; + } + set { + _sampleOffset = value; + } + } + + public int BitsPerSample { + get { + return 16; + } + } + + public int ChannelCount { + get { + return 2; + } + } + + public int SampleRate { + get { + return 44100; + } + } + + public NameValueCollection Tags + { + get + { + return new NameValueCollection(); + } + set + { + } + } + + public uint Read(byte[] buff, uint sampleCount) { + uint samplesRemaining, byteCount, i; + + samplesRemaining = (uint) (_sampleCount - _sampleOffset); + if (sampleCount > samplesRemaining) { + sampleCount = samplesRemaining; + } + + byteCount = sampleCount * 2 * 2; + for (i = 0; i < byteCount; i++) { + buff[i] = 0; + } + + _sampleOffset += sampleCount; + + return sampleCount; + } + + public void Close() { + } + } +} \ No newline at end of file diff --git a/CUETools/Program.cs b/CUETools/Program.cs new file mode 100644 index 0000000..e6ebabf --- /dev/null +++ b/CUETools/Program.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace JDP { + static class Program { + [STAThread] + static void Main(string[] args) + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + if (args.Length == 2 && (args[0] == "/verify" || args[0] == "/convert" || args[0] == "/fix")) + { + frmBatch batch = new frmBatch(); + batch.InputPath = args[1]; + batch.AccurateRip = (args[0] != "/convert"); + batch.AccurateOffset = (args[0] == "/fix"); + Application.Run (batch); + return; + } + frmCUETools form = new frmCUETools(); + if (args.Length == 1) + form.InputPath = args[0]; + Application.Run(form); + } + } +} \ No newline at end of file diff --git a/CUETools/Properties/AssemblyInfo.cs b/CUETools/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7498d64 --- /dev/null +++ b/CUETools/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CUE Tools")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Copyright 2006-2007 Moitah")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8ce8b79b-411e-4989-982b-df51ae457e80")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.9.0.1")] +[assembly: AssemblyFileVersion("1.9.0.1")] diff --git a/CUETools/Properties/Resources.Designer.cs b/CUETools/Properties/Resources.Designer.cs new file mode 100644 index 0000000..3164933 --- /dev/null +++ b/CUETools/Properties/Resources.Designer.cs @@ -0,0 +1,72 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.1434 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace JDP.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JDP.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Verify. + /// + internal static string Verify { + get { + return ResourceManager.GetString("Verify", resourceCulture); + } + } + } +} diff --git a/CUETools/Properties/Resources.resx b/CUETools/Properties/Resources.resx new file mode 100644 index 0000000..a6953b8 --- /dev/null +++ b/CUETools/Properties/Resources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Verify + + \ No newline at end of file diff --git a/CUETools/Properties/Settings.Designer.cs b/CUETools/Properties/Settings.Designer.cs new file mode 100644 index 0000000..7ae0902 --- /dev/null +++ b/CUETools/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.832 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace JDP.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/CUETools/Properties/Settings.settings b/CUETools/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/CUETools/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/CUETools/ReadMe.txt b/CUETools/ReadMe.txt new file mode 100644 index 0000000..27dcfca --- /dev/null +++ b/CUETools/ReadMe.txt @@ -0,0 +1,74 @@ +There is no installation, just unzip to a new folder in the "Program Files" +folder. The .NET Framework 2.0 (x86) is required. If you get a "could not +load file or assembly" error message for FLACDotNet or WavPackDotNet, make sure +the Visual C++ 2005 SP1 runtime files (x86) are installed. + +As an alternative to the Browse button, the input path may be set by dragging +a .cue file onto the input path text box. + +"Output Style" naming compared to Exact Audio Copy: + CUE Tools: Exact Audio Copy: + Single File Single WAV File + Gaps Appended Multiple WAV Files With Gaps (Noncompliant) + Gaps Prepended Multiple WAV Files With Corrected Gaps + Gaps Left Out Multiple WAV Files With Leftout Gaps + +Audio filename formatting variables (case sensitive). The values are obtained +from the CUE sheet only (not from any tags within the input audio files): + %D - Album artist + %C - Album title + %N - Track number + %A - Track artist + %T - Track title + %F - Filename of the input CUE sheet without extension + +A "special character" is anything other than a-z, A-Z, 0-9, space, or +underscore. + +Custom output path formatting variables (case sensitive). The remove special +characters and replace spaces audio filename settings also apply to %D and %C +here: + %D - Album artist + %C - Album title + %F - Filename of the input CUE sheet without extension + %0 - Full directory of the input CUE sheet + %x (where x is an integer) - Part of the directory of the input CUE sheet. + For example if the input CUE sheet is located in C:\Stuff\CUEs, %1 = C:, + %2 = Stuff, %3 = CUEs. Negative numbers start from the end of the + directory, i.e. %-1 = CUEs, %-2 = Stuff, %-3 = E:. + %x:y (where x/y are integers) - Same as above but specifies a range. + +"Write offset" is the same as "Write samples offset" in Exact Audio Copy. For +negative offsets, silence is added at the beginning and samples are removed +from the end. For positive offsets, samples are removed from the beginning and +silence is added at the end. + +The "Preserve HTOA" (hidden track one audio) setting will cause an extra file +to be created when outputting a gaps appended CUE sheet if an index 0 for track +1 exists. If disabled, a PREGAP line will be written instead and the HTOA will +be discarded. + +AccurateRip online database keeps CRCs of the ripped CDs. AccurateRip 'Verify' +option accesses this database to compare the CRCs and ensure you have the +exact copy. If the CD has been ripped with software, which doesn't handle +CD drive read offset, or with incorrectly specified read offset, CRCs won't +match, but the correct offset will be detected. AccurateRip 'Fix offset' +option is a two-pass operation, which computes that offset during +the first step, and applies it during the second step. If the output format +is FLAC, and 'Add tags with CRCs' option in advanced settings is checked, +the output flac file will contain ACCURATERIPCOUNT tag for each track, +which shows that the track was ripped from the CD correctly, and also +demonstrates how popular is this CD. You can set up foobar2000 to display +this nice statictics for each file. + +The settings file is located in the "%AppData%\CUE Tools" folder. For example, +on Windows XP if your username is "John", the settings folder is likely +"C:\Documents and Settings\John\Application Data\CUE Tools". + +Command line format: CUETools.exe [/verify] "filename" +When called with a file name as argument, opens the usual dialog +with this file name in the input box. +When called with /verify switch and a filename, starts automatic +AccurateRip verification, /convert stats conversion, and /fix +starts AccurateRip verification and convertion (with possible +offset correction). diff --git a/CUETools/Settings.cs b/CUETools/Settings.cs new file mode 100644 index 0000000..b32c3dc --- /dev/null +++ b/CUETools/Settings.cs @@ -0,0 +1,92 @@ +// **************************************************************************** +// +// CUE Tools +// Copyright (C) 2006-2007 Moitah (moitah@yahoo.com) +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// **************************************************************************** + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace JDP { + static class SettingsShared { + public static string GetMyAppDataDir(string appName) { + string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + string myAppDataDir = Path.Combine(appDataDir, appName); + + if (Directory.Exists(myAppDataDir) == false) { + Directory.CreateDirectory(myAppDataDir); + } + + return myAppDataDir; + } + } + + public class SettingsReader { + Dictionary _settings; + + public SettingsReader(string appName, string fileName) { + _settings = new Dictionary(); + + string path = Path.Combine(SettingsShared.GetMyAppDataDir(appName), fileName); + if (!File.Exists(path)) { + return; + } + + using (StreamReader sr = new StreamReader(path, Encoding.UTF8)) { + string line, name, val; + int pos; + + while ((line = sr.ReadLine()) != null) { + pos = line.IndexOf('='); + if (pos != -1) { + name = line.Substring(0, pos); + val = line.Substring(pos + 1); + + if (!_settings.ContainsKey(name)) { + _settings.Add(name, val); + } + } + } + } + } + + public string Load(string name) { + return _settings.ContainsKey(name) ? _settings[name] : null; + } + } + + public class SettingsWriter { + StreamWriter _sw; + + public SettingsWriter(string appName, string fileName) { + string path = Path.Combine(SettingsShared.GetMyAppDataDir(appName), fileName); + + _sw = new StreamWriter(path, false, Encoding.UTF8); + } + + public void Save(string name, string value) { + _sw.WriteLine(name + "=" + value); + } + + public void Close() { + _sw.Close(); + } + } +} \ No newline at end of file diff --git a/CUETools/app.config b/CUETools/app.config new file mode 100644 index 0000000..3201f86 --- /dev/null +++ b/CUETools/app.config @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/CUETools/frmBatch.Designer.cs b/CUETools/frmBatch.Designer.cs new file mode 100644 index 0000000..29bdad9 --- /dev/null +++ b/CUETools/frmBatch.Designer.cs @@ -0,0 +1,96 @@ +namespace JDP +{ + partial class frmBatch + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.progressBar1 = new System.Windows.Forms.ProgressBar(); + this.progressBar2 = new System.Windows.Forms.ProgressBar(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // progressBar1 + // + this.progressBar1.Location = new System.Drawing.Point(12, 12); + this.progressBar1.Margin = new System.Windows.Forms.Padding(10); + this.progressBar1.MinimumSize = new System.Drawing.Size(440, 20); + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new System.Drawing.Size(533, 20); + this.progressBar1.TabIndex = 0; + // + // progressBar2 + // + this.progressBar2.Location = new System.Drawing.Point(12, 38); + this.progressBar2.Margin = new System.Windows.Forms.Padding(10); + this.progressBar2.MinimumSize = new System.Drawing.Size(440, 20); + this.progressBar2.Name = "progressBar2"; + this.progressBar2.Size = new System.Drawing.Size(533, 20); + this.progressBar2.TabIndex = 1; + // + // textBox1 + // + this.textBox1.BackColor = System.Drawing.SystemColors.Control; + this.textBox1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); + this.textBox1.Location = new System.Drawing.Point(13, 71); + this.textBox1.Multiline = true; + this.textBox1.Name = "textBox1"; + this.textBox1.ReadOnly = true; + this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox1.Size = new System.Drawing.Size(532, 180); + this.textBox1.TabIndex = 2; + // + // frmBatch + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.AutoSize = true; + this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + this.ClientSize = new System.Drawing.Size(569, 341); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.progressBar2); + this.Controls.Add(this.progressBar1); + this.Cursor = System.Windows.Forms.Cursors.Default; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.MaximizeBox = false; + this.MinimumSize = new System.Drawing.Size(480, 60); + this.Name = "frmBatch"; + this.Padding = new System.Windows.Forms.Padding(10); + this.Text = "Working..."; + this.Load += new System.EventHandler(this.frmBatch_Load); + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmBatch_FormClosing); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.ProgressBar progressBar1; + private System.Windows.Forms.ProgressBar progressBar2; + private System.Windows.Forms.TextBox textBox1; + } +} \ No newline at end of file diff --git a/CUETools/frmBatch.cs b/CUETools/frmBatch.cs new file mode 100644 index 0000000..af7154b --- /dev/null +++ b/CUETools/frmBatch.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.IO; +using System.Threading; + +namespace JDP +{ + public partial class frmBatch : Form + { + public frmBatch() + { + InitializeComponent(); + _config = new CUEConfig(); + _cueStyle = CUEStyle.SingleFile; + _audioFormat = OutputAudioFormat.WAV; + _accurateRip = true; + _accurateOffset = false; + } + + public string InputPath + { + get { return pathIn; } + set { pathIn = value; } + } + public bool AccurateRip + { + get { return _accurateRip; } + set { _accurateRip = value; } + } + public bool AccurateOffset + { + get { return _accurateOffset; } + set { _accurateOffset = value; } + } + + Thread _workThread; + CUESheet _workClass; + CUEConfig _config; + CUEStyle _cueStyle; + OutputAudioFormat _audioFormat; + string pathIn; + string pathOut; + bool _accurateRip; + bool _accurateOffset; + DateTime _startedAt; + + public void SetStatus(string status, uint percentTrack, double percentDisk) + { + this.BeginInvoke((MethodInvoker)delegate() + { + if (percentDisk == 0) + { + _startedAt = DateTime.Now; + } + else if (percentDisk > 0.02) + { + TimeSpan span = DateTime.Now - _startedAt; + TimeSpan eta = new TimeSpan ((long) (span.Ticks/percentDisk)); + Text = String.Format("{0}, ETA {1}:{2:00}.", status, (int)eta.TotalMinutes, eta.Seconds); + } else + Text = status; + progressBar1.Value = (int)percentTrack; + progressBar2.Value = (int)(percentDisk*100); + }); + } + + private void WriteAudioFilesThread(object o) + { + CUESheet cueSheet = (CUESheet)o; + + try + { + cueSheet.WriteAudioFiles(Path.GetDirectoryName(pathOut), _cueStyle, new SetStatus(this.SetStatus)); + this.Invoke((MethodInvoker)delegate() + { + //if (_batchPaths.Count == 0) + { + //TimeSpan span = DateTime.Now - _startedAt; + Text = "Done."; + progressBar1.Value = 0; + progressBar2.Value = 0; + if (cueSheet.AccurateRip) + { + StringWriter sw = new StringWriter(); + cueSheet.GenerateAccurateRipLog(sw); + textBox1.Text = sw.ToString(); + sw.Close(); + textBox1.Show(); + } + } + }); + } + catch (StopException) + { + ////_batchPaths.Clear(); + //this.Invoke((MethodInvoker)delegate() + //{ + // MessageBox.Show("Conversion was stopped.", "Stopped", MessageBoxButtons.OK, + // MessageBoxIcon.Exclamation); + // Close(); + //}); + + this.Invoke((MethodInvoker)delegate() + { + Text = "Aborted."; + progressBar1.Value = 0; + progressBar2.Value = 0; + }); + } + catch (Exception ex) + { + this.Invoke((MethodInvoker)delegate() + { + //if (_batchPaths.Count == 0) SetupControls(false); + //if (!ShowErrorMessage(ex)) + //{ + // _batchPaths.Clear(); + // SetupControls(false); + //} + Text = "Error: " + ex.Message; + }); + } + + //if (_batchPaths.Count != 0) + //{ + // _batchPaths.RemoveAt(0); + // this.BeginInvoke((MethodInvoker)delegate() + // { + // if (_batchPaths.Count == 0) + // { + // SetupControls(false); + // ShowBatchDoneMessage(); + // } + // else + // { + // StartConvert(); + // } + // }); + //} + } + + public void StartConvert() + { + CUESheet cueSheet; + + try + { + _startedAt = DateTime.Now; + + _workThread = null; + //if (_batchPaths.Count != 0) + //{ + // txtInputPath.Text = _batchPaths[0]; + //} + + if (!File.Exists(pathIn)) + { + throw new Exception("Input CUE Sheet not found."); + } + + bool outputAudio = _accurateOffset || !_accurateRip; + cueSheet = new CUESheet(pathIn, _config); + if (outputAudio) + { + bool pathFound = false; + for (int i = 0; i < 20; i++) + { + string outDir = Path.Combine(Path.GetDirectoryName (pathIn), "CUEToolsOutput" + (i > 0? String.Format("({0})",i) : "")); + if (!Directory.Exists(outDir)) + { + Directory.CreateDirectory(outDir); + pathOut = Path.Combine(outDir, Path.GetFileNameWithoutExtension(pathIn) + ".cue"); + pathFound = true; + break; + } + } + if (!pathFound) + { + Text = "Could not create a folder"; + return; + } + } else + pathOut = pathIn; + cueSheet.GenerateFilenames(_audioFormat, pathOut); + if (outputAudio) + { + if (_cueStyle == CUEStyle.SingleFileWithCUE) + cueSheet.SingleFilename = Path.ChangeExtension(Path.GetFileName (pathOut), General.FormatExtension (_audioFormat)); + } + + cueSheet.UsePregapForFirstTrackInSingleFile = false; + cueSheet.AccurateRip = _accurateRip; + cueSheet.AccurateOffset = _accurateOffset; + + _workThread = new Thread(WriteAudioFilesThread); + _workClass = cueSheet; + _workThread.Start(cueSheet); + } + catch (Exception ex) + { + Text = "Error: " + ex.Message; + //if (!ShowErrorMessage(ex)) + //{ + // _batchPaths.Clear(); + //} + //Close(); + } + } + + private void frmBatch_Load(object sender, EventArgs e) + { + //_batchPaths = new List(); + textBox1.Hide(); + SettingsReader sr = new SettingsReader("CUE Tools", "settings.txt"); + string val; + _config.Load(sr); + + try + { + val = sr.Load("CUEStyle"); + _cueStyle = (val != null) ? (CUEStyle)Int32.Parse(val) : CUEStyle.SingleFile; + val = sr.Load("OutputAudioFormat"); + _audioFormat = (val != null) ? (OutputAudioFormat)Int32.Parse(val) : OutputAudioFormat.WAV; + } + catch { }; + + StartConvert(); + } + + private void frmBatch_FormClosing(Object sender, FormClosingEventArgs e) + { + if ((_workThread != null) && (_workThread.IsAlive)) + { + _workClass.Stop(); + e.Cancel = true; + } + } + } +} \ No newline at end of file diff --git a/CUETools/frmBatch.resx b/CUETools/frmBatch.resx new file mode 100644 index 0000000..ff31a6d --- /dev/null +++ b/CUETools/frmBatch.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CUETools/frmCUETools.Designer.cs b/CUETools/frmCUETools.Designer.cs new file mode 100644 index 0000000..46bbf8b --- /dev/null +++ b/CUETools/frmCUETools.Designer.cs @@ -0,0 +1,497 @@ +namespace JDP { + partial class frmCUETools { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmCUETools)); + this.btnConvert = new System.Windows.Forms.Button(); + this.grpCUEPaths = new System.Windows.Forms.GroupBox(); + this.btnBrowseOutput = new System.Windows.Forms.Button(); + this.btnBrowseInput = new System.Windows.Forms.Button(); + this.lblOutput = new System.Windows.Forms.Label(); + this.lblInput = new System.Windows.Forms.Label(); + this.txtOutputPath = new System.Windows.Forms.TextBox(); + this.txtInputPath = new System.Windows.Forms.TextBox(); + this.grpOutputStyle = new System.Windows.Forms.GroupBox(); + this.rbEmbedCUE = new System.Windows.Forms.RadioButton(); + this.rbGapsLeftOut = new System.Windows.Forms.RadioButton(); + this.rbGapsPrepended = new System.Windows.Forms.RadioButton(); + this.rbGapsAppended = new System.Windows.Forms.RadioButton(); + this.rbSingleFile = new System.Windows.Forms.RadioButton(); + this.btnAbout = new System.Windows.Forms.Button(); + this.grpOutputPathGeneration = new System.Windows.Forms.GroupBox(); + this.txtCustomFormat = new System.Windows.Forms.TextBox(); + this.rbCustomFormat = new System.Windows.Forms.RadioButton(); + this.txtCreateSubdirectory = new System.Windows.Forms.TextBox(); + this.rbDontGenerate = new System.Windows.Forms.RadioButton(); + this.rbCreateSubdirectory = new System.Windows.Forms.RadioButton(); + this.rbAppendFilename = new System.Windows.Forms.RadioButton(); + this.txtAppendFilename = new System.Windows.Forms.TextBox(); + this.grpAudioOutput = new System.Windows.Forms.GroupBox(); + this.rbNoAudio = new System.Windows.Forms.RadioButton(); + this.rbWavPack = new System.Windows.Forms.RadioButton(); + this.rbFLAC = new System.Windows.Forms.RadioButton(); + this.rbWAV = new System.Windows.Forms.RadioButton(); + this.btnBatch = new System.Windows.Forms.Button(); + this.btnFilenameCorrector = new System.Windows.Forms.Button(); + this.btnSettings = new System.Windows.Forms.Button(); + this.grpAccurateRip = new System.Windows.Forms.GroupBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtDataTrackLength = new System.Windows.Forms.MaskedTextBox(); + this.rbArApplyOffset = new System.Windows.Forms.RadioButton(); + this.rbArVerify = new System.Windows.Forms.RadioButton(); + this.rbArNone = new System.Windows.Forms.RadioButton(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar(); + this.toolStripProgressBar2 = new System.Windows.Forms.ToolStripProgressBar(); + this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); + this.btnCUECreator = new System.Windows.Forms.Button(); + this.grpCUEPaths.SuspendLayout(); + this.grpOutputStyle.SuspendLayout(); + this.grpOutputPathGeneration.SuspendLayout(); + this.grpAudioOutput.SuspendLayout(); + this.grpAccurateRip.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // btnConvert + // + resources.ApplyResources(this.btnConvert, "btnConvert"); + this.btnConvert.Name = "btnConvert"; + this.btnConvert.UseVisualStyleBackColor = true; + this.btnConvert.Click += new System.EventHandler(this.btnConvert_Click); + // + // grpCUEPaths + // + this.grpCUEPaths.Controls.Add(this.btnBrowseOutput); + this.grpCUEPaths.Controls.Add(this.btnBrowseInput); + this.grpCUEPaths.Controls.Add(this.lblOutput); + this.grpCUEPaths.Controls.Add(this.lblInput); + this.grpCUEPaths.Controls.Add(this.txtOutputPath); + this.grpCUEPaths.Controls.Add(this.txtInputPath); + resources.ApplyResources(this.grpCUEPaths, "grpCUEPaths"); + this.grpCUEPaths.Name = "grpCUEPaths"; + this.grpCUEPaths.TabStop = false; + // + // btnBrowseOutput + // + resources.ApplyResources(this.btnBrowseOutput, "btnBrowseOutput"); + this.btnBrowseOutput.Name = "btnBrowseOutput"; + this.btnBrowseOutput.UseVisualStyleBackColor = true; + this.btnBrowseOutput.Click += new System.EventHandler(this.btnBrowseOutput_Click); + // + // btnBrowseInput + // + resources.ApplyResources(this.btnBrowseInput, "btnBrowseInput"); + this.btnBrowseInput.Name = "btnBrowseInput"; + this.btnBrowseInput.UseVisualStyleBackColor = true; + this.btnBrowseInput.Click += new System.EventHandler(this.btnBrowseInput_Click); + // + // lblOutput + // + resources.ApplyResources(this.lblOutput, "lblOutput"); + this.lblOutput.Name = "lblOutput"; + // + // lblInput + // + resources.ApplyResources(this.lblInput, "lblInput"); + this.lblInput.Name = "lblInput"; + // + // txtOutputPath + // + this.txtOutputPath.AllowDrop = true; + resources.ApplyResources(this.txtOutputPath, "txtOutputPath"); + this.txtOutputPath.Name = "txtOutputPath"; + this.txtOutputPath.DragDrop += new System.Windows.Forms.DragEventHandler(this.PathTextBox_DragDrop); + this.txtOutputPath.DragEnter += new System.Windows.Forms.DragEventHandler(this.PathTextBox_DragEnter); + // + // txtInputPath + // + this.txtInputPath.AllowDrop = true; + resources.ApplyResources(this.txtInputPath, "txtInputPath"); + this.txtInputPath.Name = "txtInputPath"; + this.txtInputPath.TextChanged += new System.EventHandler(this.txtInputPath_TextChanged); + this.txtInputPath.DragDrop += new System.Windows.Forms.DragEventHandler(this.PathTextBox_DragDrop); + this.txtInputPath.DragEnter += new System.Windows.Forms.DragEventHandler(this.PathTextBox_DragEnter); + // + // grpOutputStyle + // + this.grpOutputStyle.Controls.Add(this.rbEmbedCUE); + this.grpOutputStyle.Controls.Add(this.rbGapsLeftOut); + this.grpOutputStyle.Controls.Add(this.rbGapsPrepended); + this.grpOutputStyle.Controls.Add(this.rbGapsAppended); + this.grpOutputStyle.Controls.Add(this.rbSingleFile); + resources.ApplyResources(this.grpOutputStyle, "grpOutputStyle"); + this.grpOutputStyle.Name = "grpOutputStyle"; + this.grpOutputStyle.TabStop = false; + // + // rbEmbedCUE + // + resources.ApplyResources(this.rbEmbedCUE, "rbEmbedCUE"); + this.rbEmbedCUE.Name = "rbEmbedCUE"; + this.rbEmbedCUE.TabStop = true; + this.toolTip1.SetToolTip(this.rbEmbedCUE, resources.GetString("rbEmbedCUE.ToolTip")); + this.rbEmbedCUE.UseVisualStyleBackColor = true; + this.rbEmbedCUE.CheckedChanged += new System.EventHandler(this.rbEmbedCUE_CheckedChanged); + // + // rbGapsLeftOut + // + resources.ApplyResources(this.rbGapsLeftOut, "rbGapsLeftOut"); + this.rbGapsLeftOut.Name = "rbGapsLeftOut"; + this.toolTip1.SetToolTip(this.rbGapsLeftOut, resources.GetString("rbGapsLeftOut.ToolTip")); + this.rbGapsLeftOut.UseVisualStyleBackColor = true; + // + // rbGapsPrepended + // + resources.ApplyResources(this.rbGapsPrepended, "rbGapsPrepended"); + this.rbGapsPrepended.Name = "rbGapsPrepended"; + this.toolTip1.SetToolTip(this.rbGapsPrepended, resources.GetString("rbGapsPrepended.ToolTip")); + this.rbGapsPrepended.UseVisualStyleBackColor = true; + // + // rbGapsAppended + // + resources.ApplyResources(this.rbGapsAppended, "rbGapsAppended"); + this.rbGapsAppended.Name = "rbGapsAppended"; + this.toolTip1.SetToolTip(this.rbGapsAppended, resources.GetString("rbGapsAppended.ToolTip")); + this.rbGapsAppended.UseVisualStyleBackColor = true; + // + // rbSingleFile + // + resources.ApplyResources(this.rbSingleFile, "rbSingleFile"); + this.rbSingleFile.Checked = true; + this.rbSingleFile.Name = "rbSingleFile"; + this.rbSingleFile.TabStop = true; + this.toolTip1.SetToolTip(this.rbSingleFile, resources.GetString("rbSingleFile.ToolTip")); + this.rbSingleFile.UseVisualStyleBackColor = true; + // + // btnAbout + // + resources.ApplyResources(this.btnAbout, "btnAbout"); + this.btnAbout.Name = "btnAbout"; + this.btnAbout.UseVisualStyleBackColor = true; + this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); + // + // grpOutputPathGeneration + // + this.grpOutputPathGeneration.Controls.Add(this.txtCustomFormat); + this.grpOutputPathGeneration.Controls.Add(this.rbCustomFormat); + this.grpOutputPathGeneration.Controls.Add(this.txtCreateSubdirectory); + this.grpOutputPathGeneration.Controls.Add(this.rbDontGenerate); + this.grpOutputPathGeneration.Controls.Add(this.rbCreateSubdirectory); + this.grpOutputPathGeneration.Controls.Add(this.rbAppendFilename); + this.grpOutputPathGeneration.Controls.Add(this.txtAppendFilename); + resources.ApplyResources(this.grpOutputPathGeneration, "grpOutputPathGeneration"); + this.grpOutputPathGeneration.Name = "grpOutputPathGeneration"; + this.grpOutputPathGeneration.TabStop = false; + // + // txtCustomFormat + // + resources.ApplyResources(this.txtCustomFormat, "txtCustomFormat"); + this.txtCustomFormat.Name = "txtCustomFormat"; + this.txtCustomFormat.TextChanged += new System.EventHandler(this.txtCustomFormat_TextChanged); + // + // rbCustomFormat + // + resources.ApplyResources(this.rbCustomFormat, "rbCustomFormat"); + this.rbCustomFormat.Name = "rbCustomFormat"; + this.rbCustomFormat.TabStop = true; + this.rbCustomFormat.UseVisualStyleBackColor = true; + this.rbCustomFormat.CheckedChanged += new System.EventHandler(this.rbCustomFormat_CheckedChanged); + // + // txtCreateSubdirectory + // + resources.ApplyResources(this.txtCreateSubdirectory, "txtCreateSubdirectory"); + this.txtCreateSubdirectory.Name = "txtCreateSubdirectory"; + this.txtCreateSubdirectory.TextChanged += new System.EventHandler(this.txtCreateSubdirectory_TextChanged); + // + // rbDontGenerate + // + resources.ApplyResources(this.rbDontGenerate, "rbDontGenerate"); + this.rbDontGenerate.Name = "rbDontGenerate"; + this.rbDontGenerate.UseVisualStyleBackColor = true; + // + // rbCreateSubdirectory + // + resources.ApplyResources(this.rbCreateSubdirectory, "rbCreateSubdirectory"); + this.rbCreateSubdirectory.Checked = true; + this.rbCreateSubdirectory.Name = "rbCreateSubdirectory"; + this.rbCreateSubdirectory.TabStop = true; + this.rbCreateSubdirectory.UseVisualStyleBackColor = true; + this.rbCreateSubdirectory.CheckedChanged += new System.EventHandler(this.rbCreateSubdirectory_CheckedChanged); + // + // rbAppendFilename + // + resources.ApplyResources(this.rbAppendFilename, "rbAppendFilename"); + this.rbAppendFilename.Name = "rbAppendFilename"; + this.rbAppendFilename.UseVisualStyleBackColor = true; + this.rbAppendFilename.CheckedChanged += new System.EventHandler(this.rbAppendFilename_CheckedChanged); + // + // txtAppendFilename + // + resources.ApplyResources(this.txtAppendFilename, "txtAppendFilename"); + this.txtAppendFilename.Name = "txtAppendFilename"; + this.txtAppendFilename.TextChanged += new System.EventHandler(this.txtAppendFilename_TextChanged); + // + // grpAudioOutput + // + this.grpAudioOutput.Controls.Add(this.rbNoAudio); + this.grpAudioOutput.Controls.Add(this.rbWavPack); + this.grpAudioOutput.Controls.Add(this.rbFLAC); + this.grpAudioOutput.Controls.Add(this.rbWAV); + resources.ApplyResources(this.grpAudioOutput, "grpAudioOutput"); + this.grpAudioOutput.Name = "grpAudioOutput"; + this.grpAudioOutput.TabStop = false; + // + // rbNoAudio + // + resources.ApplyResources(this.rbNoAudio, "rbNoAudio"); + this.rbNoAudio.Name = "rbNoAudio"; + this.toolTip1.SetToolTip(this.rbNoAudio, resources.GetString("rbNoAudio.ToolTip")); + this.rbNoAudio.UseVisualStyleBackColor = true; + this.rbNoAudio.CheckedChanged += new System.EventHandler(this.rbNoAudio_CheckedChanged); + // + // rbWavPack + // + resources.ApplyResources(this.rbWavPack, "rbWavPack"); + this.rbWavPack.Name = "rbWavPack"; + this.rbWavPack.UseVisualStyleBackColor = true; + this.rbWavPack.CheckedChanged += new System.EventHandler(this.rbWavPack_CheckedChanged); + // + // rbFLAC + // + resources.ApplyResources(this.rbFLAC, "rbFLAC"); + this.rbFLAC.Name = "rbFLAC"; + this.rbFLAC.UseVisualStyleBackColor = true; + this.rbFLAC.CheckedChanged += new System.EventHandler(this.rbFLAC_CheckedChanged); + // + // rbWAV + // + resources.ApplyResources(this.rbWAV, "rbWAV"); + this.rbWAV.Checked = true; + this.rbWAV.Name = "rbWAV"; + this.rbWAV.TabStop = true; + this.rbWAV.UseVisualStyleBackColor = true; + this.rbWAV.CheckedChanged += new System.EventHandler(this.rbWAV_CheckedChanged); + // + // btnBatch + // + resources.ApplyResources(this.btnBatch, "btnBatch"); + this.btnBatch.Name = "btnBatch"; + this.btnBatch.UseVisualStyleBackColor = true; + this.btnBatch.Click += new System.EventHandler(this.btnBatch_Click); + // + // btnFilenameCorrector + // + resources.ApplyResources(this.btnFilenameCorrector, "btnFilenameCorrector"); + this.btnFilenameCorrector.Name = "btnFilenameCorrector"; + this.btnFilenameCorrector.UseVisualStyleBackColor = true; + this.btnFilenameCorrector.Click += new System.EventHandler(this.btnFilenameCorrector_Click); + // + // btnSettings + // + resources.ApplyResources(this.btnSettings, "btnSettings"); + this.btnSettings.Name = "btnSettings"; + this.btnSettings.UseVisualStyleBackColor = true; + this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click); + // + // grpAccurateRip + // + this.grpAccurateRip.Controls.Add(this.label1); + this.grpAccurateRip.Controls.Add(this.txtDataTrackLength); + this.grpAccurateRip.Controls.Add(this.rbArApplyOffset); + this.grpAccurateRip.Controls.Add(this.rbArVerify); + this.grpAccurateRip.Controls.Add(this.rbArNone); + resources.ApplyResources(this.grpAccurateRip, "grpAccurateRip"); + this.grpAccurateRip.Name = "grpAccurateRip"; + this.grpAccurateRip.TabStop = false; + // + // label1 + // + resources.ApplyResources(this.label1, "label1"); + this.label1.Name = "label1"; + // + // txtDataTrackLength + // + this.txtDataTrackLength.Culture = new System.Globalization.CultureInfo(""); + this.txtDataTrackLength.CutCopyMaskFormat = System.Windows.Forms.MaskFormat.IncludePromptAndLiterals; + this.txtDataTrackLength.InsertKeyMode = System.Windows.Forms.InsertKeyMode.Overwrite; + resources.ApplyResources(this.txtDataTrackLength, "txtDataTrackLength"); + this.txtDataTrackLength.Name = "txtDataTrackLength"; + this.txtDataTrackLength.TextMaskFormat = System.Windows.Forms.MaskFormat.IncludePromptAndLiterals; + this.toolTip1.SetToolTip(this.txtDataTrackLength, resources.GetString("txtDataTrackLength.ToolTip")); + // + // rbArApplyOffset + // + resources.ApplyResources(this.rbArApplyOffset, "rbArApplyOffset"); + this.rbArApplyOffset.Name = "rbArApplyOffset"; + this.toolTip1.SetToolTip(this.rbArApplyOffset, resources.GetString("rbArApplyOffset.ToolTip")); + this.rbArApplyOffset.UseVisualStyleBackColor = true; + // + // rbArVerify + // + resources.ApplyResources(this.rbArVerify, "rbArVerify"); + this.rbArVerify.Name = "rbArVerify"; + this.toolTip1.SetToolTip(this.rbArVerify, resources.GetString("rbArVerify.ToolTip")); + this.rbArVerify.UseVisualStyleBackColor = true; + this.rbArVerify.CheckedChanged += new System.EventHandler(this.rbArVerify_CheckedChanged); + // + // rbArNone + // + resources.ApplyResources(this.rbArNone, "rbArNone"); + this.rbArNone.Checked = true; + this.rbArNone.Name = "rbArNone"; + this.rbArNone.TabStop = true; + this.toolTip1.SetToolTip(this.rbArNone, resources.GetString("rbArNone.ToolTip")); + this.rbArNone.UseVisualStyleBackColor = true; + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel1, + this.toolStripProgressBar1, + this.toolStripProgressBar2}); + resources.ApplyResources(this.statusStrip1, "statusStrip1"); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.SizingGrip = false; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1"); + this.toolStripStatusLabel1.Spring = true; + // + // toolStripProgressBar1 + // + this.toolStripProgressBar1.AutoToolTip = true; + this.toolStripProgressBar1.Name = "toolStripProgressBar1"; + resources.ApplyResources(this.toolStripProgressBar1, "toolStripProgressBar1"); + this.toolStripProgressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous; + // + // toolStripProgressBar2 + // + this.toolStripProgressBar2.AutoToolTip = true; + this.toolStripProgressBar2.Name = "toolStripProgressBar2"; + resources.ApplyResources(this.toolStripProgressBar2, "toolStripProgressBar2"); + this.toolStripProgressBar2.Style = System.Windows.Forms.ProgressBarStyle.Continuous; + // + // toolTip1 + // + this.toolTip1.AutoPopDelay = 15000; + this.toolTip1.InitialDelay = 500; + this.toolTip1.ReshowDelay = 100; + // + // btnCUECreator + // + resources.ApplyResources(this.btnCUECreator, "btnCUECreator"); + this.btnCUECreator.Name = "btnCUECreator"; + this.btnCUECreator.UseVisualStyleBackColor = true; + this.btnCUECreator.Click += new System.EventHandler(this.btnCUECreator_Click); + // + // frmCUETools + // + resources.ApplyResources(this, "$this"); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.btnCUECreator); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.grpAccurateRip); + this.Controls.Add(this.btnSettings); + this.Controls.Add(this.btnFilenameCorrector); + this.Controls.Add(this.btnBatch); + this.Controls.Add(this.grpAudioOutput); + this.Controls.Add(this.grpOutputPathGeneration); + this.Controls.Add(this.btnAbout); + this.Controls.Add(this.grpOutputStyle); + this.Controls.Add(this.grpCUEPaths); + this.Controls.Add(this.btnConvert); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.Name = "frmCUETools"; + this.Load += new System.EventHandler(this.frmCUETools_Load); + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmCUETools_FormClosed); + this.grpCUEPaths.ResumeLayout(false); + this.grpCUEPaths.PerformLayout(); + this.grpOutputStyle.ResumeLayout(false); + this.grpOutputStyle.PerformLayout(); + this.grpOutputPathGeneration.ResumeLayout(false); + this.grpOutputPathGeneration.PerformLayout(); + this.grpAudioOutput.ResumeLayout(false); + this.grpAudioOutput.PerformLayout(); + this.grpAccurateRip.ResumeLayout(false); + this.grpAccurateRip.PerformLayout(); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnConvert; + private System.Windows.Forms.GroupBox grpCUEPaths; + private System.Windows.Forms.Button btnBrowseOutput; + private System.Windows.Forms.Button btnBrowseInput; + private System.Windows.Forms.Label lblOutput; + private System.Windows.Forms.Label lblInput; + private System.Windows.Forms.TextBox txtOutputPath; + private System.Windows.Forms.TextBox txtInputPath; + private System.Windows.Forms.GroupBox grpOutputStyle; + private System.Windows.Forms.Button btnAbout; + private System.Windows.Forms.RadioButton rbGapsLeftOut; + private System.Windows.Forms.RadioButton rbGapsPrepended; + private System.Windows.Forms.RadioButton rbGapsAppended; + private System.Windows.Forms.RadioButton rbSingleFile; + private System.Windows.Forms.GroupBox grpOutputPathGeneration; + private System.Windows.Forms.RadioButton rbDontGenerate; + private System.Windows.Forms.RadioButton rbCreateSubdirectory; + private System.Windows.Forms.RadioButton rbAppendFilename; + private System.Windows.Forms.TextBox txtAppendFilename; + private System.Windows.Forms.TextBox txtCreateSubdirectory; + private System.Windows.Forms.GroupBox grpAudioOutput; + private System.Windows.Forms.RadioButton rbFLAC; + private System.Windows.Forms.RadioButton rbWAV; + private System.Windows.Forms.RadioButton rbWavPack; + private System.Windows.Forms.RadioButton rbCustomFormat; + private System.Windows.Forms.TextBox txtCustomFormat; + private System.Windows.Forms.Button btnBatch; + private System.Windows.Forms.Button btnFilenameCorrector; + private System.Windows.Forms.Button btnSettings; + private System.Windows.Forms.RadioButton rbNoAudio; + private System.Windows.Forms.GroupBox grpAccurateRip; + private System.Windows.Forms.RadioButton rbArApplyOffset; + private System.Windows.Forms.RadioButton rbArVerify; + private System.Windows.Forms.RadioButton rbArNone; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1; + private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar2; + private System.Windows.Forms.ToolTip toolTip1; + private System.Windows.Forms.RadioButton rbEmbedCUE; + private System.Windows.Forms.Button btnCUECreator; + private System.Windows.Forms.MaskedTextBox txtDataTrackLength; + private System.Windows.Forms.Label label1; + } +} + diff --git a/CUETools/frmCUETools.cs b/CUETools/frmCUETools.cs new file mode 100644 index 0000000..2779d6b --- /dev/null +++ b/CUETools/frmCUETools.cs @@ -0,0 +1,907 @@ +// **************************************************************************** +// +// CUE Tools +// Copyright (C) 2006-2007 Moitah (moitah@yahoo.com) +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// **************************************************************************** + +// **************************************************************************** +// Access to AccurateRip is regulated, see +// http://www.accuraterip.com/3rdparty-access.htm for details. +// **************************************************************************** + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.IO; +using System.Threading; + +namespace JDP { + public partial class frmCUETools : Form { + public frmCUETools() { + _config = new CUEConfig(); + InitializeComponent(); + } + + private void btnBrowseInput_Click(object sender, EventArgs e) { + OpenFileDialog fileDlg = new OpenFileDialog(); + DialogResult dlgRes; + + fileDlg.Title = "Input CUE Sheet or FLAC image"; + fileDlg.Filter = "CUE Sheets (*.cue)|*.cue|FLAC images (*.flac)|*.flac"; + + dlgRes = fileDlg.ShowDialog(); + if (dlgRes == DialogResult.OK) { + txtInputPath.Text = fileDlg.FileName; + } + } + + private void btnBrowseOutput_Click(object sender, EventArgs e) { + SaveFileDialog fileDlg = new SaveFileDialog(); + DialogResult dlgRes; + + fileDlg.Title = "Output CUE Sheet"; + fileDlg.Filter = "CUE Sheets (*.cue)|*.cue"; + + dlgRes = fileDlg.ShowDialog(); + if (dlgRes == DialogResult.OK) { + txtOutputPath.Text = fileDlg.FileName; + } + } + + private void btnConvert_Click(object sender, EventArgs e) { + if ((_workThread != null) && (_workThread.IsAlive)) { + _workClass.Stop(); + } + else { + if (!CheckWriteOffset()) return; + StartConvert(); + } + } + + private void btnBatch_Click(object sender, EventArgs e) { + if (rbDontGenerate.Checked) { + MessageBox.Show("Batch mode cannot be used with the output path set manually.", + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + FolderBrowserDialog folderDialog = new FolderBrowserDialog(); + folderDialog.Description = "Select the folder containing the CUE sheets you want to convert. Subfolders will be included automatically."; + folderDialog.ShowNewFolderButton = false; + if (folderDialog.ShowDialog() == DialogResult.OK) { + if (!CheckWriteOffset()) return; + AddDirToBatch(folderDialog.SelectedPath); + StartConvert(); + } + } + + private void btnFilenameCorrector_Click(object sender, EventArgs e) { + if ((_fcForm == null) || _fcForm.IsDisposed) { + _fcForm = new frmFilenameCorrector(); + CenterSubForm(_fcForm); + _fcForm.Show(); + } + else { + _fcForm.Activate(); + } + } + + private void btnSettings_Click(object sender, EventArgs e) { + using (frmSettings settingsForm = new frmSettings()) { + settingsForm.WriteOffset = _writeOffset; + settingsForm.Config = _config; + + CenterSubForm(settingsForm); + settingsForm.ShowDialog(); + + _writeOffset = settingsForm.WriteOffset; + _config = settingsForm.Config; + _config.BuildCharMap(); + UpdateOutputPath(); + } + } + + private void btnAbout_Click(object sender, EventArgs e) { + using (frmReport reportForm = new frmReport()) + { + StringWriter sw = new StringWriter(); + sw.WriteLine("CUE Tools v1.9.2"); + sw.WriteLine("Copyright 2006-2007 Moitah http://www.moitah.net/."); + sw.WriteLine("AccurateRip, Monkey's Audio (APE) input and FLAC embedded CUE sheet support added in 2008 by Greg Chudov, gchudov@gmail.com."); + sw.WriteLine("Thanks go out to Christopher Key and Whitehobbit for insight on AccurateRip functionality and to Mr Spoon for permission to use the database."); + sw.WriteLine("Monkey's Audio library by Matthew T. Ashland."); + reportForm.Message = sw.ToString(); + sw.Close(); + CenterSubForm(reportForm); + reportForm.Text = "About CUE Tools"; + reportForm.ShowDialog(this); + } + } + + private void PathTextBox_DragEnter(object sender, DragEventArgs e) { + if (e.Data.GetDataPresent(DataFormats.FileDrop) && !((TextBox)sender).ReadOnly) { + e.Effect = DragDropEffects.Copy; + } + } + + private void PathTextBox_DragDrop(object sender, DragEventArgs e) { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) { + string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); + if (files.Length == 1) { + ((TextBox)sender).Text = files[0]; + } + } + } + + public string InputPath { + get { + return txtInputPath.Text; + } + set { + txtInputPath.Text = value; + } + } + + private void txtInputPath_TextChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void rbCreateSubdirectory_CheckedChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void rbAppendFilename_CheckedChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void rbCustomFormat_CheckedChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void txtCreateSubdirectory_TextChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void txtAppendFilename_TextChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void txtCustomFormat_TextChanged(object sender, EventArgs e) { + UpdateOutputPath(); + } + + private void frmCUETools_Load(object sender, EventArgs e) { + _batchPaths = new List(); + LoadSettings(); + SetupControls(false); + UpdateOutputPath(); + updateOutputStyles(); + } + + private void frmCUETools_FormClosed(object sender, FormClosedEventArgs e) { + SaveSettings(); + } + + + // ******************************************************************************** + + frmFilenameCorrector _fcForm; + List _batchPaths; + bool _usePregapForFirstTrackInSingleFile; + int _writeOffset; + Thread _workThread; + CUESheet _workClass; + CUEConfig _config; + + private void StartConvert() { + string pathIn, pathOut, outDir; + CUESheet cueSheet; + CUEStyle cueStyle; + + try { + _workThread = null; + if (_batchPaths.Count != 0) { + txtInputPath.Text = _batchPaths[0]; + } + pathIn = txtInputPath.Text; + cueStyle = SelectedCUEStyle; + + bool outputAudio = !rbNoAudio.Checked && !rbArVerify.Checked; + bool outputCUE = (cueStyle != CUEStyle.SingleFileWithCUE) && !rbArVerify.Checked; + bool accurateRip = !rbArNone.Checked; + + if (!File.Exists(pathIn)) { + throw new Exception("Input CUE Sheet not found."); + } + + cueSheet = new CUESheet(pathIn, _config); + + cueSheet.WriteOffset = _writeOffset; + + UpdateOutputPath(cueSheet.Artist != "" ? cueSheet.Artist : "Unknown Artist", cueSheet.Title != "" ? cueSheet.Title : "Unknown Title"); + pathOut = txtOutputPath.Text; + cueSheet.GenerateFilenames(SelectedOutputAudioFormat, pathOut); + outDir = Path.GetDirectoryName(pathOut); + if (cueStyle == CUEStyle.SingleFileWithCUE) + cueSheet.SingleFilename = Path.GetFileName (pathOut); + + bool outputExists = false; + if (outputCUE) + outputExists = File.Exists(pathOut); + if (outputAudio) { + if (cueStyle == CUEStyle.SingleFile || cueStyle == CUEStyle.SingleFileWithCUE) { + outputExists |= File.Exists(Path.Combine(outDir, cueSheet.SingleFilename)); + } + else { + if ((cueStyle == CUEStyle.GapsAppended) && _config.preserveHTOA) { + outputExists |= File.Exists(Path.Combine(outDir, cueSheet.HTOAFilename)); + } + for (int i = 0; i < cueSheet.TrackCount; i++) { + outputExists |= File.Exists(Path.Combine(outDir, cueSheet.TrackFilenames[i])); + } + } + } + if (outputExists) { + DialogResult dlgRes = MessageBox.Show("One or more output file already exists, " + + "do you want to overwrite?", "Overwrite?", (_batchPaths.Count == 0) ? + MessageBoxButtons.YesNo : MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); + + if (dlgRes == DialogResult.Cancel) { + _batchPaths.Clear(); + } + if (dlgRes != DialogResult.Yes) { + goto SkipConversion; + } + } + + cueSheet.UsePregapForFirstTrackInSingleFile = _usePregapForFirstTrackInSingleFile && !outputAudio; + cueSheet.AccurateRip = accurateRip; + cueSheet.AccurateOffset = rbArApplyOffset.Checked; + cueSheet.DataTrackLength = txtDataTrackLength.Text; + + if (outputAudio || accurateRip) { + object[] p = new object[3]; + + _workThread = new Thread(WriteAudioFilesThread); + _workClass = cueSheet; + + p[0] = cueSheet; + p[1] = outDir; + p[2] = cueStyle; + + SetupControls(true); + _workThread.Start(p); + } + else { + if (!Directory.Exists(outDir)) + Directory.CreateDirectory(outDir); + if (outputCUE) + cueSheet.Write(pathOut, cueStyle); + ShowFinishedMessage(cueSheet.PaddedToFrame); + } + } + catch (Exception ex) { + if (!ShowErrorMessage(ex)) { + _batchPaths.Clear(); + } + } + + SkipConversion: + if ((_workThread == null) && (_batchPaths.Count != 0)) { + _batchPaths.RemoveAt(0); + if (_batchPaths.Count == 0) { + ShowBatchDoneMessage(); + } + else { + StartConvert(); + } + } + } + + private void WriteAudioFilesThread(object o) { + object[] p = (object[])o; + + CUESheet cueSheet = (CUESheet)p[0]; + string outDir = (string)p[1]; + CUEStyle cueStyle = (CUEStyle)p[2]; + + try { + cueSheet.WriteAudioFiles(outDir, cueStyle, new SetStatus(this.SetStatus)); + this.Invoke((MethodInvoker)delegate() { + if (_batchPaths.Count == 0) + { + if (cueSheet.AccurateRip) + { + using (frmReport reportForm = new frmReport()) + { + StringWriter sw = new StringWriter(); + cueSheet.GenerateAccurateRipLog(sw); + reportForm.Message = sw.ToString(); + sw.Close(); + CenterSubForm(reportForm); + reportForm.ShowDialog(this); + } + } + else + ShowFinishedMessage(cueSheet.PaddedToFrame); + SetupControls(false); + } + }); + } + catch (StopException) { + _batchPaths.Clear(); + this.Invoke((MethodInvoker)delegate() { + SetupControls(false); + MessageBox.Show("Conversion was stopped.", "Stopped", MessageBoxButtons.OK, + MessageBoxIcon.Exclamation); + }); + } + catch (Exception ex) { + this.Invoke((MethodInvoker)delegate() { + if (_batchPaths.Count == 0) SetupControls(false); + if (!ShowErrorMessage(ex)) { + _batchPaths.Clear(); + SetupControls(false); + } + }); + } + + if (_batchPaths.Count != 0) { + _batchPaths.RemoveAt(0); + this.BeginInvoke((MethodInvoker)delegate() { + if (_batchPaths.Count == 0) { + SetupControls(false); + ShowBatchDoneMessage(); + } + else { + StartConvert(); + } + }); + } + } + + public void SetStatus(string status, uint percentTrack, double percentDisk) { + this.BeginInvoke((MethodInvoker)delegate() { + toolStripStatusLabel1.Text = status; + toolStripProgressBar1.Value = (int)percentTrack; + toolStripProgressBar2.Value = (int)(percentDisk*100); + }); + } + + private void SetupControls(bool running) { + grpCUEPaths.Enabled = !running; + grpOutputPathGeneration.Enabled = !running; + grpAudioOutput.Enabled = !running && !rbArVerify.Checked; + grpAccurateRip.Enabled = !running; + grpOutputStyle.Enabled = !running && !rbArVerify.Checked; + txtDataTrackLength.Enabled = !running && !rbArNone.Checked; + btnAbout.Enabled = !running; + btnSettings.Enabled = !running; + btnFilenameCorrector.Enabled = !running; + btnCUECreator.Enabled = !running; + btnBatch.Enabled = !running; + btnConvert.Text = running ? "&Stop" : "&Convert"; + toolStripStatusLabel1.Text = String.Empty; + toolStripProgressBar1.Value = 0; + toolStripProgressBar2.Value = 0; + } + + private bool ShowErrorMessage(Exception ex) { + DialogResult dlgRes = MessageBox.Show(ex.Message, "Error", (_batchPaths.Count == 0) ? + MessageBoxButtons.OK : MessageBoxButtons.OKCancel, MessageBoxIcon.Error); + return (dlgRes == DialogResult.OK); + } + + private void ShowFinishedMessage(bool warnAboutPadding) { + if (_batchPaths.Count != 0) { + return; + } + if (warnAboutPadding) { + MessageBox.Show("One or more input file doesn't end on a CD frame boundary. " + + "The output has been padded where necessary to fix this. If your input " + + "files are from a CD source, this may indicate a problem with your files.", + "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + MessageBox.Show("Conversion was successful!", "Done", MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + + private void ShowBatchDoneMessage() { + MessageBox.Show("Batch conversion is complete!", "Done", MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + + private bool CheckWriteOffset() { + if ((_writeOffset == 0) || rbNoAudio.Checked || rbArVerify.Checked) { + return true; + } + + DialogResult dlgRes = MessageBox.Show("Write offset setting is non-zero which " + + "will cause some samples to be discarded. You should only use this setting " + + "to make temporary files for burning. Are you sure you want to continue?", + "Write offset is enabled", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + return (dlgRes == DialogResult.Yes); + } + + private void AddDirToBatch(string dir) { + string[] files = Directory.GetFiles(dir, "*.cue"); + string[] subDirs = Directory.GetDirectories(dir); + _batchPaths.AddRange(files); + foreach (string subDir in subDirs) { + AddDirToBatch(subDir); + } + } + + private void LoadSettings() { + SettingsReader sr = new SettingsReader("CUE Tools", "settings.txt"); + string val; + + val = sr.Load("OutputPathGeneration"); + if (val != null) { + try { + SelectedOutputPathGeneration = (OutputPathGeneration)Int32.Parse(val); + } + catch { } + } + + val = sr.Load("OutputSubdirectory"); + if (val != null) { + txtCreateSubdirectory.Text = val; + } + + val = sr.Load("OutputFilenameSuffix"); + if (val != null) { + txtAppendFilename.Text = val; + } + + val = sr.Load("OutputCustomFormat"); + if (val != null) { + txtCustomFormat.Text = val; + } + + val = sr.Load("OutputAudioFormat"); + if (val != null) { + try { + SelectedOutputAudioFormat = (OutputAudioFormat)Int32.Parse(val); + } + catch { } + } + + val = sr.Load("AccurateRipMode"); + if (val != null) { + try { + SelectedAccurateRipMode = (AccurateRipMode)Int32.Parse(val); + } + catch { } + } + + val = sr.Load("CUEStyle"); + if (val != null) { + try { + SelectedCUEStyle = (CUEStyle)Int32.Parse(val); + } + catch { } + } + + val = sr.Load("WriteOffset"); + if (val != null) { + if (!Int32.TryParse(val, out _writeOffset)) _writeOffset = 0; + } + + val = sr.Load("UsePregapForFirstTrackInSingleFile"); + _usePregapForFirstTrackInSingleFile = (val != null) ? (val != "0") : false; + + _config.Load(sr); + } + + private void SaveSettings() { + SettingsWriter sw = new SettingsWriter("CUE Tools", "settings.txt"); + + sw.Save("OutputPathGeneration", ((int)SelectedOutputPathGeneration).ToString()); + + sw.Save("OutputSubdirectory", txtCreateSubdirectory.Text); + + sw.Save("OutputFilenameSuffix", txtAppendFilename.Text); + + sw.Save("OutputCustomFormat", txtCustomFormat.Text); + + sw.Save("OutputAudioFormat", ((int)SelectedOutputAudioFormat).ToString()); + + sw.Save("AccurateRipMode", ((int)SelectedAccurateRipMode).ToString()); + + sw.Save("CUEStyle", ((int)SelectedCUEStyle).ToString()); + + sw.Save("WriteOffset", _writeOffset.ToString()); + + sw.Save("UsePregapForFirstTrackInSingleFile", _usePregapForFirstTrackInSingleFile ? "1" : "0"); + + _config.Save(sw); + + sw.Close(); + } + + private void BuildOutputPathFindReplace(string inputPath, string format, List find, List replace) { + int i, j, first, last, maxFindLen; + string range; + string[] rangeSplit; + List tmpFind = new List(); + List tmpReplace = new List(); + + i = 0; + last = 0; + while (i < format.Length) { + if (format[i++] == '%') { + j = i; + while (j < format.Length) { + char c = format[j]; + if (((c < '0') || (c > '9')) && (c != '-') && (c != ':')) { + break; + } + j++; + } + range = format.Substring(i, j - i); + if (range.Length != 0) { + rangeSplit = range.Split(new char[] { ':' }, 2); + if (Int32.TryParse(rangeSplit[0], out first)) { + if (rangeSplit.Length == 1) { + last = first; + } + if ((rangeSplit.Length == 1) || Int32.TryParse(rangeSplit[1], out last)) { + tmpFind.Add("%" + range); + tmpReplace.Add(General.EmptyStringToNull(GetDirectoryElements(Path.GetDirectoryName(inputPath), first, last))); + } + } + } + i = j; + } + } + + // Sort so that longest find strings are first, so when the replacing is done the + // longer strings are checked first. This avoids problems with overlapping find + // strings, for example if one of the strings is "%1" and another is "%1:3". + maxFindLen = 0; + for (i = 0; i < tmpFind.Count; i++) { + if (tmpFind[i].Length > maxFindLen) { + maxFindLen = tmpFind[i].Length; + } + } + for (j = maxFindLen; j >= 1; j--) { + for (i = 0; i < tmpFind.Count; i++) { + if (tmpFind[i].Length == j) { + find.Add(tmpFind[i]); + replace.Add(tmpReplace[i]); + } + } + } + + find.Add("%F"); + replace.Add(Path.GetFileNameWithoutExtension(inputPath)); + } + + private string GetDirectoryElements(string dir, int first, int last) { + string[] dirSplit = dir.Split(Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar); + int count = dirSplit.Length; + + if ((first == 0) && (last == 0)) { + first = 1; + last = count; + } + + if (first < 0) first = (count + 1) + first; + if (last < 0) last = (count + 1) + last; + + if ((first < 1) && (last < 1)) { + return String.Empty; + } + else if ((first > count) && (last > count)) { + return String.Empty; + } + else { + int i; + StringBuilder sb = new StringBuilder(); + + if (first < 1) first = 1; + if (first > count) first = count; + if (last < 1) last = 1; + if (last > count) last = count; + + if (last >= first) { + for (i = first; i <= last; i++) { + sb.Append(dirSplit[i - 1]); + sb.Append(Path.DirectorySeparatorChar); + } + } + else { + for (i = first; i >= last; i--) { + sb.Append(dirSplit[i - 1]); + sb.Append(Path.DirectorySeparatorChar); + } + } + + return sb.ToString(0, sb.Length - 1); + } + } + + private CUEStyle SelectedCUEStyle { + get { + if (rbGapsAppended.Checked) return CUEStyle.GapsAppended; + if (rbGapsPrepended.Checked) return CUEStyle.GapsPrepended; + if (rbGapsLeftOut.Checked) return CUEStyle.GapsLeftOut; + if (rbEmbedCUE.Checked) return CUEStyle.SingleFileWithCUE; + return CUEStyle.SingleFile; + } + set { + switch (value) { + case CUEStyle.SingleFileWithCUE: rbEmbedCUE.Checked = true; break; + case CUEStyle.SingleFile: rbSingleFile.Checked = true; break; + case CUEStyle.GapsAppended: rbGapsAppended.Checked = true; break; + case CUEStyle.GapsPrepended: rbGapsPrepended.Checked = true; break; + case CUEStyle.GapsLeftOut: rbGapsLeftOut.Checked = true; break; + } + } + } + + private OutputPathGeneration SelectedOutputPathGeneration { + get { + if (rbCreateSubdirectory.Checked) return OutputPathGeneration.CreateSubdirectory; + if (rbAppendFilename.Checked) return OutputPathGeneration.AppendFilename; + if (rbCustomFormat.Checked) return OutputPathGeneration.CustomFormat; + return OutputPathGeneration.Disabled; + } + set { + switch (value) { + case OutputPathGeneration.CreateSubdirectory: rbCreateSubdirectory.Checked = true; break; + case OutputPathGeneration.AppendFilename: rbAppendFilename.Checked = true; break; + case OutputPathGeneration.CustomFormat: rbCustomFormat.Checked = true; break; + case OutputPathGeneration.Disabled: rbDontGenerate.Checked = true; break; + } + } + } + + private OutputAudioFormat SelectedOutputAudioFormat { + get { + if (rbFLAC.Checked) return OutputAudioFormat.FLAC; + if (rbWavPack.Checked) return OutputAudioFormat.WavPack; + if (rbNoAudio.Checked) return OutputAudioFormat.NoAudio; + return OutputAudioFormat.WAV; + } + set { + switch (value) { + case OutputAudioFormat.FLAC: rbFLAC.Checked = true; break; + case OutputAudioFormat.WavPack: rbWavPack.Checked = true; break; + case OutputAudioFormat.WAV: rbWAV.Checked = true; break; + case OutputAudioFormat.NoAudio: rbNoAudio.Checked = true; break; + } + } + } + + private AccurateRipMode SelectedAccurateRipMode { + get { + if (rbArVerify.Checked) return AccurateRipMode.Verify; + if (rbArApplyOffset.Checked) return AccurateRipMode.Offset; + return AccurateRipMode.None; + } + set { + switch (value) { + case AccurateRipMode.Verify: rbArVerify.Checked = true; break; + case AccurateRipMode.Offset: rbArApplyOffset.Checked = true; break; + default: rbArNone.Checked = true; break; + } + } + } + + private void CenterSubForm(Form form) { + int centerX, centerY, formX, formY; + Rectangle formRect, maxRect; + + centerX = ((Left * 2) + Width ) / 2; + centerY = ((Top * 2) + Height) / 2; + formX = ((Left * 2) + Width - form.Width ) / 2; + formY = ((Top * 2) + Height - form.Height) / 2; + + formRect = new Rectangle(formX, formY, form.Width, form.Height); + maxRect = Screen.GetWorkingArea(new Point(centerX, centerY)); + + if (formRect.Right > maxRect.Right) { + formRect.X -= formRect.Right - maxRect.Right; + } + if (formRect.Bottom > maxRect.Bottom) { + formRect.Y -= formRect.Bottom - maxRect.Bottom; + } + if (formRect.X < maxRect.X) { + formRect.X = maxRect.X; + } + if (formRect.Y < maxRect.Y) { + formRect.Y = maxRect.Y; + } + + form.Location = formRect.Location; + } + + private void UpdateOutputPath() { + UpdateOutputPath("Artist", "Album"); + } + + private void UpdateOutputPath(string artist, string album) { + /* if (rbArVerify.Checked) + { + txtOutputPath.Text = txtInputPath.Text; + txtOutputPath.ReadOnly = true; + btnBrowseOutput.Enabled = false; + } + else */ if (rbDontGenerate.Checked) + { + txtOutputPath.ReadOnly = false; + btnBrowseOutput.Enabled = true; + } + else + { + txtOutputPath.ReadOnly = true; + btnBrowseOutput.Enabled = false; + txtOutputPath.Text = GenerateOutputPath(artist, album); + } + } + + private string GenerateOutputPath(string artist, string album) { + string pathIn, pathOut, dir, file, ext; + + pathIn = txtInputPath.Text; + pathOut = String.Empty; + + if ((pathIn.Length != 0) && File.Exists(pathIn)) { + dir = Path.GetDirectoryName(pathIn); + file = Path.GetFileNameWithoutExtension(pathIn); + ext = ".cue"; + + if (rbEmbedCUE.Checked) + ext = General.FormatExtension (SelectedOutputAudioFormat); + + if (rbCreateSubdirectory.Checked) { + pathOut = Path.Combine(Path.Combine(dir, txtCreateSubdirectory.Text), file + ext); + } + else if (rbAppendFilename.Checked) { + pathOut = Path.Combine(dir, file + txtAppendFilename.Text + ext); + } + else if (rbCustomFormat.Checked) { + string format = txtCustomFormat.Text; + List find = new List(); + List replace = new List(); + bool rs = _config.replaceSpaces; + + find.Add("%D"); + find.Add("%C"); + replace.Add(General.EmptyStringToNull(_config.CleanseString(rs ? artist.Replace(' ', '_') : artist))); + replace.Add(General.EmptyStringToNull(_config.CleanseString(rs ? album.Replace(' ', '_') : album))); + BuildOutputPathFindReplace(pathIn, format, find, replace); + + pathOut = General.ReplaceMultiple(format, find, replace); + if (pathOut == null) pathOut = String.Empty; + pathOut = Path.ChangeExtension(pathOut, ext); + } + } + + return pathOut; + } + + private void updateOutputStyles() + { + rbEmbedCUE.Enabled = rbFLAC.Checked; + rbNoAudio.Enabled = rbWAV.Enabled = rbWavPack.Enabled = !rbEmbedCUE.Checked; + } + + private void rbWAV_CheckedChanged(object sender, EventArgs e) + { + updateOutputStyles(); + } + + private void rbFLAC_CheckedChanged(object sender, EventArgs e) + { + updateOutputStyles(); + } + + private void rbWavPack_CheckedChanged(object sender, EventArgs e) + { + updateOutputStyles(); + } + + private void rbEmbedCUE_CheckedChanged(object sender, EventArgs e) + { + updateOutputStyles(); + UpdateOutputPath(); + } + + private void rbNoAudio_CheckedChanged(object sender, EventArgs e) + { + updateOutputStyles(); + UpdateOutputPath(); + } + + private void rbArVerify_CheckedChanged(object sender, EventArgs e) + { + UpdateOutputPath(); + SetupControls (false); + } + + private void CUECreator (string dir) + { + string[] cueFiles = Directory.GetFiles(dir, "*.cue"); + if (cueFiles.Length == 0) + { + string[] audioExts = new string[] { "*.wav", "*.flac", "*.wv", "*.ape" }; + for (int i = 0; i < audioExts.Length; i++) + { + string [] audioFiles = Directory.GetFiles(dir, audioExts[i]); + if (audioFiles.Length < 2) + continue; + Array.Sort (audioFiles); + string cueName = Path.GetFileName(dir) + ".cuetools" + audioExts[i].Substring(1) + ".cue"; + cueName = Path.Combine(dir, cueName); + StreamWriter sw = new StreamWriter(cueName, false, CUESheet.Encoding); + sw.WriteLine(String.Format("REM COMMENT \"CUETools generated dummy CUE sheet\"")); + for (int iFile = 0; iFile < audioFiles.Length; iFile++) + { + sw.WriteLine(String.Format("FILE \"{0}\" WAVE", Path.GetFileName (audioFiles[iFile]))); + sw.WriteLine(String.Format(" TRACK {0:00} AUDIO", iFile+1)); + sw.WriteLine(String.Format(" INDEX 01 00:00:00")); + } + sw.Close(); + break; + } + } + string[] subDirs = Directory.GetDirectories(dir); + foreach (string subDir in subDirs) + { + CUECreator (subDir); + } + } + + private void btnCUECreator_Click(object sender, EventArgs e) + { + FolderBrowserDialog folderDialog = new FolderBrowserDialog(); + folderDialog.Description = "Select the folder containing the audio files without CUE sheets. Subfolders will be included automatically."; + folderDialog.ShowNewFolderButton = false; + if (folderDialog.ShowDialog() == DialogResult.OK) + { + try + { + CUECreator(folderDialog.SelectedPath); + } + catch (Exception ex) + { + ShowErrorMessage(ex); + } + } + } + } + + enum OutputPathGeneration { + CreateSubdirectory, + AppendFilename, + CustomFormat, + Disabled + } + + enum AccurateRipMode { + None, + Verify, + Offset + } +} diff --git a/CUETools/frmCUETools.resx b/CUETools/frmCUETools.resx new file mode 100644 index 0000000..e41e1cc --- /dev/null +++ b/CUETools/frmCUETools.resx @@ -0,0 +1,1488 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + 410, 290 + + + 131, 23 + + + + 5 + + + &Convert + + + btnConvert + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 11 + + + btnBrowseOutput + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 0 + + + btnBrowseInput + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 1 + + + lblOutput + + + System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 2 + + + lblInput + + + System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 3 + + + txtOutputPath + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 4 + + + txtInputPath + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 5 + + + 12, 2 + + + 534, 84 + + + 0 + + + CUE Paths + + + grpCUEPaths + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 10 + + + 461, 49 + + + 62, 23 + + + 5 + + + Browse... + + + btnBrowseOutput + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 0 + + + 461, 20 + + + 62, 23 + + + 2 + + + Browse... + + + btnBrowseInput + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 1 + + + True + + + 8, 52 + + + 45, 13 + + + 3 + + + &Output: + + + lblOutput + + + System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 2 + + + True + + + 8, 24 + + + 37, 13 + + + 0 + + + &Input: + + + lblInput + + + System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 3 + + + 51, 48 + + + 404, 21 + + + 4 + + + txtOutputPath + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 4 + + + 51, 22 + + + 404, 21 + + + 1 + + + txtInputPath + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpCUEPaths + + + 5 + + + rbEmbedCUE + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 0 + + + rbGapsLeftOut + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 1 + + + rbGapsPrepended + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 2 + + + rbGapsAppended + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 3 + + + rbSingleFile + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 4 + + + 114, 211 + + + 119, 118 + + + 3 + + + CUE Style + + + grpOutputStyle + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 9 + + + 153, 8 + + + True + + + + NoControl + + + 12, 19 + + + 57, 17 + + + 4 + + + &Embed + + + Create single file with embedded CUE sheet. Currently supported only for FLAC output + + + rbEmbedCUE + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 0 + + + True + + + 12, 87 + + + 92, 17 + + + 3 + + + Gaps Left Out + + + Create multiple files with gaps left out + + + rbGapsLeftOut + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 1 + + + True + + + 12, 70 + + + 104, 17 + + + 2 + + + Gaps Prepended + + + Create multiple files with gaps prepended + + + rbGapsPrepended + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 2 + + + True + + + 12, 53 + + + 101, 17 + + + 1 + + + Gaps &Appended + + + Create multiple files with gaps appended + + + rbGapsAppended + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 3 + + + True + + + 12, 36 + + + 106, 17 + + + 0 + + + &Single File + CUE + + + Create single file + CUE sheet + + + rbSingleFile + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputStyle + + + 4 + + + 410, 135 + + + 131, 23 + + + 9 + + + About + + + btnAbout + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 8 + + + txtCustomFormat + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 0 + + + rbCustomFormat + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 1 + + + txtCreateSubdirectory + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 2 + + + rbDontGenerate + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 3 + + + rbCreateSubdirectory + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 4 + + + rbAppendFilename + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 5 + + + txtAppendFilename + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 6 + + + 12, 92 + + + 328, 113 + + + 1 + + + Output Path + + + grpOutputPathGeneration + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 7 + + + 144, 62 + + + 178, 21 + + + 5 + + + %1:-2\New\%-1\%F.cue + + + txtCustomFormat + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 0 + + + True + + + 11, 66 + + + 119, 17 + + + 4 + + + Use custom format: + + + rbCustomFormat + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 1 + + + 144, 20 + + + 178, 21 + + + 1 + + + New + + + txtCreateSubdirectory + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 2 + + + True + + + 11, 89 + + + 59, 17 + + + 6 + + + &Manual + + + rbDontGenerate + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 3 + + + True + + + 12, 20 + + + 125, 17 + + + 0 + + + C&reate subdirectory: + + + rbCreateSubdirectory + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 4 + + + True + + + 12, 43 + + + 122, 17 + + + 2 + + + Append to filename: + + + rbAppendFilename + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 5 + + + 144, 41 + + + 178, 21 + + + 3 + + + -New + + + txtAppendFilename + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpOutputPathGeneration + + + 6 + + + rbNoAudio + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 0 + + + rbWavPack + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 1 + + + rbFLAC + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 2 + + + rbWAV + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 3 + + + 12, 211 + + + 96, 118 + + + 2 + + + Audio Output + + + grpAudioOutput + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 6 + + + True + + + 12, 71 + + + 50, 17 + + + 6 + + + &None + + + Don't create any audio files, only CUE sheet + + + rbNoAudio + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 0 + + + True + + + 12, 54 + + + 69, 17 + + + 3 + + + Wav&Pack + + + rbWavPack + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 1 + + + True + + + 12, 37 + + + 50, 17 + + + 2 + + + &FLAC + + + rbFLAC + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 2 + + + True + + + 12, 20 + + + 48, 17 + + + 1 + + + &WAV + + + rbWAV + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAudioOutput + + + 3 + + + 410, 259 + + + 131, 23 + + + 6 + + + Batch... + + + btnBatch + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 5 + + + 410, 228 + + + 131, 23 + + + 7 + + + Filename Corrector... + + + btnFilenameCorrector + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 4 + + + 410, 166 + + + 131, 23 + + + 8 + + + Advanced Settings... + + + btnSettings + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 3 + + + True + + + 6, 89 + + + 57, 13 + + + 5 + + + Data track + + + label1 + + + System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAccurateRip + + + 0 + + + 68, 86 + + + 00:00:00 + + + 0 + + + 53, 21 + + + 4 + + + Not used for normal music CDs. Enhanced CDs with data tracks cannot be found in database unless you know the length of the data track. You can often find it in EAC log. If EAC log is found next to the CUE sheet, it will be parsed automaticly and you won't have to enter anything here. + + + txtDataTrackLength + + + System.Windows.Forms.MaskedTextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAccurateRip + + + 1 + + + True + + + 11, 52 + + + 120, 17 + + + 3 + + + Verify, &then encode + + + 153, 8 + + + On the first pass, verify and try to find an offset correction which makes the rip accurate according to the AccurateRip database. On the second pass, convert, possibly applying offset correction. + + + rbArApplyOffset + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAccurateRip + + + 2 + + + True + + + 11, 35 + + + 53, 17 + + + 1 + + + &Verify + + + Contact the AccurateRip databse for validation and compare the image against database + + + rbArVerify + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAccurateRip + + + 3 + + + True + + + 11, 18 + + + 81, 17 + + + 0 + + + &Don't verify + + + Don't contact the AccurateRip database for validation + + + rbArNone + + + System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + grpAccurateRip + + + 4 + + + 238, 211 + + + 144, 118 + + + 11 + + + AccurateRip + + + grpAccurateRip + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 2 + + + 0, 339 + + + 0, 339 + + + 553, 22 + + + 14 + + + statusStrip1 + + + statusStrip1 + + + System.Windows.Forms.StatusStrip, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 1 + + + 254, 17 + + + MiddleLeft + + + 140, 16 + + + Track progress + + + 140, 16 + + + Disk progress + + + NoControl + + + 410, 197 + + + 131, 23 + + + 15 + + + CUE Sheet Creator... + + + btnCUECreator + + + System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 0 + + + True + + + 6, 13 + + + 553, 361 + + + Tahoma, 8.25pt + + + CenterScreen + + + CUE Tools + + + toolStripStatusLabel1 + + + System.Windows.Forms.ToolStripStatusLabel, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + toolStripProgressBar1 + + + System.Windows.Forms.ToolStripProgressBar, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + toolStripProgressBar2 + + + System.Windows.Forms.ToolStripProgressBar, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + toolTip1 + + + System.Windows.Forms.ToolTip, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + frmCUETools + + + System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CUETools/frmFilenameCorrector.Designer.cs b/CUETools/frmFilenameCorrector.Designer.cs new file mode 100644 index 0000000..6d21892 --- /dev/null +++ b/CUETools/frmFilenameCorrector.Designer.cs @@ -0,0 +1,63 @@ +namespace JDP { + partial class frmFilenameCorrector { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmFilenameCorrector)); + this.lblDescription = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // lblDescription + // + this.lblDescription.Location = new System.Drawing.Point(8, 8); + this.lblDescription.Name = "lblDescription"; + this.lblDescription.Size = new System.Drawing.Size(272, 144); + this.lblDescription.TabIndex = 0; + this.lblDescription.Text = resources.GetString("lblDescription.Text"); + this.lblDescription.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // frmFilenameCorrector + // + this.AllowDrop = true; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(286, 159); + this.Controls.Add(this.lblDescription); + this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.Name = "frmFilenameCorrector"; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "Filename Corrector"; + this.TopMost = true; + this.DragDrop += new System.Windows.Forms.DragEventHandler(this.frmFilenameCorrector_DragDrop); + this.DragEnter += new System.Windows.Forms.DragEventHandler(this.frmFilenameCorrector_DragEnter); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Label lblDescription; + } +} \ No newline at end of file diff --git a/CUETools/frmFilenameCorrector.cs b/CUETools/frmFilenameCorrector.cs new file mode 100644 index 0000000..2804188 --- /dev/null +++ b/CUETools/frmFilenameCorrector.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.IO; +using System.Threading; + +namespace JDP { + public partial class frmFilenameCorrector : Form { + private Thread _workThread; + + public frmFilenameCorrector() { + InitializeComponent(); + } + + private void frmFilenameCorrector_DragEnter(object sender, DragEventArgs e) { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) { + e.Effect = DragDropEffects.Copy; + } + } + + private void frmFilenameCorrector_DragDrop(object sender, DragEventArgs e) { + if ((_workThread != null) && (_workThread.IsAlive)) { + return; + } + if (e.Data.GetDataPresent(DataFormats.FileDrop)) { + _workThread = new Thread(new ParameterizedThreadStart(CorrectCUEThread)); + _workThread.Start(e.Data.GetData(DataFormats.FileDrop)); + } + } + + private void CorrectCUEThread(object p) { + string[] paths = (string[])p; + bool oneSuccess = false; + bool cancel = false; + + foreach (string path in paths) { + if (Path.GetExtension(path).ToLower() == ".cue") { + try { + string fixedCue = CUESheet.CorrectAudioFilenames(path, true); + using (StreamWriter sw = new StreamWriter(path, false, CUESheet.Encoding)) + sw.Write (fixedCue); + oneSuccess = true; + } + catch (Exception ex) { + Invoke((MethodInvoker)delegate() { + cancel = (MessageBox.Show(this, path + Environment.NewLine + + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OKCancel, + MessageBoxIcon.Error) == DialogResult.Cancel); + }); + if (cancel) break; + } + } + } + + if (oneSuccess) { + Invoke((MethodInvoker)delegate() { + MessageBox.Show(this, "Filename correction is complete!", "Done", + MessageBoxButtons.OK, MessageBoxIcon.Information); + }); + } + } + } +} \ No newline at end of file diff --git a/CUETools/frmFilenameCorrector.resx b/CUETools/frmFilenameCorrector.resx new file mode 100644 index 0000000..a2d1ab4 --- /dev/null +++ b/CUETools/frmFilenameCorrector.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Drop CUE sheets here to correct the audio filenames contained inside. The audio files must be located in the same folder as the CUE sheet. The number of audio files in that folder must match the number of files referenced by the CUE sheet. The audio files must be named such that when sorted they are in order by track number. To correct multiple CUE sheets at once, you can drop the search results for *.cue. + + \ No newline at end of file diff --git a/CUETools/frmReport.Designer.cs b/CUETools/frmReport.Designer.cs new file mode 100644 index 0000000..4f44c7f --- /dev/null +++ b/CUETools/frmReport.Designer.cs @@ -0,0 +1,79 @@ +namespace JDP +{ + partial class frmReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.button1.Location = new System.Drawing.Point(254, 322); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "Close"; + this.button1.UseVisualStyleBackColor = true; + // + // textBox1 + // + this.textBox1.BackColor = System.Drawing.SystemColors.Control; + this.textBox1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); + this.textBox1.Location = new System.Drawing.Point(21, 16); + this.textBox1.Multiline = true; + this.textBox1.Name = "textBox1"; + this.textBox1.ReadOnly = true; + this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox1.Size = new System.Drawing.Size(540, 287); + this.textBox1.TabIndex = 1; + // + // frmReport + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.button1; + this.ClientSize = new System.Drawing.Size(582, 357); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.button1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.MaximizeBox = false; + this.Name = "frmReport"; + this.Text = "Status report"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox textBox1; + } +} \ No newline at end of file diff --git a/CUETools/frmReport.cs b/CUETools/frmReport.cs new file mode 100644 index 0000000..64dfab0 --- /dev/null +++ b/CUETools/frmReport.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace JDP +{ + public partial class frmReport : Form + { + public frmReport() + { + InitializeComponent(); + } + public string Message { + get { return textBox1.Text; } + set { textBox1.Text = value; } + } + } +} \ No newline at end of file diff --git a/CUETools/frmReport.resx b/CUETools/frmReport.resx new file mode 100644 index 0000000..ff31a6d --- /dev/null +++ b/CUETools/frmReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CUETools/frmSettings.Designer.cs b/CUETools/frmSettings.Designer.cs new file mode 100644 index 0000000..51e6f56 --- /dev/null +++ b/CUETools/frmSettings.Designer.cs @@ -0,0 +1,687 @@ +namespace JDP { + partial class frmSettings { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); + System.Windows.Forms.Button btnCancel; + this.grpGeneral = new System.Windows.Forms.GroupBox(); + this.numericWriteOffset = new System.Windows.Forms.NumericUpDown(); + this.chkAutoCorrectFilenames = new System.Windows.Forms.CheckBox(); + this.chkPreserveHTOA = new System.Windows.Forms.CheckBox(); + this.lblWriteOffset = new System.Windows.Forms.Label(); + this.grpFLAC = new System.Windows.Forms.GroupBox(); + this.numericFLACCompressionLevel = new System.Windows.Forms.NumericUpDown(); + this.lblFLACCompressionLevel = new System.Windows.Forms.Label(); + this.chkFLACVerify = new System.Windows.Forms.CheckBox(); + this.btnOK = new System.Windows.Forms.Button(); + this.grpWavPack = new System.Windows.Forms.GroupBox(); + this.chkWVExtraMode = new System.Windows.Forms.CheckBox(); + this.rbWVVeryHigh = new System.Windows.Forms.RadioButton(); + this.rbWVHigh = new System.Windows.Forms.RadioButton(); + this.rbWVNormal = new System.Windows.Forms.RadioButton(); + this.rbWVFast = new System.Windows.Forms.RadioButton(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.label2 = new System.Windows.Forms.Label(); + this.numFixWhenConfidence = new System.Windows.Forms.NumericUpDown(); + this.label1 = new System.Windows.Forms.Label(); + this.numFixWhenPercent = new System.Windows.Forms.NumericUpDown(); + this.chkArAddCRCs = new System.Windows.Forms.CheckBox(); + this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); + this.grpAudioFilenames = new System.Windows.Forms.GroupBox(); + this.chkKeepOriginalFilenames = new System.Windows.Forms.CheckBox(); + this.txtSpecialExceptions = new System.Windows.Forms.TextBox(); + this.chkRemoveSpecial = new System.Windows.Forms.CheckBox(); + this.chkReplaceSpaces = new System.Windows.Forms.CheckBox(); + this.txtTrackFilenameFormat = new System.Windows.Forms.TextBox(); + this.lblTrackFilenameFormat = new System.Windows.Forms.Label(); + this.lblSingleFilenameFormat = new System.Windows.Forms.Label(); + this.txtSingleFilenameFormat = new System.Windows.Forms.TextBox(); + this.chkArSaveLog = new System.Windows.Forms.CheckBox(); + this.chkArNoUnverifiedAudio = new System.Windows.Forms.CheckBox(); + this.numWVExtraMode = new System.Windows.Forms.NumericUpDown(); + this.numEncodeWhenConfidence = new System.Windows.Forms.NumericUpDown(); + this.label3 = new System.Windows.Forms.Label(); + this.numEncodeWhenPercent = new System.Windows.Forms.NumericUpDown(); + this.label4 = new System.Windows.Forms.Label(); + this.chkArFixOffset = new System.Windows.Forms.CheckBox(); + btnCancel = new System.Windows.Forms.Button(); + this.grpGeneral.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericWriteOffset)).BeginInit(); + this.grpFLAC.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericFLACCompressionLevel)).BeginInit(); + this.grpWavPack.SuspendLayout(); + this.groupBox1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numFixWhenConfidence)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numFixWhenPercent)).BeginInit(); + this.grpAudioFilenames.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numWVExtraMode)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numEncodeWhenConfidence)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numEncodeWhenPercent)).BeginInit(); + this.SuspendLayout(); + // + // btnCancel + // + btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + btnCancel.Location = new System.Drawing.Point(267, 373); + btnCancel.Name = "btnCancel"; + btnCancel.Size = new System.Drawing.Size(73, 23); + btnCancel.TabIndex = 5; + btnCancel.Text = "Cancel"; + btnCancel.UseVisualStyleBackColor = true; + // + // grpGeneral + // + this.grpGeneral.Controls.Add(this.numericWriteOffset); + this.grpGeneral.Controls.Add(this.chkAutoCorrectFilenames); + this.grpGeneral.Controls.Add(this.chkPreserveHTOA); + this.grpGeneral.Controls.Add(this.lblWriteOffset); + this.grpGeneral.Location = new System.Drawing.Point(8, 4); + this.grpGeneral.Name = "grpGeneral"; + this.grpGeneral.Size = new System.Drawing.Size(246, 128); + this.grpGeneral.TabIndex = 0; + this.grpGeneral.TabStop = false; + this.grpGeneral.Text = "General"; + // + // numericWriteOffset + // + this.numericWriteOffset.Location = new System.Drawing.Point(133, 20); + this.numericWriteOffset.Maximum = new decimal(new int[] { + 5000, + 0, + 0, + 0}); + this.numericWriteOffset.Minimum = new decimal(new int[] { + 5000, + 0, + 0, + -2147483648}); + this.numericWriteOffset.Name = "numericWriteOffset"; + this.numericWriteOffset.Size = new System.Drawing.Size(62, 21); + this.numericWriteOffset.TabIndex = 5; + this.numericWriteOffset.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + // + // chkAutoCorrectFilenames + // + this.chkAutoCorrectFilenames.Location = new System.Drawing.Point(12, 68); + this.chkAutoCorrectFilenames.Name = "chkAutoCorrectFilenames"; + this.chkAutoCorrectFilenames.Size = new System.Drawing.Size(232, 36); + this.chkAutoCorrectFilenames.TabIndex = 3; + this.chkAutoCorrectFilenames.Text = "Preprocess with filename corrector if unable to locate audio files"; + this.chkAutoCorrectFilenames.UseVisualStyleBackColor = true; + // + // chkPreserveHTOA + // + this.chkPreserveHTOA.AutoSize = true; + this.chkPreserveHTOA.Location = new System.Drawing.Point(12, 48); + this.chkPreserveHTOA.Name = "chkPreserveHTOA"; + this.chkPreserveHTOA.Size = new System.Drawing.Size(229, 17); + this.chkPreserveHTOA.TabIndex = 2; + this.chkPreserveHTOA.Text = "Preserve HTOA for gaps appended output"; + this.chkPreserveHTOA.UseVisualStyleBackColor = true; + // + // lblWriteOffset + // + this.lblWriteOffset.AutoSize = true; + this.lblWriteOffset.Location = new System.Drawing.Point(9, 23); + this.lblWriteOffset.Name = "lblWriteOffset"; + this.lblWriteOffset.Size = new System.Drawing.Size(118, 13); + this.lblWriteOffset.TabIndex = 0; + this.lblWriteOffset.Text = "Write offset (samples):"; + // + // grpFLAC + // + this.grpFLAC.Controls.Add(this.numericFLACCompressionLevel); + this.grpFLAC.Controls.Add(this.lblFLACCompressionLevel); + this.grpFLAC.Controls.Add(this.chkFLACVerify); + this.grpFLAC.Location = new System.Drawing.Point(267, 282); + this.grpFLAC.Name = "grpFLAC"; + this.grpFLAC.Size = new System.Drawing.Size(259, 48); + this.grpFLAC.TabIndex = 1; + this.grpFLAC.TabStop = false; + this.grpFLAC.Text = "FLAC"; + // + // numericFLACCompressionLevel + // + this.numericFLACCompressionLevel.Location = new System.Drawing.Point(213, 15); + this.numericFLACCompressionLevel.Maximum = new decimal(new int[] { + 8, + 0, + 0, + 0}); + this.numericFLACCompressionLevel.Name = "numericFLACCompressionLevel"; + this.numericFLACCompressionLevel.Size = new System.Drawing.Size(35, 21); + this.numericFLACCompressionLevel.TabIndex = 4; + this.numericFLACCompressionLevel.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + this.numericFLACCompressionLevel.Value = new decimal(new int[] { + 5, + 0, + 0, + 0}); + // + // lblFLACCompressionLevel + // + this.lblFLACCompressionLevel.AutoSize = true; + this.lblFLACCompressionLevel.Location = new System.Drawing.Point(99, 17); + this.lblFLACCompressionLevel.Name = "lblFLACCompressionLevel"; + this.lblFLACCompressionLevel.Size = new System.Drawing.Size(97, 13); + this.lblFLACCompressionLevel.TabIndex = 0; + this.lblFLACCompressionLevel.Text = "Compression level:"; + // + // chkFLACVerify + // + this.chkFLACVerify.AutoSize = true; + this.chkFLACVerify.Location = new System.Drawing.Point(12, 16); + this.chkFLACVerify.Name = "chkFLACVerify"; + this.chkFLACVerify.Size = new System.Drawing.Size(54, 17); + this.chkFLACVerify.TabIndex = 2; + this.chkFLACVerify.Text = "Verify"; + this.chkFLACVerify.UseVisualStyleBackColor = true; + // + // btnOK + // + this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; + this.btnOK.Location = new System.Drawing.Point(185, 373); + this.btnOK.Name = "btnOK"; + this.btnOK.Size = new System.Drawing.Size(73, 23); + this.btnOK.TabIndex = 3; + this.btnOK.Text = "OK"; + this.btnOK.UseVisualStyleBackColor = true; + this.btnOK.Click += new System.EventHandler(this.btnOK_Click); + // + // grpWavPack + // + this.grpWavPack.Controls.Add(this.numWVExtraMode); + this.grpWavPack.Controls.Add(this.chkWVExtraMode); + this.grpWavPack.Controls.Add(this.rbWVVeryHigh); + this.grpWavPack.Controls.Add(this.rbWVHigh); + this.grpWavPack.Controls.Add(this.rbWVNormal); + this.grpWavPack.Controls.Add(this.rbWVFast); + this.grpWavPack.Location = new System.Drawing.Point(267, 182); + this.grpWavPack.Name = "grpWavPack"; + this.grpWavPack.Size = new System.Drawing.Size(259, 94); + this.grpWavPack.TabIndex = 2; + this.grpWavPack.TabStop = false; + this.grpWavPack.Text = "WavPack"; + // + // chkWVExtraMode + // + this.chkWVExtraMode.AutoSize = true; + this.chkWVExtraMode.Location = new System.Drawing.Point(94, 20); + this.chkWVExtraMode.Name = "chkWVExtraMode"; + this.chkWVExtraMode.Size = new System.Drawing.Size(112, 17); + this.chkWVExtraMode.TabIndex = 4; + this.chkWVExtraMode.Text = "Extra mode (1-6):"; + this.chkWVExtraMode.UseVisualStyleBackColor = true; + this.chkWVExtraMode.CheckedChanged += new System.EventHandler(this.chkWVExtraMode_CheckedChanged); + // + // rbWVVeryHigh + // + this.rbWVVeryHigh.AutoSize = true; + this.rbWVVeryHigh.Location = new System.Drawing.Point(13, 70); + this.rbWVVeryHigh.Name = "rbWVVeryHigh"; + this.rbWVVeryHigh.Size = new System.Drawing.Size(71, 17); + this.rbWVVeryHigh.TabIndex = 3; + this.rbWVVeryHigh.Text = "Very High"; + this.rbWVVeryHigh.UseVisualStyleBackColor = true; + // + // rbWVHigh + // + this.rbWVHigh.AutoSize = true; + this.rbWVHigh.Location = new System.Drawing.Point(13, 53); + this.rbWVHigh.Name = "rbWVHigh"; + this.rbWVHigh.Size = new System.Drawing.Size(46, 17); + this.rbWVHigh.TabIndex = 1; + this.rbWVHigh.Text = "High"; + this.rbWVHigh.UseVisualStyleBackColor = true; + // + // rbWVNormal + // + this.rbWVNormal.AutoSize = true; + this.rbWVNormal.Checked = true; + this.rbWVNormal.Location = new System.Drawing.Point(13, 36); + this.rbWVNormal.Name = "rbWVNormal"; + this.rbWVNormal.Size = new System.Drawing.Size(58, 17); + this.rbWVNormal.TabIndex = 2; + this.rbWVNormal.TabStop = true; + this.rbWVNormal.Text = "Normal"; + this.rbWVNormal.UseVisualStyleBackColor = true; + // + // rbWVFast + // + this.rbWVFast.AutoSize = true; + this.rbWVFast.Location = new System.Drawing.Point(13, 19); + this.rbWVFast.Name = "rbWVFast"; + this.rbWVFast.Size = new System.Drawing.Size(46, 17); + this.rbWVFast.TabIndex = 0; + this.rbWVFast.Text = "Fast"; + this.rbWVFast.UseVisualStyleBackColor = true; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.chkArFixOffset); + this.groupBox1.Controls.Add(this.label4); + this.groupBox1.Controls.Add(this.numEncodeWhenPercent); + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.numEncodeWhenConfidence); + this.groupBox1.Controls.Add(this.chkArNoUnverifiedAudio); + this.groupBox1.Controls.Add(this.chkArSaveLog); + this.groupBox1.Controls.Add(this.label2); + this.groupBox1.Controls.Add(this.numFixWhenConfidence); + this.groupBox1.Controls.Add(this.label1); + this.groupBox1.Controls.Add(this.numFixWhenPercent); + this.groupBox1.Controls.Add(this.chkArAddCRCs); + this.groupBox1.Location = new System.Drawing.Point(267, 4); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(259, 172); + this.groupBox1.TabIndex = 4; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "AccurateRip"; + // + // label2 + // + this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(62, 146); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(101, 13); + this.label2.TabIndex = 5; + this.label2.Text = "with confidence >="; + // + // numFixWhenConfidence + // + this.numFixWhenConfidence.Location = new System.Drawing.Point(168, 144); + this.numFixWhenConfidence.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numFixWhenConfidence.Name = "numFixWhenConfidence"; + this.numFixWhenConfidence.Size = new System.Drawing.Size(37, 21); + this.numFixWhenConfidence.TabIndex = 4; + this.numFixWhenConfidence.Value = new decimal(new int[] { + 1, + 0, + 0, + 0}); + // + // label1 + // + this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(42, 125); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(121, 13); + this.label1.TabIndex = 3; + this.label1.Text = "% of verified tracks >="; + // + // numFixWhenPercent + // + this.numFixWhenPercent.Increment = new decimal(new int[] { + 5, + 0, + 0, + 0}); + this.numFixWhenPercent.Location = new System.Drawing.Point(168, 123); + this.numFixWhenPercent.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numFixWhenPercent.Name = "numFixWhenPercent"; + this.numFixWhenPercent.Size = new System.Drawing.Size(38, 21); + this.numFixWhenPercent.TabIndex = 2; + this.numFixWhenPercent.Value = new decimal(new int[] { + 51, + 0, + 0, + 0}); + // + // chkArAddCRCs + // + this.chkArAddCRCs.AutoSize = true; + this.chkArAddCRCs.Checked = true; + this.chkArAddCRCs.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkArAddCRCs.Location = new System.Drawing.Point(12, 21); + this.chkArAddCRCs.Name = "chkArAddCRCs"; + this.chkArAddCRCs.Size = new System.Drawing.Size(76, 17); + this.chkArAddCRCs.TabIndex = 1; + this.chkArAddCRCs.Text = "Write tags"; + this.toolTip1.SetToolTip(this.chkArAddCRCs, "When using \"apply offset\" AccurateRip mode, also add ACCURATERIPCOUNT tag to flac" + + " files. You can set up foobar2000 to show this value, and see if your music was " + + "ripped correctly or how popular it is."); + this.chkArAddCRCs.UseVisualStyleBackColor = true; + // + // toolTip1 + // + this.toolTip1.AutoPopDelay = 15000; + this.toolTip1.InitialDelay = 500; + this.toolTip1.ReshowDelay = 100; + // + // grpAudioFilenames + // + this.grpAudioFilenames.Controls.Add(this.chkKeepOriginalFilenames); + this.grpAudioFilenames.Controls.Add(this.txtSpecialExceptions); + this.grpAudioFilenames.Controls.Add(this.chkRemoveSpecial); + this.grpAudioFilenames.Controls.Add(this.chkReplaceSpaces); + this.grpAudioFilenames.Controls.Add(this.txtTrackFilenameFormat); + this.grpAudioFilenames.Controls.Add(this.lblTrackFilenameFormat); + this.grpAudioFilenames.Controls.Add(this.lblSingleFilenameFormat); + this.grpAudioFilenames.Controls.Add(this.txtSingleFilenameFormat); + this.grpAudioFilenames.Location = new System.Drawing.Point(12, 138); + this.grpAudioFilenames.Name = "grpAudioFilenames"; + this.grpAudioFilenames.Size = new System.Drawing.Size(246, 192); + this.grpAudioFilenames.TabIndex = 6; + this.grpAudioFilenames.TabStop = false; + this.grpAudioFilenames.Text = "Audio Filenames"; + // + // chkKeepOriginalFilenames + // + this.chkKeepOriginalFilenames.AutoSize = true; + this.chkKeepOriginalFilenames.Checked = true; + this.chkKeepOriginalFilenames.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkKeepOriginalFilenames.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.chkKeepOriginalFilenames.Location = new System.Drawing.Point(12, 20); + this.chkKeepOriginalFilenames.Name = "chkKeepOriginalFilenames"; + this.chkKeepOriginalFilenames.Size = new System.Drawing.Size(135, 17); + this.chkKeepOriginalFilenames.TabIndex = 0; + this.chkKeepOriginalFilenames.Text = "Keep original filenames"; + this.chkKeepOriginalFilenames.UseVisualStyleBackColor = true; + // + // txtSpecialExceptions + // + this.txtSpecialExceptions.Location = new System.Drawing.Point(92, 123); + this.txtSpecialExceptions.Name = "txtSpecialExceptions"; + this.txtSpecialExceptions.Size = new System.Drawing.Size(136, 21); + this.txtSpecialExceptions.TabIndex = 6; + this.txtSpecialExceptions.Text = "-()"; + // + // chkRemoveSpecial + // + this.chkRemoveSpecial.AutoSize = true; + this.chkRemoveSpecial.Checked = true; + this.chkRemoveSpecial.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkRemoveSpecial.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.chkRemoveSpecial.Location = new System.Drawing.Point(12, 100); + this.chkRemoveSpecial.Name = "chkRemoveSpecial"; + this.chkRemoveSpecial.Size = new System.Drawing.Size(194, 17); + this.chkRemoveSpecial.TabIndex = 5; + this.chkRemoveSpecial.Text = "Remove special characters except:"; + this.chkRemoveSpecial.UseVisualStyleBackColor = true; + // + // chkReplaceSpaces + // + this.chkReplaceSpaces.AutoSize = true; + this.chkReplaceSpaces.Checked = true; + this.chkReplaceSpaces.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkReplaceSpaces.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.chkReplaceSpaces.Location = new System.Drawing.Point(12, 150); + this.chkReplaceSpaces.Name = "chkReplaceSpaces"; + this.chkReplaceSpaces.Size = new System.Drawing.Size(185, 17); + this.chkReplaceSpaces.TabIndex = 7; + this.chkReplaceSpaces.Text = "Replace spaces with underscores"; + this.chkReplaceSpaces.UseVisualStyleBackColor = true; + // + // txtTrackFilenameFormat + // + this.txtTrackFilenameFormat.Location = new System.Drawing.Point(92, 72); + this.txtTrackFilenameFormat.Name = "txtTrackFilenameFormat"; + this.txtTrackFilenameFormat.Size = new System.Drawing.Size(136, 21); + this.txtTrackFilenameFormat.TabIndex = 4; + this.txtTrackFilenameFormat.Text = "%N-%A-%T"; + // + // lblTrackFilenameFormat + // + this.lblTrackFilenameFormat.AutoSize = true; + this.lblTrackFilenameFormat.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.lblTrackFilenameFormat.Location = new System.Drawing.Point(10, 76); + this.lblTrackFilenameFormat.Name = "lblTrackFilenameFormat"; + this.lblTrackFilenameFormat.Size = new System.Drawing.Size(72, 13); + this.lblTrackFilenameFormat.TabIndex = 3; + this.lblTrackFilenameFormat.Text = "Track format:"; + // + // lblSingleFilenameFormat + // + this.lblSingleFilenameFormat.AutoSize = true; + this.lblSingleFilenameFormat.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.lblSingleFilenameFormat.Location = new System.Drawing.Point(10, 48); + this.lblSingleFilenameFormat.Name = "lblSingleFilenameFormat"; + this.lblSingleFilenameFormat.Size = new System.Drawing.Size(74, 13); + this.lblSingleFilenameFormat.TabIndex = 1; + this.lblSingleFilenameFormat.Text = "Single format:"; + // + // txtSingleFilenameFormat + // + this.txtSingleFilenameFormat.Location = new System.Drawing.Point(92, 44); + this.txtSingleFilenameFormat.Name = "txtSingleFilenameFormat"; + this.txtSingleFilenameFormat.Size = new System.Drawing.Size(136, 21); + this.txtSingleFilenameFormat.TabIndex = 2; + this.txtSingleFilenameFormat.Text = "%F"; + // + // chkArSaveLog + // + this.chkArSaveLog.AutoSize = true; + this.chkArSaveLog.Checked = true; + this.chkArSaveLog.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkArSaveLog.Location = new System.Drawing.Point(94, 21); + this.chkArSaveLog.Name = "chkArSaveLog"; + this.chkArSaveLog.Size = new System.Drawing.Size(69, 17); + this.chkArSaveLog.TabIndex = 6; + this.chkArSaveLog.Text = "Write log"; + this.chkArSaveLog.UseVisualStyleBackColor = true; + // + // chkArNoUnverifiedAudio + // + this.chkArNoUnverifiedAudio.AutoSize = true; + this.chkArNoUnverifiedAudio.Checked = true; + this.chkArNoUnverifiedAudio.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkArNoUnverifiedAudio.Location = new System.Drawing.Point(12, 44); + this.chkArNoUnverifiedAudio.Name = "chkArNoUnverifiedAudio"; + this.chkArNoUnverifiedAudio.Size = new System.Drawing.Size(93, 17); + this.chkArNoUnverifiedAudio.TabIndex = 7; + this.chkArNoUnverifiedAudio.Text = "Encode only if"; + this.chkArNoUnverifiedAudio.UseVisualStyleBackColor = true; + this.chkArNoUnverifiedAudio.CheckedChanged += new System.EventHandler(this.chkArNoUnverifiedAudio_CheckedChanged); + // + // numWVExtraMode + // + this.numWVExtraMode.Location = new System.Drawing.Point(212, 19); + this.numWVExtraMode.Maximum = new decimal(new int[] { + 6, + 0, + 0, + 0}); + this.numWVExtraMode.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numWVExtraMode.Name = "numWVExtraMode"; + this.numWVExtraMode.Size = new System.Drawing.Size(29, 21); + this.numWVExtraMode.TabIndex = 5; + this.numWVExtraMode.Value = new decimal(new int[] { + 1, + 0, + 0, + 0}); + // + // numEncodeWhenConfidence + // + this.numEncodeWhenConfidence.Location = new System.Drawing.Point(168, 87); + this.numEncodeWhenConfidence.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numEncodeWhenConfidence.Name = "numEncodeWhenConfidence"; + this.numEncodeWhenConfidence.Size = new System.Drawing.Size(38, 21); + this.numEncodeWhenConfidence.TabIndex = 8; + this.numEncodeWhenConfidence.Value = new decimal(new int[] { + 1, + 0, + 0, + 0}); + // + // label3 + // + this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(62, 89); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(101, 13); + this.label3.TabIndex = 9; + this.label3.Text = "with confidence >="; + // + // numEncodeWhenPercent + // + this.numEncodeWhenPercent.Increment = new decimal(new int[] { + 5, + 0, + 0, + 0}); + this.numEncodeWhenPercent.Location = new System.Drawing.Point(168, 66); + this.numEncodeWhenPercent.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numEncodeWhenPercent.Name = "numEncodeWhenPercent"; + this.numEncodeWhenPercent.Size = new System.Drawing.Size(38, 21); + this.numEncodeWhenPercent.TabIndex = 10; + this.numEncodeWhenPercent.Value = new decimal(new int[] { + 100, + 0, + 0, + 0}); + // + // label4 + // + this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(41, 68); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(121, 13); + this.label4.TabIndex = 11; + this.label4.Text = "% of verified tracks >="; + // + // chkArFixOffset + // + this.chkArFixOffset.AutoSize = true; + this.chkArFixOffset.Checked = true; + this.chkArFixOffset.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkArFixOffset.Location = new System.Drawing.Point(12, 105); + this.chkArFixOffset.Name = "chkArFixOffset"; + this.chkArFixOffset.Size = new System.Drawing.Size(81, 17); + this.chkArFixOffset.TabIndex = 12; + this.chkArFixOffset.Text = "Fix offset if"; + this.chkArFixOffset.UseVisualStyleBackColor = true; + this.chkArFixOffset.CheckedChanged += new System.EventHandler(this.chkArFixOffset_CheckedChanged); + // + // frmSettings + // + this.AcceptButton = this.btnOK; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = btnCancel; + this.ClientSize = new System.Drawing.Size(540, 430); + this.Controls.Add(this.grpAudioFilenames); + this.Controls.Add(btnCancel); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.grpWavPack); + this.Controls.Add(this.btnOK); + this.Controls.Add(this.grpFLAC); + this.Controls.Add(this.grpGeneral); + this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.Name = "frmSettings"; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "Advanced Settings"; + this.Load += new System.EventHandler(this.frmSettings_Load); + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmSettings_FormClosing); + this.grpGeneral.ResumeLayout(false); + this.grpGeneral.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericWriteOffset)).EndInit(); + this.grpFLAC.ResumeLayout(false); + this.grpFLAC.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericFLACCompressionLevel)).EndInit(); + this.grpWavPack.ResumeLayout(false); + this.grpWavPack.PerformLayout(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numFixWhenConfidence)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numFixWhenPercent)).EndInit(); + this.grpAudioFilenames.ResumeLayout(false); + this.grpAudioFilenames.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numWVExtraMode)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numEncodeWhenConfidence)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numEncodeWhenPercent)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox grpGeneral; + private System.Windows.Forms.CheckBox chkPreserveHTOA; + private System.Windows.Forms.Label lblWriteOffset; + private System.Windows.Forms.GroupBox grpFLAC; + private System.Windows.Forms.Label lblFLACCompressionLevel; + private System.Windows.Forms.CheckBox chkFLACVerify; + private System.Windows.Forms.Button btnOK; + private System.Windows.Forms.GroupBox grpWavPack; + private System.Windows.Forms.RadioButton rbWVVeryHigh; + private System.Windows.Forms.RadioButton rbWVHigh; + private System.Windows.Forms.RadioButton rbWVNormal; + private System.Windows.Forms.RadioButton rbWVFast; + private System.Windows.Forms.CheckBox chkWVExtraMode; + private System.Windows.Forms.CheckBox chkAutoCorrectFilenames; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.CheckBox chkArAddCRCs; + private System.Windows.Forms.NumericUpDown numericFLACCompressionLevel; + private System.Windows.Forms.NumericUpDown numericWriteOffset; + private System.Windows.Forms.ToolTip toolTip1; + private System.Windows.Forms.NumericUpDown numFixWhenPercent; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.NumericUpDown numFixWhenConfidence; + private System.Windows.Forms.GroupBox grpAudioFilenames; + private System.Windows.Forms.CheckBox chkKeepOriginalFilenames; + private System.Windows.Forms.TextBox txtSpecialExceptions; + private System.Windows.Forms.CheckBox chkRemoveSpecial; + private System.Windows.Forms.CheckBox chkReplaceSpaces; + private System.Windows.Forms.TextBox txtTrackFilenameFormat; + private System.Windows.Forms.Label lblTrackFilenameFormat; + private System.Windows.Forms.Label lblSingleFilenameFormat; + private System.Windows.Forms.TextBox txtSingleFilenameFormat; + private System.Windows.Forms.CheckBox chkArNoUnverifiedAudio; + private System.Windows.Forms.CheckBox chkArSaveLog; + private System.Windows.Forms.NumericUpDown numWVExtraMode; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.NumericUpDown numEncodeWhenConfidence; + private System.Windows.Forms.NumericUpDown numEncodeWhenPercent; + private System.Windows.Forms.CheckBox chkArFixOffset; + private System.Windows.Forms.Label label4; + + } +} \ No newline at end of file diff --git a/CUETools/frmSettings.cs b/CUETools/frmSettings.cs new file mode 100644 index 0000000..7ef20d4 --- /dev/null +++ b/CUETools/frmSettings.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace JDP { + public partial class frmSettings : Form { + int _writeOffset; + CUEConfig _config; + + public frmSettings() { + InitializeComponent(); + } + + private void frmSettings_Load(object sender, EventArgs e) { + numericWriteOffset.Value = _writeOffset; + chkPreserveHTOA.Checked = _config.preserveHTOA; + chkAutoCorrectFilenames.Checked = _config.autoCorrectFilenames; + numericFLACCompressionLevel.Value = _config.flacCompressionLevel; + numFixWhenConfidence.Value = _config.fixWhenConfidence; + numFixWhenPercent.Value = _config.fixWhenPercent; + numEncodeWhenConfidence.Value = _config.encodeWhenConfidence; + numEncodeWhenPercent.Value = _config.encodeWhenPercent; + chkFLACVerify.Checked = _config.flacVerify; + chkArAddCRCs.Checked = _config.writeCRC; + if (_config.wvCompressionMode == 0) rbWVFast.Checked = true; + if (_config.wvCompressionMode == 1) rbWVNormal.Checked = true; + if (_config.wvCompressionMode == 2) rbWVHigh.Checked = true; + if (_config.wvCompressionMode == 3) rbWVVeryHigh.Checked = true; + chkWVExtraMode.Checked = (_config.wvExtraMode != 0); + chkWVExtraMode_CheckedChanged(null, null); + if (_config.wvExtraMode != 0) numWVExtraMode.Value = _config.wvExtraMode; + chkKeepOriginalFilenames.Checked = _config.keepOriginalFilenames; + txtSingleFilenameFormat.Text = _config.singleFilenameFormat; + txtTrackFilenameFormat.Text = _config.trackFilenameFormat; + chkRemoveSpecial.Checked = _config.removeSpecial; + txtSpecialExceptions.Text = _config.specialExceptions; + chkReplaceSpaces.Checked = _config.replaceSpaces; + chkArSaveLog.Checked = _config.writeArLog; + chkArNoUnverifiedAudio.Checked = _config.noUnverifiedOutput; + chkArFixOffset.Checked = _config.fixOffset; + } + + private void frmSettings_FormClosing(object sender, FormClosingEventArgs e) { + } + + public int WriteOffset { + get { return _writeOffset; } + set { _writeOffset = value; } + } + + public CUEConfig Config { + get { return _config; } + set { _config = value; } + } + + private void chkWVExtraMode_CheckedChanged(object sender, EventArgs e) { + if (chkWVExtraMode.Checked) { + numWVExtraMode.Enabled = true; + } + else { + numWVExtraMode.Enabled = false; + } + } + + private void btnOK_Click(object sender, EventArgs e) + { + _writeOffset = (int)numericWriteOffset.Value; + _config.preserveHTOA = chkPreserveHTOA.Checked; + _config.autoCorrectFilenames = chkAutoCorrectFilenames.Checked; + _config.flacCompressionLevel = (uint)numericFLACCompressionLevel.Value; + _config.fixWhenPercent = (uint)numFixWhenPercent.Value; + _config.fixWhenConfidence = (uint)numFixWhenConfidence.Value; + _config.encodeWhenPercent = (uint)numEncodeWhenPercent.Value; + _config.encodeWhenConfidence = (uint)numEncodeWhenConfidence.Value; + _config.flacVerify = chkFLACVerify.Checked; + _config.writeCRC = chkArAddCRCs.Checked; + if (rbWVFast.Checked) _config.wvCompressionMode = 0; + else if (rbWVHigh.Checked) _config.wvCompressionMode = 2; + else if (rbWVVeryHigh.Checked) _config.wvCompressionMode = 3; + else _config.wvCompressionMode = 1; + if (!chkWVExtraMode.Checked) _config.wvExtraMode = 0; + else _config.wvExtraMode = (int) numWVExtraMode.Value; + _config.keepOriginalFilenames = chkKeepOriginalFilenames.Checked; + _config.singleFilenameFormat = txtSingleFilenameFormat.Text; + _config.trackFilenameFormat = txtTrackFilenameFormat.Text; + _config.removeSpecial = chkRemoveSpecial.Checked; + _config.specialExceptions = txtSpecialExceptions.Text; + _config.replaceSpaces = chkReplaceSpaces.Checked; + _config.writeArLog = chkArSaveLog.Checked; + _config.noUnverifiedOutput = chkArNoUnverifiedAudio.Checked; + _config.fixOffset = chkArFixOffset.Checked; + } + + private void chkArFixOffset_CheckedChanged(object sender, EventArgs e) + { + numFixWhenConfidence.Enabled = chkArFixOffset.Checked; + numFixWhenPercent.Enabled = chkArFixOffset.Checked; + } + + private void chkArNoUnverifiedAudio_CheckedChanged(object sender, EventArgs e) + { + numEncodeWhenConfidence.Enabled = chkArNoUnverifiedAudio.Checked; + numEncodeWhenPercent.Enabled = chkArNoUnverifiedAudio.Checked; + } + } +} \ No newline at end of file diff --git a/CUETools/frmSettings.resx b/CUETools/frmSettings.resx new file mode 100644 index 0000000..c41c4d2 --- /dev/null +++ b/CUETools/frmSettings.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + False + + + 17, 17 + + + 17, 17 + + \ No newline at end of file diff --git a/CUETools/obj/CUETools.csproj.FileListAbsolute.txt b/CUETools/obj/CUETools.csproj.FileListAbsolute.txt new file mode 100644 index 0000000..2aced4e --- /dev/null +++ b/CUETools/obj/CUETools.csproj.FileListAbsolute.txt @@ -0,0 +1,40 @@ +C:\Work\bin\x64\Release\CUETools.exe.config +C:\Work\bin\x64\Release\CUETools.exe +C:\Work\bin\x64\Release\CUETools.pdb +C:\Work\CUETools\obj\x64\Release\ResolveAssemblyReference.cache +C:\Work\CUETools\obj\x64\Release\JDP.frmBatch.resources +C:\Work\CUETools\obj\x64\Release\JDP.frmCUETools.resources +C:\Work\CUETools\obj\x64\Release\JDP.frmFilenameCorrector.resources +C:\Work\CUETools\obj\x64\Release\JDP.frmReport.resources +C:\Work\CUETools\obj\x64\Release\JDP.frmSettings.resources +C:\Work\CUETools\obj\x64\Release\JDP.Properties.Resources.resources +C:\Work\CUETools\obj\x64\Release\CUETools.csproj.GenerateResource.Cache +C:\Work\CUETools\obj\x64\Release\CUETools.exe +C:\Work\CUETools\obj\x64\Release\CUETools.pdb +C:\Work\bin\win32\Release\CUETools.exe.config +C:\Work\CUETools\obj\x86\Release\ResolveAssemblyReference.cache +C:\Work\CUETools\obj\x86\Release\JDP.frmBatch.resources +C:\Work\CUETools\obj\x86\Release\JDP.frmCUETools.resources +C:\Work\CUETools\obj\x86\Release\JDP.frmFilenameCorrector.resources +C:\Work\CUETools\obj\x86\Release\JDP.frmReport.resources +C:\Work\CUETools\obj\x86\Release\JDP.frmSettings.resources +C:\Work\CUETools\obj\x86\Release\JDP.Properties.Resources.resources +C:\Work\CUETools\obj\x86\Release\CUETools.csproj.GenerateResource.Cache +C:\Work\bin\win32\Release\CUETools.exe +C:\Work\bin\win32\Release\CUETools.pdb +C:\Work\CUETools\obj\x86\Release\CUETools.exe +C:\Work\CUETools\obj\x86\Release\CUETools.pdb +C:\Work\bin\win32\Debug\CUETools.exe.config +C:\Work\bin\x64\Debug\CUETools.exe.config +C:\Work\CUETools\obj\x86\Debug\ResolveAssemblyReference.cache +C:\Work\CUETools\obj\x86\Debug\JDP.frmBatch.resources +C:\Work\CUETools\obj\x86\Debug\JDP.frmCUETools.resources +C:\Work\CUETools\obj\x86\Debug\JDP.frmFilenameCorrector.resources +C:\Work\CUETools\obj\x86\Debug\JDP.frmReport.resources +C:\Work\CUETools\obj\x86\Debug\JDP.frmSettings.resources +C:\Work\CUETools\obj\x86\Debug\JDP.Properties.Resources.resources +C:\Work\CUETools\obj\x86\Debug\CUETools.csproj.GenerateResource.Cache +C:\Work\bin\win32\Debug\CUETools.exe +C:\Work\bin\win32\Debug\CUETools.pdb +C:\Work\CUETools\obj\x86\Debug\CUETools.exe +C:\Work\CUETools\obj\x86\Debug\CUETools.pdb diff --git a/CUETools/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..6712707 Binary files /dev/null and b/CUETools/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/Debug/build.force b/CUETools/obj/Debug/build.force new file mode 100644 index 0000000..e69de29 diff --git a/CUETools/obj/Release/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/Release/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..4d5f80c Binary files /dev/null and b/CUETools/obj/Release/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/Release/build.force b/CUETools/obj/Release/build.force new file mode 100644 index 0000000..e69de29 diff --git a/CUETools/obj/x64/Debug/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/x64/Debug/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..d4df47e Binary files /dev/null and b/CUETools/obj/x64/Debug/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/x64/Debug/build.force b/CUETools/obj/x64/Debug/build.force new file mode 100644 index 0000000..e69de29 diff --git a/CUETools/obj/x64/Release/CUETools.csproj.GenerateResource.Cache b/CUETools/obj/x64/Release/CUETools.csproj.GenerateResource.Cache new file mode 100644 index 0000000..e575237 Binary files /dev/null and b/CUETools/obj/x64/Release/CUETools.csproj.GenerateResource.Cache differ diff --git a/CUETools/obj/x64/Release/CUETools.exe b/CUETools/obj/x64/Release/CUETools.exe new file mode 100644 index 0000000..8eacbf9 Binary files /dev/null and b/CUETools/obj/x64/Release/CUETools.exe differ diff --git a/CUETools/obj/x64/Release/CUETools.pdb b/CUETools/obj/x64/Release/CUETools.pdb new file mode 100644 index 0000000..3a0bfc3 Binary files /dev/null and b/CUETools/obj/x64/Release/CUETools.pdb differ diff --git a/CUETools/obj/x64/Release/JDP.Properties.Resources.resources b/CUETools/obj/x64/Release/JDP.Properties.Resources.resources new file mode 100644 index 0000000..09c7a79 Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.Properties.Resources.resources differ diff --git a/CUETools/obj/x64/Release/JDP.frmBatch.resources b/CUETools/obj/x64/Release/JDP.frmBatch.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.frmBatch.resources differ diff --git a/CUETools/obj/x64/Release/JDP.frmCUETools.resources b/CUETools/obj/x64/Release/JDP.frmCUETools.resources new file mode 100644 index 0000000..7352f82 Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.frmCUETools.resources differ diff --git a/CUETools/obj/x64/Release/JDP.frmFilenameCorrector.resources b/CUETools/obj/x64/Release/JDP.frmFilenameCorrector.resources new file mode 100644 index 0000000..ac142fd Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.frmFilenameCorrector.resources differ diff --git a/CUETools/obj/x64/Release/JDP.frmReport.resources b/CUETools/obj/x64/Release/JDP.frmReport.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.frmReport.resources differ diff --git a/CUETools/obj/x64/Release/JDP.frmSettings.resources b/CUETools/obj/x64/Release/JDP.frmSettings.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x64/Release/JDP.frmSettings.resources differ diff --git a/CUETools/obj/x64/Release/ResolveAssemblyReference.cache b/CUETools/obj/x64/Release/ResolveAssemblyReference.cache new file mode 100644 index 0000000..6f21a73 Binary files /dev/null and b/CUETools/obj/x64/Release/ResolveAssemblyReference.cache differ diff --git a/CUETools/obj/x64/Release/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/x64/Release/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..ad4fc40 Binary files /dev/null and b/CUETools/obj/x64/Release/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/x64/Release/build.force b/CUETools/obj/x64/Release/build.force new file mode 100644 index 0000000..e69de29 diff --git a/CUETools/obj/x86/Debug/CUETools.csproj.GenerateResource.Cache b/CUETools/obj/x86/Debug/CUETools.csproj.GenerateResource.Cache new file mode 100644 index 0000000..e575237 Binary files /dev/null and b/CUETools/obj/x86/Debug/CUETools.csproj.GenerateResource.Cache differ diff --git a/CUETools/obj/x86/Debug/CUETools.exe b/CUETools/obj/x86/Debug/CUETools.exe new file mode 100644 index 0000000..c73e50f Binary files /dev/null and b/CUETools/obj/x86/Debug/CUETools.exe differ diff --git a/CUETools/obj/x86/Debug/CUETools.pdb b/CUETools/obj/x86/Debug/CUETools.pdb new file mode 100644 index 0000000..8ab8adc Binary files /dev/null and b/CUETools/obj/x86/Debug/CUETools.pdb differ diff --git a/CUETools/obj/x86/Debug/JDP.Properties.Resources.resources b/CUETools/obj/x86/Debug/JDP.Properties.Resources.resources new file mode 100644 index 0000000..09c7a79 Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.Properties.Resources.resources differ diff --git a/CUETools/obj/x86/Debug/JDP.frmBatch.resources b/CUETools/obj/x86/Debug/JDP.frmBatch.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.frmBatch.resources differ diff --git a/CUETools/obj/x86/Debug/JDP.frmCUETools.resources b/CUETools/obj/x86/Debug/JDP.frmCUETools.resources new file mode 100644 index 0000000..7352f82 Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.frmCUETools.resources differ diff --git a/CUETools/obj/x86/Debug/JDP.frmFilenameCorrector.resources b/CUETools/obj/x86/Debug/JDP.frmFilenameCorrector.resources new file mode 100644 index 0000000..ac142fd Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.frmFilenameCorrector.resources differ diff --git a/CUETools/obj/x86/Debug/JDP.frmReport.resources b/CUETools/obj/x86/Debug/JDP.frmReport.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.frmReport.resources differ diff --git a/CUETools/obj/x86/Debug/JDP.frmSettings.resources b/CUETools/obj/x86/Debug/JDP.frmSettings.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Debug/JDP.frmSettings.resources differ diff --git a/CUETools/obj/x86/Debug/ResolveAssemblyReference.cache b/CUETools/obj/x86/Debug/ResolveAssemblyReference.cache new file mode 100644 index 0000000..9c67f16 Binary files /dev/null and b/CUETools/obj/x86/Debug/ResolveAssemblyReference.cache differ diff --git a/CUETools/obj/x86/Debug/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/x86/Debug/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..9072741 Binary files /dev/null and b/CUETools/obj/x86/Debug/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/x86/Release/CUETools.csproj.GenerateResource.Cache b/CUETools/obj/x86/Release/CUETools.csproj.GenerateResource.Cache new file mode 100644 index 0000000..e575237 Binary files /dev/null and b/CUETools/obj/x86/Release/CUETools.csproj.GenerateResource.Cache differ diff --git a/CUETools/obj/x86/Release/CUETools.exe b/CUETools/obj/x86/Release/CUETools.exe new file mode 100644 index 0000000..385e99e Binary files /dev/null and b/CUETools/obj/x86/Release/CUETools.exe differ diff --git a/CUETools/obj/x86/Release/CUETools.pdb b/CUETools/obj/x86/Release/CUETools.pdb new file mode 100644 index 0000000..e381d4d Binary files /dev/null and b/CUETools/obj/x86/Release/CUETools.pdb differ diff --git a/CUETools/obj/x86/Release/JDP.Properties.Resources.resources b/CUETools/obj/x86/Release/JDP.Properties.Resources.resources new file mode 100644 index 0000000..09c7a79 Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.Properties.Resources.resources differ diff --git a/CUETools/obj/x86/Release/JDP.frmBatch.resources b/CUETools/obj/x86/Release/JDP.frmBatch.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.frmBatch.resources differ diff --git a/CUETools/obj/x86/Release/JDP.frmCUETools.resources b/CUETools/obj/x86/Release/JDP.frmCUETools.resources new file mode 100644 index 0000000..7352f82 Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.frmCUETools.resources differ diff --git a/CUETools/obj/x86/Release/JDP.frmFilenameCorrector.resources b/CUETools/obj/x86/Release/JDP.frmFilenameCorrector.resources new file mode 100644 index 0000000..ac142fd Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.frmFilenameCorrector.resources differ diff --git a/CUETools/obj/x86/Release/JDP.frmReport.resources b/CUETools/obj/x86/Release/JDP.frmReport.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.frmReport.resources differ diff --git a/CUETools/obj/x86/Release/JDP.frmSettings.resources b/CUETools/obj/x86/Release/JDP.frmSettings.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/CUETools/obj/x86/Release/JDP.frmSettings.resources differ diff --git a/CUETools/obj/x86/Release/ResolveAssemblyReference.cache b/CUETools/obj/x86/Release/ResolveAssemblyReference.cache new file mode 100644 index 0000000..fb88e5c Binary files /dev/null and b/CUETools/obj/x86/Release/ResolveAssemblyReference.cache differ diff --git a/CUETools/obj/x86/Release/TempPE/Properties.Resources.Designer.cs.dll b/CUETools/obj/x86/Release/TempPE/Properties.Resources.Designer.cs.dll new file mode 100644 index 0000000..68fb03d Binary files /dev/null and b/CUETools/obj/x86/Release/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/CUETools/obj/x86/Release/build.force b/CUETools/obj/x86/Release/build.force new file mode 100644 index 0000000..e69de29 diff --git a/CUETools/tmp.cs b/CUETools/tmp.cs new file mode 100644 index 0000000..33cf0e8 --- /dev/null +++ b/CUETools/tmp.cs @@ -0,0 +1,79 @@ + uint bestTracksMatch = 0; + int bestWorstConfidence = 0; + int bestOffset = 0; + int bestDisk = -1; + + for (int di = 0; di < (int)accDisks.Count; di++) + { + for (int offset = -_arOffsetRange; offset <= _arOffsetRange; offset++) + { + uint tracksMatch = 0; + int worstConfidence = -1; + + for (int iTrack = 0; iTrack < TrackCount; iTrack++) + if (_tracks[iTrack].OffsetedCRC[_arOffsetRange - offset] == accDisks[di].tracks[iTrack].CRC) + { + tracksMatch++; + //confidence += accDisks[di].tracks[iTrack].count; + if (accDisks[di].tracks[iTrack].CRC != 0) + if (worstConfidence == -1 || worstConfidence > accDisks[di].tracks[iTrack].count) + worstConfidence = (int) accDisks[di].tracks[iTrack].count; + //if (_config.fixWhenConfidence) + //tracksMatchWithConfidence++; + } + + if (tracksMatch > bestTracksMatch + || (tracksMatch == bestTracksMatch && worstConfidence > bestWorstConfidence) + || (tracksMatch == bestTracksMatch && worstConfidence == bestWorstConfidence && Math.Abs(offset) < Math.Abs(bestOffset)) + ) + { + bestTracksMatch = tracksMatch; + bestWorstConfidence = worstConfidence; + bestOffset = offset; + bestDisk = di; + } + } + } + if (bestWorstConfidence > _config.fixWhenConfidence && + (bestTracksMatch == TrackCount || + (TrackCount > 2 && bestTracksMatch * 100 > TrackCount * _config.fixWhenPercent))) + _writeOffset = bestOffset; + else + if (bestTracksMatch != TrackCount && _config.noUnverifiedOutput) + SkipOutput = true; + + + + + + + + + + + + + + + + int s1 = (int) Math.Min(count, Math.Max(0, 450 * 588 - _arOffsetRange - (int)currentOffset)); + int s2 = (int) Math.Min(count, Math.Max(0, 451 * 588 + _arOffsetRange - (int)currentOffset)); + if ( s1 < s2 ) + fixed (uint* FrameCRCs = _tracks[iTrack].OffsetedFrame450CRC) + for (int sj = s1; sj < s2; sj++) + { + int magicFrameOffsetBase = (int)currentOffset + sj - 450 * 588 + 1; + for (int oi = -_arOffsetRange; oi <= _arOffsetRange; oi++) + { + int magicFrameOffset = magicFrameOffsetBase + oi; + if (magicFrameOffset > 0 && magicFrameOffset <= 588) + FrameCRCs[_arOffsetRange - oi] += (uint)(samples[sj] * magicFrameOffset); + } + } + + + int magicFrameOffset = (int)currentOffset + sj - 450 * 588 + 1; + int firstOffset = Math.Max(-_arOffsetRange, 1 - magicFrameOffset); + int lastOffset = Math.Min(_arOffsetRange, 588 - magicFrameOffset); + for (int oi = firstOffset; oi <= lastOffset; oi++) + FrameCRCs[_arOffsetRange - oi] += (uint)(samples[sj] * (magicFrameOffset + oi)); diff --git a/FLACDotNet/AssemblyInfo.cpp b/FLACDotNet/AssemblyInfo.cpp new file mode 100644 index 0000000..ff2a0c9 --- /dev/null +++ b/FLACDotNet/AssemblyInfo.cpp @@ -0,0 +1,39 @@ + +using namespace System; +using namespace System::Reflection; +using namespace System::Runtime::CompilerServices; +using namespace System::Runtime::InteropServices; +using namespace System::Security::Permissions; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly:AssemblyTitleAttribute("FLACDotNet")]; +[assembly:AssemblyDescriptionAttribute("")]; +[assembly:AssemblyConfigurationAttribute("")]; +[assembly:AssemblyCompanyAttribute("")]; +[assembly:AssemblyProductAttribute("")]; +[assembly:AssemblyCopyrightAttribute("Copyright 2006-2007 Moitah")]; +[assembly:AssemblyTrademarkAttribute("")]; +[assembly:AssemblyCultureAttribute("")]; + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the value or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly:AssemblyVersionAttribute("1.5.0.0")]; + +[assembly:ComVisible(false)]; + +[assembly:CLSCompliantAttribute(true)]; + +[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/FLACDotNet/FLACDotNet.sln b/FLACDotNet/FLACDotNet.sln new file mode 100644 index 0000000..7a2796c --- /dev/null +++ b/FLACDotNet/FLACDotNet.sln @@ -0,0 +1,36 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FLACDotNet", "FLACDotNet.vcproj", "{E70FA90A-7012-4A52-86B5-362B699D1540}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "APEDotNet", "..\APEDotNet\APEDotNet.vcproj", "{9AE965C4-301E-4C01-B90F-297AF341ACC6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|Win32.ActiveCfg = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|Win32.Build.0 = Debug|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x64.ActiveCfg = Debug|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Debug|x64.Build.0 = Debug|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|Win32.ActiveCfg = Release|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|Win32.Build.0 = Release|Win32 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x64.ActiveCfg = Release|x64 + {E70FA90A-7012-4A52-86B5-362B699D1540}.Release|x64.Build.0 = Release|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|Win32.ActiveCfg = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|Win32.Build.0 = Debug|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x64.ActiveCfg = Debug|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Debug|x64.Build.0 = Debug|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|Win32.ActiveCfg = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|Win32.Build.0 = Release|Win32 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x64.ActiveCfg = Release|x64 + {9AE965C4-301E-4C01-B90F-297AF341ACC6}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/FLACDotNet/FLACDotNet.vcproj b/FLACDotNet/FLACDotNet.vcproj new file mode 100644 index 0000000..cb73c9f --- /dev/null +++ b/FLACDotNet/FLACDotNet.vcproj @@ -0,0 +1,414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FLACDotNet/app.ico b/FLACDotNet/app.ico new file mode 100644 index 0000000..3a5525f Binary files /dev/null and b/FLACDotNet/app.ico differ diff --git a/FLACDotNet/app.rc b/FLACDotNet/app.rc new file mode 100644 index 0000000..8c1d640 --- /dev/null +++ b/FLACDotNet/app.rc @@ -0,0 +1,63 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon placed first or with lowest ID value becomes application icon + +LANGUAGE 9, 1 +#pragma code_page(1252) +1 ICON "app.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" + "\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/FLACDotNet/cuesheet.c b/FLACDotNet/cuesheet.c new file mode 100644 index 0000000..9037f32 --- /dev/null +++ b/FLACDotNet/cuesheet.c @@ -0,0 +1,610 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" +#include +#include +#include + +unsigned grabbag__cuesheet_msf_to_frame(unsigned minutes, unsigned seconds, unsigned frames) +{ + return ((minutes * 60) + seconds) * 75 + frames; +} + +void grabbag__cuesheet_frame_to_msf(unsigned frame, unsigned *minutes, unsigned *seconds, unsigned *frames) +{ + *frames = frame % 75; + frame /= 75; + *seconds = frame % 60; + frame /= 60; + *minutes = frame; +} + +/* since we only care about values >= 0 or error, returns < 0 for any illegal string, else value */ +static int local__parse_int_(const char *s) +{ + int ret = 0; + char c; + + if(*s == '\0') + return -1; + + while('\0' != (c = *s++)) + if(c >= '0' && c <= '9') + ret = ret * 10 + (c - '0'); + else + return -1; + + return ret; +} + +/* since we only care about values >= 0 or error, returns < 0 for any illegal string, else value */ +static FLAC__int64 local__parse_int64_(const char *s) +{ + FLAC__int64 ret = 0; + char c; + + if(*s == '\0') + return -1; + + while('\0' != (c = *s++)) + if(c >= '0' && c <= '9') + ret = ret * 10 + (c - '0'); + else + return -1; + + return ret; +} + +/* accept '[0-9]+:[0-9][0-9]?:[0-9][0-9]?', but max second of 59 and max frame of 74, e.g. 0:0:0, 123:45:67 + * return sample number or <0 for error + */ +static FLAC__int64 local__parse_msf_(const char *s) +{ + FLAC__int64 ret, field; + char c; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + while(':' != (c = *s++)) { + if(c >= '0' && c <= '9') + field = field * 10 + (c - '0'); + else + return -1; + } + + ret = field * 60 * 44100; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + if(':' != (c = *s++)) { + if(c >= '0' && c <= '9') { + field = field * 10 + (c - '0'); + c = *s++; + if(c != ':') + return -1; + } + else + return -1; + } + + if(field >= 60) + return -1; + + ret += field * 44100; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + if('\0' != (c = *s++)) { + if(c >= '0' && c <= '9') { + field = field * 10 + (c - '0'); + c = *s++; + } + else + return -1; + } + + if(c != '\0') + return -1; + + if(field >= 75) + return -1; + + ret += field * (44100 / 75); + + return ret; +} + +static char *local__get_field_(char **s, FLAC__bool allow_quotes) +{ + FLAC__bool has_quote = false; + char *p; + + FLAC__ASSERT(0 != s); + + if(0 == *s) + return 0; + + /* skip leading whitespace */ + while(**s && 0 != strchr(" \t\r\n", **s)) + (*s)++; + + if(**s == 0) { + *s = 0; + return 0; + } + + if(allow_quotes && (**s == '"')) { + has_quote = true; + (*s)++; + if(**s == 0) { + *s = 0; + return 0; + } + } + + p = *s; + + if(has_quote) { + *s = strchr(*s, '\"'); + /* if there is no matching end quote, it's an error */ + if(0 == *s) + p = *s = 0; + else { + **s = '\0'; + (*s)++; + } + } + else { + while(**s && 0 == strchr(" \t\r\n", **s)) + (*s)++; + if(**s) { + **s = '\0'; + (*s)++; + } + else + *s = 0; + } + + return p; +} + +static FLAC__bool local__cuesheet_parse_(FILE *file, const char **error_message, unsigned *last_line_read, FLAC__StreamMetadata *cuesheet, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset) +{ +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ +#define FLAC__STRCASECMP stricmp +#else +#define FLAC__STRCASECMP strcasecmp +#endif + char buffer[4096], *line, *field; + unsigned forced_leadout_track_num = 0; + FLAC__uint64 forced_leadout_track_offset = 0; + int in_track_num = -1, in_index_num = -1; + FLAC__bool disc_has_catalog = false, track_has_flags = false, track_has_isrc = false, has_forced_leadout = false; + FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet; + + cs->lead_in = is_cdda? 2 * 44100 /* The default lead-in size for CD-DA */ : 0; + cs->is_cd = is_cdda; + + while(0 != fgets(buffer, sizeof(buffer), file)) { + (*last_line_read)++; + line = buffer; + + { + size_t linelen = strlen(line); + if((linelen == sizeof(buffer)-1) && line[linelen-1] != '\n') { + *error_message = "line too long"; + return false; + } + } + + if(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == FLAC__STRCASECMP(field, "CATALOG")) { + if(disc_has_catalog) { + *error_message = "found multiple CATALOG commands"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/true))) { + *error_message = "CATALOG is missing catalog number"; + return false; + } + if(strlen(field) >= sizeof(cs->media_catalog_number)) { + *error_message = "CATALOG number is too long"; + return false; + } + if(is_cdda && (strlen(field) != 13 || strspn(field, "0123456789") != 13)) { + *error_message = "CD-DA CATALOG number must be 13 decimal digits"; + return false; + } + strcpy(cs->media_catalog_number, field); + disc_has_catalog = true; + } + else if(0 == FLAC__STRCASECMP(field, "FLAGS")) { + if(track_has_flags) { + *error_message = "found multiple FLAGS commands"; + return false; + } + if(in_track_num < 0 || in_index_num >= 0) { + *error_message = "FLAGS command must come after TRACK but before INDEX"; + return false; + } + while(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == FLAC__STRCASECMP(field, "PRE")) + cs->tracks[cs->num_tracks-1].pre_emphasis = 1; + } + track_has_flags = true; + } + else if(0 == FLAC__STRCASECMP(field, "INDEX")) { + FLAC__int64 xx; + FLAC__StreamMetadata_CueSheet_Track *track = &cs->tracks[cs->num_tracks-1]; + if(in_track_num < 0) { + *error_message = "found INDEX before any TRACK"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "INDEX is missing index number"; + return false; + } + in_index_num = local__parse_int_(field); + if(in_index_num < 0) { + *error_message = "INDEX has invalid index number"; + return false; + } + FLAC__ASSERT(cs->num_tracks > 0); + if(track->num_indices == 0) { + /* it's the first index point of the track */ + if(in_index_num > 1) { + *error_message = "first INDEX number of a TRACK must be 0 or 1"; + return false; + } + } + else { + if(in_index_num != track->indices[track->num_indices-1].number + 1) { + *error_message = "INDEX numbers must be sequential"; + return false; + } + } + if(is_cdda && in_index_num > 99) { + *error_message = "CD-DA INDEX number must be between 0 and 99, inclusive"; + return false; + } + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "INDEX is missing an offset after the index number"; + return false; + } + xx = local__parse_msf_(field); + if(xx < 0) { + if(is_cdda) { + *error_message = "illegal INDEX offset (not of the form MM:SS:FF)"; + return false; + } + xx = local__parse_int64_(field); + if(xx < 0) { + *error_message = "illegal INDEX offset"; + return false; + } + } + if(is_cdda && cs->num_tracks == 1 && cs->tracks[0].num_indices == 0 && xx != 0) { + *error_message = "first INDEX of first TRACK must have an offset of 00:00:00"; + return false; + } + if(is_cdda && track->num_indices > 0 && (FLAC__uint64)xx <= track->indices[track->num_indices-1].offset) { + *error_message = "CD-DA INDEX offsets must increase in time"; + return false; + } + /* fill in track offset if it's the first index of the track */ + if(track->num_indices == 0) + track->offset = (FLAC__uint64)xx; + if(is_cdda && cs->num_tracks > 1) { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-2]; + if((FLAC__uint64)xx <= prev->offset + prev->indices[prev->num_indices-1].offset) { + *error_message = "CD-DA INDEX offsets must increase in time"; + return false; + } + } + if(!FLAC__metadata_object_cuesheet_track_insert_blank_index(cuesheet, cs->num_tracks-1, track->num_indices)) { + *error_message = "memory allocation error"; + return false; + } + track->indices[track->num_indices-1].offset = (FLAC__uint64)xx - track->offset; + track->indices[track->num_indices-1].number = in_index_num; + } + else if(0 == FLAC__STRCASECMP(field, "ISRC")) { + char *l, *r; + if(track_has_isrc) { + *error_message = "found multiple ISRC commands"; + return false; + } + if(in_track_num < 0 || in_index_num >= 0) { + *error_message = "ISRC command must come after TRACK but before INDEX"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "ISRC is missing ISRC number"; + return false; + } + /* strip out dashes */ + for(l = r = field; *r; r++) { + if(*r != '-') + *l++ = *r; + } + *l = '\0'; + if(strlen(field) != 12 || strspn(field, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") < 5 || strspn(field+5, "1234567890") != 7) { + *error_message = "invalid ISRC number"; + return false; + } + strcpy(cs->tracks[cs->num_tracks-1].isrc, field); + track_has_isrc = true; + } + else if(0 == FLAC__STRCASECMP(field, "TRACK")) { + if(cs->num_tracks > 0) { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-1]; + if( + prev->num_indices == 0 || + ( + is_cdda && + ( + (prev->num_indices == 1 && prev->indices[0].number != 1) || + (prev->num_indices == 2 && prev->indices[0].number != 1 && prev->indices[1].number != 1) + ) + ) + ) { + *error_message = is_cdda? + "previous TRACK must specify at least one INDEX 01" : + "previous TRACK must specify at least one INDEX"; + return false; + } + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "TRACK is missing track number"; + return false; + } + in_track_num = local__parse_int_(field); + if(in_track_num < 0) { + *error_message = "TRACK has invalid track number"; + return false; + } + if(in_track_num == 0) { + *error_message = "TRACK number must be greater than 0"; + return false; + } + if(is_cdda) { + if(in_track_num > 99) { + *error_message = "CD-DA TRACK number must be between 1 and 99, inclusive"; + return false; + } + } + else { + if(in_track_num == 255) { + *error_message = "TRACK number 255 is reserved for the lead-out"; + return false; + } + else if(in_track_num > 255) { + *error_message = "TRACK number must be between 1 and 254, inclusive"; + return false; + } + } + if(is_cdda && cs->num_tracks > 0 && in_track_num != cs->tracks[cs->num_tracks-1].number + 1) { + *error_message = "CD-DA TRACK numbers must be sequential"; + return false; + } + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "TRACK is missing a track type after the track number"; + return false; + } + if(!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, cs->num_tracks)) { + *error_message = "memory allocation error"; + return false; + } + cs->tracks[cs->num_tracks-1].number = in_track_num; + cs->tracks[cs->num_tracks-1].type = (0 == FLAC__STRCASECMP(field, "AUDIO"))? 0 : 1; /*@@@ should we be more strict with the value here? */ + in_index_num = -1; + track_has_flags = false; + track_has_isrc = false; + } + else if(0 == FLAC__STRCASECMP(field, "REM")) { + if(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == strcmp(field, "FLAC__lead-in")) { + FLAC__int64 xx; + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-in is missing offset"; + return false; + } + xx = local__parse_int64_(field); + if(xx < 0) { + *error_message = "illegal FLAC__lead-in offset"; + return false; + } + if(is_cdda && xx % 588 != 0) { + *error_message = "illegal CD-DA FLAC__lead-in offset, must be even multiple of 588 samples"; + return false; + } + cs->lead_in = (FLAC__uint64)xx; + } + else if(0 == strcmp(field, "FLAC__lead-out")) { + int track_num; + FLAC__int64 offset; + if(has_forced_leadout) { + *error_message = "multiple FLAC__lead-out commands"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-out is missing track number"; + return false; + } + track_num = local__parse_int_(field); + if(track_num < 0) { + *error_message = "illegal FLAC__lead-out track number"; + return false; + } + forced_leadout_track_num = (unsigned)track_num; + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-out is missing offset"; + return false; + } + offset = local__parse_int64_(field); + if(offset < 0) { + *error_message = "illegal FLAC__lead-out offset"; + return false; + } + forced_leadout_track_offset = (FLAC__uint64)offset; + if(forced_leadout_track_offset != lead_out_offset) { + *error_message = "FLAC__lead-out offset does not match end-of-stream offset"; + return false; + } + has_forced_leadout = true; + } + } + } + } + } + + if(cs->num_tracks == 0) { + *error_message = "there must be at least one TRACK command"; + return false; + } + else { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-1]; + if( + prev->num_indices == 0 || + ( + is_cdda && + ( + (prev->num_indices == 1 && prev->indices[0].number != 1) || + (prev->num_indices == 2 && prev->indices[0].number != 1 && prev->indices[1].number != 1) + ) + ) + ) { + *error_message = is_cdda? + "previous TRACK must specify at least one INDEX 01" : + "previous TRACK must specify at least one INDEX"; + return false; + } + } + + if(!has_forced_leadout) { + forced_leadout_track_num = is_cdda? 170 : 255; + forced_leadout_track_offset = lead_out_offset; + } + if(!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, cs->num_tracks)) { + *error_message = "memory allocation error"; + return false; + } + cs->tracks[cs->num_tracks-1].number = forced_leadout_track_num; + cs->tracks[cs->num_tracks-1].offset = forced_leadout_track_offset; + + if(!feof(file)) { + *error_message = "read error"; + return false; + } + return true; +#undef FLAC__STRCASECMP +} + +FLAC__StreamMetadata *grabbag__cuesheet_parse(FILE *file, const char **error_message, unsigned *last_line_read, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset) +{ + FLAC__StreamMetadata *cuesheet; + + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != error_message); + FLAC__ASSERT(0 != last_line_read); + + *last_line_read = 0; + cuesheet = FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET); + + if(0 == cuesheet) { + *error_message = "memory allocation error"; + return 0; + } + + if(!local__cuesheet_parse_(file, error_message, last_line_read, cuesheet, is_cdda, lead_out_offset)) { + FLAC__metadata_object_delete(cuesheet); + return 0; + } + + return cuesheet; +} + +void grabbag__cuesheet_emit(FILE *file, const FLAC__StreamMetadata *cuesheet, const char *file_reference) +{ + const FLAC__StreamMetadata_CueSheet *cs; + unsigned track_num, index_num; + + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != cuesheet); + FLAC__ASSERT(cuesheet->type == FLAC__METADATA_TYPE_CUESHEET); + + cs = &cuesheet->data.cue_sheet; + + if(*(cs->media_catalog_number)) + fprintf(file, "CATALOG %s\n", cs->media_catalog_number); + fprintf(file, "FILE %s\n", file_reference); + + for(track_num = 0; track_num < cs->num_tracks-1; track_num++) { + const FLAC__StreamMetadata_CueSheet_Track *track = cs->tracks + track_num; + + fprintf(file, " TRACK %02u %s\n", (unsigned)track->number, track->type == 0? "AUDIO" : "DATA"); + + if(track->pre_emphasis) + fprintf(file, " FLAGS PRE\n"); + if(*(track->isrc)) + fprintf(file, " ISRC %s\n", track->isrc); + + for(index_num = 0; index_num < track->num_indices; index_num++) { + const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + index_num; + + fprintf(file, " INDEX %02u ", (unsigned)index->number); + if(cs->is_cd) { + const unsigned logical_frame = (unsigned)((track->offset + index->offset) / (44100 / 75)); + unsigned m, s, f; + grabbag__cuesheet_frame_to_msf(logical_frame, &m, &s, &f); + fprintf(file, "%02u:%02u:%02u\n", m, s, f); + } + else +#ifdef _MSC_VER + fprintf(file, "%I64u\n", track->offset + index->offset); +#else + fprintf(file, "%llu\n", (unsigned long long)(track->offset + index->offset)); +#endif + } + } + +#ifdef _MSC_VER + fprintf(file, "REM FLAC__lead-in %I64u\n", cs->lead_in); + fprintf(file, "REM FLAC__lead-out %u %I64u\n", (unsigned)cs->tracks[track_num].number, cs->tracks[track_num].offset); +#else + fprintf(file, "REM FLAC__lead-in %llu\n", (unsigned long long)cs->lead_in); + fprintf(file, "REM FLAC__lead-out %u %llu\n", (unsigned)cs->tracks[track_num].number, (unsigned long long)cs->tracks[track_num].offset); +#endif +} diff --git a/FLACDotNet/flacdotnet.cpp b/FLACDotNet/flacdotnet.cpp new file mode 100644 index 0000000..0aec40b --- /dev/null +++ b/FLACDotNet/flacdotnet.cpp @@ -0,0 +1,547 @@ +// **************************************************************************** +// +// Copyright (c) 2006-2007 Moitah (moitah@yahoo.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of the author nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. +// +// **************************************************************************** + +using namespace System; +using namespace System::Text; +using namespace System::Collections::Generic; +using namespace System::Collections::Specialized; +using namespace System::Runtime::InteropServices; + +#include "FLAC\all.h" +#include + +struct FLAC__Metadata_Iterator +{ + int dummy; +}; + +struct FLAC__Metadata_Chain +{ + int dummy; +}; + +namespace FLACDotNet { + [UnmanagedFunctionPointer(CallingConvention::Cdecl)] + public delegate FLAC__StreamDecoderWriteStatus DecoderWriteDelegate(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); + [UnmanagedFunctionPointer(CallingConvention::Cdecl)] + public delegate void DecoderMetadataDelegate(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); + [UnmanagedFunctionPointer(CallingConvention::Cdecl)] + public delegate void DecoderErrorDelegate(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + + public ref class FLACReader { + public: + FLACReader(String^ path) { + IntPtr pathChars; + FILE *hFile; + _tags = gcnew NameValueCollection(); + + _writeDel = gcnew DecoderWriteDelegate(this, &FLACReader::WriteCallback); + _metadataDel = gcnew DecoderMetadataDelegate(this, &FLACReader::MetadataCallback); + _errorDel = gcnew DecoderErrorDelegate(this, &FLACReader::ErrorCallback); + + _decoderActive = false; + + _sampleOffset = 0; + _samplesWaiting = false; + _sampleBuffer = nullptr; + _path = path; + + pathChars = Marshal::StringToHGlobalUni(_path); + hFile = _wfopen ((const wchar_t*)pathChars.ToPointer(), L"rb"); + Marshal::FreeHGlobal(pathChars); + if (!hFile) { + throw gcnew Exception("Unable to open file."); + } + + _decoder = FLAC__stream_decoder_new(); + + if (!FLAC__stream_decoder_set_metadata_respond (_decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT)) + throw gcnew Exception("Unable to setup the decoder."); + + if (FLAC__stream_decoder_init_FILE(_decoder, hFile, + (FLAC__StreamDecoderWriteCallback)Marshal::GetFunctionPointerForDelegate(_writeDel).ToPointer(), + (FLAC__StreamDecoderMetadataCallback)Marshal::GetFunctionPointerForDelegate(_metadataDel).ToPointer(), + (FLAC__StreamDecoderErrorCallback)Marshal::GetFunctionPointerForDelegate(_errorDel).ToPointer(), + NULL) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + { + throw gcnew Exception("Unable to initialize the decoder."); + } + + _decoderActive = true; + + if (!FLAC__stream_decoder_process_until_end_of_metadata(_decoder)) { + throw gcnew Exception("Unable to retrieve metadata."); + } + + } + + ~FLACReader () + { + Close (); + } + + property Int32 BitsPerSample { + Int32 get() { + return _bitsPerSample; + } + } + + property Int32 ChannelCount { + Int32 get() { + return _channelCount; + } + } + + property Int32 SampleRate { + Int32 get() { + return _sampleRate; + } + } + + property Int64 Length { + Int64 get() { + return _sampleCount; + } + } + + property Int64 Position { + Int64 get() { + return _sampleOffset; + } + void set(Int64 offset) { + _sampleOffset = offset; + _samplesWaiting = false; + if (!FLAC__stream_decoder_seek_absolute(_decoder, offset)) { + throw gcnew Exception("Unable to seek."); + } + } + } + + property NameValueCollection^ Tags { + NameValueCollection^ get () { + return _tags; + } + void set (NameValueCollection ^tags) { + _tags = tags; + } + } + + bool UpdateTags () + { + Close (); + + FLAC__Metadata_Chain* chain = FLAC__metadata_chain_new (); + if (!chain) return false; + + IntPtr pathChars = Marshal::StringToHGlobalAnsi(_path); + int res = FLAC__metadata_chain_read (chain, (const char*)pathChars.ToPointer()); + Marshal::FreeHGlobal(pathChars); + if (!res) { + FLAC__metadata_chain_delete (chain); + return false; + } + FLAC__Metadata_Iterator* i = FLAC__metadata_iterator_new (); + FLAC__metadata_iterator_init (i, chain); + do { + FLAC__StreamMetadata* metadata = FLAC__metadata_iterator_get_block (i); + if (metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + FLAC__metadata_iterator_delete_block (i, false); + } while (FLAC__metadata_iterator_next (i)); + + FLAC__StreamMetadata * vorbiscomment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + for (int tagno = 0; tagno <_tags->Count; tagno++) + { + String ^ tag_name = _tags->GetKey(tagno); + int tag_len = tag_name->Length; + char * tag = new char [tag_len + 1]; + IntPtr nameChars = Marshal::StringToHGlobalAnsi(tag_name); + memcpy (tag, (const char*)nameChars.ToPointer(), tag_len); + Marshal::FreeHGlobal(nameChars); + tag[tag_len] = 0; + + array^ tag_values = _tags->GetValues(tagno); + for (int valno = 0; valno < tag_values->Length; valno++) + { + UTF8Encoding^ enc = gcnew UTF8Encoding(); + array^ value_array = enc->GetBytes (tag_values[valno]); + int value_len = value_array->Length; + char * value = new char [value_len + 1]; + Marshal::Copy (value_array, 0, (IntPtr) value, value_len); + value[value_len] = 0; + + FLAC__StreamMetadata_VorbisComment_Entry entry; + /* create and entry and append it */ + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, tag, value)) { + throw gcnew Exception("Unable to add tags, must be valid utf8."); + } + if(!FLAC__metadata_object_vorbiscomment_append_comment(vorbiscomment, entry, /*copy=*/false)) { + throw gcnew Exception("Unable to add tags."); + } + delete [] value; + } + delete [] tag; + } + + FLAC__metadata_iterator_insert_block_after (i, vorbiscomment); + FLAC__metadata_iterator_delete (i); + FLAC__metadata_chain_sort_padding (chain); + res = FLAC__metadata_chain_write (chain, true, false); + FLAC__metadata_chain_delete (chain); + return 0 != res; + } + + property Int64 Remaining { + Int64 get() { + return _sampleCount - _sampleOffset; + } + } + + void Close() { + if (!_decoderActive) return; + FLAC__stream_decoder_finish(_decoder); + FLAC__stream_decoder_delete(_decoder); + _decoderActive = false; + } + + Int32 Read([Out] array^% sampleBuffer) { + int sampleCount; + + while (!_samplesWaiting) { + if (!FLAC__stream_decoder_process_single(_decoder)) { + throw gcnew Exception("An error occurred while decoding."); + } + } + + sampleCount = _sampleBuffer->GetLength(0); + sampleBuffer = _sampleBuffer; + _sampleOffset += sampleCount; + _samplesWaiting = false; + + return sampleCount; + } + + private: + DecoderWriteDelegate^ _writeDel; + DecoderMetadataDelegate^ _metadataDel; + DecoderErrorDelegate^ _errorDel; + FLAC__StreamDecoder *_decoder; + Int64 _sampleCount, _sampleOffset; + Int32 _bitsPerSample, _channelCount, _sampleRate; + array^ _sampleBuffer; + bool _samplesWaiting; + NameValueCollection^ _tags; + String^ _path; + bool _decoderActive; + + FLAC__StreamDecoderWriteStatus WriteCallback(const FLAC__StreamDecoder *decoder, + const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) + { + Int32 sampleCount = frame->header.blocksize; + + if (_samplesWaiting) { + throw gcnew Exception("Received unrequested samples."); + } + + if ((frame->header.bits_per_sample != _bitsPerSample) || + (frame->header.channels != _channelCount) || + (frame->header.sample_rate != _sampleRate)) + { + throw gcnew Exception("Format changes within a file are not allowed."); + } + + if ((_sampleBuffer == nullptr) || (_sampleBuffer->GetLength(0) != sampleCount)) { + _sampleBuffer = gcnew array(sampleCount, _channelCount); + } + + for (Int32 iChan = 0; iChan < _channelCount; iChan++) { + interior_ptr pMyBuffer = &_sampleBuffer[0, iChan]; + const FLAC__int32 *pFLACBuffer = buffer[iChan]; + const FLAC__int32 *pFLACBufferEnd = pFLACBuffer + sampleCount; + + while (pFLACBuffer < pFLACBufferEnd) { + *pMyBuffer = *pFLACBuffer; + pMyBuffer += _channelCount; + pFLACBuffer++; + } + } + + _samplesWaiting = true; + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; + } + + void MetadataCallback(const FLAC__StreamDecoder *decoder, + const FLAC__StreamMetadata *metadata, void *client_data) + { + if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) + { + _bitsPerSample = metadata->data.stream_info.bits_per_sample; + _channelCount = metadata->data.stream_info.channels; + _sampleRate = metadata->data.stream_info.sample_rate; + _sampleCount = metadata->data.stream_info.total_samples; + } + if (metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + { + for (unsigned tagno = 0; tagno < metadata->data.vorbis_comment.num_comments; tagno ++) + { + char * field_name, * field_value; + if(!FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(metadata->data.vorbis_comment.comments[tagno], &field_name, &field_value)) + throw gcnew Exception("Unable to parse vorbis comment."); + String^ name = Marshal::PtrToStringAnsi ((IntPtr) field_name); + free (field_name); + array^ bvalue = gcnew array((int) strlen (field_value)); + Marshal::Copy ((IntPtr) field_value, bvalue, 0, (int) strlen (field_value)); + free (field_value); + UTF8Encoding^ enc = gcnew UTF8Encoding(); + String ^value = enc->GetString (bvalue); + _tags->Add (name, value); + } + } + } + + void ErrorCallback(const FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderErrorStatus status, void *client_data) + { + switch (status) { + case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC: + throw gcnew Exception("Synchronization was lost."); + case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER: + throw gcnew Exception("Encountered a corrupted frame header."); + case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH: + throw gcnew Exception("Frame CRC mismatch."); + default: + throw gcnew Exception("An unknown error has occurred."); + } + } + }; + + public ref class FLACWriter { + public: + FLACWriter(String^ path, Int32 bitsPerSample, Int32 channelCount, Int32 sampleRate) { + _initialized = false; + _path = path; + _finalSampleCount = 0; + _samplesWritten = 0; + _bitsPerSample = bitsPerSample; + _channelCount = channelCount; + _sampleRate = sampleRate; + _compressionLevel = 5; + _paddingLength = 8192; + _verify = false; + _tags = gcnew NameValueCollection(); + + _encoder = FLAC__stream_encoder_new(); + + FLAC__stream_encoder_set_bits_per_sample(_encoder, bitsPerSample); + FLAC__stream_encoder_set_channels(_encoder, channelCount); + FLAC__stream_encoder_set_sample_rate(_encoder, sampleRate); + } + + void Close() { + FLAC__stream_encoder_finish(_encoder); + + for (int i = 0; i < _metadataCount; i++) { + FLAC__metadata_object_delete(_metadataList[i]); + } + delete[] _metadataList; + _metadataList = 0; + _metadataCount = 0; + + FLAC__stream_encoder_delete(_encoder); + + if ((_finalSampleCount != 0) && (_samplesWritten != _finalSampleCount)) { + throw gcnew Exception("Samples written differs from the expected sample count."); + } + + _tags->Clear (); + } + + property Int64 FinalSampleCount { + Int64 get() { + return _finalSampleCount; + } + void set(Int64 value) { + if (value < 0) { + throw gcnew Exception("Invalid final sample count."); + } + if (_initialized) { + throw gcnew Exception("Final sample count cannot be changed after encoding begins."); + } + _finalSampleCount = value; + } + } + + property Int32 CompressionLevel { + Int32 get() { + return _compressionLevel; + } + void set(Int32 value) { + if ((value < 0) || (value > 8)) { + throw gcnew Exception("Invalid compression level."); + } + _compressionLevel = value; + } + } + + property Boolean Verify { + Boolean get() { + return _verify; + } + void set(Boolean value) { + _verify = value; + } + } + + property Int32 PaddingLength { + Int32 get() { + return _paddingLength; + } + void set(Int32 value) { + if (value < 0) { + throw gcnew Exception("Invalid padding length."); + } + _paddingLength = value; + } + } + + void SetTags (NameValueCollection^ tags) { + _tags = tags; + } + + void Write(array^ sampleBuffer, Int32 sampleCount) { + if (!_initialized) Initialize(); + + pin_ptr pSampleBuffer = &sampleBuffer[0, 0]; + + if (!FLAC__stream_encoder_process_interleaved(_encoder, + (const FLAC__int32*)pSampleBuffer, sampleCount)) + { + throw gcnew Exception("An error occurred while encoding."); + } + + _samplesWritten += sampleCount; + } + + private: + FLAC__StreamEncoder *_encoder; + bool _initialized; + String^ _path; + Int64 _finalSampleCount, _samplesWritten; + Int32 _bitsPerSample, _channelCount, _sampleRate; + Int32 _compressionLevel; + Int32 _paddingLength; + Boolean _verify; + FLAC__StreamMetadata **_metadataList; + int _metadataCount; + NameValueCollection^ _tags; + + void Initialize() { + FLAC__StreamMetadata *padding, *seektable, *vorbiscomment; + IntPtr pathChars; + FILE *hFile; + + _metadataList = new FLAC__StreamMetadata*[8]; + _metadataCount = 0; + + if (_finalSampleCount != 0) { + seektable = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__metadata_object_seektable_template_append_spaced_points_by_samples( + seektable, _sampleRate * 10, _finalSampleCount); + FLAC__metadata_object_seektable_template_sort(seektable, true); + _metadataList[_metadataCount++] = seektable; + } + + vorbiscomment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + + for (int tagno = 0; tagno < _tags->Count; tagno++) + { + String ^ tag_name = _tags->GetKey(tagno); + int tag_len = tag_name->Length; + char * tag = new char [tag_len + 1]; + IntPtr nameChars = Marshal::StringToHGlobalAnsi(tag_name); + memcpy (tag, (const char*)nameChars.ToPointer(), tag_len); + Marshal::FreeHGlobal(nameChars); + tag[tag_len] = 0; + + array^ tag_values = _tags->GetValues(tagno); + for (int valno = 0; valno < tag_values->Length; valno++) + { + UTF8Encoding^ enc = gcnew UTF8Encoding(); + array^ value_array = enc->GetBytes (tag_values[valno]); + int value_len = value_array->Length; + char * value = new char [value_len + 1]; + Marshal::Copy (value_array, 0, (IntPtr) value, value_len); + value[value_len] = 0; + + FLAC__StreamMetadata_VorbisComment_Entry entry; + /* create and entry and append it */ + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, tag, value)) { + throw gcnew Exception("Unable to add tags, must be valid utf8."); + } + if(!FLAC__metadata_object_vorbiscomment_append_comment(vorbiscomment, entry, /*copy=*/false)) { + throw gcnew Exception("Unable to add tags."); + } + delete [] value; + } + delete [] tag; + } + _metadataList[_metadataCount++] = vorbiscomment; + + if (_paddingLength != 0) { + padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + padding->length = _paddingLength; + _metadataList[_metadataCount++] = padding; + } + + FLAC__stream_encoder_set_metadata(_encoder, _metadataList, _metadataCount); + + FLAC__stream_encoder_set_verify(_encoder, _verify); + + if (_finalSampleCount != 0) { + FLAC__stream_encoder_set_total_samples_estimate(_encoder, _finalSampleCount); + } + + FLAC__stream_encoder_set_compression_level(_encoder, _compressionLevel); + + pathChars = Marshal::StringToHGlobalUni(_path); + hFile = _wfopen((const wchar_t*)pathChars.ToPointer(), L"w+b"); + Marshal::FreeHGlobal(pathChars); + + if (FLAC__stream_encoder_init_FILE(_encoder, hFile, NULL, NULL) != + FLAC__STREAM_ENCODER_INIT_STATUS_OK) + { + throw gcnew Exception("Unable to initialize the encoder."); + } + + _initialized = true; + } + }; +} diff --git a/FLACDotNet/resource.h b/FLACDotNet/resource.h new file mode 100644 index 0000000..1f2251c --- /dev/null +++ b/FLACDotNet/resource.h @@ -0,0 +1,3 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by app.rc diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/APEtag.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/APEtag.pas new file mode 100644 index 0000000..3751574 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/APEtag.pas @@ -0,0 +1,488 @@ +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TAPEtag - for manipulating with APE tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.0 (21 April 2002) } +{ - Reading & writing support for APE 1.0 tags } +{ - Reading support for APE 2.0 tags (UTF-8 decoding) } +{ - Tag info: title, artist, album, track, year, genre, comment, copyright } +{ } +{ *************************************************************************** } + +unit APEtag; + +interface + +uses + Classes, SysUtils; + +type + { Class TAPEtag } + TAPEtag = class(TObject) + private + { Private declarations } + FExists: Boolean; + FVersion: Integer; + FSize: Integer; + FTitle: string; + FArtist: string; + FAlbum: string; + FTrack: Byte; + FYear: string; + FGenre: string; + FComment: string; + FCopyright: string; + procedure FSetTitle(const NewTitle: string); + procedure FSetArtist(const NewArtist: string); + procedure FSetAlbum(const NewAlbum: string); + procedure FSetTrack(const NewTrack: Byte); + procedure FSetYear(const NewYear: string); + procedure FSetGenre(const NewGenre: string); + procedure FSetComment(const NewComment: string); + procedure FSetCopyright(const NewCopyright: string); + public + { Public declarations } + constructor Create; { Create object } + procedure ResetData; { Reset all data } + function ReadFromFile(const FileName: string): Boolean; { Load tag } + function RemoveFromFile(const FileName: string): Boolean; { Delete tag } + function SaveToFile(const FileName: string): Boolean; { Save tag } + property Exists: Boolean read FExists; { True if tag found } + property Version: Integer read FVersion; { Tag version } + property Size: Integer read FSize; { Total tag size } + property Title: string read FTitle write FSetTitle; { Song title } + property Artist: string read FArtist write FSetArtist; { Artist name } + property Album: string read FAlbum write FSetAlbum; { Album title } + property Track: Byte read FTrack write FSetTrack; { Track number } + property Year: string read FYear write FSetYear; { Release year } + property Genre: string read FGenre write FSetGenre; { Genre name } + property Comment: string read FComment write FSetComment; { Comment } + property Copyright: string read FCopyright write FSetCopyright; { (c) } + end; + +implementation + +const + { Tag ID } + ID3V1_ID = 'TAG'; { ID3v1 } + APE_ID = 'APETAGEX'; { APE } + + { Size constants } + ID3V1_TAG_SIZE = 128; { ID3v1 tag } + APE_TAG_FOOTER_SIZE = 32; { APE tag footer } + APE_TAG_HEADER_SIZE = 32; { APE tag header } + + { First version of APE tag } + APE_VERSION_1_0 = 1000; + + { Max. number of supported tag fields } + APE_FIELD_COUNT = 8; + + { Names of supported tag fields } + APE_FIELD: array [1..APE_FIELD_COUNT] of string = + ('Title', 'Artist', 'Album', 'Track', 'Year', 'Genre', + 'Comment', 'Copyright'); + +type + { APE tag data - for internal use } + TagInfo = record + { Real structure of APE footer } + ID: array [1..8] of Char; { Always "APETAGEX" } + Version: Integer; { Tag version } + Size: Integer; { Tag size including footer } + Fields: Integer; { Number of fields } + Flags: Integer; { Tag flags } + Reserved: array [1..8] of Char; { Reserved for later use } + { Extended data } + DataShift: Byte; { Used if ID3v1 tag found } + FileSize: Integer; { File size (bytes) } + Field: array [1..APE_FIELD_COUNT] of string; { Information from fields } + end; + +{ ********************* Auxiliary functions & procedures ******************** } + +function ReadFooter(const FileName: string; var Tag: TagInfo): Boolean; +var + SourceFile: file; + TagID: array [1..3] of Char; + Transferred: Integer; +begin + { Load footer from file to variable } + try + Result := true; + { Set read-access and open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + Tag.FileSize := FileSize(SourceFile); + { Check for existing ID3v1 tag } + Seek(SourceFile, Tag.FileSize - ID3V1_TAG_SIZE); + BlockRead(SourceFile, TagID, SizeOf(TagID)); + if TagID = ID3V1_ID then Tag.DataShift := ID3V1_TAG_SIZE; + { Read footer data } + Seek(SourceFile, Tag.FileSize - Tag.DataShift - APE_TAG_FOOTER_SIZE); + BlockRead(SourceFile, Tag, APE_TAG_FOOTER_SIZE, Transferred); + CloseFile(SourceFile); + { if transfer is not complete } + if Transferred < APE_TAG_FOOTER_SIZE then Result := false; + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function ConvertFromUTF8(const Source: string): string; +var + Iterator, SourceLength, FChar, NChar: Integer; +begin + { Convert UTF-8 string to ANSI string } + Result := ''; + Iterator := 0; + SourceLength := Length(Source); + while Iterator < SourceLength do + begin + Inc(Iterator); + FChar := Ord(Source[Iterator]); + if FChar >= $80 then + begin + Inc(Iterator); + if Iterator > SourceLength then break; + FChar := FChar and $3F; + if (FChar and $20) <> 0 then + begin + FChar := FChar and $1F; + NChar := Ord(Source[Iterator]); + if (NChar and $C0) <> $80 then break; + FChar := (FChar shl 6) or (NChar and $3F); + Inc(Iterator); + if Iterator > SourceLength then break; + end; + NChar := Ord(Source[Iterator]); + if (NChar and $C0) <> $80 then break; + Result := Result + WideChar((FChar shl 6) or (NChar and $3F)); + end + else + Result := Result + WideChar(FChar); + end; +end; + +{ --------------------------------------------------------------------------- } + +procedure SetTagItem(const FieldName, FieldValue: string; var Tag: TagInfo); +var + Iterator: Byte; +begin + { Set tag item if supported field found } + for Iterator := 1 to APE_FIELD_COUNT do + if UpperCase(FieldName) = UpperCase(APE_FIELD[Iterator]) then + if Tag.Version > APE_VERSION_1_0 then + Tag.Field[Iterator] := ConvertFromUTF8(FieldValue) + else + Tag.Field[Iterator] := FieldValue; +end; + +{ --------------------------------------------------------------------------- } + +procedure ReadFields(const FileName: string; var Tag: TagInfo); +var + SourceFile: file; + FieldName: string; + FieldValue: array [1..250] of Char; + NextChar: Char; + Iterator, ValueSize, ValuePosition, FieldFlags: Integer; +begin + try + { Set read-access, open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + Seek(SourceFile, Tag.FileSize - Tag.DataShift - Tag.Size); + { Read all stored fields } + for Iterator := 1 to Tag.Fields do + begin + FillChar(FieldValue, SizeOf(FieldValue), 0); + BlockRead(SourceFile, ValueSize, SizeOf(ValueSize)); + BlockRead(SourceFile, FieldFlags, SizeOf(FieldFlags)); + FieldName := ''; + repeat + BlockRead(SourceFile, NextChar, SizeOf(NextChar)); + FieldName := FieldName + NextChar; + until Ord(NextChar) = 0; + ValuePosition := FilePos(SourceFile); + BlockRead(SourceFile, FieldValue, ValueSize mod SizeOf(FieldValue)); + SetTagItem(Trim(FieldName), Trim(FieldValue), Tag); + Seek(SourceFile, ValuePosition + ValueSize); + end; + CloseFile(SourceFile); + except + end; +end; + +{ --------------------------------------------------------------------------- } + +function GetTrack(const TrackString: string): Byte; +var + Index, Value, Code: Integer; +begin + { Get track from string } + Index := Pos('/', TrackString); + if Index = 0 then Val(TrackString, Value, Code) + else Val(Copy(TrackString, 1, Index - 1), Value, Code); + if Code = 0 then Result := Value + else Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TruncateFile(const FileName: string; TagSize: Integer): Boolean; +var + SourceFile: file; +begin + try + Result := true; + { Allow write-access and open file } + FileSetAttr(FileName, 0); + AssignFile(SourceFile, FileName); + FileMode := 2; + Reset(SourceFile, 1); + { Delete tag } + Seek(SourceFile, FileSize(SourceFile) - TagSize); + Truncate(SourceFile); + CloseFile(SourceFile); + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +procedure BuildFooter(var Tag: TagInfo); +var + Iterator: Integer; +begin + { Build tag footer } + Tag.ID := APE_ID; + Tag.Version := APE_VERSION_1_0; + Tag.Size := APE_TAG_FOOTER_SIZE; + for Iterator := 1 to APE_FIELD_COUNT do + if Tag.Field[Iterator] <> '' then + begin + Inc(Tag.Size, Length(APE_FIELD[Iterator] + Tag.Field[Iterator]) + 10); + Inc(Tag.Fields); + end; +end; + +{ --------------------------------------------------------------------------- } + +function AddToFile(const FileName: string; TagData: TStream): Boolean; +var + FileData: TFileStream; +begin + try + { Add tag data to file } + FileData := TFileStream.Create(FileName, fmOpenWrite or fmShareExclusive); + FileData.Seek(0, soFromEnd); + TagData.Seek(0, soFromBeginning); + FileData.CopyFrom(TagData, TagData.Size); + FileData.Free; + Result := true; + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function SaveTag(const FileName: string; Tag: TagInfo): Boolean; +var + TagData: TStringStream; + Iterator, ValueSize, Flags: Integer; +begin + { Build and write tag fields and footer to stream } + TagData := TStringStream.Create(''); + for Iterator := 1 to APE_FIELD_COUNT do + if Tag.Field[Iterator] <> '' then + begin + ValueSize := Length(Tag.Field[Iterator]) + 1; + Flags := 0; + TagData.Write(ValueSize, SizeOf(ValueSize)); + TagData.Write(Flags, SizeOf(Flags)); + TagData.WriteString(APE_FIELD[Iterator] + #0); + TagData.WriteString(Tag.Field[Iterator] + #0); + end; + BuildFooter(Tag); + TagData.Write(Tag, APE_TAG_FOOTER_SIZE); + { Add created tag to file } + Result := AddToFile(FileName, TagData); + TagData.Free; +end; + +{ ********************** Private functions & procedures ********************* } + +procedure TAPEtag.FSetTitle(const NewTitle: string); +begin + { Set song title } + FTitle := Trim(NewTitle); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetArtist(const NewArtist: string); +begin + { Set artist name } + FArtist := Trim(NewArtist); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetAlbum(const NewAlbum: string); +begin + { Set album title } + FAlbum := Trim(NewAlbum); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetTrack(const NewTrack: Byte); +begin + { Set track number } + FTrack := NewTrack; +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetYear(const NewYear: string); +begin + { Set release year } + FYear := Trim(NewYear); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetGenre(const NewGenre: string); +begin + { Set genre name } + FGenre := Trim(NewGenre); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetComment(const NewComment: string); +begin + { Set comment } + FComment := Trim(NewComment); +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.FSetCopyright(const NewCopyright: string); +begin + { Set copyright information } + FCopyright := Trim(NewCopyright); +end; + +{ ********************** Public functions & procedures ********************** } + +constructor TAPEtag.Create; +begin + { Create object } + inherited; + ResetData; +end; + +{ --------------------------------------------------------------------------- } + +procedure TAPEtag.ResetData; +begin + { Reset all variables } + FExists := false; + FVersion := 0; + FSize := 0; + FTitle := ''; + FArtist := ''; + FAlbum := ''; + FTrack := 0; + FYear := ''; + FGenre := ''; + FComment := ''; + FCopyright := ''; +end; + +{ --------------------------------------------------------------------------- } + +function TAPEtag.ReadFromFile(const FileName: string): Boolean; +var + Tag: TagInfo; +begin + { Reset data and load footer from file to variable } + ResetData; + FillChar(Tag, SizeOf(Tag), 0); + Result := ReadFooter(FileName, Tag); + { Process data if loaded and footer valid } + if (Result) and (Tag.ID = APE_ID) then + begin + FExists := true; + { Fill properties with footer data } + FVersion := Tag.Version; + FSize := Tag.Size; + { Get information from fields } + ReadFields(FileName, Tag); + FTitle := Tag.Field[1]; + FArtist := Tag.Field[2]; + FAlbum := Tag.Field[3]; + FTrack := GetTrack(Tag.Field[4]); + FYear := Tag.Field[5]; + FGenre := Tag.Field[6]; + FComment := Tag.Field[7]; + FCopyright := Tag.Field[8]; + end; +end; + +{ --------------------------------------------------------------------------- } + +function TAPEtag.RemoveFromFile(const FileName: string): Boolean; +var + Tag: TagInfo; +begin + { Remove tag from file if found } + FillChar(Tag, SizeOf(Tag), 0); + if ReadFooter(FileName, Tag) then + begin + if Tag.ID <> APE_ID then Tag.Size := 0; + if (Tag.Flags shr 31) > 0 then Inc(Tag.Size, APE_TAG_HEADER_SIZE); + Result := TruncateFile(FileName, Tag.DataShift + Tag.Size) + end + else + Result := false; +end; + +{ --------------------------------------------------------------------------- } + +function TAPEtag.SaveToFile(const FileName: string): Boolean; +var + Tag: TagInfo; +begin + { Prepare tag data and save to file } + FillChar(Tag, SizeOf(Tag), 0); + Tag.Field[1] := FTitle; + Tag.Field[2] := FArtist; + Tag.Field[3] := FAlbum; + if FTrack > 0 then Tag.Field[4] := IntToStr(FTrack); + Tag.Field[5] := FYear; + Tag.Field[6] := FGenre; + Tag.Field[7] := FComment; + Tag.Field[8] := FCopyright; + { Delete old tag if exists and write new tag } + Result := (RemoveFromFile(FileName)) and (SaveTag(FileName, Tag)); +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Info.txt b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Info.txt new file mode 100644 index 0000000..f649184 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Info.txt @@ -0,0 +1,18 @@ +APEtag.pas +Tested with Borland Delphi 3,4,5,6 + +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TAPEtag - for manipulating with APE tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.0 (21 April 2002) } +{ - Reading & writing support for APE 1.0 tags } +{ - Reading support for APE 2.0 tags (UTF-8 decoding) } +{ - Tag info: title, artist, album, track, year, genre, comment, copyright } +{ } +{ *************************************************************************** } \ No newline at end of file diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.dfm b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.dfm new file mode 100644 index 0000000..e9fccb0 Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.dfm differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.pas new file mode 100644 index 0000000..2547c3f --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Main.pas @@ -0,0 +1,159 @@ +unit Main; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + StdCtrls, FileCtrl, ExtCtrls, APEtag; + +type + TMainForm = class(TForm) + DriveList: TDriveComboBox; + FolderList: TDirectoryListBox; + FileList: TFileListBox; + SaveButton: TButton; + RemoveButton: TButton; + CloseButton: TButton; + InfoBevel: TBevel; + IconImage: TImage; + TagExistsLabel: TLabel; + TagExistsValue: TEdit; + VersionLabel: TLabel; + VersionValue: TEdit; + SizeLabel: TLabel; + SizeValue: TEdit; + TitleLabel: TLabel; + TitleEdit: TEdit; + ArtistLabel: TLabel; + ArtistEdit: TEdit; + AlbumLabel: TLabel; + AlbumEdit: TEdit; + TrackLabel: TLabel; + TrackEdit: TEdit; + YearLabel: TLabel; + YearEdit: TEdit; + GenreLabel: TLabel; + GenreEdit: TEdit; + CommentLabel: TLabel; + CommentEdit: TEdit; + CopyrightLabel: TLabel; + CopyrightEdit: TEdit; + procedure FormCreate(Sender: TObject); + procedure FileListChange(Sender: TObject); + procedure FormClose(Sender: TObject; var Action: TCloseAction); + procedure SaveButtonClick(Sender: TObject); + procedure RemoveButtonClick(Sender: TObject); + procedure CloseButtonClick(Sender: TObject); + private + { Private declarations } + FileTag: TAPEtag; + procedure ClearAll; + end; + +var + MainForm: TMainForm; + +implementation + +{$R *.dfm} + +procedure TMainForm.ClearAll; +begin + { Clear all captions } + TagExistsValue.Text := ''; + VersionValue.Text := ''; + SizeValue.Text := ''; + TitleEdit.Text := ''; + ArtistEdit.Text := ''; + AlbumEdit.Text := ''; + TrackEdit.Text := ''; + YearEdit.Text := ''; + GenreEdit.Text := ''; + CommentEdit.Text := ''; + CopyrightEdit.Text := ''; +end; + +procedure TMainForm.FormCreate(Sender: TObject); +begin + { Create object and clear captions } + FileTag := TAPEtag.Create; + ClearAll; +end; + +procedure TMainForm.FileListChange(Sender: TObject); +begin + { Clear captions } + ClearAll; + if FileList.FileName = '' then exit; + if FileExists(FileList.FileName) then + { Load tag data } + if FileTag.ReadFromFile(FileList.FileName) then + if FileTag.Exists then + begin + { Fill captions } + TagExistsValue.Text := 'Yes'; + VersionValue.Text := FormatFloat('0,000', FileTag.Version); + SizeValue.Text := IntToStr(FileTag.Size) + ' bytes'; + TitleEdit.Text := FileTag.Title; + ArtistEdit.Text := FileTag.Artist; + AlbumEdit.Text := FileTag.Album; + if FileTag.Track > 0 then TrackEdit.Text := IntToStr(FileTag.Track); + YearEdit.Text := FileTag.Year; + GenreEdit.Text := FileTag.Genre; + CommentEdit.Text := FileTag.Comment; + CopyrightEdit.Text := FileTag.Copyright; + end + else + { Tag not found } + TagExistsValue.Text := 'No' + else + { Read error } + ShowMessage('Can not read tag from the file: ' + FileList.FileName) + else + { File does not exist } + ShowMessage('The file does not exist: ' + FileList.FileName); +end; + +procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); +begin + { Free memory } + FileTag.Free; +end; + +procedure TMainForm.SaveButtonClick(Sender: TObject); +var + Value, Code: Integer; +begin + { Prepare tag data } + FileTag.Title := TitleEdit.Text; + FileTag.Artist := ArtistEdit.Text; + FileTag.Album := AlbumEdit.Text; + Val(TrackEdit.Text, Value, Code); + if (Code = 0) and (Value > 0) then FileTag.Track := Value + else FileTag.Track := 0; + FileTag.Year := YearEdit.Text; + FileTag.Genre := GenreEdit.Text; + FileTag.Comment := CommentEdit.Text; + FileTag.Copyright := CopyrightEdit.Text; + { Save tag data } + if (not FileExists(FileList.FileName)) or + (not FileTag.SaveToFile(FileList.FileName)) then + ShowMessage('Can not save tag to the file: ' + FileList.FileName); + FileListChange(Self); +end; + +procedure TMainForm.RemoveButtonClick(Sender: TObject); +begin + { Delete tag data } + if (FileExists(FileList.FileName)) and + (FileTag.RemoveFromFile(FileList.FileName)) then ClearAll + else ShowMessage('Can not remove tag from the file: ' + FileList.FileName); +end; + +procedure TMainForm.CloseButtonClick(Sender: TObject); +begin + { Exit } + Close; +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.cfg b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.cfg new file mode 100644 index 0000000..dc18277 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.cfg @@ -0,0 +1,35 @@ +-$A8 +-$B- +-$C+ +-$D+ +-$E- +-$F- +-$G+ +-$H+ +-$I+ +-$J- +-$K- +-$L+ +-$M- +-$N+ +-$O+ +-$P+ +-$Q- +-$R- +-$S- +-$T- +-$U- +-$V+ +-$W- +-$X+ +-$YD +-$Z1 +-cg +-AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +-H+ +-W+ +-M +-$M16384,1048576 +-K$00400000 +-LE"c:\program files\borland\delphi6\Projects\Bpl" +-LN"c:\program files\borland\delphi6\Projects\Bpl" diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dof b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dof new file mode 100644 index 0000000..216ddb6 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dof @@ -0,0 +1,96 @@ +[FileVersion] +Version=6.0 +[Compiler] +A=8 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=0 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=1 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +RemoteSymbols=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +PackageDLLOutputDir= +PackageDCPOutputDir= +SearchPath= +Packages=vcl;rtl;dbrtl;adortl;vcldb;vclx;bdertl;vcldbx;ibxpress;dsnap;cds;bdecds;qrpt;teeui;teedb;tee;dss;teeqr;visualclx;visualdbclx;dsnapcrba;dsnapcon;VclSmp;vclshlctrls;vclie;xmlrtl;inet;inetdbbde;inetdbxpress;inetdb;nmfast;webdsnap;websnap;dbexpress;dbxcds;indy;dclOffice2k +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +Launcher= +UseLauncher=0 +DebugCWD= +[Language] +ActiveLang= +ProjectLang= +RootDir= +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1031 +CodePage=1252 +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= +[HistoryLists\hlUnitAliases] +Count=1 +Item0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[HistoryLists\hlUnitOutputDirectory] +Count=1 +Item0=DCU +[HistoryLists\hlOutputDirectorry] +Count=1 +Item0=Data diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dpr b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dpr new file mode 100644 index 0000000..78f2042 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.dpr @@ -0,0 +1,15 @@ +program Test; + +uses + Forms, + Main in 'Main.pas' {MainForm}, + APEtag in 'APEtag.pas'; + +{$R *.res} + +begin + Application.Initialize; + Application.Title := 'APEtag Test'; + Application.CreateForm(TMainForm, MainForm); + Application.Run; +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.res b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.res new file mode 100644 index 0000000..1ce496d Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/APEtag/Test.res differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/ID3v1.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/ID3v1.pas new file mode 100644 index 0000000..197a62c --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/ID3v1.pas @@ -0,0 +1,475 @@ +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TID3v1 - for manipulating with ID3v1 tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.0 (25 July 2001) } +{ - Reading & writing support for ID3v1.x tags } +{ - Tag info: title, artist, album, track, year, genre, comment } +{ } +{ *************************************************************************** } + +unit ID3v1; + +interface + +uses + Classes, SysUtils; + +const + MAX_MUSIC_GENRES = 148; { Max. number of music genres } + DEFAULT_GENRE = 255; { Index for default genre } + + { Used with VersionID property } + TAG_VERSION_1_0 = 1; { Index for ID3v1.0 tag } + TAG_VERSION_1_1 = 2; { Index for ID3v1.1 tag } + +var + MusicGenre: array [0..MAX_MUSIC_GENRES - 1] of string; { Genre names } + +type + { Used in TID3v1 class } + String04 = string[4]; { String with max. 4 symbols } + String30 = string[30]; { String with max. 30 symbols } + + { Class TID3v1 } + TID3v1 = class(TObject) + private + { Private declarations } + FExists: Boolean; + FVersionID: Byte; + FTitle: String30; + FArtist: String30; + FAlbum: String30; + FYear: String04; + FComment: String30; + FTrack: Byte; + FGenreID: Byte; + procedure FSetTitle(const NewTitle: String30); + procedure FSetArtist(const NewArtist: String30); + procedure FSetAlbum(const NewAlbum: String30); + procedure FSetYear(const NewYear: String04); + procedure FSetComment(const NewComment: String30); + procedure FSetTrack(const NewTrack: Byte); + procedure FSetGenreID(const NewGenreID: Byte); + function FGetGenre: string; + public + { Public declarations } + constructor Create; { Create object } + procedure ResetData; { Reset all data } + function ReadFromFile(const FileName: string): Boolean; { Load tag } + function RemoveFromFile(const FileName: string): Boolean; { Delete tag } + function SaveToFile(const FileName: string): Boolean; { Save tag } + property Exists: Boolean read FExists; { True if tag found } + property VersionID: Byte read FVersionID; { Version code } + property Title: String30 read FTitle write FSetTitle; { Song title } + property Artist: String30 read FArtist write FSetArtist; { Artist name } + property Album: String30 read FAlbum write FSetAlbum; { Album name } + property Year: String04 read FYear write FSetYear; { Year } + property Comment: String30 read FComment write FSetComment; { Comment } + property Track: Byte read FTrack write FSetTrack; { Track number } + property GenreID: Byte read FGenreID write FSetGenreID; { Genre code } + property Genre: string read FGetGenre; { Genre name } + end; + +implementation + +type + { Real structure of ID3v1 tag } + TagRecord = record + Header: array [1..3] of Char; { Tag header - must be "TAG" } + Title: array [1..30] of Char; { Title data } + Artist: array [1..30] of Char; { Artist data } + Album: array [1..30] of Char; { Album data } + Year: array [1..4] of Char; { Year data } + Comment: array [1..30] of Char; { Comment data } + Genre: Byte; { Genre data } + end; + +{ ********************* Auxiliary functions & procedures ******************** } + +function ReadTag(const FileName: string; var TagData: TagRecord): Boolean; +var + SourceFile: file; +begin + try + Result := true; + { Set read-access and open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + { Read tag } + Seek(SourceFile, FileSize(SourceFile) - 128); + BlockRead(SourceFile, TagData, 128); + CloseFile(SourceFile); + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function RemoveTag(const FileName: string): Boolean; +var + SourceFile: file; +begin + try + Result := true; + { Allow write-access and open file } + FileSetAttr(FileName, 0); + AssignFile(SourceFile, FileName); + FileMode := 2; + Reset(SourceFile, 1); + { Delete tag } + Seek(SourceFile, FileSize(SourceFile) - 128); + Truncate(SourceFile); + CloseFile(SourceFile); + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function SaveTag(const FileName: string; TagData: TagRecord): Boolean; +var + SourceFile: file; +begin + try + Result := true; + { Allow write-access and open file } + FileSetAttr(FileName, 0); + AssignFile(SourceFile, FileName); + FileMode := 2; + Reset(SourceFile, 1); + { Write tag } + Seek(SourceFile, FileSize(SourceFile)); + BlockWrite(SourceFile, TagData, SizeOf(TagData)); + CloseFile(SourceFile); + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function GetTagVersion(const TagData: TagRecord): Byte; +begin + Result := TAG_VERSION_1_0; + { Terms for ID3v1.1 } + if ((TagData.Comment[29] = #0) and (TagData.Comment[30] <> #0)) or + ((TagData.Comment[29] = #32) and (TagData.Comment[30] <> #32)) then + Result := TAG_VERSION_1_1; +end; + +{ ********************** Private functions & procedures ********************* } + +procedure TID3v1.FSetTitle(const NewTitle: String30); +begin + FTitle := TrimRight(NewTitle); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetArtist(const NewArtist: String30); +begin + FArtist := TrimRight(NewArtist); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetAlbum(const NewAlbum: String30); +begin + FAlbum := TrimRight(NewAlbum); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetYear(const NewYear: String04); +begin + FYear := TrimRight(NewYear); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetComment(const NewComment: String30); +begin + FComment := TrimRight(NewComment); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetTrack(const NewTrack: Byte); +begin + FTrack := NewTrack; +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.FSetGenreID(const NewGenreID: Byte); +begin + FGenreID := NewGenreID; +end; + +{ --------------------------------------------------------------------------- } + +function TID3v1.FGetGenre: string; +begin + Result := ''; + { Return an empty string if the current GenreID is not valid } + if FGenreID in [0..MAX_MUSIC_GENRES - 1] then Result := MusicGenre[FGenreID]; +end; + +{ ********************** Public functions & procedures ********************** } + +constructor TID3v1.Create; +begin + inherited; + ResetData; +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v1.ResetData; +begin + FExists := false; + FVersionID := TAG_VERSION_1_0; + FTitle := ''; + FArtist := ''; + FAlbum := ''; + FYear := ''; + FComment := ''; + FTrack := 0; + FGenreID := DEFAULT_GENRE; +end; + +{ --------------------------------------------------------------------------- } + +function TID3v1.ReadFromFile(const FileName: string): Boolean; +var + TagData: TagRecord; +begin + { Reset and load tag data from file to variable } + ResetData; + Result := ReadTag(FileName, TagData); + { Process data if loaded and tag header OK } + if (Result) and (TagData.Header = 'TAG') then + begin + FExists := true; + FVersionID := GetTagVersion(TagData); + { Fill properties with tag data } + FTitle := TrimRight(TagData.Title); + FArtist := TrimRight(TagData.Artist); + FAlbum := TrimRight(TagData.Album); + FYear := TrimRight(TagData.Year); + if FVersionID = TAG_VERSION_1_0 then + FComment := TrimRight(TagData.Comment) + else + begin + FComment := TrimRight(Copy(TagData.Comment, 1, 28)); + FTrack := Ord(TagData.Comment[30]); + end; + FGenreID := TagData.Genre; + end; +end; + +{ --------------------------------------------------------------------------- } + +function TID3v1.RemoveFromFile(const FileName: string): Boolean; +var + TagData: TagRecord; +begin + { Find tag } + Result := ReadTag(FileName, TagData); + { Delete tag if loaded and tag header OK } + if (Result) and (TagData.Header = 'TAG') then Result := RemoveTag(FileName); +end; + +{ --------------------------------------------------------------------------- } + +function TID3v1.SaveToFile(const FileName: string): Boolean; +var + TagData: TagRecord; +begin + { Prepare tag record } + FillChar(TagData, SizeOf(TagData), 0); + TagData.Header := 'TAG'; + Move(FTitle[1], TagData.Title, Length(FTitle)); + Move(FArtist[1], TagData.Artist, Length(FArtist)); + Move(FAlbum[1], TagData.Album, Length(FAlbum)); + Move(FYear[1], TagData.Year, Length(FYear)); + Move(FComment[1], TagData.Comment, Length(FComment)); + if FTrack > 0 then + begin + TagData.Comment[29] := #0; + TagData.Comment[30] := Chr(FTrack); + end; + TagData.Genre := FGenreID; + { Delete old tag and write new tag } + Result := (RemoveFromFile(FileName)) and (SaveTag(FileName, TagData)); +end; + +{ ************************** Initialize music genres ************************ } + +initialization +begin + { Standard genres } + MusicGenre[0] := 'Blues'; + MusicGenre[1] := 'Classic Rock'; + MusicGenre[2] := 'Country'; + MusicGenre[3] := 'Dance'; + MusicGenre[4] := 'Disco'; + MusicGenre[5] := 'Funk'; + MusicGenre[6] := 'Grunge'; + MusicGenre[7] := 'Hip-Hop'; + MusicGenre[8] := 'Jazz'; + MusicGenre[9] := 'Metal'; + MusicGenre[10] := 'New Age'; + MusicGenre[11] := 'Oldies'; + MusicGenre[12] := 'Other'; + MusicGenre[13] := 'Pop'; + MusicGenre[14] := 'R&B'; + MusicGenre[15] := 'Rap'; + MusicGenre[16] := 'Reggae'; + MusicGenre[17] := 'Rock'; + MusicGenre[18] := 'Techno'; + MusicGenre[19] := 'Industrial'; + MusicGenre[20] := 'Alternative'; + MusicGenre[21] := 'Ska'; + MusicGenre[22] := 'Death Metal'; + MusicGenre[23] := 'Pranks'; + MusicGenre[24] := 'Soundtrack'; + MusicGenre[25] := 'Euro-Techno'; + MusicGenre[26] := 'Ambient'; + MusicGenre[27] := 'Trip-Hop'; + MusicGenre[28] := 'Vocal'; + MusicGenre[29] := 'Jazz+Funk'; + MusicGenre[30] := 'Fusion'; + MusicGenre[31] := 'Trance'; + MusicGenre[32] := 'Classical'; + MusicGenre[33] := 'Instrumental'; + MusicGenre[34] := 'Acid'; + MusicGenre[35] := 'House'; + MusicGenre[36] := 'Game'; + MusicGenre[37] := 'Sound Clip'; + MusicGenre[38] := 'Gospel'; + MusicGenre[39] := 'Noise'; + MusicGenre[40] := 'AlternRock'; + MusicGenre[41] := 'Bass'; + MusicGenre[42] := 'Soul'; + MusicGenre[43] := 'Punk'; + MusicGenre[44] := 'Space'; + MusicGenre[45] := 'Meditative'; + MusicGenre[46] := 'Instrumental Pop'; + MusicGenre[47] := 'Instrumental Rock'; + MusicGenre[48] := 'Ethnic'; + MusicGenre[49] := 'Gothic'; + MusicGenre[50] := 'Darkwave'; + MusicGenre[51] := 'Techno-Industrial'; + MusicGenre[52] := 'Electronic'; + MusicGenre[53] := 'Pop-Folk'; + MusicGenre[54] := 'Eurodance'; + MusicGenre[55] := 'Dream'; + MusicGenre[56] := 'Southern Rock'; + MusicGenre[57] := 'Comedy'; + MusicGenre[58] := 'Cult'; + MusicGenre[59] := 'Gangsta'; + MusicGenre[60] := 'Top 40'; + MusicGenre[61] := 'Christian Rap'; + MusicGenre[62] := 'Pop/Funk'; + MusicGenre[63] := 'Jungle'; + MusicGenre[64] := 'Native American'; + MusicGenre[65] := 'Cabaret'; + MusicGenre[66] := 'New Wave'; + MusicGenre[67] := 'Psychadelic'; + MusicGenre[68] := 'Rave'; + MusicGenre[69] := 'Showtunes'; + MusicGenre[70] := 'Trailer'; + MusicGenre[71] := 'Lo-Fi'; + MusicGenre[72] := 'Tribal'; + MusicGenre[73] := 'Acid Punk'; + MusicGenre[74] := 'Acid Jazz'; + MusicGenre[75] := 'Polka'; + MusicGenre[76] := 'Retro'; + MusicGenre[77] := 'Musical'; + MusicGenre[78] := 'Rock & Roll'; + MusicGenre[79] := 'Hard Rock'; + { Extended genres } + MusicGenre[80] := 'Folk'; + MusicGenre[81] := 'Folk-Rock'; + MusicGenre[82] := 'National Folk'; + MusicGenre[83] := 'Swing'; + MusicGenre[84] := 'Fast Fusion'; + MusicGenre[85] := 'Bebob'; + MusicGenre[86] := 'Latin'; + MusicGenre[87] := 'Revival'; + MusicGenre[88] := 'Celtic'; + MusicGenre[89] := 'Bluegrass'; + MusicGenre[90] := 'Avantgarde'; + MusicGenre[91] := 'Gothic Rock'; + MusicGenre[92] := 'Progessive Rock'; + MusicGenre[93] := 'Psychedelic Rock'; + MusicGenre[94] := 'Symphonic Rock'; + MusicGenre[95] := 'Slow Rock'; + MusicGenre[96] := 'Big Band'; + MusicGenre[97] := 'Chorus'; + MusicGenre[98] := 'Easy Listening'; + MusicGenre[99] := 'Acoustic'; + MusicGenre[100]:= 'Humour'; + MusicGenre[101]:= 'Speech'; + MusicGenre[102]:= 'Chanson'; + MusicGenre[103]:= 'Opera'; + MusicGenre[104]:= 'Chamber Music'; + MusicGenre[105]:= 'Sonata'; + MusicGenre[106]:= 'Symphony'; + MusicGenre[107]:= 'Booty Bass'; + MusicGenre[108]:= 'Primus'; + MusicGenre[109]:= 'Porn Groove'; + MusicGenre[110]:= 'Satire'; + MusicGenre[111]:= 'Slow Jam'; + MusicGenre[112]:= 'Club'; + MusicGenre[113]:= 'Tango'; + MusicGenre[114]:= 'Samba'; + MusicGenre[115]:= 'Folklore'; + MusicGenre[116]:= 'Ballad'; + MusicGenre[117]:= 'Power Ballad'; + MusicGenre[118]:= 'Rhythmic Soul'; + MusicGenre[119]:= 'Freestyle'; + MusicGenre[120]:= 'Duet'; + MusicGenre[121]:= 'Punk Rock'; + MusicGenre[122]:= 'Drum Solo'; + MusicGenre[123]:= 'A capella'; + MusicGenre[124]:= 'Euro-House'; + MusicGenre[125]:= 'Dance Hall'; + MusicGenre[126]:= 'Goa'; + MusicGenre[127]:= 'Drum & Bass'; + MusicGenre[128]:= 'Club-House'; + MusicGenre[129]:= 'Hardcore'; + MusicGenre[130]:= 'Terror'; + MusicGenre[131]:= 'Indie'; + MusicGenre[132]:= 'BritPop'; + MusicGenre[133]:= 'Negerpunk'; + MusicGenre[134]:= 'Polsk Punk'; + MusicGenre[135]:= 'Beat'; + MusicGenre[136]:= 'Christian Gangsta Rap'; + MusicGenre[137]:= 'Heavy Metal'; + MusicGenre[138]:= 'Black Metal'; + MusicGenre[139]:= 'Crossover'; + MusicGenre[140]:= 'Contemporary Christian'; + MusicGenre[141]:= 'Christian Rock'; + MusicGenre[142]:= 'Merengue'; + MusicGenre[143]:= 'Salsa'; + MusicGenre[144]:= 'Trash Metal'; + MusicGenre[145]:= 'Anime'; + MusicGenre[146]:= 'JPop'; + MusicGenre[147]:= 'Synthpop'; +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Info.txt b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Info.txt new file mode 100644 index 0000000..3e8f48a --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Info.txt @@ -0,0 +1,17 @@ +ID3v1.pas +Tested with Borland Delphi 3,4,5,6 + +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TID3v1 - for manipulating with ID3v1 tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.0 (25 July 2001) } +{ - Reading & writing support for ID3v1.x tags } +{ - Tag info: title, artist, album, track, year, genre, comment } +{ } +{ *************************************************************************** } \ No newline at end of file diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.dfm b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.dfm new file mode 100644 index 0000000..4a0acfa Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.dfm differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.pas new file mode 100644 index 0000000..aca653e --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Main.pas @@ -0,0 +1,162 @@ +unit Main; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + StdCtrls, FileCtrl, ExtCtrls, ID3v1; + +type + TMainForm = class(TForm) + DriveList: TDriveComboBox; + FolderList: TDirectoryListBox; + FileList: TFileListBox; + CloseButton: TButton; + RemoveButton: TButton; + SaveButton: TButton; + InfoBevel: TBevel; + IconImage: TImage; + TagExistsLabel: TLabel; + TagVersionLabel: TLabel; + TitleLabel: TLabel; + ArtistLabel: TLabel; + AlbumLabel: TLabel; + YearLabel: TLabel; + CommentLabel: TLabel; + TrackLabel: TLabel; + GenreLabel: TLabel; + TitleEdit: TEdit; + ArtistEdit: TEdit; + AlbumEdit: TEdit; + TrackEdit: TEdit; + YearEdit: TEdit; + CommentEdit: TEdit; + GenreComboBox: TComboBox; + TagExistsValue: TEdit; + TagVersionValue: TEdit; + procedure CloseButtonClick(Sender: TObject); + procedure FormCreate(Sender: TObject); + procedure FileListChange(Sender: TObject); + procedure FormClose(Sender: TObject; var Action: TCloseAction); + procedure SaveButtonClick(Sender: TObject); + procedure RemoveButtonClick(Sender: TObject); + private + { Private declarations } + FileTag: TID3v1; + procedure ClearAll; + end; + +var + MainForm: TMainForm; + +implementation + +{$R *.dfm} + +procedure TMainForm.ClearAll; +begin + { Clear all captions } + TagExistsValue.Text := ''; + TagVersionValue.Text := ''; + TitleEdit.Text := ''; + ArtistEdit.Text := ''; + AlbumEdit.Text := ''; + TrackEdit.Text := ''; + YearEdit.Text := ''; + GenreComboBox.ItemIndex := 0; + CommentEdit.Text := ''; +end; + +procedure TMainForm.CloseButtonClick(Sender: TObject); +begin + { Exit } + Close; +end; + +procedure TMainForm.FormCreate(Sender: TObject); +var + Iterator: Integer; +begin + { Create object } + FileTag := TID3v1.Create; + { Fill and initialize genres } + GenreComboBox.Items.Add(''); + for Iterator := 0 to MAX_MUSIC_GENRES - 1 do + GenreComboBox.Items.Add(MusicGenre[Iterator]); + { Reset } + ClearAll; +end; + +procedure TMainForm.FileListChange(Sender: TObject); +begin + { Clear captions } + ClearAll; + if FileList.FileName = '' then exit; + if FileExists(FileList.FileName) then + { Load tag data } + if FileTag.ReadFromFile(FileList.FileName) then + if FileTag.Exists then + begin + { Fill captions } + TagExistsValue.Text := 'Yes'; + if FileTag.VersionID = TAG_VERSION_1_0 then + TagVersionValue.Text := '1.0' + else + TagVersionValue.Text := '1.1'; + TitleEdit.Text := FileTag.Title; + ArtistEdit.Text := FileTag.Artist; + AlbumEdit.Text := FileTag.Album; + TrackEdit.Text := IntToStr(FileTag.Track); + YearEdit.Text := FileTag.Year; + if FileTag.GenreID < MAX_MUSIC_GENRES then + GenreComboBox.ItemIndex := FileTag.GenreID + 1; + CommentEdit.Text := FileTag.Comment; + end + else + { Tag not found } + TagExistsValue.Text := 'No' + else + { Read error } + ShowMessage('Can not read tag from the file: ' + FileList.FileName) + else + { File does not exist } + ShowMessage('The file does not exist: ' + FileList.FileName); +end; + +procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); +begin + { Free memory } + FileTag.Free; +end; + +procedure TMainForm.SaveButtonClick(Sender: TObject); +var + Value, Code: Integer; +begin + { Prepare tag data } + FileTag.Title := TitleEdit.Text; + FileTag.Artist := ArtistEdit.Text; + FileTag.Album := AlbumEdit.Text; + FileTag.Year := YearEdit.Text; + Val(TrackEdit.Text, Value, Code); + if (Code = 0) and (Value > 0) then FileTag.Track := Value + else FileTag.Track := 0; + if GenreComboBox.ItemIndex = 0 then FileTag.GenreID := DEFAULT_GENRE + else FileTag.GenreID := GenreComboBox.ItemIndex - 1; + FileTag.Comment := CommentEdit.Text; + { Save tag data } + if (not FileExists(FileList.FileName)) or + (not FileTag.SaveToFile(FileList.FileName)) then + ShowMessage('Can not save tag to the file: ' + FileList.FileName); + FileListChange(Self); +end; + +procedure TMainForm.RemoveButtonClick(Sender: TObject); +begin + { Delete tag data } + if (FileExists(FileList.FileName)) and + (FileTag.RemoveFromFile(FileList.FileName)) then ClearAll + else ShowMessage('Can not remove tag from the file: ' + FileList.FileName); +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.cfg b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.cfg new file mode 100644 index 0000000..dc18277 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.cfg @@ -0,0 +1,35 @@ +-$A8 +-$B- +-$C+ +-$D+ +-$E- +-$F- +-$G+ +-$H+ +-$I+ +-$J- +-$K- +-$L+ +-$M- +-$N+ +-$O+ +-$P+ +-$Q- +-$R- +-$S- +-$T- +-$U- +-$V+ +-$W- +-$X+ +-$YD +-$Z1 +-cg +-AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +-H+ +-W+ +-M +-$M16384,1048576 +-K$00400000 +-LE"c:\program files\borland\delphi6\Projects\Bpl" +-LN"c:\program files\borland\delphi6\Projects\Bpl" diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dof b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dof new file mode 100644 index 0000000..216ddb6 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dof @@ -0,0 +1,96 @@ +[FileVersion] +Version=6.0 +[Compiler] +A=8 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=0 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=1 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +RemoteSymbols=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +PackageDLLOutputDir= +PackageDCPOutputDir= +SearchPath= +Packages=vcl;rtl;dbrtl;adortl;vcldb;vclx;bdertl;vcldbx;ibxpress;dsnap;cds;bdecds;qrpt;teeui;teedb;tee;dss;teeqr;visualclx;visualdbclx;dsnapcrba;dsnapcon;VclSmp;vclshlctrls;vclie;xmlrtl;inet;inetdbbde;inetdbxpress;inetdb;nmfast;webdsnap;websnap;dbexpress;dbxcds;indy;dclOffice2k +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +Launcher= +UseLauncher=0 +DebugCWD= +[Language] +ActiveLang= +ProjectLang= +RootDir= +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1031 +CodePage=1252 +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= +[HistoryLists\hlUnitAliases] +Count=1 +Item0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[HistoryLists\hlUnitOutputDirectory] +Count=1 +Item0=DCU +[HistoryLists\hlOutputDirectorry] +Count=1 +Item0=Data diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dpr b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dpr new file mode 100644 index 0000000..8c4aa94 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.dpr @@ -0,0 +1,15 @@ +program Test; + +uses + Forms, + Main in 'Main.pas' {MainForm}, + ID3v1 in 'ID3v1.pas'; + +{$R *.res} + +begin + Application.Initialize; + Application.Title := 'ID3v1 Test'; + Application.CreateForm(TMainForm, MainForm); + Application.Run; +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.res b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.res new file mode 100644 index 0000000..3c80f0b Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v1/Test.res differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/ID3v2.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/ID3v2.pas new file mode 100644 index 0000000..1c19978 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/ID3v2.pas @@ -0,0 +1,631 @@ +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TID3v2 - for manipulating with ID3v2 tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.4 (24 March 2002) } +{ - Reading support for ID3v2.2.x & ID3v2.4.x tags } +{ } +{ Version 1.3 (16 February 2002) } +{ - Fixed bug with property Comment } +{ - Added info: composer, encoder, copyright, language, link } +{ } +{ Version 1.2 (17 October 2001) } +{ - Writing support for ID3v2.3.x tags } +{ - Fixed bug with track number detection } +{ - Fixed bug with tag reading } +{ } +{ Version 1.1 (31 August 2001) } +{ - Added public procedure ResetData } +{ } +{ Version 1.0 (14 August 2001) } +{ - Reading support for ID3v2.3.x tags } +{ - Tag info: title, artist, album, track, year, genre, comment } +{ } +{ *************************************************************************** } + +unit ID3v2; + +interface + +uses + Classes, SysUtils; + +const + TAG_VERSION_2_2 = 2; { Code for ID3v2.2.x tag } + TAG_VERSION_2_3 = 3; { Code for ID3v2.3.x tag } + TAG_VERSION_2_4 = 4; { Code for ID3v2.4.x tag } + +type + { Class TID3v2 } + TID3v2 = class(TObject) + private + { Private declarations } + FExists: Boolean; + FVersionID: Byte; + FSize: Integer; + FTitle: string; + FArtist: string; + FAlbum: string; + FTrack: Byte; + FYear: string; + FGenre: string; + FComment: string; + FComposer: string; + FEncoder: string; + FCopyright: string; + FLanguage: string; + FLink: string; + procedure FSetTitle(const NewTitle: string); + procedure FSetArtist(const NewArtist: string); + procedure FSetAlbum(const NewAlbum: string); + procedure FSetTrack(const NewTrack: Byte); + procedure FSetYear(const NewYear: string); + procedure FSetGenre(const NewGenre: string); + procedure FSetComment(const NewComment: string); + procedure FSetComposer(const NewComposer: string); + procedure FSetEncoder(const NewEncoder: string); + procedure FSetCopyright(const NewCopyright: string); + procedure FSetLanguage(const NewLanguage: string); + procedure FSetLink(const NewLink: string); + public + { Public declarations } + constructor Create; { Create object } + procedure ResetData; { Reset all data } + function ReadFromFile(const FileName: string): Boolean; { Load tag } + function SaveToFile(const FileName: string): Boolean; { Save tag } + function RemoveFromFile(const FileName: string): Boolean; { Delete tag } + property Exists: Boolean read FExists; { True if tag found } + property VersionID: Byte read FVersionID; { Version code } + property Size: Integer read FSize; { Total tag size } + property Title: string read FTitle write FSetTitle; { Song title } + property Artist: string read FArtist write FSetArtist; { Artist name } + property Album: string read FAlbum write FSetAlbum; { Album title } + property Track: Byte read FTrack write FSetTrack; { Track number } + property Year: string read FYear write FSetYear; { Release year } + property Genre: string read FGenre write FSetGenre; { Genre name } + property Comment: string read FComment write FSetComment; { Comment } + property Composer: string read FComposer write FSetComposer; { Composer } + property Encoder: string read FEncoder write FSetEncoder; { Encoder } + property Copyright: string read FCopyright write FSetCopyright; { (c) } + property Language: string read FLanguage write FSetLanguage; { Language } + property Link: string read FLink write FSetLink; { URL link } + end; + +implementation + +const + { ID3v2 tag ID } + ID3V2_ID = 'ID3'; + + { Max. number of supported tag frames } + ID3V2_FRAME_COUNT = 16; + + { Names of supported tag frames (ID3v2.3.x & ID3v2.4.x) } + ID3V2_FRAME_NEW: array [1..ID3V2_FRAME_COUNT] of string = + ('TIT2', 'TPE1', 'TALB', 'TRCK', 'TYER', 'TCON', 'COMM', 'TCOM', 'TENC', + 'TCOP', 'TLAN', 'WXXX', 'TDRC', 'TOPE', 'TIT1', 'TOAL'); + + { Names of supported tag frames (ID3v2.2.x) } + ID3V2_FRAME_OLD: array [1..ID3V2_FRAME_COUNT] of string = + ('TT2', 'TP1', 'TAL', 'TRK', 'TYE', 'TCO', 'COM', 'TCM', 'TEN', + 'TCR', 'TLA', 'WXX', 'TOR', 'TOA', 'TT1', 'TOT'); + +type + { Frame header (ID3v2.3.x & ID3v2.4.x) } + FrameHeaderNew = record + ID: array [1..4] of Char; { Frame ID } + Size: Integer; { Size excluding header } + Flags: Word; { Flags } + end; + + { Frame header (ID3v2.2.x) } + FrameHeaderOld = record + ID: array [1..3] of Char; { Frame ID } + Size: array [1..3] of Byte; { Size excluding header } + end; + + { ID3v2 header data - for internal use } + TagInfo = record + { Real structure of ID3v2 header } + ID: array [1..3] of Char; { Always "ID3" } + Version: Byte; { Version number } + Revision: Byte; { Revision number } + Flags: Byte; { Flags of tag } + Size: array [1..4] of Byte; { Tag size excluding header } + { Extended data } + FileSize: Integer; { File size (bytes) } + Frame: array [1..ID3V2_FRAME_COUNT] of string; { Information from frames } + end; + +{ ********************* Auxiliary functions & procedures ******************** } + +function ReadHeader(const FileName: string; var Tag: TagInfo): Boolean; +var + SourceFile: file; + Transferred: Integer; +begin + try + Result := true; + { Set read-access and open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + { Read header and get file size } + BlockRead(SourceFile, Tag, 10, Transferred); + Tag.FileSize := FileSize(SourceFile); + CloseFile(SourceFile); + { if transfer is not complete } + if Transferred < 10 then Result := false; + except + { Error } + Result := false; + end; +end; + +{ --------------------------------------------------------------------------- } + +function GetTagSize(const Tag: TagInfo): Integer; +begin + { Get total tag size } + Result := + Tag.Size[1] * $200000 + + Tag.Size[2] * $4000 + + Tag.Size[3] * $80 + + Tag.Size[4] + 10; + if Tag.Flags and $10 > 0 then Inc(Result, 10); + if Result > Tag.FileSize then Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +procedure SetTagItem(const ID, Data: string; var Tag: TagInfo); +var + Iterator: Byte; + FrameID: string; +begin + { Set tag item if supported frame found } + for Iterator := 1 to ID3V2_FRAME_COUNT do + begin + if Tag.Version > TAG_VERSION_2_2 then FrameID := ID3V2_FRAME_NEW[Iterator] + else FrameID := ID3V2_FRAME_OLD[Iterator]; + if FrameID = ID then Tag.Frame[Iterator] := Data; + end; +end; + +{ --------------------------------------------------------------------------- } + +function Swap32(const Figure: Integer): Integer; +var + ByteArray: array [1..4] of Byte absolute Figure; +begin + { Swap 4 bytes } + Result := + ByteArray[1] * $1000000 + + ByteArray[2] * $10000 + + ByteArray[3] * $100 + + ByteArray[4]; +end; + +{ --------------------------------------------------------------------------- } + +procedure ReadFramesNew(const FileName: string; var Tag: TagInfo); +var + SourceFile: file; + Frame: FrameHeaderNew; + Data: array [1..250] of Char; + DataPosition, DataSize: Integer; +begin + { Get information from frames (ID3v2.3.x & ID3v2.4.x) } + try + { Set read-access, open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + Seek(SourceFile, 10); + while (FilePos(SourceFile) < GetTagSize(Tag)) and (not EOF(SourceFile)) do + begin + FillChar(Data, SizeOf(Data), 0); + { Read frame header and check frame ID } + BlockRead(SourceFile, Frame, 10); + if not (Frame.ID[1] in ['A'..'Z']) then break; + { Note data position and determine significant data size } + DataPosition := FilePos(SourceFile); + if Swap32(Frame.Size) > SizeOf(Data) then DataSize := SizeOf(Data) + else DataSize := Swap32(Frame.Size); + { Read frame data and set tag item if frame supported } + BlockRead(SourceFile, Data, DataSize); + SetTagItem(Frame.ID, Data, Tag); + Seek(SourceFile, DataPosition + Swap32(Frame.Size)); + end; + CloseFile(SourceFile); + except + end; +end; + +{ --------------------------------------------------------------------------- } + +procedure ReadFramesOld(const FileName: string; var Tag: TagInfo); +var + SourceFile: file; + Frame: FrameHeaderOld; + Data: array [1..250] of Char; + DataPosition, FrameSize, DataSize: Integer; +begin + { Get information from frames (ID3v2.2.x) } + try + { Set read-access, open file } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + Seek(SourceFile, 10); + while (FilePos(SourceFile) < GetTagSize(Tag)) and (not EOF(SourceFile)) do + begin + FillChar(Data, SizeOf(Data), 0); + { Read frame header and check frame ID } + BlockRead(SourceFile, Frame, 6); + if not (Frame.ID[1] in ['A'..'Z']) then break; + { Note data position and determine significant data size } + DataPosition := FilePos(SourceFile); + FrameSize := Frame.Size[1] shl 16 + Frame.Size[2] shl 8 + Frame.Size[3]; + if FrameSize > SizeOf(Data) then DataSize := SizeOf(Data) + else DataSize := FrameSize; + { Read frame data and set tag item if frame supported } + BlockRead(SourceFile, Data, DataSize); + SetTagItem(Frame.ID, Data, Tag); + Seek(SourceFile, DataPosition + FrameSize); + end; + CloseFile(SourceFile); + except + end; +end; + +{ --------------------------------------------------------------------------- } + +function GetContent(const Content1, Content2: string): string; +begin + { Get content preferring the first content } + Result := Trim(Content1); + if Result = '' then Result := Trim(Content2); +end; + +{ --------------------------------------------------------------------------- } + +function ExtractTrack(const TrackString: string): Byte; +var + Index, Value, Code: Integer; +begin + { Extract track from string } + Index := Pos('/', Trim(TrackString)); + if Index = 0 then Val(Trim(TrackString), Value, Code) + else Val(Copy(Trim(TrackString), 1, Index - 1), Value, Code); + if Code = 0 then Result := Value + else Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function ExtractYear(const YearString, DateString: string): string; +begin + { Extract year from strings } + Result := Trim(YearString); + if Result = '' then Result := Copy(Trim(DateString), 1, 4); +end; + +{ --------------------------------------------------------------------------- } + +function ExtractGenre(const GenreString: string): string; +begin + { Extract genre from string } + Result := Trim(GenreString); + if Pos(')', Result) > 0 then Delete(Result, 1, LastDelimiter(')', Result)); +end; + +{ --------------------------------------------------------------------------- } + +function ExtractComment(const CommentString: string): string; +var + Comment: string; +begin + { Extract comment from string } + Comment := CommentString; + Delete(Comment, 1, 4); + Delete(Comment, 1, Pos(#0, Comment)); + Result := Trim(Comment); +end; + +{ --------------------------------------------------------------------------- } + +function ExtractLink(const LinkString: string): string; +var + Link: string; +begin + { Extract URL link from string } + Link := LinkString; + Delete(Link, 1, 1); + Delete(Link, 1, Pos(#0, Link)); + Result := Trim(Link); +end; + +{ --------------------------------------------------------------------------- } + +procedure BuildHeader(var Tag: TagInfo); +var + Iterator, TagSize: Integer; +begin + { Build tag header } + Tag.ID := ID3V2_ID; + Tag.Version := TAG_VERSION_2_3; + Tag.Revision := 0; + Tag.Flags := 0; + TagSize := 0; + for Iterator := 1 to ID3V2_FRAME_COUNT do + if Tag.Frame[Iterator] <> '' then + Inc(TagSize, Length(Tag.Frame[Iterator]) + 11); + { Convert tag size } + Tag.Size[1] := TagSize div $200000; + Tag.Size[2] := TagSize div $4000; + Tag.Size[3] := TagSize div $80; + Tag.Size[4] := TagSize mod $80; +end; + +{ --------------------------------------------------------------------------- } + +function RebuildFile(const FileName: string; TagData: TStream): Boolean; +var + Tag: TagInfo; + Source, Destination: TFileStream; + BufferName: string; +begin + { Rebuild file with old file data and new tag data (optional) } + Result := false; + if (not FileExists(FileName)) or (FileSetAttr(FileName, 0) <> 0) then exit; + if not ReadHeader(FileName, Tag) then exit; + if (TagData = nil) and (Tag.ID <> ID3V2_ID) then exit; + try + { Create file streams } + BufferName := FileName + '~'; + Source := TFileStream.Create(FileName, fmOpenRead or fmShareExclusive); + Destination := TFileStream.Create(BufferName, fmCreate); + { Copy data blocks } + if Tag.ID = ID3V2_ID then Source.Seek(GetTagSize(Tag), soFromBeginning); + if TagData <> nil then Destination.CopyFrom(TagData, 0); + Destination.CopyFrom(Source, Source.Size - Source.Position); + { Free resources } + Source.Free; + Destination.Free; + { Replace old file and delete temporary file } + if (DeleteFile(FileName)) and (RenameFile(BufferName, FileName)) then + Result := true + else + raise Exception.Create(''); + except + { Access error } + if FileExists(BufferName) then DeleteFile(BufferName); + end; +end; + +{ --------------------------------------------------------------------------- } + +function SaveTag(const FileName: string; Tag: TagInfo): Boolean; +var + TagData: TStringStream; + Iterator, FrameSize: Integer; +begin + { Build and write tag header and frames to stream } + TagData := TStringStream.Create(''); + BuildHeader(Tag); + TagData.Write(Tag, 10); + for Iterator := 1 to ID3V2_FRAME_COUNT do + if Tag.Frame[Iterator] <> '' then + begin + TagData.WriteString(ID3V2_FRAME_NEW[Iterator]); + FrameSize := Swap32(Length(Tag.Frame[Iterator]) + 1); + TagData.Write(FrameSize, SizeOf(FrameSize)); + TagData.WriteString(#0#0#0 + Tag.Frame[Iterator]); + end; + { Rebuild file with new tag data } + Result := RebuildFile(FileName, TagData); + TagData.Free; +end; + +{ ********************** Private functions & procedures ********************* } + +procedure TID3v2.FSetTitle(const NewTitle: string); +begin + { Set song title } + FTitle := Trim(NewTitle); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetArtist(const NewArtist: string); +begin + { Set artist name } + FArtist := Trim(NewArtist); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetAlbum(const NewAlbum: string); +begin + { Set album title } + FAlbum := Trim(NewAlbum); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetTrack(const NewTrack: Byte); +begin + { Set track number } + FTrack := NewTrack; +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetYear(const NewYear: string); +begin + { Set release year } + FYear := Trim(NewYear); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetGenre(const NewGenre: string); +begin + { Set genre name } + FGenre := Trim(NewGenre); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetComment(const NewComment: string); +begin + { Set comment } + FComment := Trim(NewComment); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetComposer(const NewComposer: string); +begin + { Set composer name } + FComposer := Trim(NewComposer); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetEncoder(const NewEncoder: string); +begin + { Set encoder name } + FEncoder := Trim(NewEncoder); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetCopyright(const NewCopyright: string); +begin + { Set copyright information } + FCopyright := Trim(NewCopyright); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetLanguage(const NewLanguage: string); +begin + { Set language } + FLanguage := Trim(NewLanguage); +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.FSetLink(const NewLink: string); +begin + { Set URL link } + FLink := Trim(NewLink); +end; + +{ ********************** Public functions & procedures ********************** } + +constructor TID3v2.Create; +begin + { Create object } + inherited; + ResetData; +end; + +{ --------------------------------------------------------------------------- } + +procedure TID3v2.ResetData; +begin + { Reset all variables } + FExists := false; + FVersionID := 0; + FSize := 0; + FTitle := ''; + FArtist := ''; + FAlbum := ''; + FTrack := 0; + FYear := ''; + FGenre := ''; + FComment := ''; + FComposer := ''; + FEncoder := ''; + FCopyright := ''; + FLanguage := ''; + FLink := ''; +end; + +{ --------------------------------------------------------------------------- } + +function TID3v2.ReadFromFile(const FileName: string): Boolean; +var + Tag: TagInfo; +begin + { Reset data and load header from file to variable } + ResetData; + Result := ReadHeader(FileName, Tag); + { Process data if loaded and header valid } + if (Result) and (Tag.ID = ID3V2_ID) then + begin + FExists := true; + { Fill properties with header data } + FVersionID := Tag.Version; + FSize := GetTagSize(Tag); + { Get information from frames if version supported } + if (FVersionID in [TAG_VERSION_2_2..TAG_VERSION_2_4]) and (FSize > 0) then + begin + if FVersionID > TAG_VERSION_2_2 then ReadFramesNew(FileName, Tag) + else ReadFramesOld(FileName, Tag); + FTitle := GetContent(Tag.Frame[1], Tag.Frame[15]); + FArtist := GetContent(Tag.Frame[2], Tag.Frame[14]); + FAlbum := GetContent(Tag.Frame[3], Tag.Frame[16]); + FTrack := ExtractTrack(Tag.Frame[4]); + FYear := ExtractYear(Tag.Frame[5], Tag.Frame[13]); + FGenre := ExtractGenre(Tag.Frame[6]); + FComment := ExtractComment(Tag.Frame[7]); + FComposer := Trim(Tag.Frame[8]); + FEncoder := Trim(Tag.Frame[9]); + FCopyright := Trim(Tag.Frame[10]); + FLanguage := Trim(Tag.Frame[11]); + FLink := ExtractLink(Tag.Frame[12]); + end; + end; +end; + +{ --------------------------------------------------------------------------- } + +function TID3v2.SaveToFile(const FileName: string): Boolean; +var + Tag: TagInfo; +begin + { Prepare tag data and save to file } + FillChar(Tag, SizeOf(Tag), 0); + Tag.Frame[1] := FTitle; + Tag.Frame[2] := FArtist; + Tag.Frame[3] := FAlbum; + if FTrack > 0 then Tag.Frame[4] := IntToStr(FTrack); + Tag.Frame[5] := FYear; + Tag.Frame[6] := FGenre; + if FComment <> '' then Tag.Frame[7] := 'eng' + #0 + FComment; + Tag.Frame[8] := FComposer; + Tag.Frame[9] := FEncoder; + Tag.Frame[10] := FCopyright; + Tag.Frame[11] := FLanguage; + if FLink <> '' then Tag.Frame[12] := #0 + FLink; + Result := SaveTag(FileName, Tag); +end; + +{ --------------------------------------------------------------------------- } + +function TID3v2.RemoveFromFile(const FileName: string): Boolean; +begin + { Remove tag from file } + Result := RebuildFile(FileName, nil); +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Info.txt b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Info.txt new file mode 100644 index 0000000..85b5077 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Info.txt @@ -0,0 +1,32 @@ +ID3v2.pas +Tested with Borland Delphi 3,4,5,6 + +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TID3v2 - for manipulating with ID3v2 tags } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.4 (24 March 2002) } +{ - Reading support for ID3v2.2.x & ID3v2.4.x tags } +{ } +{ Version 1.3 (16 February 2002) } +{ - Fixed bug with property Comment } +{ - Added info: composer, encoder, copyright, language, link } +{ } +{ Version 1.2 (17 October 2001) } +{ - Writing support for ID3v2.3.x tags } +{ - Fixed bug with track number detection } +{ - Fixed bug with tag reading } +{ } +{ Version 1.1 (31 August 2001) } +{ - Added public procedure ResetData } +{ } +{ Version 1.0 (14 August 2001) } +{ - Reading support for ID3v2.3.x tags } +{ - Tag info: title, artist, album, track, year, genre, comment } +{ } +{ *************************************************************************** } \ No newline at end of file diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.dfm b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.dfm new file mode 100644 index 0000000..544b7be Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.dfm differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.pas new file mode 100644 index 0000000..b91c525 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Main.pas @@ -0,0 +1,179 @@ +unit Main; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + StdCtrls, FileCtrl, ExtCtrls, ID3v2; + +type + TMainForm = class(TForm) + DriveList: TDriveComboBox; + FolderList: TDirectoryListBox; + FileList: TFileListBox; + SaveButton: TButton; + RemoveButton: TButton; + CloseButton: TButton; + InfoBevel: TBevel; + IconImage: TImage; + TagExistsLabel: TLabel; + TagExistsValue: TEdit; + VersionLabel: TLabel; + VersionValue: TEdit; + SizeLabel: TLabel; + SizeValue: TEdit; + TitleLabel: TLabel; + TitleEdit: TEdit; + ArtistLabel: TLabel; + ArtistEdit: TEdit; + AlbumLabel: TLabel; + AlbumEdit: TEdit; + TrackLabel: TLabel; + TrackEdit: TEdit; + YearLabel: TLabel; + YearEdit: TEdit; + GenreLabel: TLabel; + GenreEdit: TEdit; + CommentLabel: TLabel; + CommentEdit: TEdit; + ComposerLabel: TLabel; + ComposerEdit: TEdit; + EncoderLabel: TLabel; + EncoderEdit: TEdit; + CopyrightLabel: TLabel; + CopyrightEdit: TEdit; + LanguageLabel: TLabel; + LanguageEdit: TEdit; + LinkLabel: TLabel; + LinkEdit: TEdit; + procedure FormCreate(Sender: TObject); + procedure FileListChange(Sender: TObject); + procedure FormClose(Sender: TObject; var Action: TCloseAction); + procedure SaveButtonClick(Sender: TObject); + procedure RemoveButtonClick(Sender: TObject); + procedure CloseButtonClick(Sender: TObject); + private + { Private declarations } + FileTag: TID3v2; + procedure ClearAll; + end; + +var + MainForm: TMainForm; + +implementation + +{$R *.dfm} + +procedure TMainForm.ClearAll; +begin + { Clear all captions } + TagExistsValue.Text := ''; + VersionValue.Text := ''; + SizeValue.Text := ''; + TitleEdit.Text := ''; + ArtistEdit.Text := ''; + AlbumEdit.Text := ''; + TrackEdit.Text := ''; + YearEdit.Text := ''; + GenreEdit.Text := ''; + CommentEdit.Text := ''; + ComposerEdit.Text := ''; + EncoderEdit.Text := ''; + CopyrightEdit.Text := ''; + LanguageEdit.Text := ''; + LinkEdit.Text := ''; +end; + +procedure TMainForm.FormCreate(Sender: TObject); +begin + { Create object and clear captions } + FileTag := TID3v2.Create; + ClearAll; +end; + +procedure TMainForm.FileListChange(Sender: TObject); +begin + { Clear captions } + ClearAll; + if FileList.FileName = '' then exit; + if FileExists(FileList.FileName) then + { Load tag data } + if FileTag.ReadFromFile(FileList.FileName) then + if FileTag.Exists then + begin + { Fill captions } + TagExistsValue.Text := 'Yes'; + VersionValue.Text := '2.' + IntToStr(FileTag.VersionID); + SizeValue.Text := IntToStr(FileTag.Size) + ' bytes'; + TitleEdit.Text := FileTag.Title; + ArtistEdit.Text := FileTag.Artist; + AlbumEdit.Text := FileTag.Album; + if FileTag.Track > 0 then TrackEdit.Text := IntToStr(FileTag.Track); + YearEdit.Text := FileTag.Year; + GenreEdit.Text := FileTag.Genre; + CommentEdit.Text := FileTag.Comment; + ComposerEdit.Text := FileTag.Composer; + EncoderEdit.Text := FileTag.Encoder; + CopyrightEdit.Text := FileTag.Copyright; + LanguageEdit.Text := FileTag.Language; + LinkEdit.Text := FileTag.Link; + end + else + { Tag not found } + TagExistsValue.Text := 'No' + else + { Read error } + ShowMessage('Can not read tag from the file: ' + FileList.FileName) + else + { File does not exist } + ShowMessage('The file does not exist: ' + FileList.FileName); +end; + +procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); +begin + { Free memory } + FileTag.Free; +end; + +procedure TMainForm.SaveButtonClick(Sender: TObject); +var + Value, Code: Integer; +begin + { Prepare tag data } + FileTag.Title := TitleEdit.Text; + FileTag.Artist := ArtistEdit.Text; + FileTag.Album := AlbumEdit.Text; + Val(TrackEdit.Text, Value, Code); + if (Code = 0) and (Value > 0) then FileTag.Track := Value + else FileTag.Track := 0; + FileTag.Year := YearEdit.Text; + FileTag.Genre := GenreEdit.Text; + FileTag.Comment := CommentEdit.Text; + FileTag.Composer := ComposerEdit.Text; + FileTag.Encoder := EncoderEdit.Text; + FileTag.Copyright := CopyrightEdit.Text; + FileTag.Language := LanguageEdit.Text; + FileTag.Link := LinkEdit.Text; + { Save tag data } + if (not FileExists(FileList.FileName)) or + (not FileTag.SaveToFile(FileList.FileName)) then + ShowMessage('Can not save tag to the file: ' + FileList.FileName); + FileListChange(Self); +end; + +procedure TMainForm.RemoveButtonClick(Sender: TObject); +begin + { Delete tag data } + if (FileExists(FileList.FileName)) and + (FileTag.RemoveFromFile(FileList.FileName)) then ClearAll + else ShowMessage('Can not remove tag from the file: ' + FileList.FileName); +end; + +procedure TMainForm.CloseButtonClick(Sender: TObject); +begin + { Exit } + Close; +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.cfg b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.cfg new file mode 100644 index 0000000..dc18277 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.cfg @@ -0,0 +1,35 @@ +-$A8 +-$B- +-$C+ +-$D+ +-$E- +-$F- +-$G+ +-$H+ +-$I+ +-$J- +-$K- +-$L+ +-$M- +-$N+ +-$O+ +-$P+ +-$Q- +-$R- +-$S- +-$T- +-$U- +-$V+ +-$W- +-$X+ +-$YD +-$Z1 +-cg +-AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +-H+ +-W+ +-M +-$M16384,1048576 +-K$00400000 +-LE"c:\program files\borland\delphi6\Projects\Bpl" +-LN"c:\program files\borland\delphi6\Projects\Bpl" diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dof b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dof new file mode 100644 index 0000000..216ddb6 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dof @@ -0,0 +1,96 @@ +[FileVersion] +Version=6.0 +[Compiler] +A=8 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=0 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=1 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +RemoteSymbols=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +PackageDLLOutputDir= +PackageDCPOutputDir= +SearchPath= +Packages=vcl;rtl;dbrtl;adortl;vcldb;vclx;bdertl;vcldbx;ibxpress;dsnap;cds;bdecds;qrpt;teeui;teedb;tee;dss;teeqr;visualclx;visualdbclx;dsnapcrba;dsnapcon;VclSmp;vclshlctrls;vclie;xmlrtl;inet;inetdbbde;inetdbxpress;inetdb;nmfast;webdsnap;websnap;dbexpress;dbxcds;indy;dclOffice2k +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +Launcher= +UseLauncher=0 +DebugCWD= +[Language] +ActiveLang= +ProjectLang= +RootDir= +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1031 +CodePage=1252 +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= +[HistoryLists\hlUnitAliases] +Count=1 +Item0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[HistoryLists\hlUnitOutputDirectory] +Count=1 +Item0=DCU +[HistoryLists\hlOutputDirectorry] +Count=1 +Item0=Data diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dpr b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dpr new file mode 100644 index 0000000..e6ad934 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.dpr @@ -0,0 +1,15 @@ +program Test; + +uses + Forms, + Main in 'Main.pas' {MainForm}, + ID3v2 in 'ID3v2.pas'; + +{$R *.res} + +begin + Application.Initialize; + Application.Title := 'ID3v2 Test'; + Application.CreateForm(TMainForm, MainForm); + Application.Run; +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.res b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.res new file mode 100644 index 0000000..bf41bf1 Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/ID3v2/Test.res differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Info.txt b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Info.txt new file mode 100644 index 0000000..83cb471 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Info.txt @@ -0,0 +1,30 @@ +Monkey.pas (ID3v1.pas, ID3v2.pas, APEtag.pas needed) +Tested with Borland Delphi 3,4,5,6 + +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TMonkey - for manipulating with Monkey's Audio file information } +{ } +{ Uses: } +{ - Class TID3v1 } +{ - Class TID3v2 } +{ - Class TAPEtag } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.2 (21 April 2002) } +{ - Class TID3v2: support for ID3v2 tags } +{ - Class TAPEtag: support for APE tags } +{ } +{ Version 1.1 (11 September 2001) } +{ - Added property Samples } +{ - Removed WAV header information } +{ } +{ Version 1.0 (7 September 2001) } +{ - Support for Monkey's Audio files } +{ - Class TID3v1: reading & writing support for ID3v1.x tags } +{ } +{ *************************************************************************** } \ No newline at end of file diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.dfm b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.dfm new file mode 100644 index 0000000..6f6cc37 Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.dfm differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.pas new file mode 100644 index 0000000..45c7089 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Main.pas @@ -0,0 +1,131 @@ +unit Main; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + StdCtrls, FileCtrl, ExtCtrls, Monkey; + +type + TMainForm = class(TForm) + DriveList: TDriveComboBox; + FolderList: TDirectoryListBox; + FileList: TFileListBox; + CloseButton: TButton; + InfoBevel: TBevel; + IconImage: TImage; + ValidHeaderLabel: TLabel; + FileLengthLabel: TLabel; + ValidHeaderValue: TEdit; + ChannelModeValue: TEdit; + ChannelModeLabel: TLabel; + SampleRateLabel: TLabel; + BitsPerSampleLabel: TLabel; + DurationLabel: TLabel; + SampleRateValue: TEdit; + BitsPerSampleValue: TEdit; + DurationValue: TEdit; + FileLengthValue: TEdit; + CompressionLabel: TLabel; + CompressionValue: TEdit; + PeakLevelLabel: TLabel; + PeakLevelValue: TEdit; + FramesLabel: TLabel; + FramesValue: TEdit; + FlagsLabel: TLabel; + FlagsValue: TEdit; + SeekElementsLabel: TLabel; + SeekElementsValue: TEdit; + TotalSamplesLabel: TLabel; + TotalSamplesValue: TEdit; + procedure CloseButtonClick(Sender: TObject); + procedure FormCreate(Sender: TObject); + procedure FileListChange(Sender: TObject); + procedure FormClose(Sender: TObject; var Action: TCloseAction); + private + { Private declarations } + Monkey: TMonkey; + procedure ClearAll; + end; + +var + MainForm: TMainForm; + +implementation + +{$R *.dfm} + +procedure TMainForm.ClearAll; +begin + { Clear all captions } + ValidHeaderValue.Text := ''; + FileLengthValue.Text := ''; + ChannelModeValue.Text := ''; + SampleRateValue.Text := ''; + BitsPerSampleValue.Text := ''; + DurationValue.Text := ''; + FlagsValue.Text := ''; + FramesValue.Text := ''; + TotalSamplesValue.Text := ''; + PeakLevelValue.Text := ''; + SeekElementsValue.Text := ''; + CompressionValue.Text := ''; +end; + +procedure TMainForm.CloseButtonClick(Sender: TObject); +begin + { Exit } + Close; +end; + +procedure TMainForm.FormCreate(Sender: TObject); +begin + { Create object and reset captions } + Monkey := TMonkey.Create; + ClearAll; +end; + +procedure TMainForm.FileListChange(Sender: TObject); +begin + { Clear captions } + ClearAll; + if FileList.FileName = '' then exit; + if FileExists(FileList.FileName) then + { Load Monkey's Audio data } + if Monkey.ReadFromFile(FileList.FileName) then + if Monkey.Valid then + begin + { Fill captions } + ValidHeaderValue.Text := 'Yes, version ' + Monkey.Version; + FileLengthValue.Text := IntToStr(Monkey.FileLength) + ' bytes'; + ChannelModeValue.Text := Monkey.ChannelMode; + SampleRateValue.Text := IntToStr(Monkey.Header.SampleRate) + ' hz'; + BitsPerSampleValue.Text := IntToStr(Monkey.Bits) + ' bit'; + DurationValue.Text := FormatFloat('.000', Monkey.Duration) + ' sec.'; + FlagsValue.Text := IntToStr(Monkey.Header.Flags); + FramesValue.Text := IntToStr(Monkey.Header.Frames); + TotalSamplesValue.Text := IntToStr(Monkey.Samples); + PeakLevelValue.Text := FormatFloat('00.00', Monkey.Peak) + '% - ' + + IntToStr(Monkey.Header.PeakLevel); + SeekElementsValue.Text := IntToStr(Monkey.Header.SeekElements); + CompressionValue.Text := FormatFloat('00.00', Monkey.Ratio) + '% - ' + + Monkey.Compression; + end + else + { Header not found } + ValidHeaderValue.Text := 'No' + else + { Read error } + ShowMessage('Can not read header in the file: ' + FileList.FileName) + else + { File does not exist } + ShowMessage('The file does not exist: ' + FileList.FileName); +end; + +procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); +begin + { Free memory } + Monkey.Free; +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Monkey.pas b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Monkey.pas new file mode 100644 index 0000000..2816561 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Monkey.pas @@ -0,0 +1,300 @@ +{ *************************************************************************** } +{ } +{ Audio Tools Library (Freeware) } +{ Class TMonkey - for manipulating with Monkey's Audio file information } +{ } +{ Uses: } +{ - Class TID3v1 } +{ - Class TID3v2 } +{ - Class TAPEtag } +{ } +{ Copyright (c) 2001,2002 by Jurgen Faul } +{ E-mail: jfaul@gmx.de } +{ http://jfaul.de/atl } +{ } +{ Version 1.2 (21 April 2002) } +{ - Class TID3v2: support for ID3v2 tags } +{ - Class TAPEtag: support for APE tags } +{ } +{ Version 1.1 (11 September 2001) } +{ - Added property Samples } +{ - Removed WAV header information } +{ } +{ Version 1.0 (7 September 2001) } +{ - Support for Monkey's Audio files } +{ - Class TID3v1: reading & writing support for ID3v1.x tags } +{ } +{ *************************************************************************** } + +unit Monkey; + +interface + +uses + Classes, SysUtils, ID3v1, ID3v2, APEtag; + +const + { Compression level codes } + MONKEY_COMPRESSION_FAST = 1000; { Fast (poor) } + MONKEY_COMPRESSION_NORMAL = 2000; { Normal (good) } + MONKEY_COMPRESSION_HIGH = 3000; { High (very good) } + MONKEY_COMPRESSION_EXTRA_HIGH = 4000; { Extra high (best) } + + { Compression level names } + MONKEY_COMPRESSION: array [0..4] of string = + ('Unknown', 'Fast', 'Normal', 'High', 'Extra High'); + + { Format flags } + MONKEY_FLAG_8_BIT = 1; { Audio 8-bit } + MONKEY_FLAG_CRC = 2; { New CRC32 error detection } + MONKEY_FLAG_PEAK_LEVEL = 4; { Peak level stored } + MONKEY_FLAG_24_BIT = 8; { Audio 24-bit } + MONKEY_FLAG_SEEK_ELEMENTS = 16; { Number of seek elements stored } + MONKEY_FLAG_WAV_NOT_STORED = 32; { WAV header not stored } + + { Channel mode names } + MONKEY_MODE: array [0..2] of string = + ('Unknown', 'Mono', 'Stereo'); + +type + { Real structure of Monkey's Audio header } + MonkeyHeader = record + ID: array [1..4] of Char; { Always "MAC " } + VersionID: Word; { Version number * 1000 (3.91 = 3910) } + CompressionID: Word; { Compression level code } + Flags: Word; { Any format flags } + Channels: Word; { Number of channels } + SampleRate: Integer; { Sample rate (hz) } + HeaderBytes: Integer; { Header length (without header ID) } + TerminatingBytes: Integer; { Extended data } + Frames: Integer; { Number of frames in the file } + FinalSamples: Integer; { Number of samples in the final frame } + PeakLevel: Integer; { Peak level (if stored) } + SeekElements: Integer; { Number of seek elements (if stored) } + end; + + { Class TMonkey } + TMonkey = class(TObject) + private + { Private declarations } + FFileLength: Integer; + FHeader: MonkeyHeader; + FID3v1: TID3v1; + FID3v2: TID3v2; + FAPEtag: TAPEtag; + procedure FResetData; + function FGetValid: Boolean; + function FGetVersion: string; + function FGetCompression: string; + function FGetBits: Byte; + function FGetChannelMode: string; + function FGetPeak: Double; + function FGetSamplesPerFrame: Integer; + function FGetSamples: Integer; + function FGetDuration: Double; + function FGetRatio: Double; + public + { Public declarations } + constructor Create; { Create object } + destructor Destroy; override; { Destroy object } + function ReadFromFile(const FileName: string): Boolean; { Load header } + property FileLength: Integer read FFileLength; { File length (bytes) } + property Header: MonkeyHeader read FHeader; { Monkey's Audio header } + property ID3v1: TID3v1 read FID3v1; { ID3v1 tag data } + property ID3v2: TID3v2 read FID3v2; { ID3v2 tag data } + property APEtag: TAPEtag read FAPEtag; { APE tag data } + property Valid: Boolean read FGetValid; { True if header valid } + property Version: string read FGetVersion; { Encoder version } + property Compression: string read FGetCompression; { Compression level } + property Bits: Byte read FGetBits; { Bits per sample } + property ChannelMode: string read FGetChannelMode; { Channel mode } + property Peak: Double read FGetPeak; { Peak level ratio (%) } + property Samples: Integer read FGetSamples; { Number of samples } + property Duration: Double read FGetDuration; { Duration (seconds) } + property Ratio: Double read FGetRatio; { Compression ratio (%) } + end; + +implementation + +{ ********************** Private functions & procedures ********************* } + +procedure TMonkey.FResetData; +begin + { Reset data } + FFileLength := 0; + FillChar(FHeader, SizeOf(FHeader), 0); + FID3v1.ResetData; + FID3v2.ResetData; + FAPEtag.ResetData; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetValid: Boolean; +begin + { Check for right Monkey's Audio file data } + Result := + (FHeader.ID = 'MAC ') and + (FHeader.SampleRate > 0) and + (FHeader.Channels > 0); +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetVersion: string; +begin + { Get encoder version } + if FHeader.VersionID = 0 then Result := '' + else Str(FHeader.VersionID / 1000 : 4 : 2, Result); +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetCompression: string; +begin + { Get compression level } + Result := MONKEY_COMPRESSION[FHeader.CompressionID div 1000]; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetBits: Byte; +begin + { Get number of bits per sample } + if FGetValid then + begin + Result := 16; + if FHeader.Flags and MONKEY_FLAG_8_BIT > 0 then Result := 8; + if FHeader.Flags and MONKEY_FLAG_24_BIT > 0 then Result := 24; + end + else + Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetChannelMode: string; +begin + { Get channel mode } + Result := MONKEY_MODE[FHeader.Channels]; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetPeak: Double; +begin + { Get peak level ratio } + if (FGetValid) and (FHeader.Flags and MONKEY_FLAG_PEAK_LEVEL > 0) then + case FGetBits of + 16: Result := FHeader.PeakLevel / 32768 * 100; + 24: Result := FHeader.PeakLevel / 8388608 * 100; + else Result := FHeader.PeakLevel / 128 * 100; + end + else + Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetSamplesPerFrame: Integer; +begin + { Get number of samples in a frame } + if FGetValid then + if (FHeader.VersionID >= 3900) or + ((FHeader.VersionID >= 3800) and + (FHeader.CompressionID = MONKEY_COMPRESSION_EXTRA_HIGH)) then + Result := 73728 + else + Result := 9216 + else + Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetSamples: Integer; +begin + { Get number of samples } + if FGetValid then + Result := (FHeader.Frames - 1) * FGetSamplesPerFrame + FHeader.FinalSamples + else + Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetDuration: Double; +begin + { Get song duration } + if FGetValid then Result := FGetSamples / FHeader.SampleRate + else Result := 0; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.FGetRatio: Double; +begin + { Get compression ratio } + if FGetValid then + Result := FFileLength / + (FGetSamples * FHeader.Channels * FGetBits / 8 + 44) * 100 + else + Result := 0; +end; + +{ ********************** Public functions & procedures ********************** } + +constructor TMonkey.Create; +begin + { Create object } + inherited; + FID3v1 := TID3v1.Create; + FID3v2 := TID3v2.Create; + FAPEtag := TAPEtag.Create; + FResetData; +end; + +{ --------------------------------------------------------------------------- } + +destructor TMonkey.Destroy; +begin + { Destroy object } + FID3v1.Free; + FID3v2.Free; + FAPEtag.Free; + inherited; +end; + +{ --------------------------------------------------------------------------- } + +function TMonkey.ReadFromFile(const FileName: string): Boolean; +var + SourceFile: file; +begin + try + { Reset data and search for file tag } + FResetData; + if (not FID3v1.ReadFromFile(FileName)) or + (not FID3v2.ReadFromFile(FileName)) or + (not FAPEtag.ReadFromFile(FileName)) then raise Exception.Create(''); + { Set read-access, open file and get file length } + AssignFile(SourceFile, FileName); + FileMode := 0; + Reset(SourceFile, 1); + FFileLength := FileSize(SourceFile); + { Read Monkey's Audio header data } + Seek(SourceFile, ID3v2.Size); + BlockRead(SourceFile, FHeader, SizeOf(FHeader)); + if FHeader.Flags and MONKEY_FLAG_PEAK_LEVEL = 0 then + FHeader.PeakLevel := 0; + if FHeader.Flags and MONKEY_FLAG_SEEK_ELEMENTS = 0 then + FHeader.SeekElements := 0; + CloseFile(SourceFile); + Result := true; + except + FResetData; + Result := false; + end; +end; + +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.cfg b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.cfg new file mode 100644 index 0000000..dc18277 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.cfg @@ -0,0 +1,35 @@ +-$A8 +-$B- +-$C+ +-$D+ +-$E- +-$F- +-$G+ +-$H+ +-$I+ +-$J- +-$K- +-$L+ +-$M- +-$N+ +-$O+ +-$P+ +-$Q- +-$R- +-$S- +-$T- +-$U- +-$V+ +-$W- +-$X+ +-$YD +-$Z1 +-cg +-AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +-H+ +-W+ +-M +-$M16384,1048576 +-K$00400000 +-LE"c:\program files\borland\delphi6\Projects\Bpl" +-LN"c:\program files\borland\delphi6\Projects\Bpl" diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dof b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dof new file mode 100644 index 0000000..216ddb6 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dof @@ -0,0 +1,96 @@ +[FileVersion] +Version=6.0 +[Compiler] +A=8 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=0 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=1 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +RemoteSymbols=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +PackageDLLOutputDir= +PackageDCPOutputDir= +SearchPath= +Packages=vcl;rtl;dbrtl;adortl;vcldb;vclx;bdertl;vcldbx;ibxpress;dsnap;cds;bdecds;qrpt;teeui;teedb;tee;dss;teeqr;visualclx;visualdbclx;dsnapcrba;dsnapcon;VclSmp;vclshlctrls;vclie;xmlrtl;inet;inetdbbde;inetdbxpress;inetdb;nmfast;webdsnap;websnap;dbexpress;dbxcds;indy;dclOffice2k +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +Launcher= +UseLauncher=0 +DebugCWD= +[Language] +ActiveLang= +ProjectLang= +RootDir= +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1031 +CodePage=1252 +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= +[HistoryLists\hlUnitAliases] +Count=1 +Item0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[HistoryLists\hlUnitOutputDirectory] +Count=1 +Item0=DCU +[HistoryLists\hlOutputDirectorry] +Count=1 +Item0=Data diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dpr b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dpr new file mode 100644 index 0000000..729fecf --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.dpr @@ -0,0 +1,18 @@ +program Test; + +uses + Forms, + Main in 'Main.pas' {MainForm}, + Monkey in 'Monkey.pas', + ID3v1 in '..\ID3v1\ID3v1.pas', + ID3v2 in '..\ID3v2\ID3v2.pas', + APEtag in '..\APEtag\APEtag.pas'; + +{$R *.res} + +begin + Application.Initialize; + Application.Title := 'Monkey Test'; + Application.CreateForm(TMainForm, MainForm); + Application.Run; +end. diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.res b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.res new file mode 100644 index 0000000..1ce496d Binary files /dev/null and b/MAC_SDK/3rd Party/TMonkey (Delphi)/Monkey/Test.res differ diff --git a/MAC_SDK/3rd Party/TMonkey (Delphi)/Readme.txt b/MAC_SDK/3rd Party/TMonkey (Delphi)/Readme.txt new file mode 100644 index 0000000..1d9e267 --- /dev/null +++ b/MAC_SDK/3rd Party/TMonkey (Delphi)/Readme.txt @@ -0,0 +1,5 @@ +TMonkey Delphi Class for analyzing APE files + +Sumbitted by Jurgen Faul ( jfaul@gmx.de ) + +(note: this does not directly use the MAC SDK, so it is not guaranteed to work with future APE files) \ No newline at end of file diff --git a/MAC_SDK/Analyze/Sample 1/Sample 1.cpp b/MAC_SDK/Analyze/Sample 1/Sample 1.cpp new file mode 100644 index 0000000..0b43b89 --- /dev/null +++ b/MAC_SDK/Analyze/Sample 1/Sample 1.cpp @@ -0,0 +1,127 @@ +/*************************************************************************************** +Analyze - Sample 1 +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example opens an APE file and displays some basic information about it. To use it, +just type Sample 1.exe followed by a file name and it'll display information about that +file. + +Notes for use in a new project: + -you need to include "MACLib.lib" in the included libraries list + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk. +***************************************************************************************/ + +// includes +#include "all.h" +#include "stdio.h" +#include "maclib.h" +#include "apetag.h" + +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // error check the command line parameters + /////////////////////////////////////////////////////////////////////////////// + if (argc != 2) + { + printf("~~~Improper Usage~~~\r\n\r\n"); + printf("Usage Example: Sample 1.exe 'c:\\1.ape'\r\n\r\n"); + return 0; + } + + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nRetVal = 0; // generic holder for return values + char cTempBuffer[256]; ZeroMemory(&cTempBuffer[0], 256); // generic buffer for string stuff + char * pFilename = argv[1]; // the file to open + IAPEDecompress * pAPEDecompress = NULL; // APE interface + + /////////////////////////////////////////////////////////////////////////////// + // open the file and error check + /////////////////////////////////////////////////////////////////////////////// + pAPEDecompress = CreateIAPEDecompress(pFilename, &nRetVal); + if (pAPEDecompress == NULL) + { + printf("Error opening APE file. (error code %d)\r\n\r\n", nRetVal); + return 0; + } + + /////////////////////////////////////////////////////////////////////////////// + // display some information about the file + /////////////////////////////////////////////////////////////////////////////// + printf("Displaying information about '%s':\r\n\r\n", pFilename); + + // file format information + printf("File Format:\r\n"); + printf("\tVersion: %.2f\r\n", float(pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)) / float(1000)); + switch (pAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL)) + { + case COMPRESSION_LEVEL_FAST: printf("\tCompression level: Fast\r\n\r\n"); break; + case COMPRESSION_LEVEL_NORMAL: printf("\tCompression level: Normal\r\n\r\n"); break; + case COMPRESSION_LEVEL_HIGH: printf("\tCompression level: High\r\n\r\n"); break; + case COMPRESSION_LEVEL_EXTRA_HIGH: printf("\tCompression level: Extra High\r\n\r\n"); break; + } + + // audio format information + printf("Audio Format:\r\n"); + printf("\tSamples per second: %d\r\n", pAPEDecompress->GetInfo(APE_INFO_SAMPLE_RATE)); + printf("\tBits per sample: %d\r\n", pAPEDecompress->GetInfo(APE_INFO_BITS_PER_SAMPLE)); + printf("\tNumber of channels: %d\r\n", pAPEDecompress->GetInfo(APE_INFO_CHANNELS)); + printf("\tPeak level: %d\r\n\r\n", pAPEDecompress->GetInfo(APE_INFO_PEAK_LEVEL)); + + // size and duration information + printf("Size and Duration:\r\n"); + printf("\tLength of file (s): %d\r\n", pAPEDecompress->GetInfo(APE_INFO_LENGTH_MS) / 1000); + printf("\tFile Size (kb): %d\r\n\r\n", pAPEDecompress->GetInfo(APE_INFO_APE_TOTAL_BYTES) / 1024); + + // tag information + printf("Tag Information:\r\n"); + + CAPETag * pAPETag = (CAPETag *) pAPEDecompress->GetInfo(APE_INFO_TAG); + BOOL bHasID3Tag = pAPETag->GetHasID3Tag(); + BOOL bHasAPETag = pAPETag->GetHasAPETag(); + + if (bHasID3Tag || bHasAPETag) + { + // iterate through all the tag fields + BOOL bFirst = TRUE; + CAPETagField * pTagField; + while (pAPETag->GetNextTagField(bFirst, &pTagField)) + { + bFirst = FALSE; + + // output the tag field properties (don't output huge fields like images, etc.) + if (pTagField->GetFieldValueSize() > 128) + { + printf("\t%s: --- too much data to display ---\r\n", pTagField->GetFieldName()); + } + else + { + printf("\t%s: %s\r\n", pTagField->GetFieldName(), pTagField->GetFieldValue()); + } + } + } + else + { + printf("\tNot tagged\r\n\r\n"); + } + + /////////////////////////////////////////////////////////////////////////////// + // cleanup (just delete the object + /////////////////////////////////////////////////////////////////////////////// + delete pAPEDecompress; + + /////////////////////////////////////////////////////////////////////////////// + // quit + /////////////////////////////////////////////////////////////////////////////// + return 0; +} diff --git a/MAC_SDK/Analyze/Sample 1/Sample 1.dsp b/MAC_SDK/Analyze/Sample 1/Sample 1.dsp new file mode 100644 index 0000000..2483420 --- /dev/null +++ b/MAC_SDK/Analyze/Sample 1/Sample 1.dsp @@ -0,0 +1,102 @@ +# Microsoft Developer Studio Project File - Name="Sample 1" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 1 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak" CFG="Sample 1 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 1 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 1 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 1 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\Shared" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /machine:I386 /libpath:"..\..\Shared" + +!ELSEIF "$(CFG)" == "Sample 1 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\Shared" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\Shared" + +!ENDIF + +# Begin Target + +# Name "Sample 1 - Win32 Release" +# Name "Sample 1 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 1.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\Shared\APEInfo.h +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Compress/Sample 1/Sample 1.cpp b/MAC_SDK/Compress/Sample 1/Sample 1.cpp new file mode 100644 index 0000000..a907b8e --- /dev/null +++ b/MAC_SDK/Compress/Sample 1/Sample 1.cpp @@ -0,0 +1,121 @@ +/*************************************************************************************** +Compress - Sample 1 +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example illustrates using MACLib.lib to create an APE file by encoding some +random data. + +The IAPECompress interface fully supports on-the-fly encoding. To use on- +the-fly encoding, be sure to tell the encoder to create the proper WAV header on +decompression. Also, you need to specify the absolute maximum audio bytes that will +get encoded. (trying to encode more than the limit set on Start() will cause failure) +This maximum is used to allocates space in the seek table at the front of the file. Currently, +it takes around 8k per hour of CD music, so it isn't a big deal to allocate more than +needed. You can also specify MAX_AUDIO_BYTES_UNKNOWN to allocate as much space as possible. (2 GB) + +Notes for use in a new project: + -you need to include "MACLib.lib" in the included libraries list + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk +***************************************************************************************/ + +// includes +#include +#include +#include "stdio.h" +#include "all.h" +#include "MACLib.h" + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nAudioBytes = 1048576*10; + const char cOutputFile[MAX_PATH] = "c:\\Noise.ape"; + + printf("Creating file: %s\n", cOutputFile); + + /////////////////////////////////////////////////////////////////////////////// + // create and start the encoder + /////////////////////////////////////////////////////////////////////////////// + + // set the input WAV format + WAVEFORMATEX wfeAudioFormat; FillWaveFormatEx(&wfeAudioFormat, 44100, 16, 2); + + // create the encoder interface + IAPECompress * pAPECompress = CreateIAPECompress(); + + // start the encoder + int nRetVal = pAPECompress->Start(cOutputFile, &wfeAudioFormat, nAudioBytes, + COMPRESSION_LEVEL_HIGH, NULL, CREATE_WAV_HEADER_ON_DECOMPRESSION); + + if (nRetVal != 0) + { + SAFE_DELETE(pAPECompress) + printf("Error starting encoder.\n"); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // pump through and feed the encoder audio data (white noise for the sample) + /////////////////////////////////////////////////////////////////////////////// + int nAudioBytesLeft = nAudioBytes; + + while (nAudioBytesLeft > 0) + { + /////////////////////////////////////////////////////////////////////////////// + // NOTE: we're locking the buffer used internally by MAC and copying the data + // directly into it... however, you could also use the AddData(...) command + // to avoid the added complexity of locking and unlocking + // the buffer (but it may be a little slower ) + /////////////////////////////////////////////////////////////////////////////// + + // lock the compression buffer + int nBufferBytesAvailable = 0; + unsigned char * pBuffer = pAPECompress->LockBuffer(&nBufferBytesAvailable); + + // fill the buffer with white noise + int nNoiseBytes = min(nBufferBytesAvailable, nAudioBytesLeft); + for (int z = 0; z < nNoiseBytes; z++) + { + pBuffer[z] = rand() % 255; + } + + // unlock the buffer and let it get processed + int nRetVal = pAPECompress->UnlockBuffer(nNoiseBytes, TRUE); + if (nRetVal != 0) + { + printf("Error Encoding Frame (error: %d)\n", nRetVal); + break; + } + + // update the audio bytes left + nAudioBytesLeft -= nNoiseBytes; + } + + /////////////////////////////////////////////////////////////////////////////// + // finalize the file (could append a tag, or WAV terminating data) + /////////////////////////////////////////////////////////////////////////////// + if (pAPECompress->Finish(NULL, 0, 0) != 0) + { + printf("Error finishing encoder.\n"); + } + + /////////////////////////////////////////////////////////////////////////////// + // clean up and quit + /////////////////////////////////////////////////////////////////////////////// + SAFE_DELETE(pAPECompress) + printf("Done.\n"); + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Compress/Sample 1/Sample 1.dsp b/MAC_SDK/Compress/Sample 1/Sample 1.dsp new file mode 100644 index 0000000..d69463c --- /dev/null +++ b/MAC_SDK/Compress/Sample 1/Sample 1.dsp @@ -0,0 +1,106 @@ +# Microsoft Developer Studio Project File - Name="Sample 1" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 1 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak" CFG="Sample 1 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 1 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 1 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 1 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\Shared" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /machine:I386 /libpath:"..\..\Shared" + +!ELSEIF "$(CFG)" == "Sample 1 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\Shared" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\Shared" + +!ENDIF + +# Begin Target + +# Name "Sample 1 - Win32 Release" +# Name "Sample 1 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 1.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\Shared\All.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\MAC.h +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Compress/Sample 2/Sample 2.cpp b/MAC_SDK/Compress/Sample 2/Sample 2.cpp new file mode 100644 index 0000000..d454b1f --- /dev/null +++ b/MAC_SDK/Compress/Sample 2/Sample 2.cpp @@ -0,0 +1,217 @@ +/*************************************************************************************** +Compress - Sample 2 +Copyright (C) 2000-2002 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example illustrates dynamic linkage to MACDll.dll to create an APE file using +on-the-fly encoding. + +The IAPECompress interface fully supports on-the-fly encoding. To use on- +the-fly encoding, be sure to tell the encoder to create the proper WAV header on +decompression. Also, you need to specify the absolute maximum audio bytes that will +get encoded. (trying to encode more than the limit set on Start() will cause failure) +This maximum is used to allocates space in the seek table at the front of the file. Currently, +it takes around 8k per hour of CD music, so it isn't a big deal to allocate more than +needed. You can also specify MAX_AUDIO_BYTES_UNKNOWN to allocate as much space as possible. (2 GB) + +Notes for use in a new project: + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk +***************************************************************************************/ + +// includes +#include +#include +#include "stdio.h" +#include "all.h" +#include "MACDll.h" + +/*************************************************************************************** +MAC_DLL structure (holds function pointers) +***************************************************************************************/ +struct MAC_COMPRESS_DLL +{ + // APECompress functions + proc_APECompress_Create Create; + proc_APECompress_Destroy Destroy; + proc_APECompress_Start Start; + proc_APECompress_AddData AddData; + proc_APECompress_Finish Finish; +}; + +/*************************************************************************************** +GetFunctions - helper that gets the function addresses for the functions we need +***************************************************************************************/ +int GetFunctions(HMODULE hMACDll, MAC_COMPRESS_DLL * pMACDll) +{ + // clear + memset(pMACDll, 0, sizeof(MAC_COMPRESS_DLL)); + + // load the functions + if (hMACDll != NULL) + { + pMACDll->Create = (proc_APECompress_Create) GetProcAddress(hMACDll, "c_APECompress_Create"); + pMACDll->Destroy = (proc_APECompress_Destroy) GetProcAddress(hMACDll, "c_APECompress_Destroy"); + pMACDll->Start = (proc_APECompress_Start) GetProcAddress(hMACDll, "c_APECompress_Start"); + pMACDll->AddData = (proc_APECompress_AddData) GetProcAddress(hMACDll, "c_APECompress_AddData"); + pMACDll->Finish = (proc_APECompress_Finish) GetProcAddress(hMACDll, "c_APECompress_Finish"); + } + + // error check + if ((pMACDll->Create == NULL) || + (pMACDll->Destroy == NULL) || + (pMACDll->Start == NULL) || + (pMACDll->AddData == NULL) || + (pMACDll->Finish == NULL)) + { + return -1; + } + + return 0; +} + +/*************************************************************************************** +Version checks the dll / interface +***************************************************************************************/ +int VersionCheckInterface(HMODULE hMACDll) +{ + int nRetVal = -1; + proc_GetInterfaceCompatibility GetInterfaceCompatibility = (proc_GetInterfaceCompatibility) GetProcAddress(hMACDll, "GetInterfaceCompatibility"); + if (GetInterfaceCompatibility) + { + nRetVal = GetInterfaceCompatibility(MAC_VERSION_NUMBER, TRUE, NULL); + } + + return nRetVal; +} + +/*************************************************************************************** +Fill a WAVEFORMATEX structure +***************************************************************************************/ +int FillWaveFormatExStructure(WAVEFORMATEX *pWaveFormatEx, int nSampleRate, int nBitsPerSample, int nChannels) +{ + pWaveFormatEx->cbSize = 0; + pWaveFormatEx->nSamplesPerSec = nSampleRate; + pWaveFormatEx->wBitsPerSample = nBitsPerSample; + pWaveFormatEx->nChannels = nChannels; + pWaveFormatEx->wFormatTag = 1; + + pWaveFormatEx->nBlockAlign = (pWaveFormatEx->wBitsPerSample / 8) * pWaveFormatEx->nChannels; + pWaveFormatEx->nAvgBytesPerSec = pWaveFormatEx->nBlockAlign * pWaveFormatEx->nSamplesPerSec; + + return 0; +} + + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nTotalAudioBytes = 1048576; + const char cOutputFile[MAX_PATH] = "c:\\Noise.ape"; + int nRetVal; + + printf("Creating file: %s\n", cOutputFile); + + /////////////////////////////////////////////////////////////////////////////// + // load MACDll.dll and get the functions + /////////////////////////////////////////////////////////////////////////////// + + // load the DLL + HMODULE hMACDll = LoadLibrary("MACDll.dll"); + if (hMACDll == NULL) + return -1; + + // always check the interface version (so we don't crash if something changed) + if (VersionCheckInterface(hMACDll) != 0) + { + FreeLibrary(hMACDll); + return -1; + } + + // get the functions + MAC_COMPRESS_DLL MACDll; + if (GetFunctions(hMACDll, &MACDll) != 0) + { + FreeLibrary(hMACDll); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // create and start the encoder + /////////////////////////////////////////////////////////////////////////////// + + // set the input WAV format + WAVEFORMATEX wfeAudioFormat; FillWaveFormatExStructure(&wfeAudioFormat, 44100, 16, 2); + + // create the encoder interface + APE_COMPRESS_HANDLE hAPECompress = MACDll.Create(&nRetVal); + if (hAPECompress == NULL) + { + printf("Error creating encoder (error code: %d)\r\n", nRetVal); + FreeLibrary(hMACDll); + return -1; + } + + // start the encoder + nRetVal = MACDll.Start(hAPECompress, cOutputFile, &wfeAudioFormat, nTotalAudioBytes, + COMPRESSION_LEVEL_HIGH, NULL, CREATE_WAV_HEADER_ON_DECOMPRESSION); + + if (nRetVal != 0) + { + printf("Error starting encoder.\n"); + MACDll.Destroy(hAPECompress); + FreeLibrary(hMACDll); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // pump through and feed the encoder audio data (white noise for the sample) + /////////////////////////////////////////////////////////////////////////////// + int nAudioBytesLeft = nTotalAudioBytes; + unsigned char cBuffer[1024]; + + while (nAudioBytesLeft > 0) + { + // fill the buffer with white noise + for (int z = 0; z < 1024; z++) + cBuffer[z] = rand() % 255; + + // give the data to MAC + // (we can safely add any amount, but of course larger chunks take longer to process) + int nBytesToAdd = min(1024, nAudioBytesLeft); + nRetVal = MACDll.AddData(hAPECompress, &cBuffer[0], nBytesToAdd); + + if (nRetVal != ERROR_SUCCESS) + printf("Encoding error (error code: %d)\r\n", nRetVal); + + // update the audio bytes left + nAudioBytesLeft -= nBytesToAdd; + } + + /////////////////////////////////////////////////////////////////////////////// + // finalize the file (could append a tag, or WAV terminating data) + /////////////////////////////////////////////////////////////////////////////// + if (MACDll.Finish(hAPECompress, NULL, 0, 0) != 0) + { + printf("Error finishing encoder.\n"); + } + + /////////////////////////////////////////////////////////////////////////////// + // clean up and quit + /////////////////////////////////////////////////////////////////////////////// + MACDll.Destroy(hAPECompress); + FreeLibrary(hMACDll); + printf("Done.\n"); + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Compress/Sample 2/Sample 2.dsp b/MAC_SDK/Compress/Sample 2/Sample 2.dsp new file mode 100644 index 0000000..5ebc0b4 --- /dev/null +++ b/MAC_SDK/Compress/Sample 2/Sample 2.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="Sample 2" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 2 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 2.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 2.mak" CFG="Sample 2 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 2 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 2 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 2 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /I "..\..\Shared" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "Sample 2 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\..\Shared" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "Sample 2 - Win32 Release" +# Name "Sample 2 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 2.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Decompress/Sample 1/Sample 1.cpp b/MAC_SDK/Decompress/Sample 1/Sample 1.cpp new file mode 100644 index 0000000..18e5b2f --- /dev/null +++ b/MAC_SDK/Decompress/Sample 1/Sample 1.cpp @@ -0,0 +1,92 @@ +/*************************************************************************************** +Decompress - Sample 1 +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example illustrates using MACDLib.lib and the simple IAPESimple class to verify +or decompress a file. (verify and decompress work the same, except that verify doesn't +have an output file) Also, shows how to use a callback to display the progress. + +General Notes: + -the terminology "Sample" refers to a single sample value, and "Block" refers + to a collection of "Channel" samples. For simplicity, MAC typically uses blocks + everywhere so that channel mis-alignment cannot happen. + +Notes for use in a new project: + -you need to include "MACLib.lib" in the included libraries list + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk. +***************************************************************************************/ + +// includes +#include +#include "stdio.h" +#include "all.h" +#include "maclib.h" + +// global variables (evil... but alright for a simple sample) +unsigned __int32 g_nInitialTickCount; + +/*************************************************************************************** +Progress callback +***************************************************************************************/ +void CALLBACK ProgressCallback(int nPercentageDone) +{ + double dProgress = double(nPercentageDone) / 1000; + double dElapsedMS = (GetTickCount() - g_nInitialTickCount); + + double dSecondsRemaining = (((dElapsedMS * 100) / dProgress) - dElapsedMS) / 1000; + printf("Progress: %.1f%% (%.1f seconds remaining) \r", dProgress, dSecondsRemaining); +} + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // error check the command line parameters + /////////////////////////////////////////////////////////////////////////////// + if (argc != 2) + { + printf("~~~Improper Usage~~~\n\n"); + printf("Usage Example: Sample 1.exe \"c:\\1.ape\"\n\n"); + return 0; + } + + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nPercentageDone = 0; //the percentage done... continually updated by the decoder + int nKillFlag = 0; //the kill flag for controlling the decoder + int nRetVal = 0; //generic holder for return values + char * pFilename = argv[1]; //the file to open + + /////////////////////////////////////////////////////////////////////////////// + // attempt to verify the file + /////////////////////////////////////////////////////////////////////////////// + + // set the start time and display the starting message + g_nInitialTickCount = GetTickCount(); + printf("Verifying '%s'...\n", pFilename); + + // do the verify (call unmac.dll) + nRetVal = VerifyFile(pFilename, &nPercentageDone, ProgressCallback, &nKillFlag); + + // process the return value + if (nRetVal == 0) + printf("\nPassed...\n"); + else + printf("\nFailed (error: %d)\n", nRetVal); + + /////////////////////////////////////////////////////////////////////////////// + // quit + /////////////////////////////////////////////////////////////////////////////// + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Decompress/Sample 1/Sample 1.dsp b/MAC_SDK/Decompress/Sample 1/Sample 1.dsp new file mode 100644 index 0000000..2f07507 --- /dev/null +++ b/MAC_SDK/Decompress/Sample 1/Sample 1.dsp @@ -0,0 +1,110 @@ +# Microsoft Developer Studio Project File - Name="Sample 1" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 1 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 1.mak" CFG="Sample 1 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 1 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 1 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 1 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\Shared" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /machine:I386 /libpath:"..\..\Shared" + +!ELSEIF "$(CFG)" == "Sample 1 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\Shared" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\Shared" + +!ENDIF + +# Begin Target + +# Name "Sample 1 - Win32 Release" +# Name "Sample 1 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 1.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\Shared\All.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\APEInfo.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\UnMAC.h +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Decompress/Sample 1/Sample 1.vcproj b/MAC_SDK/Decompress/Sample 1/Sample 1.vcproj new file mode 100644 index 0000000..6cd4ad1 --- /dev/null +++ b/MAC_SDK/Decompress/Sample 1/Sample 1.vcproj @@ -0,0 +1,460 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Decompress/Sample 2/Sample 2.cpp b/MAC_SDK/Decompress/Sample 2/Sample 2.cpp new file mode 100644 index 0000000..ba977b7 --- /dev/null +++ b/MAC_SDK/Decompress/Sample 2/Sample 2.cpp @@ -0,0 +1,117 @@ +/*************************************************************************************** +Decompress - Sample 2 +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example illustrates using MACLib.lib to do decoding and seeking of an APE file. +The library manages all seeking and buffering, so you simply seek +to a location and ask for the amount of data required. (Seek() and GetData()) + +GetData will return the amount requested unless you're at the end of the file. (in +which case it returns everything up to the end) It's typically a good idea to check +the return value of each decode. A value other than ERROR_SUCCESS (0) means errors +were encountered. In these cases, the decoder will do the best job it can to keep +returning valid data. (corrupt data will be converted to silence) + +General Notes: + -the terminology "Sample" refers to a single sample value, and "Block" refers + to a collection of "Channel" samples. For simplicity, MAC typically uses blocks + everywhere so that channel mis-alignment cannot happen. + +Notes for use in a new project: + -you need to include "MACLib.lib" in the included libraries list + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk +***************************************************************************************/ + +// includes +#include +#include "stdio.h" +#include "all.h" +#include "maclib.h" + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // error check the command line parameters + /////////////////////////////////////////////////////////////////////////////// + if (argc != 2) + { + printf("~~~Improper Usage~~~\r\n\r\n"); + printf("Usage Example: Sample 2.exe \"c:\\1.ape\"\r\n\r\n"); + return 0; + } + + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nPercentageDone = 0; // the percentage done... continually updated by the decoder + int nKillFlag = 0; // the kill flag for controlling the decoder + int nRetVal = 0; // generic holder for return values + char * pFilename = argv[1]; // the file to open + + /////////////////////////////////////////////////////////////////////////////// + // open the APE file + /////////////////////////////////////////////////////////////////////////////// + IAPEDecompress * pAPEDecompress = CreateIAPEDecompress(L"E:\\Music\\Babylon 5\\Episodic CDs\\Babylon 5 (1997, River Of Souls, APE) - Christopher Franke\\01 - Suite 1.ape" , &nRetVal); + if (pAPEDecompress == NULL) + { + printf("Error opening APE file (error code: %d)\r\n", nRetVal); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // allocate space for the raw decompressed data + /////////////////////////////////////////////////////////////////////////////// + char * pRawData = new char [1024 * pAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN)]; + if (pRawData == NULL) { return -1; } + + /////////////////////////////////////////////////////////////////////////////// + // ask for data at a a few random locations and display the sum of 1024 blocks + /////////////////////////////////////////////////////////////////////////////// + for (int z = 0; z < 160; z++) + { + // figure a random location in the file and seek to it + int nRandomBlock = rand() % (pAPEDecompress->GetInfo(APE_DECOMPRESS_TOTAL_BLOCKS) - 1024); + nRetVal = pAPEDecompress->Seek(nRandomBlock); + if (nRetVal != 0) { + printf("Seek error (%d)\r\n", nRetVal); + return -1; + } + + // decompress 1024 blocks from that location + int nBlocksRetrieved; + nRetVal = pAPEDecompress->GetData(pRawData, 1024, &nBlocksRetrieved); + if (nRetVal != ERROR_SUCCESS) + { + printf("Decoding error (%d)\r\n", nRetVal); + } + + // figure the sum of the decoded data + int nBytesRetrieved = nBlocksRetrieved * pAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN); + int nSum = 0; + for (int x = 0; x < nBytesRetrieved; x++) + { + nSum += pRawData[x]; + } + + // display the sum + printf("Block / Sum = %.4d / %d\r\n", nRandomBlock, nSum); + + } + + /////////////////////////////////////////////////////////////////////////////// + // clean-up and quit + /////////////////////////////////////////////////////////////////////////////// + delete pAPEDecompress; + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Decompress/Sample 2/Sample 2.dsp b/MAC_SDK/Decompress/Sample 2/Sample 2.dsp new file mode 100644 index 0000000..91aa5c2 --- /dev/null +++ b/MAC_SDK/Decompress/Sample 2/Sample 2.dsp @@ -0,0 +1,114 @@ +# Microsoft Developer Studio Project File - Name="Sample 2" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 2 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 2.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 2.mak" CFG="Sample 2 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 2 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 2 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 2 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\Shared" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /machine:I386 /libpath:"..\..\Shared" + +!ELSEIF "$(CFG)" == "Sample 2 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\Shared" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\Shared" + +!ENDIF + +# Begin Target + +# Name "Sample 2 - Win32 Release" +# Name "Sample 2 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 2.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\Shared\All.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\APEInfo.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\MACDll.h +# End Source File +# Begin Source File + +SOURCE=..\..\Shared\UnMAC.h +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Decompress/Sample 2/Sample 2.vcproj b/MAC_SDK/Decompress/Sample 2/Sample 2.vcproj new file mode 100644 index 0000000..96deb6c --- /dev/null +++ b/MAC_SDK/Decompress/Sample 2/Sample 2.vcproj @@ -0,0 +1,464 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Decompress/Sample 3/Sample 3.cpp b/MAC_SDK/Decompress/Sample 3/Sample 3.cpp new file mode 100644 index 0000000..8ec781a --- /dev/null +++ b/MAC_SDK/Decompress/Sample 3/Sample 3.cpp @@ -0,0 +1,190 @@ +/*************************************************************************************** +Decompress - Sample 3 +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. +Feel free to use this code in any way that you like. + +This example illustrates dynamic linkage to MACDll.dll to decompress a whole file +and display a simple checksum. (see Sample 1 and Sample 2 for more info) + +General Notes: + -the terminology "Sample" refers to a single sample value, and "Block" refers + to a collection of "Channel" samples. For simplicity, MAC typically uses blocks + everywhere so that channel mis-alignment cannot happen. + +Notes for use in a new project: + -life will be easier if you set the [MAC SDK]\\Shared directory as an include + directory and an additional library input path in the project settings + -set the runtime library to "Mutlithreaded" + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk +***************************************************************************************/ + +// includes +#include +#include "stdio.h" +#include "MACDll.h" + +/*************************************************************************************** +MAC_DLL structure (holds function pointers) +***************************************************************************************/ +struct MAC_DLL +{ + // APEDecompress functions + proc_APEDecompress_Create Create; + proc_APEDecompress_Destroy Destroy; + proc_APEDecompress_GetData GetData; + proc_APEDecompress_Seek Seek; + proc_APEDecompress_GetInfo GetInfo; +}; + +/*************************************************************************************** +GetFunctions - helper that gets the function addresses for the functions we need +***************************************************************************************/ +int GetFunctions(HMODULE hMACDll, MAC_DLL * pMACDll) +{ + // clear + memset(pMACDll, 0, sizeof(MAC_DLL)); + + // load the functions + if (hMACDll != NULL) + { + pMACDll->Create = (proc_APEDecompress_Create) GetProcAddress(hMACDll, "c_APEDecompress_Create"); + pMACDll->Destroy = (proc_APEDecompress_Destroy) GetProcAddress(hMACDll, "c_APEDecompress_Destroy"); + pMACDll->GetData = (proc_APEDecompress_GetData) GetProcAddress(hMACDll, "c_APEDecompress_GetData"); + pMACDll->Seek = (proc_APEDecompress_Seek) GetProcAddress(hMACDll, "c_APEDecompress_Seek"); + pMACDll->GetInfo = (proc_APEDecompress_GetInfo) GetProcAddress(hMACDll, "c_APEDecompress_GetInfo"); + } + + // error check + if ((pMACDll->Create == NULL) || + (pMACDll->Destroy == NULL) || + (pMACDll->GetData == NULL) || + (pMACDll->Seek == NULL) || + (pMACDll->GetInfo == NULL)) + { + return -1; + } + + return 0; +} + +/*************************************************************************************** +Version checks the dll / interface +***************************************************************************************/ +int VersionCheckInterface(HMODULE hMACDll) +{ + int nRetVal = -1; + proc_GetInterfaceCompatibility GetInterfaceCompatibility = (proc_GetInterfaceCompatibility) GetProcAddress(hMACDll, "GetInterfaceCompatibility"); + if (GetInterfaceCompatibility) + { + nRetVal = GetInterfaceCompatibility(MAC_VERSION_NUMBER, TRUE, NULL); + } + + return nRetVal; +} + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char* argv[]) +{ + /////////////////////////////////////////////////////////////////////////////// + // error check the command line parameters + /////////////////////////////////////////////////////////////////////////////// + if (argc != 2) + { + printf("~~~Improper Usage~~~\r\n\r\n"); + printf("Usage Example: Sample 3.exe \"c:\\1.ape\"\r\n\r\n"); + return 0; + } + + /////////////////////////////////////////////////////////////////////////////// + // variable declares + /////////////////////////////////////////////////////////////////////////////// + int nRetVal = 0; // generic holder for return values + char * pFilename = argv[1]; // the file to open + + /////////////////////////////////////////////////////////////////////////////// + // load MACDll.dll and get the functions + /////////////////////////////////////////////////////////////////////////////// + + // load the DLL + HMODULE hMACDll = LoadLibrary("MACDll.dll"); + if (hMACDll == NULL) + return -1; + + // always check the interface version (so we don't crash if something changed) + if (VersionCheckInterface(hMACDll) != 0) + { + FreeLibrary(hMACDll); + return -1; + } + + // get the functions + MAC_DLL MACDll; + if (GetFunctions(hMACDll, &MACDll) != 0) + { + FreeLibrary(hMACDll); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // create the APEDecompress object for the file + /////////////////////////////////////////////////////////////////////////////// + + APE_DECOMPRESS_HANDLE hAPEDecompress = MACDll.Create(pFilename, &nRetVal); + if (hAPEDecompress == NULL) + { + printf("Error opening APE file (error code: %d)\r\n", nRetVal); + FreeLibrary(hMACDll); + return -1; + } + + /////////////////////////////////////////////////////////////////////////////// + // calculate a byte-level checksum of the whole file + /////////////////////////////////////////////////////////////////////////////// + + // make a buffer to hold 1024 blocks of audio data + int nBlockAlign = MACDll.GetInfo(hAPEDecompress, APE_INFO_BLOCK_ALIGN, 0, 0); + unsigned char * pBuffer = new unsigned char [1024 * nBlockAlign]; + + // loop through the whole file + int nTotalBlocks = MACDll.GetInfo(hAPEDecompress, APE_DECOMPRESS_TOTAL_BLOCKS, 0, 0); + int nBlocksRetrieved = 1; + int nTotalBlocksRetrieved = 0; + unsigned int nChecksum = 0; + while (nBlocksRetrieved > 0) + { + // try to decompress 1024 blocks + nRetVal = MACDll.GetData(hAPEDecompress, (char *) pBuffer, 1024, &nBlocksRetrieved); + if (nRetVal != 0) + printf("Decompression error (continuing with checksum, but file is probably corrupt)\r\n"); + + // calculate the sum (byte-by-byte) + for (int z = 0; z < (nBlockAlign * nBlocksRetrieved); z++) + { + nChecksum += abs(int(pBuffer[z])); + } + + nTotalBlocksRetrieved += nBlocksRetrieved; + + // output the progress + printf("Progress: %.1f%% \r", (float(nTotalBlocksRetrieved) * float(100)) / float(max(nTotalBlocks, 1.0))); + } + + delete [] pBuffer; + + // output the result + printf("Progress: done. \r\n"); + printf("Stupid-style Checksum: 0x%X\r\n", nChecksum); + + /////////////////////////////////////////////////////////////////////////////// + // clean-up and quit + /////////////////////////////////////////////////////////////////////////////// + MACDll.Destroy(hAPEDecompress); + FreeLibrary(hMACDll); + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Decompress/Sample 3/Sample 3.dsp b/MAC_SDK/Decompress/Sample 3/Sample 3.dsp new file mode 100644 index 0000000..bd15e25 --- /dev/null +++ b/MAC_SDK/Decompress/Sample 3/Sample 3.dsp @@ -0,0 +1,115 @@ +# Microsoft Developer Studio Project File - Name="Sample 3" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Sample 3 - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Sample 3.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Sample 3.mak" CFG="Sample 3 - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Sample 3 - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Sample 3 - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Sample 3 - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\Shared\\" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "Sample 3 - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\Shared\\" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\Shared\\" + +!ENDIF + +# Begin Target + +# Name "Sample 3 - Win32 Release" +# Name "Sample 3 - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=".\Sample 3.cpp" + +!IF "$(CFG)" == "Sample 3 - Win32 Release" + +# ADD CPP /MT + +!ELSEIF "$(CFG)" == "Sample 3 - Win32 Debug" + +# SUBTRACT CPP /YX /Yc /Yu + +!ENDIF + +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Decompress/Sample 3/Sample 3.vcproj b/MAC_SDK/Decompress/Sample 3/Sample 3.vcproj new file mode 100644 index 0000000..edecf7e --- /dev/null +++ b/MAC_SDK/Decompress/Sample 3/Sample 3.vcproj @@ -0,0 +1,451 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Shared/APETag.h b/MAC_SDK/Shared/APETag.h new file mode 100644 index 0000000..eecd8b7 --- /dev/null +++ b/MAC_SDK/Shared/APETag.h @@ -0,0 +1,293 @@ +#ifndef APE_APETAG_H +#define APE_APETAG_H + +class CIO; + +/***************************************************************************************** +APETag version history / supported formats + +1.0 (1000) - Original APE tag spec. Fully supported by this code. +2.0 (2000) - Refined APE tag spec (better streaming support, UTF encoding). Fully supported by this code. + +Notes: + - also supports reading of ID3v1.1 tags + - all saving done in the APE Tag format using CURRENT_APE_TAG_VERSION +*****************************************************************************************/ + +/***************************************************************************************** +APETag layout + +1) Header - APE_TAG_FOOTER (optional) (32 bytes) +2) Fields (array): + Value Size (4 bytes) + Flags (4 bytes) + Field Name (? ANSI bytes -- requires NULL terminator -- in range of 0x20 (space) to 0x7E (tilde)) + Value ([Value Size] bytes) +3) Footer - APE_TAG_FOOTER (32 bytes) +*****************************************************************************************/ + +/***************************************************************************************** +Notes + +-When saving images, store the filename (no directory -- i.e. Cover.jpg) in UTF-8 followed +by a null terminator, followed by the image data. +*****************************************************************************************/ + +/***************************************************************************************** +The version of the APE tag +*****************************************************************************************/ +#define CURRENT_APE_TAG_VERSION 2000 + +/***************************************************************************************** +"Standard" APE tag fields +*****************************************************************************************/ +#define APE_TAG_FIELD_TITLE L"Title" +#define APE_TAG_FIELD_ARTIST L"Artist" +#define APE_TAG_FIELD_ALBUM L"Album" +#define APE_TAG_FIELD_COMMENT L"Comment" +#define APE_TAG_FIELD_YEAR L"Year" +#define APE_TAG_FIELD_TRACK L"Track" +#define APE_TAG_FIELD_GENRE L"Genre" +#define APE_TAG_FIELD_COVER_ART_FRONT L"Cover Art (front)" +#define APE_TAG_FIELD_NOTES L"Notes" +#define APE_TAG_FIELD_LYRICS L"Lyrics" +#define APE_TAG_FIELD_COPYRIGHT L"Copyright" +#define APE_TAG_FIELD_BUY_URL L"Buy URL" +#define APE_TAG_FIELD_ARTIST_URL L"Artist URL" +#define APE_TAG_FIELD_PUBLISHER_URL L"Publisher URL" +#define APE_TAG_FIELD_FILE_URL L"File URL" +#define APE_TAG_FIELD_COPYRIGHT_URL L"Copyright URL" +#define APE_TAG_FIELD_MJ_METADATA L"Media Jukebox Metadata" +#define APE_TAG_FIELD_TOOL_NAME L"Tool Name" +#define APE_TAG_FIELD_TOOL_VERSION L"Tool Version" +#define APE_TAG_FIELD_PEAK_LEVEL L"Peak Level" +#define APE_TAG_FIELD_REPLAY_GAIN_RADIO L"Replay Gain (radio)" +#define APE_TAG_FIELD_REPLAY_GAIN_ALBUM L"Replay Gain (album)" +#define APE_TAG_FIELD_COMPOSER L"Composer" +#define APE_TAG_FIELD_KEYWORDS L"Keywords" + +/***************************************************************************************** +Standard APE tag field values +*****************************************************************************************/ +#define APE_TAG_GENRE_UNDEFINED L"Undefined" + +/***************************************************************************************** +ID3 v1.1 tag +*****************************************************************************************/ +#define ID3_TAG_BYTES 128 +struct ID3_TAG +{ + char Header[3]; // should equal 'TAG' + char Title[30]; // title + char Artist[30]; // artist + char Album[30]; // album + char Year[4]; // year + char Comment[29]; // comment + unsigned char Track; // track + unsigned char Genre; // genre +}; + +/***************************************************************************************** +Footer (and header) flags +*****************************************************************************************/ +#define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31) +#define APE_TAG_FLAG_CONTAINS_FOOTER (1 << 30) +#define APE_TAG_FLAG_IS_HEADER (1 << 29) + +#define APE_TAG_FLAGS_DEFAULT (APE_TAG_FLAG_CONTAINS_FOOTER) + +/***************************************************************************************** +Tag field flags +*****************************************************************************************/ +#define TAG_FIELD_FLAG_READ_ONLY (1 << 0) + +#define TAG_FIELD_FLAG_DATA_TYPE_MASK (6) +#define TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8 (0 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_BINARY (1 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_EXTERNAL_INFO (2 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_RESERVED (3 << 1) + +/***************************************************************************************** +The footer at the end of APE tagged files (can also optionally be at the front of the tag) +*****************************************************************************************/ +#define APE_TAG_FOOTER_BYTES 32 + +class APE_TAG_FOOTER +{ +protected: + + char m_cID[8]; // should equal 'APETAGEX' + int m_nVersion; // equals CURRENT_APE_TAG_VERSION + int m_nSize; // the complete size of the tag, including this footer (excludes header) + int m_nFields; // the number of fields in the tag + int m_nFlags; // the tag flags + char m_cReserved[8]; // reserved for later use (must be zero) + +public: + + APE_TAG_FOOTER(int nFields = 0, int nFieldBytes = 0) + { + memcpy(m_cID, "APETAGEX", 8); + memset(m_cReserved, 0, 8); + m_nFields = nFields; + m_nFlags = APE_TAG_FLAGS_DEFAULT; + m_nSize = nFieldBytes + APE_TAG_FOOTER_BYTES; + m_nVersion = CURRENT_APE_TAG_VERSION; + } + + int GetTotalTagBytes() { return m_nSize + (GetHasHeader() ? APE_TAG_FOOTER_BYTES : 0); } + int GetFieldBytes() { return m_nSize - APE_TAG_FOOTER_BYTES; } + int GetFieldsOffset() { return GetHasHeader() ? APE_TAG_FOOTER_BYTES : 0; } + int GetNumberFields() { return m_nFields; } + BOOL GetHasHeader() { return (m_nFlags & APE_TAG_FLAG_CONTAINS_HEADER) ? TRUE : FALSE; } + BOOL GetIsHeader() { return (m_nFlags & APE_TAG_FLAG_IS_HEADER) ? TRUE : FALSE; } + int GetVersion() { return m_nVersion; } + + BOOL GetIsValid(BOOL bAllowHeader) + { + BOOL bValid = (strncmp(m_cID, "APETAGEX", 8) == 0) && + (m_nVersion <= CURRENT_APE_TAG_VERSION) && + (m_nFields <= 65536) && + (GetFieldBytes() <= (1024 * 1024 * 16)); + + if (bValid && (bAllowHeader == FALSE) && GetIsHeader()) + bValid = FALSE; + + return bValid ? TRUE : FALSE; + } +}; + +/***************************************************************************************** +CAPETagField class (an APE tag is an array of these) +*****************************************************************************************/ +class CAPETagField +{ +public: + + // create a tag field (use nFieldBytes = -1 for null-terminated strings) + CAPETagField(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes = -1, int nFlags = 0); + + // destructor + ~CAPETagField(); + + // gets the size of the entire field in bytes (name, value, and metadata) + int GetFieldSize(); + + // get the name of the field + const str_utf16 * GetFieldName(); + + // get the value of the field + const char * GetFieldValue(); + + // get the size of the value (in bytes) + int GetFieldValueSize(); + + // get any special flags + int GetFieldFlags(); + + // output the entire field to a buffer (GetFieldSize() bytes) + int SaveField(char * pBuffer); + + // checks to see if the field is read-only + BOOL GetIsReadOnly() { return (m_nFieldFlags & TAG_FIELD_FLAG_READ_ONLY) ? TRUE : FALSE; } + BOOL GetIsUTF8Text() { return ((m_nFieldFlags & TAG_FIELD_FLAG_DATA_TYPE_MASK) == TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8) ? TRUE : FALSE; } + + // set helpers (use with EXTREME caution) + void SetFieldFlags(int nFlags) { m_nFieldFlags = nFlags; } + +private: + + CSmartPtr m_spFieldNameUTF16; + CSmartPtr m_spFieldValue; + int m_nFieldFlags; + int m_nFieldValueBytes; +}; + +/***************************************************************************************** +CAPETag class +*****************************************************************************************/ +class CAPETag +{ +public: + + // create an APE tag + // bAnalyze determines whether it will analyze immediately or on the first request + // be careful with multiple threads / file pointer movement if you don't analyze immediately + CAPETag(CIO * pIO, BOOL bAnalyze = TRUE); + CAPETag(const str_utf16 * pFilename, BOOL bAnalyze = TRUE); + + // destructor + ~CAPETag(); + + // save the tag to the I/O source (bUseOldID3 forces it to save as an ID3v1.1 tag instead of an APE tag) + int Save(BOOL bUseOldID3 = FALSE); + + // removes any tags from the file (bUpdate determines whether is should re-analyze after removing the tag) + int Remove(BOOL bUpdate = TRUE); + + // sets the value of a field (use nFieldBytes = -1 for null terminated strings) + // note: using NULL or "" for a string type will remove the field + int SetFieldString(const str_utf16 * pFieldName, const str_utf16 * pFieldValue); + int SetFieldString(const str_utf16 * pFieldName, const char * pFieldValue, BOOL bAlreadyUTF8Encoded); + int SetFieldBinary(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes, int nFieldFlags); + + // gets the value of a field (returns -1 and an empty buffer if the field doesn't exist) + int GetFieldBinary(const str_utf16 * pFieldName, void * pBuffer, int * pBufferBytes); + int GetFieldString(const str_utf16 * pFieldName, str_utf16 * pBuffer, int * pBufferCharacters); + int GetFieldString(const str_utf16 * pFieldName, str_ansi * pBuffer, int * pBufferCharacters, BOOL bUTF8Encode = FALSE); + + // remove a specific field + int RemoveField(const str_utf16 * pFieldName); + int RemoveField(int nIndex); + + // clear all the fields + int ClearFields(); + + // get the total tag bytes in the file from the last analyze + // need to call Save() then Analyze() to update any changes + int GetTagBytes(); + + // fills in an ID3_TAG using the current fields (useful for quickly converting the tag) + int CreateID3Tag(ID3_TAG * pID3Tag); + + // see whether the file has an ID3 or APE tag + BOOL GetHasID3Tag() { if (m_bAnalyzed == FALSE) { Analyze(); } return m_bHasID3Tag; } + BOOL GetHasAPETag() { if (m_bAnalyzed == FALSE) { Analyze(); } return m_bHasAPETag; } + int GetAPETagVersion() { return GetHasAPETag() ? m_nAPETagVersion : -1; } + + // gets a desired tag field (returns NULL if not found) + // again, be careful, because this a pointer to the actual field in this class + CAPETagField * GetTagField(const str_utf16 * pFieldName); + CAPETagField * GetTagField(int nIndex); + + // options + void SetIgnoreReadOnly(BOOL bIgnoreReadOnly) { m_bIgnoreReadOnly = bIgnoreReadOnly; } + +private: + + // private functions + int Analyze(); + int GetTagFieldIndex(const str_utf16 * pFieldName); + int WriteBufferToEndOfIO(void * pBuffer, int nBytes); + int LoadField(const char * pBuffer, int nMaximumBytes, int * pBytes); + int SortFields(); + static int CompareFields(const void * pA, const void * pB); + + // helper set / get field functions + int SetFieldID3String(const str_utf16 * pFieldName, const char * pFieldValue, int nBytes); + int GetFieldID3String(const str_utf16 * pFieldName, char * pBuffer, int nBytes); + + // private data + CSmartPtr m_spIO; + BOOL m_bAnalyzed; + int m_nTagBytes; + int m_nFields; + CAPETagField * m_aryFields[256]; + BOOL m_bHasAPETag; + int m_nAPETagVersion; + BOOL m_bHasID3Tag; + BOOL m_bIgnoreReadOnly; +}; + +#endif // #ifndef APE_APETAG_H + diff --git a/MAC_SDK/Shared/All.h b/MAC_SDK/Shared/All.h new file mode 100644 index 0000000..9150851 --- /dev/null +++ b/MAC_SDK/Shared/All.h @@ -0,0 +1,235 @@ +#ifndef APE_ALL_H +#define APE_ALL_H + +/***************************************************************************************** +Cross platform building switch +*****************************************************************************************/ +//#define BUILD_CROSS_PLATFORM + +/***************************************************************************************** +Unicode +*****************************************************************************************/ +#ifdef _UNICODE + +#else + +#endif // #ifdef _UNICODE + + +/***************************************************************************************** +Global includes +*****************************************************************************************/ +#ifndef BUILD_CROSS_PLATFORM +// #include +#endif + +#ifdef _WIN32 +// #include + #include +#else + #include + #include + #include + #include + #include + #include "NoWindows.h" +#endif + +#include +#include +#include +#include +#include +#include "SmartPtr.h" + +/***************************************************************************************** +Global compiler settings (useful for porting) +*****************************************************************************************/ +#ifndef BUILD_CROSS_PLATFORM + #define ENABLE_ASSEMBLY +#endif + +#define BACKWARDS_COMPATIBILITY + +#define ENABLE_COMPRESSION_MODE_FAST +#define ENABLE_COMPRESSION_MODE_NORMAL +#define ENABLE_COMPRESSION_MODE_HIGH +#define ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +#ifdef _WIN32 + typedef unsigned __int32 uint32; + typedef __int32 int32; + typedef unsigned __int16 uint16; + typedef __int16 int16; + typedef unsigned __int8 uint8; + typedef __int8 int8; + typedef char str_ansi; + typedef unsigned char str_utf8; + typedef wchar_t str_utf16; + + #define IO_USE_WIN_FILE_IO + #define IO_HEADER_FILE "WinFileIO.h" + #define IO_CLASS_NAME CWinFileIO + #define DLLEXPORT __declspec(dllexport) + #define SLEEP(MILLISECONDS) ::Sleep(MILLISECONDS) + #define MESSAGEBOX(PARENT, TEXT, CAPTION, TYPE) ::MessageBox(PARENT, TEXT, CAPTION, TYPE) + #define PUMP_MESSAGE_LOOP { MSG Msg; while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) != 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } + #define ODS OutputDebugString + #define TICK_COUNT_TYPE unsigned long + #define TICK_COUNT_READ(VARIABLE) VARIABLE = GetTickCount() + #define TICK_COUNT_FREQ 1000 +#else + #define IO_USE_STD_LIB_FILE_IO + #define IO_HEADER_FILE "StdLibFileIO.h" + #define IO_CLASS_NAME CStdLibFileIO + #define DLLEXPORT + #define SLEEP(MILLISECONDS) { struct timespec t; t.tv_sec = (MILLISECONDS) / 1000; t.tv_nsec = (MILLISECONDS) % 1000 * 1000000; nanosleep(&t, NULL); } + #define MESSAGEBOX(PARENT, TEXT, CAPTION, TYPE) + #define PUMP_MESSAGE_LOOP + #define ODS printf + #define TICK_COUNT_TYPE unsigned long long + #define TICK_COUNT_READ(VARIABLE) { struct timeval t; gettimeofday(&t, NULL); VARIABLE = t.tv_sec * 1000000LLU + t.tv_usec; } + #define TICK_COUNT_FREQ 1000000 +#endif + +/***************************************************************************************** +Global defines +*****************************************************************************************/ +#define MAC_VERSION_NUMBER 3990 +#define MAC_VERSION_STRING _T("3.99") +#define MAC_NAME _T("Monkey's Audio 3.99") +#define PLUGIN_NAME "Monkey's Audio Player v3.99" +#define MJ_PLUGIN_NAME _T("APE Plugin (v3.99)") +#define CONSOLE_NAME "--- Monkey's Audio Console Front End (v 3.99) (c) Matthew T. Ashland ---\n" +#define PLUGIN_ABOUT _T("Monkey's Audio Player v3.99\nCopyrighted (c) 2000-2004 by Matthew T. Ashland") +#define MAC_DLL_INTERFACE_VERSION_NUMBER 1000 + +/***************************************************************************************** +Byte order +*****************************************************************************************/ +#define __LITTLE_ENDIAN 1234 +#define __BIG_ENDIAN 4321 +#define __BYTE_ORDER __LITTLE_ENDIAN + +/***************************************************************************************** +Macros +*****************************************************************************************/ +#define MB(TEST) MESSAGEBOX(NULL, TEST, _T("Information"), MB_OK); +#define MBN(NUMBER) { TCHAR cNumber[16]; _stprintf(cNumber, _T("%d"), NUMBER); MESSAGEBOX(NULL, cNumber, _T("Information"), MB_OK); } + +#define SAFE_DELETE(POINTER) if (POINTER) { delete POINTER; POINTER = NULL; } +#define SAFE_ARRAY_DELETE(POINTER) if (POINTER) { delete [] POINTER; POINTER = NULL; } +#define SAFE_VOID_CLASS_DELETE(POINTER, Class) { Class *pClass = (Class *) POINTER; if (pClass) { delete pClass; POINTER = NULL; } } +#define SAFE_FILE_CLOSE(HANDLE) if (HANDLE != INVALID_HANDLE_VALUE) { CloseHandle(HANDLE); HANDLE = INVALID_HANDLE_VALUE; } + +#define ODN(NUMBER) { TCHAR cNumber[16]; _stprintf(cNumber, _T("%d\n"), int(NUMBER)); ODS(cNumber); } + +#define CATCH_ERRORS(CODE) try { CODE } catch(...) { } + +#define RETURN_ON_ERROR(FUNCTION) { int nRetVal = FUNCTION; if (nRetVal != 0) { return nRetVal; } } +#define RETURN_VALUE_ON_ERROR(FUNCTION, VALUE) { int nRetVal = FUNCTION; if (nRetVal != 0) { return VALUE; } } +#define RETURN_ON_EXCEPTION(CODE, VALUE) { try { CODE } catch(...) { return VALUE; } } + +#define THROW_ON_ERROR(CODE) { int nRetVal = CODE; if (nRetVal != 0) throw(nRetVal); } + +#define EXPAND_1_TIMES(CODE) CODE +#define EXPAND_2_TIMES(CODE) CODE CODE +#define EXPAND_3_TIMES(CODE) CODE CODE CODE +#define EXPAND_4_TIMES(CODE) CODE CODE CODE CODE +#define EXPAND_5_TIMES(CODE) CODE CODE CODE CODE CODE +#define EXPAND_6_TIMES(CODE) CODE CODE CODE CODE CODE CODE +#define EXPAND_7_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_8_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_9_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_12_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_14_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_15_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_16_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_30_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_31_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_32_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_64_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_N_TIMES(NUMBER, CODE) EXPAND_##NUMBER##_TIMES(CODE) + +#define UNROLL_4_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) +#define UNROLL_8_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) +#define UNROLL_15_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) +#define UNROLL_16_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) +#define UNROLL_64_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) +#define UNROLL_128_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) MACRO(64) MACRO(65) MACRO(66) MACRO(67) MACRO(68) MACRO(69) MACRO(70) MACRO(71) MACRO(72) MACRO(73) MACRO(74) MACRO(75) MACRO(76) MACRO(77) MACRO(78) MACRO(79) MACRO(80) MACRO(81) MACRO(82) MACRO(83) MACRO(84) MACRO(85) MACRO(86) MACRO(87) MACRO(88) MACRO(89) MACRO(90) MACRO(91) MACRO(92) MACRO(93) MACRO(94) MACRO(95) MACRO(96) MACRO(97) MACRO(98) MACRO(99) MACRO(100) MACRO(101) MACRO(102) MACRO(103) MACRO(104) MACRO(105) MACRO(106) MACRO(107) MACRO(108) MACRO(109) MACRO(110) MACRO(111) MACRO(112) MACRO(113) MACRO(114) MACRO(115) MACRO(116) MACRO(117) MACRO(118) MACRO(119) MACRO(120) MACRO(121) MACRO(122) MACRO(123) MACRO(124) MACRO(125) MACRO(126) MACRO(127) +#define UNROLL_256_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) MACRO(64) MACRO(65) MACRO(66) MACRO(67) MACRO(68) MACRO(69) MACRO(70) MACRO(71) MACRO(72) MACRO(73) MACRO(74) MACRO(75) MACRO(76) MACRO(77) MACRO(78) MACRO(79) MACRO(80) MACRO(81) MACRO(82) MACRO(83) MACRO(84) MACRO(85) MACRO(86) MACRO(87) MACRO(88) MACRO(89) MACRO(90) MACRO(91) MACRO(92) MACRO(93) MACRO(94) MACRO(95) MACRO(96) MACRO(97) MACRO(98) MACRO(99) MACRO(100) MACRO(101) MACRO(102) MACRO(103) MACRO(104) MACRO(105) MACRO(106) MACRO(107) MACRO(108) MACRO(109) MACRO(110) MACRO(111) MACRO(112) MACRO(113) MACRO(114) MACRO(115) MACRO(116) MACRO(117) MACRO(118) MACRO(119) MACRO(120) MACRO(121) MACRO(122) MACRO(123) MACRO(124) MACRO(125) MACRO(126) MACRO(127) \ + MACRO(128) MACRO(129) MACRO(130) MACRO(131) MACRO(132) MACRO(133) MACRO(134) MACRO(135) MACRO(136) MACRO(137) MACRO(138) MACRO(139) MACRO(140) MACRO(141) MACRO(142) MACRO(143) MACRO(144) MACRO(145) MACRO(146) MACRO(147) MACRO(148) MACRO(149) MACRO(150) MACRO(151) MACRO(152) MACRO(153) MACRO(154) MACRO(155) MACRO(156) MACRO(157) MACRO(158) MACRO(159) MACRO(160) MACRO(161) MACRO(162) MACRO(163) MACRO(164) MACRO(165) MACRO(166) MACRO(167) MACRO(168) MACRO(169) MACRO(170) MACRO(171) MACRO(172) MACRO(173) MACRO(174) MACRO(175) MACRO(176) MACRO(177) MACRO(178) MACRO(179) MACRO(180) MACRO(181) MACRO(182) MACRO(183) MACRO(184) MACRO(185) MACRO(186) MACRO(187) MACRO(188) MACRO(189) MACRO(190) MACRO(191) MACRO(192) MACRO(193) MACRO(194) MACRO(195) MACRO(196) MACRO(197) MACRO(198) MACRO(199) MACRO(200) MACRO(201) MACRO(202) MACRO(203) MACRO(204) MACRO(205) MACRO(206) MACRO(207) MACRO(208) MACRO(209) MACRO(210) MACRO(211) MACRO(212) MACRO(213) MACRO(214) MACRO(215) MACRO(216) MACRO(217) MACRO(218) MACRO(219) MACRO(220) MACRO(221) MACRO(222) MACRO(223) MACRO(224) MACRO(225) MACRO(226) MACRO(227) MACRO(228) MACRO(229) MACRO(230) MACRO(231) MACRO(232) MACRO(233) MACRO(234) MACRO(235) MACRO(236) MACRO(237) MACRO(238) MACRO(239) MACRO(240) MACRO(241) MACRO(242) MACRO(243) MACRO(244) MACRO(245) MACRO(246) MACRO(247) MACRO(248) MACRO(249) MACRO(250) MACRO(251) MACRO(252) MACRO(253) MACRO(254) MACRO(255) + +/***************************************************************************************** +Error Codes +*****************************************************************************************/ + +// success +#ifndef ERROR_SUCCESS +#define ERROR_SUCCESS 0 +#endif + +// file and i/o errors (1000's) +#define ERROR_IO_READ 1000 +#define ERROR_IO_WRITE 1001 +#define ERROR_INVALID_INPUT_FILE 1002 +#define ERROR_INVALID_OUTPUT_FILE 1003 +#define ERROR_INPUT_FILE_TOO_LARGE 1004 +#define ERROR_INPUT_FILE_UNSUPPORTED_BIT_DEPTH 1005 +#define ERROR_INPUT_FILE_UNSUPPORTED_SAMPLE_RATE 1006 +#define ERROR_INPUT_FILE_UNSUPPORTED_CHANNEL_COUNT 1007 +#define ERROR_INPUT_FILE_TOO_SMALL 1008 +#define ERROR_INVALID_CHECKSUM 1009 +#define ERROR_DECOMPRESSING_FRAME 1010 +#define ERROR_INITIALIZING_UNMAC 1011 +#define ERROR_INVALID_FUNCTION_PARAMETER 1012 +#define ERROR_UNSUPPORTED_FILE_TYPE 1013 +#define ERROR_UPSUPPORTED_FILE_VERSION 1014 + +// memory errors (2000's) +#define ERROR_INSUFFICIENT_MEMORY 2000 + +// dll errors (3000's) +#define ERROR_LOADINGAPE_DLL 3000 +#define ERROR_LOADINGAPE_INFO_DLL 3001 +#define ERROR_LOADING_UNMAC_DLL 3002 + +// general and misc errors +#define ERROR_USER_STOPPED_PROCESSING 4000 +#define ERROR_SKIPPED 4001 + +// programmer errors +#define ERROR_BAD_PARAMETER 5000 + +// IAPECompress errors +#define ERROR_APE_COMPRESS_TOO_MUCH_DATA 6000 + +// unknown error +#define ERROR_UNDEFINED -1 + +#define ERROR_EXPLANATION \ + { ERROR_IO_READ , "I/O read error" }, \ + { ERROR_IO_WRITE , "I/O write error" }, \ + { ERROR_INVALID_INPUT_FILE , "invalid input file" }, \ + { ERROR_INVALID_OUTPUT_FILE , "invalid output file" }, \ + { ERROR_INPUT_FILE_TOO_LARGE , "input file file too large" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_BIT_DEPTH , "input file unsupported bit depth" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_SAMPLE_RATE , "input file unsupported sample rate" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_CHANNEL_COUNT , "input file unsupported channel count" }, \ + { ERROR_INPUT_FILE_TOO_SMALL , "input file too small" }, \ + { ERROR_INVALID_CHECKSUM , "invalid checksum" }, \ + { ERROR_DECOMPRESSING_FRAME , "decompressing frame" }, \ + { ERROR_INITIALIZING_UNMAC , "initializing unmac" }, \ + { ERROR_INVALID_FUNCTION_PARAMETER , "invalid function parameter" }, \ + { ERROR_UNSUPPORTED_FILE_TYPE , "unsupported file type" }, \ + { ERROR_INSUFFICIENT_MEMORY , "insufficient memory" }, \ + { ERROR_LOADINGAPE_DLL , "loading MAC.dll" }, \ + { ERROR_LOADINGAPE_INFO_DLL , "loading MACinfo.dll" }, \ + { ERROR_LOADING_UNMAC_DLL , "loading UnMAC.dll" }, \ + { ERROR_USER_STOPPED_PROCESSING , "user stopped processing" }, \ + { ERROR_SKIPPED , "skipped" }, \ + { ERROR_BAD_PARAMETER , "bad parameter" }, \ + { ERROR_APE_COMPRESS_TOO_MUCH_DATA , "APE compress too much data" }, \ + { ERROR_UNDEFINED , "undefined" }, \ + +#endif // #ifndef APE_ALL_H \ No newline at end of file diff --git a/MAC_SDK/Shared/IO.h b/MAC_SDK/Shared/IO.h new file mode 100644 index 0000000..63b4d7f --- /dev/null +++ b/MAC_SDK/Shared/IO.h @@ -0,0 +1,49 @@ +#ifndef APE_IO_H +#define APE_IO_H + +#ifndef FILE_BEGIN + #define FILE_BEGIN 0 +#endif + +#ifndef FILE_CURRENT + #define FILE_CURRENT 1 +#endif + +#ifndef FILE_END + #define FILE_END 2 +#endif + +class CIO +{ + +public: + + //construction / destruction + CIO() { } + virtual ~CIO() { }; + + // open / close + virtual int Open(const wchar_t * pName) = 0; + virtual int Close() = 0; + + // read / write + virtual int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead) = 0; + virtual int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten) = 0; + + // seek + virtual int Seek(int nDistance, unsigned int nMoveMode) = 0; + + // creation / destruction + virtual int Create(const wchar_t * pName) = 0; + virtual int Delete() = 0; + + // other functions + virtual int SetEOF() = 0; + + // attributes + virtual int GetPosition() = 0; + virtual int GetSize() = 0; + virtual int GetName(wchar_t * pBuffer) = 0; +}; + +#endif // #ifndef APE_IO_H diff --git a/MAC_SDK/Shared/MACDll.h b/MAC_SDK/Shared/MACDll.h new file mode 100644 index 0000000..7940017 --- /dev/null +++ b/MAC_SDK/Shared/MACDll.h @@ -0,0 +1,99 @@ +/***************************************************************************************** +Monkey's Audio MACDll.h (include for using MACDll.dll in your projects) +Copyright (C) 2000-2004 by Matthew T. Ashland All Rights Reserved. + +Overview: + +Basically all this dll does is wrap MACLib.lib, so browse through MACLib.h for documentation +on how to use the interfaces. + +Questions / Suggestions: + +Please direct questions or comments to the Monkey's Audio developers board: + http://www.monkeysaudio.com/cgi-bin/YaBB/YaBB.cgi -> Developers +or, if necessary, matt @ monkeysaudio.com +*****************************************************************************************/ + +#ifndef APE_MACDLL_H +#define APE_MACDLL_H + +/***************************************************************************************** +Includes +*****************************************************************************************/ +#include "All.h" +#include "MACLib.h" + +/***************************************************************************************** +Defines (implemented elsewhere) +*****************************************************************************************/ +struct ID3_TAG; + +/***************************************************************************************** +Helper functions +*****************************************************************************************/ +extern "C" +{ + __declspec( dllexport ) int __stdcall GetVersionNumber(); + __declspec( dllexport ) int __stdcall GetInterfaceCompatibility(int nVersion, BOOL bDisplayWarningsOnFailure = TRUE, HWND hwndParent = NULL); + __declspec( dllexport ) int __stdcall ShowFileInfoDialog(const str_ansi * pFilename, HWND hwndWindow); + __declspec( dllexport ) int __stdcall TagFileSimple(const str_ansi * pFilename, const char * pArtist, const char * pAlbum, const char * pTitle, const char * pComment, const char * pGenre, const char * pYear, const char * pTrack, BOOL bClearFirst, BOOL bUseOldID3); + __declspec( dllexport ) int __stdcall GetID3Tag(const str_ansi * pFilename, ID3_TAG * pID3Tag); + __declspec( dllexport ) int __stdcall RemoveTag(const str_ansi * pFilename); +} + +typedef int (__stdcall * proc_GetVersionNumber)(); +typedef int (__stdcall * proc_GetInterfaceCompatibility)(int, BOOL, HWND); + +/***************************************************************************************** +IAPECompress wrapper(s) +*****************************************************************************************/ +typedef void * APE_COMPRESS_HANDLE; + +typedef APE_COMPRESS_HANDLE (__stdcall * proc_APECompress_Create)(int *); +typedef void (__stdcall * proc_APECompress_Destroy)(APE_COMPRESS_HANDLE); +typedef int (__stdcall * proc_APECompress_Start)(APE_COMPRESS_HANDLE, const char *, const WAVEFORMATEX *, int, int, const void *, int); +typedef int (__stdcall * proc_APECompress_StartW)(APE_COMPRESS_HANDLE, const char *, const WAVEFORMATEX *, int, int, const void *, int); +typedef int (__stdcall * proc_APECompress_AddData)(APE_COMPRESS_HANDLE, unsigned char *, int); +typedef int (__stdcall * proc_APECompress_GetBufferBytesAvailable)(APE_COMPRESS_HANDLE); +typedef unsigned char * (__stdcall * proc_APECompress_LockBuffer)(APE_COMPRESS_HANDLE, int *); +typedef int (__stdcall * proc_APECompress_UnlockBuffer)(APE_COMPRESS_HANDLE, int, BOOL); +typedef int (__stdcall * proc_APECompress_Finish)(APE_COMPRESS_HANDLE, unsigned char *, int, int); +typedef int (__stdcall * proc_APECompress_Kill)(APE_COMPRESS_HANDLE); + +extern "C" +{ + __declspec( dllexport ) APE_COMPRESS_HANDLE __stdcall c_APECompress_Create(int * pErrorCode = NULL); + __declspec( dllexport ) void __stdcall c_APECompress_Destroy(APE_COMPRESS_HANDLE hAPECompress); + __declspec( dllexport ) int __stdcall c_APECompress_Start(APE_COMPRESS_HANDLE hAPECompress, const char * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const unsigned char * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + __declspec( dllexport ) int __stdcall c_APECompress_StartW(APE_COMPRESS_HANDLE hAPECompress, const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const unsigned char * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + __declspec( dllexport ) int __stdcall c_APECompress_AddData(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pData, int nBytes); + __declspec( dllexport ) int __stdcall c_APECompress_GetBufferBytesAvailable(APE_COMPRESS_HANDLE hAPECompress); + __declspec( dllexport ) unsigned char * __stdcall c_APECompress_LockBuffer(APE_COMPRESS_HANDLE hAPECompress, int * pBytesAvailable); + __declspec( dllexport ) int __stdcall c_APECompress_UnlockBuffer(APE_COMPRESS_HANDLE hAPECompress, int nBytesAdded, BOOL bProcess = TRUE); + __declspec( dllexport ) int __stdcall c_APECompress_Finish(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes); + __declspec( dllexport ) int __stdcall c_APECompress_Kill(APE_COMPRESS_HANDLE hAPECompress); +} + +/***************************************************************************************** +IAPEDecompress wrapper(s) +*****************************************************************************************/ +typedef void * APE_DECOMPRESS_HANDLE; + +typedef APE_DECOMPRESS_HANDLE (__stdcall * proc_APEDecompress_Create)(const char *, int *); +typedef APE_DECOMPRESS_HANDLE (__stdcall * proc_APEDecompress_CreateW)(const char *, int *); +typedef void (__stdcall * proc_APEDecompress_Destroy)(APE_DECOMPRESS_HANDLE); +typedef int (__stdcall * proc_APEDecompress_GetData)(APE_DECOMPRESS_HANDLE, char *, int, int *); +typedef int (__stdcall * proc_APEDecompress_Seek)(APE_DECOMPRESS_HANDLE, int); +typedef int (__stdcall * proc_APEDecompress_GetInfo)(APE_DECOMPRESS_HANDLE, APE_DECOMPRESS_FIELDS, int, int); + +extern "C" +{ + __declspec( dllexport ) APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_Create(const str_ansi * pFilename, int * pErrorCode = NULL); + __declspec( dllexport ) APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_CreateW(const str_utf16 * pFilename, int * pErrorCode = NULL); + __declspec( dllexport ) void __stdcall c_APEDecompress_Destroy(APE_DECOMPRESS_HANDLE hAPEDecompress); + __declspec( dllexport ) int __stdcall c_APEDecompress_GetData(APE_DECOMPRESS_HANDLE hAPEDecompress, char * pBuffer, int nBlocks, int * pBlocksRetrieved); + __declspec( dllexport ) int __stdcall c_APEDecompress_Seek(APE_DECOMPRESS_HANDLE hAPEDecompress, int nBlockOffset); + __declspec( dllexport ) int __stdcall c_APEDecompress_GetInfo(APE_DECOMPRESS_HANDLE hAPEDecompress, APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0); +} + +#endif // #ifndef APE_MACDLL_H diff --git a/MAC_SDK/Shared/MACLib.h b/MAC_SDK/Shared/MACLib.h new file mode 100644 index 0000000..af0cbcd --- /dev/null +++ b/MAC_SDK/Shared/MACLib.h @@ -0,0 +1,450 @@ +/***************************************************************************************** +Monkey's Audio MACLib.h (include for using MACLib.lib in your projects) +Copyright (C) 2000-2003 by Matthew T. Ashland All Rights Reserved. + +Overview: + +There are two main interfaces... create one (using CreateIAPExxx) and go to town: + + IAPECompress - for creating APE files + IAPEDecompress - for decompressing and analyzing APE files + +Note(s): + +Unless otherwise specified, functions return ERROR_SUCCESS (0) on success and an +error code on failure. + +The terminology "Sample" refers to a single sample value, and "Block" refers +to a collection of "Channel" samples. For simplicity, MAC typically uses blocks +everywhere so that channel mis-alignment cannot happen. (i.e. on a CD, a sample is +2 bytes and a block is 4 bytes ([2 bytes per sample] * [2 channels] = 4 bytes)) + +Questions / Suggestions: + +Please direct questions or comments to the Monkey's Audio developers board: +http://www.monkeysaudio.com/cgi-bin/YaBB/YaBB.cgi -> Developers +or, if necessary, matt @ monkeysaudio.com +*****************************************************************************************/ + +#ifndef APE_MACLIB_H +#define APE_MACLIB_H + +/************************************************************************************************* +APE File Format Overview: (pieces in order -- only valid for the latest version APE files) + + JUNK - any amount of "junk" before the APE_DESCRIPTOR (so people that put ID3v2 tags on the files aren't hosed) + APE_DESCRIPTOR - defines the sizes (and offsets) of all the pieces, as well as the MD5 checksum + APE_HEADER - describes all of the necessary information about the APE file + SEEK TABLE - the table that represents seek offsets [optional] + HEADER DATA - the pre-audio data from the original file [optional] + APE FRAMES - the actual compressed audio (broken into frames for seekability) + TERMINATING DATA - the post-audio data from the original file [optional] + TAG - describes all the properties of the file [optional] + +Notes: + + Junk: + + This block may not be supported in the future, so don't write any software that adds meta data + before the APE_DESCRIPTOR. Please use the APE Tag for any meta data. + + Seek Table: + + A 32-bit unsigned integer array of offsets from the header to the frame data. May become "delta" + values someday to better suit huge files. + + MD5 Hash: + + Since the header is the last part written to an APE file, you must calculate the MD5 checksum out of order. + So, you first calculate from the tail of the seek table to the end of the terminating data. + Then, go back and do from the end of the descriptor to the tail of the seek table. + You may wish to just cache the header data when starting and run it last, so you don't + need to seek back in the I/O. +*************************************************************************************************/ + +/***************************************************************************************** +Defines +*****************************************************************************************/ +#define COMPRESSION_LEVEL_FAST 1000 +#define COMPRESSION_LEVEL_NORMAL 2000 +#define COMPRESSION_LEVEL_HIGH 3000 +#define COMPRESSION_LEVEL_EXTRA_HIGH 4000 +#define COMPRESSION_LEVEL_INSANE 5000 + +#define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE] +#define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE] +#define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE] +#define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE] +#define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level +#define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored) + +#define CREATE_WAV_HEADER_ON_DECOMPRESSION -1 +#define MAX_AUDIO_BYTES_UNKNOWN -1 + +typedef void (__stdcall * APE_PROGRESS_CALLBACK) (int); + +/***************************************************************************************** +WAV header structure +*****************************************************************************************/ +struct WAVE_HEADER +{ + // RIFF header + char cRIFFHeader[4]; + unsigned int nRIFFBytes; + + // data type + char cDataTypeID[4]; + + // wave format + char cFormatHeader[4]; + unsigned int nFormatBytes; + + unsigned short nFormatTag; + unsigned short nChannels; + unsigned int nSamplesPerSec; + unsigned int nAvgBytesPerSec; + unsigned short nBlockAlign; + unsigned short nBitsPerSample; + + // data chunk header + char cDataHeader[4]; + unsigned int nDataBytes; +}; + +/***************************************************************************************** +APE_DESCRIPTOR structure (file header that describes lengths, offsets, etc.) +*****************************************************************************************/ +struct APE_DESCRIPTOR +{ + char cID[4]; // should equal 'MAC ' + uint16 nVersion; // version number * 1000 (3.81 = 3810) + + uint32 nDescriptorBytes; // the number of descriptor bytes (allows later expansion of this header) + uint32 nHeaderBytes; // the number of header APE_HEADER bytes + uint32 nSeekTableBytes; // the number of bytes of the seek table + uint32 nHeaderDataBytes; // the number of header data bytes (from original file) + uint32 nAPEFrameDataBytes; // the number of bytes of APE frame data + uint32 nAPEFrameDataBytesHigh; // the high order number of APE frame data bytes + uint32 nTerminatingDataBytes; // the terminating data of the file (not including tag data) + + uint8 cFileMD5[16]; // the MD5 hash of the file (see notes for usage... it's a littly tricky) +}; + +/***************************************************************************************** +APE_HEADER structure (describes the format, duration, etc. of the APE file) +*****************************************************************************************/ +struct APE_HEADER +{ + uint16 nCompressionLevel; // the compression level (see defines I.E. COMPRESSION_LEVEL_FAST) + uint16 nFormatFlags; // any format flags (for future use) + + uint32 nBlocksPerFrame; // the number of audio blocks in one frame + uint32 nFinalFrameBlocks; // the number of audio blocks in the final frame + uint32 nTotalFrames; // the total number of frames + + uint16 nBitsPerSample; // the bits per sample (typically 16) + uint16 nChannels; // the number of channels (1 or 2) + uint32 nSampleRate; // the sample rate (typically 44100) +}; + +/************************************************************************************************* +Classes (fully defined elsewhere) +*************************************************************************************************/ +class CIO; +class CInputSource; +class CAPEInfo; + +/************************************************************************************************* +IAPEDecompress fields - used when querying for information + +Note(s): +-the distinction between APE_INFO_XXXX and APE_DECOMPRESS_XXXX is that the first is querying the APE +information engine, and the other is querying the decompressor, and since the decompressor can be +a range of an APE file (for APL), differences will arise. Typically, use the APE_DECOMPRESS_XXXX +fields when querying for info about the length, etc. so APL will work properly. +(i.e. (APE_INFO_TOTAL_BLOCKS != APE_DECOMPRESS_TOTAL_BLOCKS) for APL files) +*************************************************************************************************/ +enum APE_DECOMPRESS_FIELDS +{ + APE_INFO_FILE_VERSION = 1000, // version of the APE file * 1000 (3.93 = 3930) [ignored, ignored] + APE_INFO_COMPRESSION_LEVEL = 1001, // compression level of the APE file [ignored, ignored] + APE_INFO_FORMAT_FLAGS = 1002, // format flags of the APE file [ignored, ignored] + APE_INFO_SAMPLE_RATE = 1003, // sample rate (Hz) [ignored, ignored] + APE_INFO_BITS_PER_SAMPLE = 1004, // bits per sample [ignored, ignored] + APE_INFO_BYTES_PER_SAMPLE = 1005, // number of bytes per sample [ignored, ignored] + APE_INFO_CHANNELS = 1006, // channels [ignored, ignored] + APE_INFO_BLOCK_ALIGN = 1007, // block alignment [ignored, ignored] + APE_INFO_BLOCKS_PER_FRAME = 1008, // number of blocks in a frame (frames are used internally) [ignored, ignored] + APE_INFO_FINAL_FRAME_BLOCKS = 1009, // blocks in the final frame (frames are used internally) [ignored, ignored] + APE_INFO_TOTAL_FRAMES = 1010, // total number frames (frames are used internally) [ignored, ignored] + APE_INFO_WAV_HEADER_BYTES = 1011, // header bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_TERMINATING_BYTES = 1012, // terminating bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_DATA_BYTES = 1013, // data bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_TOTAL_BYTES = 1014, // total bytes of the decompressed WAV [ignored, ignored] + APE_INFO_APE_TOTAL_BYTES = 1015, // total bytes of the APE file [ignored, ignored] + APE_INFO_TOTAL_BLOCKS = 1016, // total blocks of audio data [ignored, ignored] + APE_INFO_LENGTH_MS = 1017, // length in ms (1 sec = 1000 ms) [ignored, ignored] + APE_INFO_AVERAGE_BITRATE = 1018, // average bitrate of the APE [ignored, ignored] + APE_INFO_FRAME_BITRATE = 1019, // bitrate of specified APE frame [frame index, ignored] + APE_INFO_DECOMPRESSED_BITRATE = 1020, // bitrate of the decompressed WAV [ignored, ignored] + APE_INFO_PEAK_LEVEL = 1021, // peak audio level (obsolete) (-1 is unknown) [ignored, ignored] + APE_INFO_SEEK_BIT = 1022, // bit offset [frame index, ignored] + APE_INFO_SEEK_BYTE = 1023, // byte offset [frame index, ignored] + APE_INFO_WAV_HEADER_DATA = 1024, // error code [buffer *, max bytes] + APE_INFO_WAV_TERMINATING_DATA = 1025, // error code [buffer *, max bytes] + APE_INFO_WAVEFORMATEX = 1026, // error code [waveformatex *, ignored] + APE_INFO_IO_SOURCE = 1027, // I/O source (CIO *) [ignored, ignored] + APE_INFO_FRAME_BYTES = 1028, // bytes (compressed) of the frame [frame index, ignored] + APE_INFO_FRAME_BLOCKS = 1029, // blocks in a given frame [frame index, ignored] + APE_INFO_TAG = 1030, // point to tag (CAPETag *) [ignored, ignored] + + APE_DECOMPRESS_CURRENT_BLOCK = 2000, // current block location [ignored, ignored] + APE_DECOMPRESS_CURRENT_MS = 2001, // current millisecond location [ignored, ignored] + APE_DECOMPRESS_TOTAL_BLOCKS = 2002, // total blocks in the decompressors range [ignored, ignored] + APE_DECOMPRESS_LENGTH_MS = 2003, // total blocks in the decompressors range [ignored, ignored] + APE_DECOMPRESS_CURRENT_BITRATE = 2004, // current bitrate [ignored, ignored] + APE_DECOMPRESS_AVERAGE_BITRATE = 2005, // average bitrate (works with ranges) [ignored, ignored] + + APE_INTERNAL_INFO = 3000, // for internal use -- don't use (returns APE_FILE_INFO *) [ignored, ignored] +}; + +/************************************************************************************************* +IAPEDecompress - interface for working with existing APE files (decoding, seeking, analyzing, etc.) +*************************************************************************************************/ +class IAPEDecompress +{ +public: + + // destructor (needed so implementation's destructor will be called) + virtual ~IAPEDecompress() {} + + /********************************************************************************************* + * Decompress / Seek + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetData(...) - gets raw decompressed audio + // + // Parameters: + // char * pBuffer + // a pointer to a buffer to put the data into + // int nBlocks + // the number of audio blocks desired (see note at intro about blocks vs. samples) + // int * pBlocksRetrieved + // the number of blocks actually retrieved (could be less at end of file or on critical failure) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Seek(...) - seeks + // + // Parameters: + // int nBlockOffset + // the block to seek to (see note at intro about blocks vs. samples) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Seek(int nBlockOffset) = 0; + + /********************************************************************************************* + * Get Information + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetInfo(...) - get information about the APE file or the state of the decompressor + // + // Parameters: + // APE_DECOMPRESS_FIELDS Field + // the field we're querying (see APE_DECOMPRESS_FIELDS above for more info) + // int nParam1 + // generic parameter... usage is listed in APE_DECOMPRESS_FIELDS + // int nParam2 + // generic parameter... usage is listed in APE_DECOMPRESS_FIELDS + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0) = 0; +}; + +/************************************************************************************************* +IAPECompress - interface for creating APE files + +Usage: + + To create an APE file, you Start(...), then add data (in a variety of ways), then Finish(...) +*************************************************************************************************/ +class IAPECompress +{ +public: + + // destructor (needed so implementation's destructor will be called) + virtual ~IAPECompress() {} + + /********************************************************************************************* + * Start + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Start(...) / StartEx(...) - starts encoding + // + // Parameters: + // CIO * pioOutput / const str_utf16 * pFilename + // the output... either a filename or an I/O source + // WAVEFORMATEX * pwfeInput + // format of the audio to encode (use FillWaveFormatEx() if necessary) + // int nMaxAudioBytes + // the absolute maximum audio bytes that will be encoded... encoding fails with a + // ERROR_APE_COMPRESS_TOO_MUCH_DATA if you attempt to encode more than specified here + // (if unknown, use MAX_AUDIO_BYTES_UNKNOWN to allocate as much storage in the seek table as + // possible... limit is then 2 GB of data (~4 hours of CD music)... this wastes around + // 30kb, so only do it if completely necessary) + // int nCompressionLevel + // the compression level for the APE file (fast - extra high) + // (note: extra-high is much slower for little gain) + // const void * pHeaderData + // a pointer to a buffer containing the WAV header (data before the data block in the WAV) + // (note: use NULL for on-the-fly encoding... see next parameter) + // int nHeaderBytes + // number of bytes in the header data buffer (use CREATE_WAV_HEADER_ON_DECOMPRESSION and + // NULL for the pHeaderData and MAC will automatically create the appropriate WAV header + // on decompression) + ////////////////////////////////////////////////////////////////////////////////////////////// + + virtual int Start(const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput, + int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, + const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0; + + virtual int StartEx(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, + int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, + const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0; + + /********************************************************************************************* + * Add / Compress Data + * - there are 3 ways to add data: + * 1) simple call AddData(...) + * 2) lock MAC's buffer, copy into it, and unlock (LockBuffer(...) / UnlockBuffer(...)) + * 3) from an I/O source (AddDataFromInputSource(...)) + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // AddData(...) - adds data to the encoder + // + // Parameters: + // unsigned char * pData + // a pointer to a buffer containing the raw audio data + // int nBytes + // the number of bytes in the buffer + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int AddData(unsigned char * pData, int nBytes) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetBufferBytesAvailable(...) - returns the number of bytes available in the buffer + // (helpful when locking) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetBufferBytesAvailable() = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // LockBuffer(...) - locks MAC's buffer so we can copy into it + // + // Parameters: + // int * pBytesAvailable + // returns the number of bytes available in the buffer (DO NOT COPY MORE THAN THIS IN) + // + // Return: + // pointer to the buffer (add at that location) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual unsigned char * LockBuffer(int * pBytesAvailable) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // UnlockBuffer(...) - releases the buffer + // + // Parameters: + // int nBytesAdded + // the number of bytes copied into the buffer + // BOOL bProcess + // whether MAC should process as much as possible of the buffer + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int UnlockBuffer(int nBytesAdded, BOOL bProcess = TRUE) = 0; + + + ////////////////////////////////////////////////////////////////////////////////////////////// + // AddDataFromInputSource(...) - use a CInputSource (input source) to add data + // + // Parameters: + // CInputSource * pInputSource + // a pointer to the input source + // int nMaxBytes + // the maximum number of bytes to let MAC add (-1 if MAC can add any amount) + // int * pBytesAdded + // returns the number of bytes added from the I/O source + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int AddDataFromInputSource(CInputSource * pInputSource, int nMaxBytes = -1, int * pBytesAdded = NULL) = 0; + + /********************************************************************************************* + * Finish / Kill + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Finish(...) - ends encoding and finalizes the file + // + // Parameters: + // unsigned char * pTerminatingData + // a pointer to a buffer containing the information to place at the end of the APE file + // (comprised of the WAV terminating data (data after the data block in the WAV) followed + // by any tag information) + // int nTerminatingBytes + // number of bytes in the terminating data buffer + // int nWAVTerminatingBytes + // the number of bytes of the terminating data buffer that should be appended to a decoded + // WAV file (it's basically nTerminatingBytes - the bytes that make up the tag) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Finish(unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Kill(...) - stops encoding and deletes the output file + // --- NOT CURRENTLY IMPLEMENTED --- + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Kill() = 0; +}; + +/************************************************************************************************* +Functions to create the interfaces + +Usage: + Interface creation returns a NULL pointer on failure (and fills error code if it was passed in) + +Usage example: + int nErrorCode; + IAPEDecompress * pAPEDecompress = CreateIAPEDecompress("c:\\1.ape", &nErrorCode); + if (pAPEDecompress == NULL) + { + // failure... nErrorCode will have specific code + } + +*************************************************************************************************/ +extern "C" +{ + IAPEDecompress * __stdcall CreateIAPEDecompress(const str_utf16 * pFilename, int * pErrorCode = NULL); + IAPEDecompress * __stdcall CreateIAPEDecompressEx(CIO * pIO, int * pErrorCode = NULL); + IAPEDecompress * __stdcall CreateIAPEDecompressEx2(CAPEInfo * pAPEInfo, int nStartBlock = -1, int nFinishBlock = -1, int * pErrorCode = NULL); + IAPECompress * __stdcall CreateIAPECompress(int * pErrorCode = NULL); +} + +/************************************************************************************************* +Simple functions - see the SDK sample projects for usage examples +*************************************************************************************************/ +extern "C" +{ + // process whole files + DLLEXPORT int __stdcall CompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL); + DLLEXPORT int __stdcall DecompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall ConvertFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall VerifyFile(const str_ansi * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + + DLLEXPORT int __stdcall CompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL); + DLLEXPORT int __stdcall DecompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall ConvertFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall VerifyFileW(const str_utf16 * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag, BOOL bQuickVerifyIfPossible = FALSE); + + // helper functions + DLLEXPORT int __stdcall FillWaveFormatEx(WAVEFORMATEX * pWaveFormatEx, int nSampleRate = 44100, int nBitsPerSample = 16, int nChannels = 2); + DLLEXPORT int __stdcall FillWaveHeader(WAVE_HEADER * pWAVHeader, int nAudioBytes, WAVEFORMATEX * pWaveFormatEx, int nTerminatingBytes = 0); +} + +#endif // #ifndef APE_MACLIB_H diff --git a/MAC_SDK/Shared/SmartPtr.h b/MAC_SDK/Shared/SmartPtr.h new file mode 100644 index 0000000..c9bb9be --- /dev/null +++ b/MAC_SDK/Shared/SmartPtr.h @@ -0,0 +1,89 @@ +#ifndef APE_SMARTPTR_H +#define APE_SMARTPTR_H + +// disable the operator -> on UDT warning +#ifdef _MSC_VER + #pragma warning(push) + #pragma warning(disable : 4284) +#endif + +/************************************************************************************************* +CSmartPtr - a simple smart pointer class that can automatically initialize and free memory + note: (doesn't do garbage collection / reference counting because of the many pitfalls) +*************************************************************************************************/ +template class CSmartPtr +{ +public: + TYPE * m_pObject; + BOOL m_bArray; + BOOL m_bDelete; + + CSmartPtr() + { + m_bDelete = TRUE; + m_pObject = NULL; + } + CSmartPtr(TYPE * a_pObject, BOOL a_bArray = FALSE, BOOL a_bDelete = TRUE) + { + m_bDelete = TRUE; + m_pObject = NULL; + Assign(a_pObject, a_bArray, a_bDelete); + } + + ~CSmartPtr() + { + Delete(); + } + + void Assign(TYPE * a_pObject, BOOL a_bArray = FALSE, BOOL a_bDelete = TRUE) + { + Delete(); + + m_bDelete = a_bDelete; + m_bArray = a_bArray; + m_pObject = a_pObject; + } + + void Delete() + { + if (m_bDelete && m_pObject) + { + if (m_bArray) + delete [] m_pObject; + else + delete m_pObject; + + m_pObject = NULL; + } + } + + void SetDelete(const BOOL a_bDelete) + { + m_bDelete = a_bDelete; + } + + __inline TYPE * GetPtr() const + { + return m_pObject; + } + + __inline operator TYPE * () const + { + return m_pObject; + } + + __inline TYPE * operator ->() const + { + return m_pObject; + } + + // declare assignment, but don't implement (compiler error if we try to use) + // that way we can't carelessly mix smart pointers and regular pointers + __inline void * operator =(void *) const; +}; + +#ifdef _MSC_VER + #pragma warning(pop) +#endif _MSC_VER + +#endif // #ifndef APE_SMARTPTR_H diff --git a/MAC_SDK/Source/Console/Console.cpp b/MAC_SDK/Source/Console/Console.cpp new file mode 100644 index 0000000..f08a790 --- /dev/null +++ b/MAC_SDK/Source/Console/Console.cpp @@ -0,0 +1,190 @@ +/*************************************************************************************** +MAC Console Frontend (MAC.exe) + +Pretty simple and straightforward console front end. If somebody ever wants to add +more functionality like tagging, auto-verify, etc., that'd be excellent. + +Copyrighted (c) 2000 - 2003 Matthew T. Ashland. All Rights Reserved. +***************************************************************************************/ +#include "All.h" +#include +#include "GlobalFunctions.h" +#include "MACLib.h" +#include "CharacterHelper.h" + +// defines +#define COMPRESS_MODE 0 +#define DECOMPRESS_MODE 1 +#define VERIFY_MODE 2 +#define CONVERT_MODE 3 +#define UNDEFINED_MODE -1 + +// global variables +TICK_COUNT_TYPE g_nInitialTickCount = 0; + +/*************************************************************************************** +Displays the proper usage for MAC.exe +***************************************************************************************/ +void DisplayProperUsage(FILE * pFile) +{ + fprintf(pFile, "Proper Usage: [EXE] [Input File] [Output File] [Mode]\n\n"); + + fprintf(pFile, "Modes: \n"); + fprintf(pFile, " Compress (fast): '-c1000'\n"); + fprintf(pFile, " Compress (normal): '-c2000'\n"); + fprintf(pFile, " Compress (high): '-c3000'\n"); + fprintf(pFile, " Compress (extra high): '-c4000'\n"); + fprintf(pFile, " Compress (insane): '-c5000'\n"); + fprintf(pFile, " Decompress: '-d'\n"); + fprintf(pFile, " Verify: '-v'\n"); + fprintf(pFile, " Convert: '-nXXXX'\n\n"); + + fprintf(pFile, "Examples:\n"); + fprintf(pFile, " Compress: mac.exe \"Metallica - One.wav\" \"Metallica - One.ape\" -c2000\n"); + fprintf(pFile, " Decompress: mac.exe \"Metallica - One.ape\" \"Metallica - One.wav\" -d\n"); + fprintf(pFile, " Verify: mac.exe \"Metallica - One.ape\" -v\n"); + fprintf(pFile, " (note: int filenames must be put inside of quotations)\n"); +} + +/*************************************************************************************** +Progress callback +***************************************************************************************/ +void CALLBACK ProgressCallback(int nPercentageDone) +{ + // get the current tick count + TICK_COUNT_TYPE nTickCount; + TICK_COUNT_READ(nTickCount); + + // calculate the progress + double dProgress = nPercentageDone / 1.e5; // [0...1] + double dElapsed = (double) (nTickCount - g_nInitialTickCount) / TICK_COUNT_FREQ; // seconds + double dRemaining = dElapsed * ((1.0 / dProgress) - 1.0); // seconds + + // output the progress + fprintf(stderr, "Progress: %.1f%% (%.1f seconds remaining, %.1f seconds total) \r", + dProgress * 100, dRemaining, dElapsed); +} + +/*************************************************************************************** +Main (the main function) +***************************************************************************************/ +int main(int argc, char * argv[]) +{ + // variable declares + CSmartPtr spInputFilename; CSmartPtr spOutputFilename; + int nRetVal = ERROR_UNDEFINED; + int nMode = UNDEFINED_MODE; + int nCompressionLevel; + int nPercentageDone; + + // output the header + fprintf(stderr, CONSOLE_NAME); + + // make sure there are at least four arguments (could be more for EAC compatibility) + if (argc < 3) + { + DisplayProperUsage(stderr); + exit(-1); + } + + // store the input file + spInputFilename.Assign(GetUTF16FromANSI(argv[1]), TRUE); + + // store the output file + spOutputFilename.Assign(GetUTF16FromANSI(argv[2]), TRUE); + + // verify that the input file exists + if (!FileExists(spInputFilename)) + { + fprintf(stderr, "Input File Not Found...\n\n"); + exit(-1); + } + + // if the output file equals '-v', then use this as the next argument + char cMode[256]; + strcpy(cMode, argv[2]); + + if (_strnicmp(cMode, "-v", 2) != 0) + { + // verify is the only mode that doesn't use at least the third argument + if (argc < 4) + { + DisplayProperUsage(stderr); + exit(-1); + } + + // check for and skip if necessary the -b XXXXXX arguments (3,4) + strcpy(cMode, argv[3]); + } + + // get the mode + nMode = UNDEFINED_MODE; + if (_strnicmp(cMode, "-c", 2) == 0) + nMode = COMPRESS_MODE; + else if (_strnicmp(cMode, "-d", 2) == 0) + nMode = DECOMPRESS_MODE; + else if (_strnicmp(cMode, "-v", 2) == 0) + nMode = VERIFY_MODE; + else if (_strnicmp(cMode, "-n", 2) == 0) + nMode = CONVERT_MODE; + + // error check the mode + if (nMode == UNDEFINED_MODE) + { + DisplayProperUsage(stderr); + exit(-1); + } + + // get and error check the compression level + if (nMode == COMPRESS_MODE || nMode == CONVERT_MODE) + { + nCompressionLevel = atoi(&cMode[2]); + if (nCompressionLevel != 1000 && nCompressionLevel != 2000 && + nCompressionLevel != 3000 && nCompressionLevel != 4000 && + nCompressionLevel != 5000) + { + DisplayProperUsage(stderr); + return -1; + } + } + + // set the initial tick count + TICK_COUNT_READ(g_nInitialTickCount); + + // process + int nKillFlag = 0; + if (nMode == COMPRESS_MODE) + { + char cCompressionLevel[16]; + if (nCompressionLevel == 1000) { strcpy(cCompressionLevel, "fast"); } + if (nCompressionLevel == 2000) { strcpy(cCompressionLevel, "normal"); } + if (nCompressionLevel == 3000) { strcpy(cCompressionLevel, "high"); } + if (nCompressionLevel == 4000) { strcpy(cCompressionLevel, "extra high"); } + if (nCompressionLevel == 5000) { strcpy(cCompressionLevel, "insane"); } + + fprintf(stderr, "Compressing (%s)...\n", cCompressionLevel); + nRetVal = CompressFileW(spInputFilename, spOutputFilename, nCompressionLevel, &nPercentageDone, ProgressCallback, &nKillFlag); + } + else if (nMode == DECOMPRESS_MODE) + { + fprintf(stderr, "Decompressing...\n"); + nRetVal = DecompressFileW(spInputFilename, spOutputFilename, &nPercentageDone, ProgressCallback, &nKillFlag); + } + else if (nMode == VERIFY_MODE) + { + fprintf(stderr, "Verifying...\n"); + nRetVal = VerifyFileW(spInputFilename, &nPercentageDone, ProgressCallback, &nKillFlag); + } + else if (nMode == CONVERT_MODE) + { + fprintf(stderr, "Converting...\n"); + nRetVal = ConvertFileW(spInputFilename, spOutputFilename, nCompressionLevel, &nPercentageDone, ProgressCallback, &nKillFlag); + } + + if (nRetVal == ERROR_SUCCESS) + fprintf(stderr, "\nSuccess...\n"); + else + fprintf(stderr, "\nError: %i\n", nRetVal); + + return nRetVal; +} diff --git a/MAC_SDK/Source/Console/Console.dsp b/MAC_SDK/Source/Console/Console.dsp new file mode 100644 index 0000000..34d47d1 --- /dev/null +++ b/MAC_SDK/Source/Console/Console.dsp @@ -0,0 +1,114 @@ +# Microsoft Developer Studio Project File - Name="Console" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Console - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Console.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Console.mak" CFG="Console - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Console - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Console - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName ""$/Monkey's Audio/Console", GKAAAAAA" +# PROP Scc_LocalPath "." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Console - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\MACLib\\" /I "..\Shared\\" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 maclib.lib kernel32.lib user32.lib gdi32.lib /nologo /subsystem:console /profile /machine:I386 /out:"Release/MAC.exe" /libpath:"..\MACLib\Release" +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Cmds=copy Release\MAC.exe C:\MAC\Application\MAC.exe +# End Special Build Tool + +!ELSEIF "$(CFG)" == "Console - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\MACLib\\" /I "..\Shared\\" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 maclib.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /out:"Debug/MAC.exe" /pdbtype:sept /libpath:"..\MACLib\Debug" +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Cmds=copy Debug\MAC.exe C:\MAC\Application\MAC.exe +# End Special Build Tool + +!ENDIF + +# Begin Target + +# Name "Console - Win32 Release" +# Name "Console - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\Console.cpp +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=".\Resource Script.rc" +# End Source File +# Begin Source File + +SOURCE=.\resource.h +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Source/Console/Console.vcproj b/MAC_SDK/Source/Console/Console.vcproj new file mode 100644 index 0000000..a805d0f --- /dev/null +++ b/MAC_SDK/Source/Console/Console.vcproj @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Source/Console/Resource Script.rc b/MAC_SDK/Source/Console/Resource Script.rc new file mode 100644 index 0000000..0dde37d --- /dev/null +++ b/MAC_SDK/Source/Console/Resource Script.rc @@ -0,0 +1,103 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 3,9,9,0 + PRODUCTVERSION 3,9,9,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Console front-end for Monkey's Audio" + VALUE "CompanyName", "Matthew T. Ashland" + VALUE "FileDescription", "Monkey's Audio Console Front-End" + VALUE "FileVersion", "3.99" + VALUE "InternalName", "MAC" + VALUE "LegalCopyright", "Copyright 2000-2004" + VALUE "OriginalFilename", "MAC.exe" + VALUE "ProductName", "Monkey's Audio" + VALUE "ProductVersion", "3.99" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/MAC_SDK/Source/Console/resource.h b/MAC_SDK/Source/Console/resource.h new file mode 100644 index 0000000..4876854 --- /dev/null +++ b/MAC_SDK/Source/Console/resource.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by Resource Script.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/MAC_SDK/Source/Credits.txt b/MAC_SDK/Source/Credits.txt new file mode 100644 index 0000000..1e09508 --- /dev/null +++ b/MAC_SDK/Source/Credits.txt @@ -0,0 +1,25 @@ +Source Code Credits: (listed in alphabetical order by first name) + +Chun-Yu Shei: +- cool suggestion for a slightly more optimized GetSaturatedShortFromInt(...) routine + +David Bryant: +- lots of ideas and support from continued discussions + +Florin Ghido: +- planted the seed for a more efficient stereo decorrelator + +Frank Klemm: +- helped with several Linux building issues, APEv2 tags, and MD5 checksums + +Janne Hyvrinen: (case@mobiili.net) +- donated some nice UTF / ANSI conversion code for APE version 2 tagging + +Torgeir Strand Henriksen: (torgshen@stud.iet.hist.no) +- did all the footwork to enable BACKWARDS_COMPATIBILITY without requiring assembly + +Michael Bevin: (support@lossless-audio.com) +- had a good entropy idea for improving entropy coding ( http://www.lossless-audio.com/theory.htm ) + +Igor Janos: (radscorpion@radlight.com) +- wrote the APE DirectShow filter \ No newline at end of file diff --git a/MAC_SDK/Source/History.txt b/MAC_SDK/Source/History.txt new file mode 100644 index 0000000..b8134a0 --- /dev/null +++ b/MAC_SDK/Source/History.txt @@ -0,0 +1,79 @@ +History: + +Monkey's Audio 3.99 Update 4 + +1. Fixed: Decoder could erroneously report a CRC error on the last frame of some files. + +Monkey's Audio 3.99 Update 3 + +1. Changed: Worked on making data types more standard / cross-platform friendly. +2. Changed: Switched code from tab-based to space based. (may still be some out-of-whack formatting) +3. Fixed: Building ID3 tags could cause a crash. +4. Fixed: APL builder treated the last part of a CUE time as a hundreth of a second instead of as a frame. (1 / 75 of a second) +5. Fixed: File Info dialog used by Winamp plugin wouldn't accept / save Unicode tag values properly. +6. Fixed: APL files could output noise or silence at the end of the file in some cases. + +Monkey's Audio 3.99 Update 2 + +1. Fixed: Possible buffer overflow attack weakness in APE tagging code. +2. Fixed: MACDll.dll was not doing ANSI to Unicode conversions properly. +3. Changed: Added Unicode versions of interface wrappers to MACDll.dll. +4. Changed: Updated Winamp plugin to better handle Unicode. +5. Changed: Removed peak-level normalize from file and Winamp plugin. (newer players can do normalize / replay gain during playback) +6. Changed: Updated Cool Edit filter to 3.99. + +Monkey's Audio 3.99 Update 1 + +1. Fixed: MACDll.dll wasn't working on Win9x / ME systems. +2. Changed: MAC.exe updated to 3.99. + +Monkey's Audio 3.99 + +1. Changed: Decoding engine better at handling corrupt streams / loss of internet connection while playing. +2. Changed: Simplified assembly code building for 3rd party developers. +3. NEW: Improved entropy coder for increased compression. +4. Changed: Removed RKAU support. (since it is no longer commonly used) + +Monkey's Audio 3.98a1 + +1. Changed: Now natively using APE tag version 2 tagging. (updated spec for better streaming and international support) +2. Changed: Using smaller frame sizes with Fast, Normal, and High for faster, smoother seeking. +3. NEW: Added built-in MD5 checking, for super secure, super fast file verification. +4. Changed: Using a new and improved file header format. +5. NEW: Added "Insane" mode for when compression is all that matters. +6. NEW: Introduced new GUI. + - full Unicode support + - few or no dependencies + - multi-thread friendly -- can process multiple files at once + - XML based external plugin architecture + +Monkey's Audio 3.97 (July 7, 2002) + +1. Changed: "Save File List Between Sessions" now on by default in front end. +2. Changed: Replaced usage of "#pragma once" with more non-MS compiler friendly alterternative. +3. NEW: MakeAPL now supports command line APL generation. (pass a .CUE file (no wildcards yet) -- operates in silent mode using existing settings) +4. Changed: Assembly support no longer required for backwards compatibility. (thanks Torgeir Strand Henriksen) +5. Changed: Several non-Windows buildability issues. +6. Changed: Using NASM to compile all assembly code. (aids cross-platform buildability) +7. Changed: Encapsulated the APELink code. +8. Changed: Tags aren't analyzed immediately when opening an http:// or m01p:// stream. +9. Changed: Added more functionality to the APL parser. +10. Changed: Added CreateIAPEDecompressEx2(...) to allow the creation of a ranged decoder. + +Monkey's Audio 3.96 (April 7, 2002) + +1. Fixed: WAV analysis could hang on invalid wav files. +2. Changed: Monkey's Audio would try to analyze files with file extensions not related to Monkey's Audio. +3. NEW: Added APE_DECOMPRESS_AVERAGE_BITRATE field so APL's can report the bitrate for the region they represent. +4. Changed: Improved overall non-Windows build-ability. (MACLib.lib doesn't require to build) +5. Changed: APL parser no longer requires Windows. +6. Fixed: APE tagging code would fail to save tags for files with existing ID3v1 tags. +7. Fixed: MakeAPL would not run on Win95 / 98. +8. Changed: More non-Windows build-ability issues. +9. Changed: Minor assembly optimizations. (like a 2% performance improvement) +10. Changed: MACLib now builds with gcc under Linux. (no backwards compatibility or assembly support yet) +11. Fixed: Bitstream fix / change that may have accounted for decompression failures in extremely rare cases. +12. Changed: Slight NNFilter optimization. (thanks to Chun-Yu Shei) +13. Changed: Turned off "Explorer" by default for the Monkey's Audio GUI. (doesn't work well under XP... will still leave it in for a while) +14. Changed: Included the WavPack 3.93. +15. Changed: Changed the history reporting method. \ No newline at end of file diff --git a/MAC_SDK/Source/License.htm b/MAC_SDK/Source/License.htm new file mode 100644 index 0000000..fe22ad4 --- /dev/null +++ b/MAC_SDK/Source/License.htm @@ -0,0 +1,48 @@ + + + + + + +Well + + + + +

Monkey's Audio Source Code +License Agreement

+

License Agreement

+

1. The use of any of the Monkeys Audio source code or any component thereof from another program requires +express written permission from the author of Monkeys Audio.

+

2. The use of Monkey's Audio or the Monkey's Audio source code for any commercial purposes including, but not +limited to, implementation in shareware packages is strictly prohibited without first obtaining written +permission from the author.

+

3. All code changes and improvements must be +contributed back to the Monkey's Audio project free from restrictions or +royalties for the sake of the common good.

+

4. Although the software has been tested thoroughly, the author is in no way responsible for damages due to +bugs or misuse. 

+

5. If you do not completely agree with all of +the previous stipulations, you must cease using this source code and remove it +from your storage device.

+

 

+

Non-legally Binding License Description

+

The above license is designed to protect both +me, and the Monkey's Audio project.  However, anyone who has ever been kind +enough to request permission to use Monkey's Audio has been granted the right to +do as they please, completely free of charge or royalty.  So, the license +exists not to hinder what considerate people can do with Monkey's Audio, but +instead to protect against the (hopefully few) inconsiderate people.

+

 

+

 

+

All +rights not expressly granted here are reserved by Matthew T. Ashland.

+

 

+

- +All materials and programs copyrighted 2000-2002 by Matthew T. Ashland -

+

- +All rights reserved. -

+ + + + diff --git a/MAC_SDK/Source/MACDll/MACDll.cpp b/MAC_SDK/Source/MACDll/MACDll.cpp new file mode 100644 index 0000000..80aaef8 --- /dev/null +++ b/MAC_SDK/Source/MACDll/MACDll.cpp @@ -0,0 +1,233 @@ +#include "MACDll.h" +#include "resource.h" +#include "WinFileIO.h" +#include "APEInfoDialog.h" +#include "WAVInfoDialog.h" +#include "APEDecompress.h" +#include "APECompressCreate.h" +#include "APECompressCore.h" +#include "APECompress.h" +#include "APEInfo.h" +#include "APETag.h" +#include "CharacterHelper.h" + +int __stdcall GetVersionNumber() +{ + return MAC_VERSION_NUMBER; +} + +int __stdcall GetInterfaceCompatibility(int nVersion, BOOL bDisplayWarningsOnFailure, HWND hwndParent) +{ + int nRetVal = 0; + if (nVersion > MAC_VERSION_NUMBER) + { + nRetVal = -1; + if (bDisplayWarningsOnFailure) + { + TCHAR cMessage[1024]; + _stprintf(cMessage, _T("You system does not have a new enough version of Monkey's Audio installed.\n") + _T("Please visit www.monkeysaudio.com for the latest version.\n\n(version %.2f or later required)"), + float(nVersion) / float(1000)); + MessageBox(hwndParent, cMessage, _T("Please Update Monkey's Audio"), MB_OK | MB_ICONINFORMATION); + } + } + else if (nVersion < 3940) + { + nRetVal = -1; + if (bDisplayWarningsOnFailure) + { + TCHAR cMessage[1024]; + _stprintf(cMessage, _T("This program is trying to use an old version of Monkey's Audio.\n") + _T("Please contact the author about updating their support for Monkey's Audio.\n\n") + _T("Monkey's Audio currently installed: %.2f\nProgram is searching for: %.2f"), + float(MAC_VERSION_NUMBER) / float(1000), float(nVersion) / float(1000)); + MessageBox(hwndParent, cMessage, _T("Program Requires Updating"), MB_OK | MB_ICONINFORMATION); + } + } + + return nRetVal; +} + +int __stdcall ShowFileInfoDialog(const str_ansi * pFilename, HWND hwndWindow) +{ + // convert the filename + CSmartPtr spFilename(GetUTF16FromANSI(pFilename), TRUE); + + // make sure the file exists + WIN32_FIND_DATA FindData = { 0 }; + HANDLE hFind = FindFirstFile(spFilename, &FindData); + if (hFind == INVALID_HANDLE_VALUE) + { + MessageBox(hwndWindow, _T("File not found."), _T("File Info"), MB_OK); + return 0; + } + else + { + FindClose(hFind); + } + + // see what type the file is + if ((_tcsicmp(&spFilename[_tcslen(spFilename) - 4], _T(".ape")) == 0) || + (_tcsicmp(&spFilename[_tcslen(spFilename) - 4], _T(".apl")) == 0)) + { + CAPEInfoDialog APEInfoDialog; + APEInfoDialog.ShowAPEInfoDialog(spFilename, GetModuleHandle(_T("MACDll.dll")), (LPCTSTR) IDD_APE_INFO, hwndWindow); + return 0; + } + else if (_tcsicmp(&spFilename[_tcslen(spFilename) - 4], _T(".wav")) == 0) + { + CWAVInfoDialog WAVInfoDialog; + WAVInfoDialog.ShowWAVInfoDialog(spFilename, GetModuleHandle(_T("MACDll.dll")), (LPCTSTR) IDD_WAV_INFO, hwndWindow); + return 0; + } + else + { + MessageBox(hwndWindow, _T("File type not supported. (only .ape, .apl, and .wav files currently supported)"), _T("File Info: Unsupported File Type"), MB_OK); + return 0; + }; +} + +int __stdcall TagFileSimple(const str_ansi * pFilename, const char * pArtist, const char * pAlbum, const char * pTitle, const char * pComment, const char * pGenre, const char * pYear, const char * pTrack, BOOL bClearFirst, BOOL bUseOldID3) +{ + CSmartPtr spFilename(GetUTF16FromANSI(pFilename), TRUE); + + IO_CLASS_NAME FileIO; + if (FileIO.Open(spFilename) != 0) + return -1; + + CAPETag APETag(&FileIO, TRUE); + + if (bClearFirst) + APETag.ClearFields(); + + APETag.SetFieldString(APE_TAG_FIELD_ARTIST, pArtist, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_ALBUM, pAlbum, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_TITLE, pTitle, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_GENRE, pGenre, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_YEAR, pYear, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_COMMENT, pComment, TRUE); + APETag.SetFieldString(APE_TAG_FIELD_TRACK, pTrack, TRUE); + + if (APETag.Save(bUseOldID3) != 0) + { + return -1; + } + + return 0; +} + +int __stdcall GetID3Tag(const str_ansi * pFilename, ID3_TAG * pID3Tag) +{ + CSmartPtr spFilename(GetUTF16FromANSI(pFilename), TRUE); + + IO_CLASS_NAME FileIO; + if (FileIO.Open(spFilename) != 0) + return -1; + + CAPETag APETag(&FileIO, TRUE); + + return APETag.CreateID3Tag(pID3Tag); +} + +int __stdcall RemoveTag(char * pFilename) +{ + CSmartPtr spFilename(GetUTF16FromANSI(pFilename), TRUE); + + int nErrorCode = ERROR_SUCCESS; + CSmartPtr spAPEDecompress(CreateIAPEDecompress(spFilename, &nErrorCode)); + if (spAPEDecompress == NULL) return -1; + GET_TAG(spAPEDecompress)->Remove(FALSE); + return 0; +} + +/***************************************************************************************** +CAPEDecompress wrapper(s) +*****************************************************************************************/ +APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_Create(const str_ansi * pFilename, int * pErrorCode) +{ + CSmartPtr spFilename(GetUTF16FromANSI(pFilename), TRUE); + return (APE_DECOMPRESS_HANDLE) CreateIAPEDecompress(spFilename, pErrorCode); +} + +APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_CreateW(const str_utf16 * pFilename, int * pErrorCode) +{ + return (APE_DECOMPRESS_HANDLE) CreateIAPEDecompress(pFilename, pErrorCode); +} + +void __stdcall c_APEDecompress_Destroy(APE_DECOMPRESS_HANDLE hAPEDecompress) +{ + IAPEDecompress * pAPEDecompress = (IAPEDecompress *) hAPEDecompress; + if (pAPEDecompress) + delete pAPEDecompress; +} + +int __stdcall c_APEDecompress_GetData(APE_DECOMPRESS_HANDLE hAPEDecompress, char * pBuffer, int nBlocks, int * pBlocksRetrieved) +{ + return ((IAPEDecompress *) hAPEDecompress)->GetData(pBuffer, nBlocks, pBlocksRetrieved); +} + +int __stdcall c_APEDecompress_Seek(APE_DECOMPRESS_HANDLE hAPEDecompress, int nBlockOffset) +{ + return ((IAPEDecompress *) hAPEDecompress)->Seek(nBlockOffset); +} + +int __stdcall c_APEDecompress_GetInfo(APE_DECOMPRESS_HANDLE hAPEDecompress, APE_DECOMPRESS_FIELDS Field, int nParam1, int nParam2) +{ + return ((IAPEDecompress *) hAPEDecompress)->GetInfo(Field, nParam1, nParam2); +} + +/***************************************************************************************** +CAPECompress wrapper(s) +*****************************************************************************************/ +APE_COMPRESS_HANDLE __stdcall c_APECompress_Create(int * pErrorCode) +{ + return (APE_COMPRESS_HANDLE) CreateIAPECompress(pErrorCode); +} + +void __stdcall c_APECompress_Destroy(APE_COMPRESS_HANDLE hAPECompress) +{ + IAPECompress * pAPECompress = (IAPECompress *) hAPECompress; + if (pAPECompress) + delete pAPECompress; +} + +int __stdcall c_APECompress_Start(APE_COMPRESS_HANDLE hAPECompress, const char * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + CSmartPtr spOutputFilename(GetUTF16FromANSI(pOutputFilename), TRUE); + return ((IAPECompress *) hAPECompress)->Start(spOutputFilename, pwfeInput, nMaxAudioBytes, nCompressionLevel, pHeaderData, nHeaderBytes); +} + +int __stdcall c_APECompress_StartW(APE_COMPRESS_HANDLE hAPECompress, const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + return ((IAPECompress *) hAPECompress)->Start(pOutputFilename, pwfeInput, nMaxAudioBytes, nCompressionLevel, pHeaderData, nHeaderBytes); +} + +int __stdcall c_APECompress_AddData(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pData, int nBytes) +{ + return ((IAPECompress *) hAPECompress)->AddData(pData, nBytes); +} + +int __stdcall c_APECompress_GetBufferBytesAvailable(APE_COMPRESS_HANDLE hAPECompress) +{ + return ((IAPECompress *) hAPECompress)->GetBufferBytesAvailable(); +} + +unsigned char * __stdcall c_APECompress_LockBuffer(APE_COMPRESS_HANDLE hAPECompress, int * pBytesAvailable) +{ + return ((IAPECompress *) hAPECompress)->LockBuffer(pBytesAvailable); +} + +int __stdcall c_APECompress_UnlockBuffer(APE_COMPRESS_HANDLE hAPECompress, int nBytesAdded, BOOL bProcess) +{ + return ((IAPECompress *) hAPECompress)->UnlockBuffer(nBytesAdded, bProcess); +} + +int __stdcall c_APECompress_Finish(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) +{ + return ((IAPECompress *) hAPECompress)->Finish(pTerminatingData, nTerminatingBytes, nWAVTerminatingBytes); +} + +int __stdcall c_APECompress_Kill(APE_COMPRESS_HANDLE hAPECompress) +{ + return ((IAPECompress *) hAPECompress)->Kill(); +} diff --git a/MAC_SDK/Source/MACDll/MACDll.def b/MAC_SDK/Source/MACDll/MACDll.def new file mode 100644 index 0000000..9bfc12d --- /dev/null +++ b/MAC_SDK/Source/MACDll/MACDll.def @@ -0,0 +1,38 @@ +LIBRARY MACDll + +EXPORTS + + ; basic functions + CompressFile + DecompressFile + ConvertFile + VerifyFile + + ; interface wrappers + c_APEDecompress_Create + c_APEDecompress_Destroy + c_APEDecompress_GetData + c_APEDecompress_Seek + c_APEDecompress_GetInfo + + c_APECompress_Create + c_APECompress_Destroy + c_APECompress_Start + c_APECompress_AddData + c_APECompress_GetBufferBytesAvailable + c_APECompress_LockBuffer + c_APECompress_UnlockBuffer + c_APECompress_Finish + c_APECompress_Kill + + ; helpers / miscellaneous + GetVersionNumber + GetInterfaceCompatibility + ShowFileInfoDialog + RemoveTag + TagFileSimple + GetID3Tag + FillWaveHeader + FillWaveFormatEx + + diff --git a/MAC_SDK/Source/MACDll/MACDll.dsp b/MAC_SDK/Source/MACDll/MACDll.dsp new file mode 100644 index 0000000..a16da73 --- /dev/null +++ b/MAC_SDK/Source/MACDll/MACDll.dsp @@ -0,0 +1,160 @@ +# Microsoft Developer Studio Project File - Name="MACDll" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=MACDll - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "MACDll.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "MACDll.mak" CFG="MACDll - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "MACDll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "MACDll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName ""$/Monkey's Audio/MACDll", KCAAAAAA" +# PROP Scc_LocalPath "." +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "MACDll - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MACDLL_EXPORTS" /YX /FD /c +# ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Ot /Og /Oi /Ob2 /I "..\MACLib\\" /I "..\Shared\\" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MACDLL_EXPORTS" /FR /YX /FD /c +# SUBTRACT CPP /Oa +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib maclib.lib /nologo /dll /machine:I386 /libpath:"..\MACLib\Release" +# SUBTRACT LINK32 /profile +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Performing post build step... +PostBuild_Cmds=copy Release\MACDll.dll c:\Windows\System32\MACDll.dll +# End Special Build Tool + +!ELSEIF "$(CFG)" == "MACDll - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MACDLL_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\MACLib\\" /I "..\Shared\\" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MACDLL_EXPORTS" /FD /GZ /c +# SUBTRACT CPP /YX +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 maclib.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\MACLib\Debug" +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Performing post build step... +PostBuild_Cmds=copy Debug\MACDll.dll c:\Windows\System32\MACDll.dll +# End Special Build Tool + +!ENDIF + +# Begin Target + +# Name "MACDll - Win32 Release" +# Name "MACDll - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\Shared\APEInfoDialog.cpp +# End Source File +# Begin Source File + +SOURCE=.\MACDll.cpp +# End Source File +# Begin Source File + +SOURCE=.\MACDll.def +# End Source File +# Begin Source File + +SOURCE=".\Resource Script.rc" +# End Source File +# Begin Source File + +SOURCE=..\Shared\WAVInfoDialog.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\Shared\APEInfoDialog.h +# End Source File +# Begin Source File + +SOURCE=.\MACDll.h +# End Source File +# Begin Source File + +SOURCE=.\resource.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\WAVInfoDialog.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=".\Monkey Head (1).ico" +# End Source File +# Begin Source File + +SOURCE=".\Monkey Head.ico" +# End Source File +# End Group +# End Target +# End Project diff --git a/MAC_SDK/Source/MACDll/MACDll.h b/MAC_SDK/Source/MACDll/MACDll.h new file mode 100644 index 0000000..7940017 --- /dev/null +++ b/MAC_SDK/Source/MACDll/MACDll.h @@ -0,0 +1,99 @@ +/***************************************************************************************** +Monkey's Audio MACDll.h (include for using MACDll.dll in your projects) +Copyright (C) 2000-2004 by Matthew T. Ashland All Rights Reserved. + +Overview: + +Basically all this dll does is wrap MACLib.lib, so browse through MACLib.h for documentation +on how to use the interfaces. + +Questions / Suggestions: + +Please direct questions or comments to the Monkey's Audio developers board: + http://www.monkeysaudio.com/cgi-bin/YaBB/YaBB.cgi -> Developers +or, if necessary, matt @ monkeysaudio.com +*****************************************************************************************/ + +#ifndef APE_MACDLL_H +#define APE_MACDLL_H + +/***************************************************************************************** +Includes +*****************************************************************************************/ +#include "All.h" +#include "MACLib.h" + +/***************************************************************************************** +Defines (implemented elsewhere) +*****************************************************************************************/ +struct ID3_TAG; + +/***************************************************************************************** +Helper functions +*****************************************************************************************/ +extern "C" +{ + __declspec( dllexport ) int __stdcall GetVersionNumber(); + __declspec( dllexport ) int __stdcall GetInterfaceCompatibility(int nVersion, BOOL bDisplayWarningsOnFailure = TRUE, HWND hwndParent = NULL); + __declspec( dllexport ) int __stdcall ShowFileInfoDialog(const str_ansi * pFilename, HWND hwndWindow); + __declspec( dllexport ) int __stdcall TagFileSimple(const str_ansi * pFilename, const char * pArtist, const char * pAlbum, const char * pTitle, const char * pComment, const char * pGenre, const char * pYear, const char * pTrack, BOOL bClearFirst, BOOL bUseOldID3); + __declspec( dllexport ) int __stdcall GetID3Tag(const str_ansi * pFilename, ID3_TAG * pID3Tag); + __declspec( dllexport ) int __stdcall RemoveTag(const str_ansi * pFilename); +} + +typedef int (__stdcall * proc_GetVersionNumber)(); +typedef int (__stdcall * proc_GetInterfaceCompatibility)(int, BOOL, HWND); + +/***************************************************************************************** +IAPECompress wrapper(s) +*****************************************************************************************/ +typedef void * APE_COMPRESS_HANDLE; + +typedef APE_COMPRESS_HANDLE (__stdcall * proc_APECompress_Create)(int *); +typedef void (__stdcall * proc_APECompress_Destroy)(APE_COMPRESS_HANDLE); +typedef int (__stdcall * proc_APECompress_Start)(APE_COMPRESS_HANDLE, const char *, const WAVEFORMATEX *, int, int, const void *, int); +typedef int (__stdcall * proc_APECompress_StartW)(APE_COMPRESS_HANDLE, const char *, const WAVEFORMATEX *, int, int, const void *, int); +typedef int (__stdcall * proc_APECompress_AddData)(APE_COMPRESS_HANDLE, unsigned char *, int); +typedef int (__stdcall * proc_APECompress_GetBufferBytesAvailable)(APE_COMPRESS_HANDLE); +typedef unsigned char * (__stdcall * proc_APECompress_LockBuffer)(APE_COMPRESS_HANDLE, int *); +typedef int (__stdcall * proc_APECompress_UnlockBuffer)(APE_COMPRESS_HANDLE, int, BOOL); +typedef int (__stdcall * proc_APECompress_Finish)(APE_COMPRESS_HANDLE, unsigned char *, int, int); +typedef int (__stdcall * proc_APECompress_Kill)(APE_COMPRESS_HANDLE); + +extern "C" +{ + __declspec( dllexport ) APE_COMPRESS_HANDLE __stdcall c_APECompress_Create(int * pErrorCode = NULL); + __declspec( dllexport ) void __stdcall c_APECompress_Destroy(APE_COMPRESS_HANDLE hAPECompress); + __declspec( dllexport ) int __stdcall c_APECompress_Start(APE_COMPRESS_HANDLE hAPECompress, const char * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const unsigned char * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + __declspec( dllexport ) int __stdcall c_APECompress_StartW(APE_COMPRESS_HANDLE hAPECompress, const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const unsigned char * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + __declspec( dllexport ) int __stdcall c_APECompress_AddData(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pData, int nBytes); + __declspec( dllexport ) int __stdcall c_APECompress_GetBufferBytesAvailable(APE_COMPRESS_HANDLE hAPECompress); + __declspec( dllexport ) unsigned char * __stdcall c_APECompress_LockBuffer(APE_COMPRESS_HANDLE hAPECompress, int * pBytesAvailable); + __declspec( dllexport ) int __stdcall c_APECompress_UnlockBuffer(APE_COMPRESS_HANDLE hAPECompress, int nBytesAdded, BOOL bProcess = TRUE); + __declspec( dllexport ) int __stdcall c_APECompress_Finish(APE_COMPRESS_HANDLE hAPECompress, unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes); + __declspec( dllexport ) int __stdcall c_APECompress_Kill(APE_COMPRESS_HANDLE hAPECompress); +} + +/***************************************************************************************** +IAPEDecompress wrapper(s) +*****************************************************************************************/ +typedef void * APE_DECOMPRESS_HANDLE; + +typedef APE_DECOMPRESS_HANDLE (__stdcall * proc_APEDecompress_Create)(const char *, int *); +typedef APE_DECOMPRESS_HANDLE (__stdcall * proc_APEDecompress_CreateW)(const char *, int *); +typedef void (__stdcall * proc_APEDecompress_Destroy)(APE_DECOMPRESS_HANDLE); +typedef int (__stdcall * proc_APEDecompress_GetData)(APE_DECOMPRESS_HANDLE, char *, int, int *); +typedef int (__stdcall * proc_APEDecompress_Seek)(APE_DECOMPRESS_HANDLE, int); +typedef int (__stdcall * proc_APEDecompress_GetInfo)(APE_DECOMPRESS_HANDLE, APE_DECOMPRESS_FIELDS, int, int); + +extern "C" +{ + __declspec( dllexport ) APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_Create(const str_ansi * pFilename, int * pErrorCode = NULL); + __declspec( dllexport ) APE_DECOMPRESS_HANDLE __stdcall c_APEDecompress_CreateW(const str_utf16 * pFilename, int * pErrorCode = NULL); + __declspec( dllexport ) void __stdcall c_APEDecompress_Destroy(APE_DECOMPRESS_HANDLE hAPEDecompress); + __declspec( dllexport ) int __stdcall c_APEDecompress_GetData(APE_DECOMPRESS_HANDLE hAPEDecompress, char * pBuffer, int nBlocks, int * pBlocksRetrieved); + __declspec( dllexport ) int __stdcall c_APEDecompress_Seek(APE_DECOMPRESS_HANDLE hAPEDecompress, int nBlockOffset); + __declspec( dllexport ) int __stdcall c_APEDecompress_GetInfo(APE_DECOMPRESS_HANDLE hAPEDecompress, APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0); +} + +#endif // #ifndef APE_MACDLL_H diff --git a/MAC_SDK/Source/MACDll/MACDll.vcproj b/MAC_SDK/Source/MACDll/MACDll.vcproj new file mode 100644 index 0000000..d6cccc4 --- /dev/null +++ b/MAC_SDK/Source/MACDll/MACDll.vcproj @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Source/MACDll/Monkey Head (1).ico b/MAC_SDK/Source/MACDll/Monkey Head (1).ico new file mode 100644 index 0000000..c04520b Binary files /dev/null and b/MAC_SDK/Source/MACDll/Monkey Head (1).ico differ diff --git a/MAC_SDK/Source/MACDll/Monkey Head.ico b/MAC_SDK/Source/MACDll/Monkey Head.ico new file mode 100644 index 0000000..ad58c34 Binary files /dev/null and b/MAC_SDK/Source/MACDll/Monkey Head.ico differ diff --git a/MAC_SDK/Source/MACDll/Resource Script.rc b/MAC_SDK/Source/MACDll/Resource Script.rc new file mode 100644 index 0000000..09179f7 --- /dev/null +++ b/MAC_SDK/Source/MACDll/Resource Script.rc @@ -0,0 +1,226 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_WAV_INFO, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 195 + TOPMARGIN, 7 + BOTTOMMARGIN, 95 + END + + IDD_APE_INFO, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 242 + TOPMARGIN, 7 + BOTTOMMARGIN, 211 + END +END +#endif // APSTUDIO_INVOKED + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_MONKEY_LEFT ICON "Monkey Head.ico" +IDI_MONKEY_RIGHT ICON "Monkey Head (1).ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_WAV_INFO DIALOG 0, 0, 202, 102 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "WAV File Info" +FONT 8, "MS Sans Serif" +BEGIN + ICON IDI_MONKEY_LEFT,IDC_STATIC,2,2,20,20 + ICON IDI_MONKEY_RIGHT,IDC_STATIC,180,0,20,20 + GROUPBOX "Size Info",IDC_STATIC,5,28,93,68 + GROUPBOX "Audio Info",IDC_STATIC,105,28,92,47 + LTEXT "Bits Per Sample:",3002,115,60,78,8,SS_NOPREFIX + LTEXT "Channels:",3001,115,50,78,8,SS_NOPREFIX + LTEXT "Sample Rate:",3000,115,39,78,8,SS_NOPREFIX + LTEXT "Track Length:",2001,15,50,78,8,SS_NOPREFIX + LTEXT "File Size:",2000,15,39,78,8,SS_NOPREFIX + LTEXT "Terminating Bytes:",2004,15,82,78,8,SS_NOPREFIX + LTEXT "Header Bytes:",2003,15,71,78,8,SS_NOPREFIX + LTEXT "Audio Bytes:",2002,15,60,78,8,SS_NOPREFIX + PUSHBUTTON "OK",4000,105,81,92,15 + CTEXT "File Name...",1000,26,2,152,18 +END + +IDD_APE_INFO DIALOG 0, 0, 249, 218 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "APE File Info" +FONT 8, "MS Sans Serif" +BEGIN + EDITTEXT 5000,49,99,189,12,ES_AUTOHSCROLL + EDITTEXT 5001,49,115,189,12,ES_AUTOHSCROLL + EDITTEXT 5002,49,131,189,12,ES_AUTOHSCROLL + EDITTEXT 5003,49,147,189,12,ES_AUTOHSCROLL + EDITTEXT 5004,49,163,24,12,ES_AUTOHSCROLL + COMBOBOX 5005,109,163,77,85,CBS_DROPDOWN | CBS_OEMCONVERT | + CBS_SORT | WS_VSCROLL | WS_TABSTOP + EDITTEXT 5006,220,163,18,12,ES_AUTOHSCROLL + PUSHBUTTON "Save Tag",6000,11,195,69,12 + PUSHBUTTON "Remove Tag",6001,90,195,69,12 + PUSHBUTTON "Cancel",6002,169,195,69,12 + ICON IDI_MONKEY_LEFT,IDC_STATIC,3,3,20,20 + ICON IDI_MONKEY_RIGHT,IDC_STATIC,225,3,20,20 + CONTROL "Format Flags:",2002,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,11,61,59,8 + CONTROL "Mode:",2001,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,11,50,59,8 + CONTROL "Version:",2000,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,11,39,59,8 + GROUPBOX "Format Info",IDC_STATIC,5,29,70,56 + GROUPBOX "Audio Info",IDC_STATIC,79,29,78,56 + CONTROL "Bits Per Sample:",3002,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,86,61,66,8 + CONTROL "Channels:",3001,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,86,50,66,8 + CONTROL "Sample Rate:",3000,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,86,39,66,8 + GROUPBOX "Tag Info",IDC_STATIC,5,88,240,94 + LTEXT "Album:",IDC_STATIC,11,134,23,8,SS_NOPREFIX + LTEXT "Artist:",IDC_STATIC,11,118,23,8,SS_NOPREFIX + LTEXT "Title:",IDC_STATIC,11,102,18,8,SS_NOPREFIX + LTEXT "Comment:",IDC_STATIC,11,150,33,8,SS_NOPREFIX + LTEXT "Year:",IDC_STATIC,11,166,18,8,SS_NOPREFIX + LTEXT "Genre: ",IDC_STATIC,82,166,24,8,SS_NOPREFIX + CONTROL "Length:",4000,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,167,39,71,8 + CONTROL "Compression:",4003,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,167,72,71,8 + LTEXT "Track:",IDC_STATIC,195,166,22,8,SS_NOPREFIX + GROUPBOX "Exit",IDC_STATIC,5,185,240,29 + CONTROL "Peak Level:",3003,"Static",SS_LEFTNOWORDWRAP | + SS_NOPREFIX | WS_GROUP,86,72,66,8 + EDITTEXT 1000,28,4,193,18,ES_CENTER | ES_MULTILINE | + ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER + CONTROL "APE:",4002,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,167,61,71,8 + CONTROL "Tagged:",2003,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,11,71,59,9 + GROUPBOX "Length / Size Info",IDC_STATIC,161,29,83,56 + CONTROL "WAV:",4001,"Static",SS_LEFTNOWORDWRAP | SS_NOPREFIX | + WS_GROUP,167,50,71,8 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 3,9,9,0 + PRODUCTVERSION 3,9,9,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Compression and decompression library for Monkey's Audio" + VALUE "CompanyName", "Matthew T. Ashland" + VALUE "FileDescription", "Monkey's Audio DLL Library" + VALUE "FileVersion", "3.99" + VALUE "LegalCopyright", "Copyright 2000-2004" + VALUE "OriginalFilename", "MACDll.dll" + VALUE "ProductName", "Monkey's Audio" + VALUE "ProductVersion", "3.99" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/MAC_SDK/Source/MACDll/resource.h b/MAC_SDK/Source/MACDll/resource.h new file mode 100644 index 0000000..6e97749 --- /dev/null +++ b/MAC_SDK/Source/MACDll/resource.h @@ -0,0 +1,20 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by Resource Script.rc +// +#define IDD_DIALOG1 101 +#define IDD_WAV_INFO 101 +#define IDD_APE_INFO 103 +#define IDI_MONKEY_LEFT 105 +#define IDI_MONKEY_RIGHT 106 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 149 +#define _APS_NEXT_COMMAND_VALUE 40002 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/MAC_SDK/Source/MACLib/APECompress.cpp b/MAC_SDK/Source/MACLib/APECompress.cpp new file mode 100644 index 0000000..a040140 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompress.cpp @@ -0,0 +1,246 @@ +#include "All.h" +#include "APECompress.h" +#include IO_HEADER_FILE +#include "APECompressCreate.h" +#include "WAVInputSource.h" + +CAPECompress::CAPECompress() +{ + m_nBufferHead = 0; + m_nBufferTail = 0; + m_nBufferSize = 0; + m_bBufferLocked = FALSE; + m_bOwnsOutputIO = FALSE; + m_pioOutput = NULL; + + m_spAPECompressCreate.Assign(new CAPECompressCreate()); + + m_pBuffer = NULL; +} + +CAPECompress::~CAPECompress() +{ + SAFE_ARRAY_DELETE(m_pBuffer) + + if (m_bOwnsOutputIO) + { + SAFE_DELETE(m_pioOutput) + } +} + +int CAPECompress::Start(const wchar_t * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + m_pioOutput = new IO_CLASS_NAME; + m_bOwnsOutputIO = TRUE; + + if (m_pioOutput->Create(pOutputFilename) != 0) + { + return ERROR_INVALID_OUTPUT_FILE; + } + + m_spAPECompressCreate->Start(m_pioOutput, pwfeInput, nMaxAudioBytes, nCompressionLevel, + pHeaderData, nHeaderBytes); + + SAFE_ARRAY_DELETE(m_pBuffer) + m_nBufferSize = m_spAPECompressCreate->GetFullFrameBytes(); + m_pBuffer = new unsigned char [m_nBufferSize]; + memcpy(&m_wfeInput, pwfeInput, sizeof(WAVEFORMATEX)); + + return ERROR_SUCCESS; +} + +int CAPECompress::StartEx(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + m_pioOutput = pioOutput; + m_bOwnsOutputIO = FALSE; + + m_spAPECompressCreate->Start(m_pioOutput, pwfeInput, nMaxAudioBytes, nCompressionLevel, + pHeaderData, nHeaderBytes); + + SAFE_ARRAY_DELETE(m_pBuffer) + m_nBufferSize = m_spAPECompressCreate->GetFullFrameBytes(); + m_pBuffer = new unsigned char [m_nBufferSize]; + memcpy(&m_wfeInput, pwfeInput, sizeof(WAVEFORMATEX)); + + return ERROR_SUCCESS; +} + +int CAPECompress::GetBufferBytesAvailable() +{ + return m_nBufferSize - m_nBufferTail; +} + +int CAPECompress::UnlockBuffer(int nBytesAdded, BOOL bProcess) +{ + if (m_bBufferLocked == FALSE) + return ERROR_UNDEFINED; + + m_nBufferTail += nBytesAdded; + m_bBufferLocked = FALSE; + + if (bProcess) + { + int nRetVal = ProcessBuffer(); + if (nRetVal != 0) { return nRetVal; } + } + + return ERROR_SUCCESS; +} + +unsigned char * CAPECompress::LockBuffer(int * pBytesAvailable) +{ + if (m_pBuffer == NULL) { return NULL; } + + if (m_bBufferLocked) + return NULL; + + m_bBufferLocked = TRUE; + + if (pBytesAvailable) + *pBytesAvailable = GetBufferBytesAvailable(); + + return &m_pBuffer[m_nBufferTail]; +} + +int CAPECompress::AddData(unsigned char * pData, int nBytes) +{ + if (m_pBuffer == NULL) return ERROR_INSUFFICIENT_MEMORY; + + int nBytesDone = 0; + + while (nBytesDone < nBytes) + { + // lock the buffer + int nBytesAvailable = 0; + unsigned char * pBuffer = LockBuffer(&nBytesAvailable); + if (pBuffer == NULL || nBytesAvailable <= 0) + return ERROR_UNDEFINED; + + // calculate how many bytes to copy and add that much to the buffer + int nBytesToProcess = min(nBytesAvailable, nBytes - nBytesDone); + memcpy(pBuffer, &pData[nBytesDone], nBytesToProcess); + + // unlock the buffer (fail if not successful) + int nRetVal = UnlockBuffer(nBytesToProcess); + if (nRetVal != ERROR_SUCCESS) + return nRetVal; + + // update our progress + nBytesDone += nBytesToProcess; + } + + return ERROR_SUCCESS; +} + +int CAPECompress::Finish(unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) +{ + RETURN_ON_ERROR(ProcessBuffer(TRUE)) + return m_spAPECompressCreate->Finish(pTerminatingData, nTerminatingBytes, nWAVTerminatingBytes); +} + +int CAPECompress::Kill() +{ + return ERROR_SUCCESS; +} + +int CAPECompress::ProcessBuffer(BOOL bFinalize) +{ + if (m_pBuffer == NULL) { return ERROR_UNDEFINED; } + + try + { + // process as much as possible + int nThreshold = (bFinalize) ? 0 : m_spAPECompressCreate->GetFullFrameBytes(); + + while ((m_nBufferTail - m_nBufferHead) >= nThreshold) + { + int nFrameBytes = min(m_spAPECompressCreate->GetFullFrameBytes(), m_nBufferTail - m_nBufferHead); + + if (nFrameBytes == 0) + break; + + int nRetVal = m_spAPECompressCreate->EncodeFrame(&m_pBuffer[m_nBufferHead], nFrameBytes); + if (nRetVal != 0) { return nRetVal; } + + m_nBufferHead += nFrameBytes; + } + + // shift the buffer + if (m_nBufferHead != 0) + { + int nBytesLeft = m_nBufferTail - m_nBufferHead; + + if (nBytesLeft != 0) + memmove(m_pBuffer, &m_pBuffer[m_nBufferHead], nBytesLeft); + + m_nBufferTail -= m_nBufferHead; + m_nBufferHead = 0; + } + } + catch(...) + { + return ERROR_UNDEFINED; + } + + return ERROR_SUCCESS; +} + +int CAPECompress::AddDataFromInputSource(CInputSource * pInputSource, int nMaxBytes, int * pBytesAdded) +{ + // error check the parameters + if (pInputSource == NULL) return ERROR_BAD_PARAMETER; + + // initialize + if (pBytesAdded) *pBytesAdded = 0; + + // lock the buffer + int nBytesAvailable = 0; + unsigned char * pBuffer = LockBuffer(&nBytesAvailable); + if ((pBuffer == NULL) || (nBytesAvailable == 0)) + return ERROR_INSUFFICIENT_MEMORY; + + // calculate the 'ideal' number of bytes + unsigned int nBytesRead = 0; + + int nIdealBytes = m_spAPECompressCreate->GetFullFrameBytes() - (m_nBufferTail - m_nBufferHead); + if (nIdealBytes > 0) + { + // get the data + int nBytesToAdd = nBytesAvailable; + + if (nMaxBytes > 0) + { + if (nBytesToAdd > nMaxBytes) nBytesToAdd = nMaxBytes; + } + + if (nBytesToAdd > nIdealBytes) nBytesToAdd = nIdealBytes; + + // always make requests along block boundaries + while ((nBytesToAdd % m_wfeInput.nBlockAlign) != 0) + nBytesToAdd--; + + int nBlocksToAdd = nBytesToAdd / m_wfeInput.nBlockAlign; + + // get data + int nBlocksAdded = 0; + int nRetVal = pInputSource->GetData(pBuffer, nBlocksToAdd, &nBlocksAdded); + if (nRetVal != 0) + return ERROR_IO_READ; + else + nBytesRead = (nBlocksAdded * m_wfeInput.nBlockAlign); + + // store the bytes read + if (pBytesAdded) + *pBytesAdded = nBytesRead; + } + + // unlock the data and process + int nRetVal = UnlockBuffer(nBytesRead, TRUE); + if (nRetVal != 0) + { + return nRetVal; + } + + return ERROR_SUCCESS; +} + diff --git a/MAC_SDK/Source/MACLib/APECompress.h b/MAC_SDK/Source/MACLib/APECompress.h new file mode 100644 index 0000000..50e80ec --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompress.h @@ -0,0 +1,56 @@ +#ifndef APE_APECOMPRESS_H +#define APE_APECOMPRESS_H + +#include "MACLib.h" +class CAPECompressCreate; + +/************************************************************************************************* +CAPECompress - uses the CAPECompressHub to provide a simpler compression interface (with buffering, etc) +*************************************************************************************************/ +class CAPECompress : public IAPECompress +{ +public: + + CAPECompress(); + ~CAPECompress(); + + // start encoding + int Start(const wchar_t * pOutputFilename, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + int StartEx(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + + // add data / compress data + + // allows linear, immediate access to the buffer (fast) + int GetBufferBytesAvailable(); + int UnlockBuffer(int nBytesAdded, BOOL bProcess = TRUE); + unsigned char * LockBuffer(int * pBytesAvailable); + + // slower, but easier than locking and unlocking (copies data) + int AddData(unsigned char * pData, int nBytes); + + // use a CIO (input source) to add data + int AddDataFromInputSource(CInputSource * pInputSource, int nMaxBytes = -1, int * pBytesAdded = NULL); + + // finish / kill + int Finish(unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes); + int Kill(); + +private: + + int ProcessBuffer(BOOL bFinalize = FALSE); + + CSmartPtr m_spAPECompressCreate; + + int m_nBufferHead; + int m_nBufferTail; + int m_nBufferSize; + unsigned char * m_pBuffer; + BOOL m_bBufferLocked; + + CIO * m_pioOutput; + BOOL m_bOwnsOutputIO; + WAVEFORMATEX m_wfeInput; + +}; + +#endif // #ifndef APE_APECOMPRESS_H diff --git a/MAC_SDK/Source/MACLib/APECompressCore.cpp b/MAC_SDK/Source/MACLib/APECompressCore.cpp new file mode 100644 index 0000000..657e8c7 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompressCore.cpp @@ -0,0 +1,126 @@ +#include "All.h" +#include "APECompressCore.h" + +#include "BitArray.h" +#include "Prepare.h" +#include "NewPredictor.h" + +CAPECompressCore::CAPECompressCore(CIO * pIO, const WAVEFORMATEX * pwfeInput, int nMaxFrameBlocks, int nCompressionLevel) +{ + m_spBitArray.Assign(new CBitArray(pIO)); + m_spDataX.Assign(new int [nMaxFrameBlocks], TRUE); + m_spDataY.Assign(new int [nMaxFrameBlocks], TRUE); + m_spTempData.Assign(new int [nMaxFrameBlocks], TRUE); + m_spPrepare.Assign(new CPrepare); + m_spPredictorX.Assign(new CPredictorCompressNormal(nCompressionLevel)); + m_spPredictorY.Assign(new CPredictorCompressNormal(nCompressionLevel)); + + memcpy(&m_wfeInput, pwfeInput, sizeof(WAVEFORMATEX)); + m_nPeakLevel = 0; +} + +CAPECompressCore::~CAPECompressCore() +{ +} + +int CAPECompressCore::EncodeFrame(const void * pInputData, int nInputBytes) +{ + // variables + const int nInputBlocks = nInputBytes / m_wfeInput.nBlockAlign; + int nSpecialCodes = 0; + + // always start a new frame on a byte boundary + m_spBitArray->AdvanceToByteBoundary(); + + // do the preparation stage + RETURN_ON_ERROR(Prepare(pInputData, nInputBytes, &nSpecialCodes)) + + m_spPredictorX->Flush(); + m_spPredictorY->Flush(); + + m_spBitArray->FlushState(m_BitArrayStateX); + m_spBitArray->FlushState(m_BitArrayStateY); + + m_spBitArray->FlushBitArray(); + + if (m_wfeInput.nChannels == 2) + { + BOOL bEncodeX = TRUE; + BOOL bEncodeY = TRUE; + + if ((nSpecialCodes & SPECIAL_FRAME_LEFT_SILENCE) && + (nSpecialCodes & SPECIAL_FRAME_RIGHT_SILENCE)) + { + bEncodeX = FALSE; + bEncodeY = FALSE; + } + + if (nSpecialCodes & SPECIAL_FRAME_PSEUDO_STEREO) + { + bEncodeY = FALSE; + } + + if (bEncodeX && bEncodeY) + { + int nLastX = 0; + for (int z = 0; z < nInputBlocks; z++) + { + m_spBitArray->EncodeValue(m_spPredictorY->CompressValue(m_spDataY[z], nLastX), m_BitArrayStateY); + m_spBitArray->EncodeValue(m_spPredictorX->CompressValue(m_spDataX[z], m_spDataY[z]), m_BitArrayStateX); + + nLastX = m_spDataX[z]; + } + } + else if (bEncodeX) + { + for (int z = 0; z < nInputBlocks; z++) + { + RETURN_ON_ERROR(m_spBitArray->EncodeValue(m_spPredictorX->CompressValue(m_spDataX[z]), m_BitArrayStateX)) + } + } + else if (bEncodeY) + { + for (int z = 0; z < nInputBlocks; z++) + { + RETURN_ON_ERROR(m_spBitArray->EncodeValue(m_spPredictorY->CompressValue(m_spDataY[z]), m_BitArrayStateY)) + } + } + } + else if (m_wfeInput.nChannels == 1) + { + if (!(nSpecialCodes & SPECIAL_FRAME_MONO_SILENCE)) + { + for (int z = 0; z < nInputBlocks; z++) + { + RETURN_ON_ERROR(m_spBitArray->EncodeValue(m_spPredictorX->CompressValue(m_spDataX[z]), m_BitArrayStateX)) + } + } + } + + m_spBitArray->Finalize(); + + // return success + return 0; +} + +int CAPECompressCore::Prepare(const void * pInputData, int nInputBytes, int * pSpecialCodes) +{ + // variable declares + *pSpecialCodes = 0; + unsigned int nCRC = 0; + + // do the preparation + RETURN_ON_ERROR(m_spPrepare->Prepare((unsigned char *) pInputData, nInputBytes, &m_wfeInput, m_spDataX, m_spDataY, + &nCRC, pSpecialCodes, &m_nPeakLevel)) + + // store the CRC + RETURN_ON_ERROR(m_spBitArray->EncodeUnsignedLong(nCRC)) + + // store any special codes + if (*pSpecialCodes != 0) + { + RETURN_ON_ERROR(m_spBitArray->EncodeUnsignedLong(*pSpecialCodes)) + } + + return 0; +} \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/APECompressCore.h b/MAC_SDK/Source/MACLib/APECompressCore.h new file mode 100644 index 0000000..5c3e8be --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompressCore.h @@ -0,0 +1,41 @@ +#ifndef APE_APECOMPRESSCORE_H +#define APE_APECOMPRESSCORE_H + +#include "APECompress.h" +#include "BitArray.h" + +class CPrepare; +class IPredictorCompress; + +/************************************************************************************************* +CAPECompressCore - manages the core of compression and bitstream output +*************************************************************************************************/ +class CAPECompressCore +{ +public: + CAPECompressCore(CIO * pIO, const WAVEFORMATEX * pwfeInput, int nMaxFrameBlocks, int nCompressionLevel); + ~CAPECompressCore(); + + int EncodeFrame(const void * pInputData, int nInputBytes); + + CBitArray * GetBitArray() { return m_spBitArray.GetPtr(); } + int GetPeakLevel() { return m_nPeakLevel; } + +private: + + int Prepare(const void * pInputData, int nInputBytes, int * pSpecialCodes); + + CSmartPtr m_spBitArray; + CSmartPtr m_spPredictorX; + CSmartPtr m_spPredictorY; + BIT_ARRAY_STATE m_BitArrayStateX; + BIT_ARRAY_STATE m_BitArrayStateY; + CSmartPtr m_spDataX; + CSmartPtr m_spDataY; + CSmartPtr m_spTempData; + CSmartPtr m_spPrepare; + WAVEFORMATEX m_wfeInput; + int m_nPeakLevel; +}; + +#endif // #ifndef APE_APECOMPRESSCORE_H diff --git a/MAC_SDK/Source/MACLib/APECompressCreate.cpp b/MAC_SDK/Source/MACLib/APECompressCreate.cpp new file mode 100644 index 0000000..5b6a088 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompressCreate.cpp @@ -0,0 +1,218 @@ +#include "All.h" +#include "IO.h" +#include "APECompressCreate.h" + +#include "APECompressCore.h" + +CAPECompressCreate::CAPECompressCreate() +{ + m_nMaxFrames = 0; +} + +CAPECompressCreate::~CAPECompressCreate() +{ +} + +int CAPECompressCreate::Start(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + // verify the parameters + if (pioOutput == NULL || pwfeInput == NULL) + return ERROR_BAD_PARAMETER; + + // verify the wave format + if ((pwfeInput->nChannels != 1) && (pwfeInput->nChannels != 2)) + { + return ERROR_INPUT_FILE_UNSUPPORTED_CHANNEL_COUNT; + } + if ((pwfeInput->wBitsPerSample != 8) && (pwfeInput->wBitsPerSample != 16) && (pwfeInput->wBitsPerSample != 24)) + { + return ERROR_INPUT_FILE_UNSUPPORTED_BIT_DEPTH; + } + + // initialize (creates the base classes) + m_nSamplesPerFrame = 73728; + if (nCompressionLevel == COMPRESSION_LEVEL_EXTRA_HIGH) + m_nSamplesPerFrame *= 4; + else if (nCompressionLevel == COMPRESSION_LEVEL_INSANE) + m_nSamplesPerFrame *= 16; + + m_spIO.Assign(pioOutput, FALSE, FALSE); + m_spAPECompressCore.Assign(new CAPECompressCore(m_spIO, pwfeInput, m_nSamplesPerFrame, nCompressionLevel)); + + // copy the format + memcpy(&m_wfeInput, pwfeInput, sizeof(WAVEFORMATEX)); + + // the compression level + m_nCompressionLevel = nCompressionLevel; + m_nFrameIndex = 0; + m_nLastFrameBlocks = m_nSamplesPerFrame; + + // initialize the file + if (nMaxAudioBytes < 0) + nMaxAudioBytes = 2147483647; + + uint32 nMaxAudioBlocks = nMaxAudioBytes / pwfeInput->nBlockAlign; + int nMaxFrames = nMaxAudioBlocks / m_nSamplesPerFrame; + if ((nMaxAudioBlocks % m_nSamplesPerFrame) != 0) nMaxFrames++; + + InitializeFile(m_spIO, &m_wfeInput, nMaxFrames, + m_nCompressionLevel, pHeaderData, nHeaderBytes); + + return ERROR_SUCCESS; +} + +int CAPECompressCreate::GetFullFrameBytes() +{ + return m_nSamplesPerFrame * m_wfeInput.nBlockAlign; +} + +int CAPECompressCreate::EncodeFrame(const void * pInputData, int nInputBytes) +{ + int nInputBlocks = nInputBytes / m_wfeInput.nBlockAlign; + + if ((nInputBlocks < m_nSamplesPerFrame) && (m_nLastFrameBlocks < m_nSamplesPerFrame)) + { + return -1; // can only pass a smaller frame for the very last time + } + + // update the seek table + m_spAPECompressCore->GetBitArray()->AdvanceToByteBoundary(); + int nRetVal = SetSeekByte(m_nFrameIndex, m_spIO->GetPosition() + (m_spAPECompressCore->GetBitArray()->GetCurrentBitIndex() / 8)); + if (nRetVal != ERROR_SUCCESS) + return nRetVal; + + // compress + nRetVal = m_spAPECompressCore->EncodeFrame(pInputData, nInputBytes); + + // update stats + m_nLastFrameBlocks = nInputBlocks; + m_nFrameIndex++; + + return nRetVal; +} + +int CAPECompressCreate::Finish(const void * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) +{ + // clear the bit array + RETURN_ON_ERROR(m_spAPECompressCore->GetBitArray()->OutputBitArray(TRUE)); + + // finalize the file + RETURN_ON_ERROR(FinalizeFile(m_spIO, m_nFrameIndex, m_nLastFrameBlocks, + pTerminatingData, nTerminatingBytes, nWAVTerminatingBytes, m_spAPECompressCore->GetPeakLevel())); + + return ERROR_SUCCESS; +} + +int CAPECompressCreate::SetSeekByte(int nFrame, int nByteOffset) +{ + if (nFrame >= m_nMaxFrames) return ERROR_APE_COMPRESS_TOO_MUCH_DATA; + m_spSeekTable[nFrame] = nByteOffset; + return ERROR_SUCCESS; +} + +int CAPECompressCreate::InitializeFile(CIO * pIO, const WAVEFORMATEX * pwfeInput, int nMaxFrames, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes) +{ + // error check the parameters + if (pIO == NULL || pwfeInput == NULL || nMaxFrames <= 0) + return ERROR_BAD_PARAMETER; + + APE_DESCRIPTOR APEDescriptor; memset(&APEDescriptor, 0, sizeof(APEDescriptor)); + APE_HEADER APEHeader; memset(&APEHeader, 0, sizeof(APEHeader)); + + // create the descriptor (only fill what we know) + APEDescriptor.cID[0] = 'M'; + APEDescriptor.cID[1] = 'A'; + APEDescriptor.cID[2] = 'C'; + APEDescriptor.cID[3] = ' '; + APEDescriptor.nVersion = MAC_VERSION_NUMBER; + + APEDescriptor.nDescriptorBytes = sizeof(APEDescriptor); + APEDescriptor.nHeaderBytes = sizeof(APEHeader); + APEDescriptor.nSeekTableBytes = nMaxFrames * sizeof(unsigned int); + APEDescriptor.nHeaderDataBytes = (nHeaderBytes == CREATE_WAV_HEADER_ON_DECOMPRESSION) ? 0 : nHeaderBytes; + + // create the header (only fill what we know now) + APEHeader.nBitsPerSample = pwfeInput->wBitsPerSample; + APEHeader.nChannels = pwfeInput->nChannels; + APEHeader.nSampleRate = pwfeInput->nSamplesPerSec; + + APEHeader.nCompressionLevel = (uint16) nCompressionLevel; + APEHeader.nFormatFlags = (nHeaderBytes == CREATE_WAV_HEADER_ON_DECOMPRESSION) ? MAC_FORMAT_FLAG_CREATE_WAV_HEADER : 0; + + APEHeader.nBlocksPerFrame = m_nSamplesPerFrame; + + // write the data to the file + unsigned int nBytesWritten = 0; + RETURN_ON_ERROR(pIO->Write(&APEDescriptor, sizeof(APEDescriptor), &nBytesWritten)) + RETURN_ON_ERROR(pIO->Write(&APEHeader, sizeof(APEHeader), &nBytesWritten)) + + // write an empty seek table + m_spSeekTable.Assign(new uint32 [nMaxFrames], TRUE); + if (m_spSeekTable == NULL) { return ERROR_INSUFFICIENT_MEMORY; } + ZeroMemory(m_spSeekTable, nMaxFrames * 4); + RETURN_ON_ERROR(pIO->Write(m_spSeekTable, (nMaxFrames * 4), &nBytesWritten)) + m_nMaxFrames = nMaxFrames; + + // write the WAV data + if ((pHeaderData != NULL) && (nHeaderBytes > 0) && (nHeaderBytes != CREATE_WAV_HEADER_ON_DECOMPRESSION)) + { + m_spAPECompressCore->GetBitArray()->GetMD5Helper().AddData(pHeaderData, nHeaderBytes); + RETURN_ON_ERROR(pIO->Write((void *) pHeaderData, nHeaderBytes, &nBytesWritten)) + } + + return ERROR_SUCCESS; +} + + +int CAPECompressCreate::FinalizeFile(CIO * pIO, int nNumberOfFrames, int nFinalFrameBlocks, const void * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes, int nPeakLevel) +{ + // store the tail position + int nTailPosition = pIO->GetPosition(); + + // append the terminating data + unsigned int nBytesWritten = 0; + unsigned int nBytesRead = 0; + int nRetVal = 0; + if (nTerminatingBytes > 0) + { + m_spAPECompressCore->GetBitArray()->GetMD5Helper().AddData(pTerminatingData, nTerminatingBytes); + if (pIO->Write((void *) pTerminatingData, nTerminatingBytes, &nBytesWritten) != 0) { return ERROR_IO_WRITE; } + } + + // go to the beginning and update the information + nRetVal = pIO->Seek(0, FILE_BEGIN); + + // get the descriptor + APE_DESCRIPTOR APEDescriptor; + nRetVal = pIO->Read(&APEDescriptor, sizeof(APEDescriptor), &nBytesRead); + if ((nRetVal != 0) || (nBytesRead != sizeof(APEDescriptor))) { return ERROR_IO_READ; } + + // get the header + APE_HEADER APEHeader; + nRetVal = pIO->Read(&APEHeader, sizeof(APEHeader), &nBytesRead); + if (nRetVal != 0 || nBytesRead != sizeof(APEHeader)) { return ERROR_IO_READ; } + + // update the header + APEHeader.nFinalFrameBlocks = nFinalFrameBlocks; + APEHeader.nTotalFrames = nNumberOfFrames; + + // update the descriptor + APEDescriptor.nAPEFrameDataBytes = nTailPosition - (APEDescriptor.nDescriptorBytes + APEDescriptor.nHeaderBytes + APEDescriptor.nSeekTableBytes + APEDescriptor.nHeaderDataBytes); + APEDescriptor.nAPEFrameDataBytesHigh = 0; + APEDescriptor.nTerminatingDataBytes = nTerminatingBytes; + + // update the MD5 + m_spAPECompressCore->GetBitArray()->GetMD5Helper().AddData(&APEHeader, sizeof(APEHeader)); + m_spAPECompressCore->GetBitArray()->GetMD5Helper().AddData(m_spSeekTable, m_nMaxFrames * 4); + m_spAPECompressCore->GetBitArray()->GetMD5Helper().GetResult(APEDescriptor.cFileMD5); + + // set the pointer and re-write the updated header and peak level + nRetVal = pIO->Seek(0, FILE_BEGIN); + if (pIO->Write(&APEDescriptor, sizeof(APEDescriptor), &nBytesWritten) != 0) { return ERROR_IO_WRITE; } + if (pIO->Write(&APEHeader, sizeof(APEHeader), &nBytesWritten) != 0) { return ERROR_IO_WRITE; } + + // write the updated seek table + if (pIO->Write(m_spSeekTable, m_nMaxFrames * 4, &nBytesWritten) != 0) { return ERROR_IO_WRITE; } + + return ERROR_SUCCESS; +} diff --git a/MAC_SDK/Source/MACLib/APECompressCreate.h b/MAC_SDK/Source/MACLib/APECompressCreate.h new file mode 100644 index 0000000..f751039 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APECompressCreate.h @@ -0,0 +1,43 @@ +#ifndef APE_APECOMPRESSCREATE_H +#define APE_APECOMPRESSCREATE_H + +#include "APECompress.h" + +class CAPECompressCore; + +class CAPECompressCreate +{ +public: + CAPECompressCreate(); + ~CAPECompressCreate(); + + int InitializeFile(CIO * pIO, const WAVEFORMATEX * pwfeInput, int nMaxFrames, int nCompressionLevel, const void * pHeaderData, int nHeaderBytes); + int FinalizeFile(CIO * pIO, int nNumberOfFrames, int nFinalFrameBlocks, const void * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes, int nPeakLevel); + + int SetSeekByte(int nFrame, int nByteOffset); + + int Start(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, int nMaxAudioBytes, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION); + + int GetFullFrameBytes(); + int EncodeFrame(const void * pInputData, int nInputBytes); + + int Finish(const void * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes); + + +private: + + CSmartPtr m_spSeekTable; + int m_nMaxFrames; + + CSmartPtr m_spIO; + CSmartPtr m_spAPECompressCore; + + WAVEFORMATEX m_wfeInput; + int m_nCompressionLevel; + int m_nSamplesPerFrame; + int m_nFrameIndex; + int m_nLastFrameBlocks; + +}; + +#endif // #ifndef APE_APECOMPRESSCREATE_H diff --git a/MAC_SDK/Source/MACLib/APEDecompress.cpp b/MAC_SDK/Source/MACLib/APEDecompress.cpp new file mode 100644 index 0000000..1db1585 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEDecompress.cpp @@ -0,0 +1,479 @@ +#include "All.h" +#include "APEDecompress.h" + +#include "APEInfo.h" +#include "Prepare.h" +#include "UnBitArray.h" +#include "NewPredictor.h" + +#define DECODE_BLOCK_SIZE 4096 + +CAPEDecompress::CAPEDecompress(int * pErrorCode, CAPEInfo * pAPEInfo, int nStartBlock, int nFinishBlock) +{ + *pErrorCode = ERROR_SUCCESS; + + // open / analyze the file + m_spAPEInfo.Assign(pAPEInfo); + + // version check (this implementation only works with 3.93 and later files) + if (GetInfo(APE_INFO_FILE_VERSION) < 3930) + { + *pErrorCode = ERROR_UNDEFINED; + return; + } + + // get format information + GetInfo(APE_INFO_WAVEFORMATEX, (int) &m_wfeInput); + m_nBlockAlign = GetInfo(APE_INFO_BLOCK_ALIGN); + + // initialize other stuff + m_bDecompressorInitialized = FALSE; + m_nCurrentFrame = 0; + m_nCurrentBlock = 0; + m_nCurrentFrameBufferBlock = 0; + m_nFrameBufferFinishedBlocks = 0; + m_bErrorDecodingCurrentFrame = FALSE; + + // set the "real" start and finish blocks + m_nStartBlock = (nStartBlock < 0) ? 0 : min(nStartBlock, GetInfo(APE_INFO_TOTAL_BLOCKS)); + m_nFinishBlock = (nFinishBlock < 0) ? GetInfo(APE_INFO_TOTAL_BLOCKS) : min(nFinishBlock, GetInfo(APE_INFO_TOTAL_BLOCKS)); + m_bIsRanged = (m_nStartBlock != 0) || (m_nFinishBlock != GetInfo(APE_INFO_TOTAL_BLOCKS)); +} + +CAPEDecompress::~CAPEDecompress() +{ + +} + +int CAPEDecompress::InitializeDecompressor() +{ + // check if we have anything to do + if (m_bDecompressorInitialized) + return ERROR_SUCCESS; + + // update the initialized flag + m_bDecompressorInitialized = TRUE; + + // create a frame buffer + m_cbFrameBuffer.CreateBuffer((GetInfo(APE_INFO_BLOCKS_PER_FRAME) + DECODE_BLOCK_SIZE) * m_nBlockAlign, m_nBlockAlign * 64); + + // create decoding components + m_spUnBitArray.Assign((CUnBitArrayBase *) CreateUnBitArray(this, GetInfo(APE_INFO_FILE_VERSION))); + + if (GetInfo(APE_INFO_FILE_VERSION) >= 3950) + { + m_spNewPredictorX.Assign(new CPredictorDecompress3950toCurrent(GetInfo(APE_INFO_COMPRESSION_LEVEL), GetInfo(APE_INFO_FILE_VERSION))); + m_spNewPredictorY.Assign(new CPredictorDecompress3950toCurrent(GetInfo(APE_INFO_COMPRESSION_LEVEL), GetInfo(APE_INFO_FILE_VERSION))); + } + else + { + m_spNewPredictorX.Assign(new CPredictorDecompressNormal3930to3950(GetInfo(APE_INFO_COMPRESSION_LEVEL), GetInfo(APE_INFO_FILE_VERSION))); + m_spNewPredictorY.Assign(new CPredictorDecompressNormal3930to3950(GetInfo(APE_INFO_COMPRESSION_LEVEL), GetInfo(APE_INFO_FILE_VERSION))); + } + + // seek to the beginning + return Seek(0); +} + +int CAPEDecompress::GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved) +{ + int nRetVal = ERROR_SUCCESS; + if (pBlocksRetrieved) *pBlocksRetrieved = 0; + + // make sure we're initialized + RETURN_ON_ERROR(InitializeDecompressor()) + + // cap + int nBlocksUntilFinish = m_nFinishBlock - m_nCurrentBlock; + const int nBlocksToRetrieve = min(nBlocks, nBlocksUntilFinish); + + // get the data + unsigned char * pOutputBuffer = (unsigned char *) pBuffer; + int nBlocksLeft = nBlocksToRetrieve; int nBlocksThisPass = 1; + while ((nBlocksLeft > 0) && (nBlocksThisPass > 0)) + { + // fill up the frame buffer + int nDecodeRetVal = FillFrameBuffer(); + if (nDecodeRetVal != ERROR_SUCCESS) + nRetVal = nDecodeRetVal; + + // analyze how much to remove from the buffer + const int nFrameBufferBlocks = m_nFrameBufferFinishedBlocks; + nBlocksThisPass = min(nBlocksLeft, nFrameBufferBlocks); + + // remove as much as possible + if (nBlocksThisPass > 0) + { + m_cbFrameBuffer.Get(pOutputBuffer, nBlocksThisPass * m_nBlockAlign); + pOutputBuffer += nBlocksThisPass * m_nBlockAlign; + nBlocksLeft -= nBlocksThisPass; + m_nFrameBufferFinishedBlocks -= nBlocksThisPass; + } + } + + // calculate the blocks retrieved + int nBlocksRetrieved = nBlocksToRetrieve - nBlocksLeft; + + // update position + m_nCurrentBlock += nBlocksRetrieved; + if (pBlocksRetrieved) *pBlocksRetrieved = nBlocksRetrieved; + + return nRetVal; +} + +int CAPEDecompress::Seek(int nBlockOffset) +{ + RETURN_ON_ERROR(InitializeDecompressor()) + + // use the offset + nBlockOffset += m_nStartBlock; + + // cap (to prevent seeking too far) + if (nBlockOffset >= m_nFinishBlock) + nBlockOffset = m_nFinishBlock - 1; + if (nBlockOffset < m_nStartBlock) + nBlockOffset = m_nStartBlock; + + // seek to the perfect location + int nBaseFrame = nBlockOffset / GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nBlocksToSkip = nBlockOffset % GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nBytesToSkip = nBlocksToSkip * m_nBlockAlign; + + m_nCurrentBlock = nBaseFrame * GetInfo(APE_INFO_BLOCKS_PER_FRAME); + m_nCurrentFrameBufferBlock = nBaseFrame * GetInfo(APE_INFO_BLOCKS_PER_FRAME); + m_nCurrentFrame = nBaseFrame; + m_nFrameBufferFinishedBlocks = 0; + m_cbFrameBuffer.Empty(); + RETURN_ON_ERROR(SeekToFrame(m_nCurrentFrame)); + + // skip necessary blocks + CSmartPtr spTempBuffer(new char [nBytesToSkip], TRUE); + if (spTempBuffer == NULL) return ERROR_INSUFFICIENT_MEMORY; + + int nBlocksRetrieved = 0; + GetData(spTempBuffer, nBlocksToSkip, &nBlocksRetrieved); + if (nBlocksRetrieved != nBlocksToSkip) + return ERROR_UNDEFINED; + + return ERROR_SUCCESS; +} + +/***************************************************************************************** +Decodes blocks of data +*****************************************************************************************/ +int CAPEDecompress::FillFrameBuffer() +{ + int nRetVal = ERROR_SUCCESS; + + // determine the maximum blocks we can decode + // note that we won't do end capping because we can't use data + // until EndFrame(...) successfully handles the frame + // that means we may decode a little extra in end capping cases + // but this allows robust error handling of bad frames + int nMaxBlocks = m_cbFrameBuffer.MaxAdd() / m_nBlockAlign; + + // loop and decode data + int nBlocksLeft = nMaxBlocks; + while (nBlocksLeft > 0) + { + int nFrameBlocks = GetInfo(APE_INFO_FRAME_BLOCKS, m_nCurrentFrame); + if (nFrameBlocks < 0) + break; + + int nFrameOffsetBlocks = m_nCurrentFrameBufferBlock % GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nFrameBlocksLeft = nFrameBlocks - nFrameOffsetBlocks; + int nBlocksThisPass = min(nFrameBlocksLeft, nBlocksLeft); + + // start the frame if we need to + if (nFrameOffsetBlocks == 0) + StartFrame(); + + // store the frame buffer bytes before we start + int nFrameBufferBytes = m_cbFrameBuffer.MaxGet(); + + // decode data + DecodeBlocksToFrameBuffer(nBlocksThisPass); + + // end the frame if we need to + if ((nFrameOffsetBlocks + nBlocksThisPass) >= nFrameBlocks) + { + EndFrame(); + if (m_bErrorDecodingCurrentFrame) + { + // remove any decoded data from the buffer + m_cbFrameBuffer.RemoveTail(m_cbFrameBuffer.MaxGet() - nFrameBufferBytes); + + // add silence + unsigned char cSilence = (GetInfo(APE_INFO_BITS_PER_SAMPLE) == 8) ? 127 : 0; + for (int z = 0; z < nFrameBlocks * m_nBlockAlign; z++) + { + *m_cbFrameBuffer.GetDirectWritePointer() = cSilence; + m_cbFrameBuffer.UpdateAfterDirectWrite(1); + } + + // seek to try to synchronize after an error + SeekToFrame(m_nCurrentFrame); + + // save the return value + nRetVal = ERROR_INVALID_CHECKSUM; + } + } + + nBlocksLeft -= nBlocksThisPass; + } + + return nRetVal; +} + +void CAPEDecompress::DecodeBlocksToFrameBuffer(int nBlocks) +{ + // decode the samples + int nBlocksProcessed = 0; + + try + { + if (m_wfeInput.nChannels == 2) + { + if ((m_nSpecialCodes & SPECIAL_FRAME_LEFT_SILENCE) && + (m_nSpecialCodes & SPECIAL_FRAME_RIGHT_SILENCE)) + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + m_Prepare.Unprepare(0, 0, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + else if (m_nSpecialCodes & SPECIAL_FRAME_PSEUDO_STEREO) + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + int X = m_spNewPredictorX->DecompressValue(m_spUnBitArray->DecodeValueRange(m_BitArrayStateX)); + m_Prepare.Unprepare(X, 0, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + else + { + if (m_spAPEInfo->GetInfo(APE_INFO_FILE_VERSION) >= 3950) + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + int nY = m_spUnBitArray->DecodeValueRange(m_BitArrayStateY); + int nX = m_spUnBitArray->DecodeValueRange(m_BitArrayStateX); + int Y = m_spNewPredictorY->DecompressValue(nY, m_nLastX); + int X = m_spNewPredictorX->DecompressValue(nX, Y); + m_nLastX = X; + + m_Prepare.Unprepare(X, Y, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + else + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + int X = m_spNewPredictorX->DecompressValue(m_spUnBitArray->DecodeValueRange(m_BitArrayStateX)); + int Y = m_spNewPredictorY->DecompressValue(m_spUnBitArray->DecodeValueRange(m_BitArrayStateY)); + + m_Prepare.Unprepare(X, Y, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + } + } + else + { + if (m_nSpecialCodes & SPECIAL_FRAME_MONO_SILENCE) + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + m_Prepare.Unprepare(0, 0, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + else + { + for (nBlocksProcessed = 0; nBlocksProcessed < nBlocks; nBlocksProcessed++) + { + int X = m_spNewPredictorX->DecompressValue(m_spUnBitArray->DecodeValueRange(m_BitArrayStateX)); + m_Prepare.Unprepare(X, 0, &m_wfeInput, m_cbFrameBuffer.GetDirectWritePointer(), &m_nCRC); + m_cbFrameBuffer.UpdateAfterDirectWrite(m_nBlockAlign); + } + } + } + } + catch(...) + { + m_bErrorDecodingCurrentFrame = TRUE; + } + + m_nCurrentFrameBufferBlock += nBlocks; +} + +void CAPEDecompress::StartFrame() +{ + m_nCRC = 0xFFFFFFFF; + + // get the frame header + m_nStoredCRC = m_spUnBitArray->DecodeValue(DECODE_VALUE_METHOD_UNSIGNED_INT); + m_bErrorDecodingCurrentFrame = FALSE; + + // get any 'special' codes if the file uses them (for silence, FALSE stereo, etc.) + m_nSpecialCodes = 0; + if (GET_USES_SPECIAL_FRAMES(m_spAPEInfo)) + { + if (m_nStoredCRC & 0x80000000) + { + m_nSpecialCodes = m_spUnBitArray->DecodeValue(DECODE_VALUE_METHOD_UNSIGNED_INT); + } + m_nStoredCRC &= 0x7FFFFFFF; + } + + m_spNewPredictorX->Flush(); + m_spNewPredictorY->Flush(); + + m_spUnBitArray->FlushState(m_BitArrayStateX); + m_spUnBitArray->FlushState(m_BitArrayStateY); + + m_spUnBitArray->FlushBitArray(); + + m_nLastX = 0; +} + +void CAPEDecompress::EndFrame() +{ + m_nFrameBufferFinishedBlocks += GetInfo(APE_INFO_FRAME_BLOCKS, m_nCurrentFrame); + m_nCurrentFrame++; + + // finalize + m_spUnBitArray->Finalize(); + + // check the CRC + m_nCRC = m_nCRC ^ 0xFFFFFFFF; + m_nCRC >>= 1; + if (m_nCRC != m_nStoredCRC) + m_bErrorDecodingCurrentFrame = TRUE; +} + +/***************************************************************************************** +Seek to the proper frame (if necessary) and do any alignment of the bit array +*****************************************************************************************/ +int CAPEDecompress::SeekToFrame(int nFrameIndex) +{ + int nSeekRemainder = (GetInfo(APE_INFO_SEEK_BYTE, nFrameIndex) - GetInfo(APE_INFO_SEEK_BYTE, 0)) % 4; + return m_spUnBitArray->FillAndResetBitArray(GetInfo(APE_INFO_SEEK_BYTE, nFrameIndex) - nSeekRemainder, nSeekRemainder * 8); +} + +/***************************************************************************************** +Get information from the decompressor +*****************************************************************************************/ +int CAPEDecompress::GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1, int nParam2) +{ + int nRetVal = 0; + BOOL bHandled = TRUE; + + switch (Field) + { + case APE_DECOMPRESS_CURRENT_BLOCK: + nRetVal = m_nCurrentBlock - m_nStartBlock; + break; + case APE_DECOMPRESS_CURRENT_MS: + { + int nSampleRate = m_spAPEInfo->GetInfo(APE_INFO_SAMPLE_RATE, 0, 0); + if (nSampleRate > 0) + nRetVal = int((double(m_nCurrentBlock) * double(1000)) / double(nSampleRate)); + break; + } + case APE_DECOMPRESS_TOTAL_BLOCKS: + nRetVal = m_nFinishBlock - m_nStartBlock; + break; + case APE_DECOMPRESS_LENGTH_MS: + { + int nSampleRate = m_spAPEInfo->GetInfo(APE_INFO_SAMPLE_RATE, 0, 0); + if (nSampleRate > 0) + nRetVal = int((double(m_nFinishBlock - m_nStartBlock) * double(1000)) / double(nSampleRate)); + break; + } + case APE_DECOMPRESS_CURRENT_BITRATE: + nRetVal = GetInfo(APE_INFO_FRAME_BITRATE, m_nCurrentFrame); + break; + case APE_DECOMPRESS_AVERAGE_BITRATE: + { + if (m_bIsRanged) + { + // figure the frame range + const int nBlocksPerFrame = GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nStartFrame = m_nStartBlock / nBlocksPerFrame; + int nFinishFrame = (m_nFinishBlock + nBlocksPerFrame - 1) / nBlocksPerFrame; + + // get the number of bytes in the first and last frame + int nTotalBytes = (GetInfo(APE_INFO_FRAME_BYTES, nStartFrame) * (m_nStartBlock % nBlocksPerFrame)) / nBlocksPerFrame; + if (nFinishFrame != nStartFrame) + nTotalBytes += (GetInfo(APE_INFO_FRAME_BYTES, nFinishFrame) * (m_nFinishBlock % nBlocksPerFrame)) / nBlocksPerFrame; + + // get the number of bytes in between + const int nTotalFrames = GetInfo(APE_INFO_TOTAL_FRAMES); + for (int nFrame = nStartFrame + 1; (nFrame < nFinishFrame) && (nFrame < nTotalFrames); nFrame++) + nTotalBytes += GetInfo(APE_INFO_FRAME_BYTES, nFrame); + + // figure the bitrate + int nTotalMS = int((double(m_nFinishBlock - m_nStartBlock) * double(1000)) / double(GetInfo(APE_INFO_SAMPLE_RATE))); + if (nTotalMS != 0) + nRetVal = (nTotalBytes * 8) / nTotalMS; + } + else + { + nRetVal = GetInfo(APE_INFO_AVERAGE_BITRATE); + } + + break; + } + default: + bHandled = FALSE; + } + + if (!bHandled && m_bIsRanged) + { + bHandled = TRUE; + + switch (Field) + { + case APE_INFO_WAV_HEADER_BYTES: + nRetVal = sizeof(WAVE_HEADER); + break; + case APE_INFO_WAV_HEADER_DATA: + { + char * pBuffer = (char *) nParam1; + int nMaxBytes = nParam2; + + if (sizeof(WAVE_HEADER) > nMaxBytes) + { + nRetVal = -1; + } + else + { + WAVEFORMATEX wfeFormat; GetInfo(APE_INFO_WAVEFORMATEX, (int) &wfeFormat, 0); + WAVE_HEADER WAVHeader; FillWaveHeader(&WAVHeader, + (m_nFinishBlock - m_nStartBlock) * GetInfo(APE_INFO_BLOCK_ALIGN), + &wfeFormat, 0); + memcpy(pBuffer, &WAVHeader, sizeof(WAVE_HEADER)); + nRetVal = 0; + } + break; + } + case APE_INFO_WAV_TERMINATING_BYTES: + nRetVal = 0; + break; + case APE_INFO_WAV_TERMINATING_DATA: + nRetVal = 0; + break; + default: + bHandled = FALSE; + } + } + + if (bHandled == FALSE) + nRetVal = m_spAPEInfo->GetInfo(Field, nParam1, nParam2); + + return nRetVal; +} diff --git a/MAC_SDK/Source/MACLib/APEDecompress.h b/MAC_SDK/Source/MACLib/APEDecompress.h new file mode 100644 index 0000000..ec49c07 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEDecompress.h @@ -0,0 +1,72 @@ +#ifndef APE_APEDECOMPRESS_H +#define APE_APEDECOMPRESS_H + +#include "APEDecompress.h" + +class CUnBitArray; +class CPrepare; +class CAPEInfo; +class IPredictorDecompress; +#include "UnBitArrayBase.h" +#include "MACLib.h" +#include "Prepare.h" +#include "CircleBuffer.h" + +class CAPEDecompress : public IAPEDecompress +{ +public: + + CAPEDecompress(int * pErrorCode, CAPEInfo * pAPEInfo, int nStartBlock = -1, int nFinishBlock = -1); + ~CAPEDecompress(); + + int GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved); + int Seek(int nBlockOffset); + + int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0); + +protected: + + // file info + int m_nBlockAlign; + int m_nCurrentFrame; + + // start / finish information + int m_nStartBlock; + int m_nFinishBlock; + int m_nCurrentBlock; + BOOL m_bIsRanged; + BOOL m_bDecompressorInitialized; + + // decoding tools + CPrepare m_Prepare; + WAVEFORMATEX m_wfeInput; + unsigned int m_nCRC; + unsigned int m_nStoredCRC; + int m_nSpecialCodes; + + int SeekToFrame(int nFrameIndex); + void DecodeBlocksToFrameBuffer(int nBlocks); + int FillFrameBuffer(); + void StartFrame(); + void EndFrame(); + int InitializeDecompressor(); + + // more decoding components + CSmartPtr m_spAPEInfo; + CSmartPtr m_spUnBitArray; + UNBIT_ARRAY_STATE m_BitArrayStateX; + UNBIT_ARRAY_STATE m_BitArrayStateY; + + CSmartPtr m_spNewPredictorX; + CSmartPtr m_spNewPredictorY; + + int m_nLastX; + + // decoding buffer + BOOL m_bErrorDecodingCurrentFrame; + int m_nCurrentFrameBufferBlock; + int m_nFrameBufferFinishedBlocks; + CCircleBuffer m_cbFrameBuffer; +}; + +#endif // #ifndef APE_APEDECOMPRESS_H diff --git a/MAC_SDK/Source/MACLib/APEHeader.cpp b/MAC_SDK/Source/MACLib/APEHeader.cpp new file mode 100644 index 0000000..51079d4 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEHeader.cpp @@ -0,0 +1,280 @@ +#include "All.h" +#include "APEHeader.h" +#include "MACLib.h" +#include "APEInfo.h" + +// TODO: should push and pop the file position + +CAPEHeader::CAPEHeader(CIO * pIO) +{ + m_pIO = pIO; +} + +CAPEHeader::~CAPEHeader() +{ + +} + +int CAPEHeader::FindDescriptor(BOOL bSeek) +{ + // store the original location and seek to the beginning + int nOriginalFileLocation = m_pIO->GetPosition(); + m_pIO->Seek(0, FILE_BEGIN); + + // set the default junk bytes to 0 + int nJunkBytes = 0; + + // skip an ID3v2 tag (which we really don't support anyway...) + unsigned int nBytesRead = 0; + unsigned char cID3v2Header[10]; + m_pIO->Read((unsigned char *) cID3v2Header, 10, &nBytesRead); + if (cID3v2Header[0] == 'I' && cID3v2Header[1] == 'D' && cID3v2Header[2] == '3') + { + // why is it so hard to figure the lenght of an ID3v2 tag ?!? + unsigned int nLength = *((unsigned int *) &cID3v2Header[6]); + + unsigned int nSyncSafeLength = 0; + nSyncSafeLength = (cID3v2Header[6] & 127) << 21; + nSyncSafeLength += (cID3v2Header[7] & 127) << 14; + nSyncSafeLength += (cID3v2Header[8] & 127) << 7; + nSyncSafeLength += (cID3v2Header[9] & 127); + + BOOL bHasTagFooter = FALSE; + + if (cID3v2Header[5] & 16) + { + bHasTagFooter = TRUE; + nJunkBytes = nSyncSafeLength + 20; + } + else + { + nJunkBytes = nSyncSafeLength + 10; + } + + // error check + if (cID3v2Header[5] & 64) + { + // this ID3v2 length calculator algorithm can't cope with extended headers + // we should be ok though, because the scan for the MAC header below should + // really do the trick + } + + m_pIO->Seek(nJunkBytes, FILE_BEGIN); + + // scan for padding (slow and stupid, but who cares here...) + if (!bHasTagFooter) + { + char cTemp = 0; + m_pIO->Read((unsigned char *) &cTemp, 1, &nBytesRead); + while (cTemp == 0 && nBytesRead == 1) + { + nJunkBytes++; + m_pIO->Read((unsigned char *) &cTemp, 1, &nBytesRead); + } + } + } + m_pIO->Seek(nJunkBytes, FILE_BEGIN); + + // scan until we hit the APE_DESCRIPTOR, the end of the file, or 1 MB later + unsigned int nGoalID = (' ' << 24) | ('C' << 16) | ('A' << 8) | ('M'); + unsigned int nReadID = 0; + int nRetVal = m_pIO->Read(&nReadID, 4, &nBytesRead); + if (nRetVal != 0 || nBytesRead != 4) return ERROR_UNDEFINED; + + nBytesRead = 1; + int nScanBytes = 0; + while ((nGoalID != nReadID) && (nBytesRead == 1) && (nScanBytes < (1024 * 1024))) + { + unsigned char cTemp; + m_pIO->Read(&cTemp, 1, &nBytesRead); + nReadID = (((unsigned int) cTemp) << 24) | (nReadID >> 8); + nJunkBytes++; + nScanBytes++; + } + + if (nGoalID != nReadID) + nJunkBytes = -1; + + // seek to the proper place (depending on result and settings) + if (bSeek && (nJunkBytes != -1)) + { + // successfully found the start of the file (seek to it and return) + m_pIO->Seek(nJunkBytes, FILE_BEGIN); + } + else + { + // restore the original file pointer + m_pIO->Seek(nOriginalFileLocation, FILE_BEGIN); + } + + return nJunkBytes; +} + +int CAPEHeader::Analyze(APE_FILE_INFO * pInfo) +{ + // error check + if ((m_pIO == NULL) || (pInfo == NULL)) + return ERROR_INVALID_PARAMETER; + + // variables + unsigned int nBytesRead = 0; + + // find the descriptor + pInfo->nJunkHeaderBytes = FindDescriptor(TRUE); + if (pInfo->nJunkHeaderBytes < 0) + return ERROR_UNDEFINED; + + // read the first 8 bytes of the descriptor (ID and version) + APE_COMMON_HEADER CommonHeader; memset(&CommonHeader, 0, sizeof(APE_COMMON_HEADER)); + m_pIO->Read(&CommonHeader, sizeof(APE_COMMON_HEADER), &nBytesRead); + + // make sure we're at the ID + if (CommonHeader.cID[0] != 'M' || CommonHeader.cID[1] != 'A' || CommonHeader.cID[2] != 'C' || CommonHeader.cID[3] != ' ') + return ERROR_UNDEFINED; + + int nRetVal = ERROR_UNDEFINED; + + if (CommonHeader.nVersion >= 3980) + { + // current header format + nRetVal = AnalyzeCurrent(pInfo); + } + else + { + // legacy support + nRetVal = AnalyzeOld(pInfo); + } + + return nRetVal; +} + +int CAPEHeader::AnalyzeCurrent(APE_FILE_INFO * pInfo) +{ + // variable declares + unsigned int nBytesRead = 0; + pInfo->spAPEDescriptor.Assign(new APE_DESCRIPTOR); memset(pInfo->spAPEDescriptor, 0, sizeof(APE_DESCRIPTOR)); + APE_HEADER APEHeader; memset(&APEHeader, 0, sizeof(APEHeader)); + + // read the descriptor + m_pIO->Seek(pInfo->nJunkHeaderBytes, FILE_BEGIN); + m_pIO->Read(pInfo->spAPEDescriptor, sizeof(APE_DESCRIPTOR), &nBytesRead); + + if ((pInfo->spAPEDescriptor->nDescriptorBytes - nBytesRead) > 0) + m_pIO->Seek(pInfo->spAPEDescriptor->nDescriptorBytes - nBytesRead, FILE_CURRENT); + + // read the header + m_pIO->Read(&APEHeader, sizeof(APEHeader), &nBytesRead); + + if ((pInfo->spAPEDescriptor->nHeaderBytes - nBytesRead) > 0) + m_pIO->Seek(pInfo->spAPEDescriptor->nHeaderBytes - nBytesRead, FILE_CURRENT); + + // fill the APE info structure + pInfo->nVersion = int(pInfo->spAPEDescriptor->nVersion); + pInfo->nCompressionLevel = int(APEHeader.nCompressionLevel); + pInfo->nFormatFlags = int(APEHeader.nFormatFlags); + pInfo->nTotalFrames = int(APEHeader.nTotalFrames); + pInfo->nFinalFrameBlocks = int(APEHeader.nFinalFrameBlocks); + pInfo->nBlocksPerFrame = int(APEHeader.nBlocksPerFrame); + pInfo->nChannels = int(APEHeader.nChannels); + pInfo->nSampleRate = int(APEHeader.nSampleRate); + pInfo->nBitsPerSample = int(APEHeader.nBitsPerSample); + pInfo->nBytesPerSample = pInfo->nBitsPerSample / 8; + pInfo->nBlockAlign = pInfo->nBytesPerSample * pInfo->nChannels; + pInfo->nTotalBlocks = (APEHeader.nTotalFrames == 0) ? 0 : ((APEHeader.nTotalFrames - 1) * pInfo->nBlocksPerFrame) + APEHeader.nFinalFrameBlocks; + pInfo->nWAVHeaderBytes = (APEHeader.nFormatFlags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER) ? sizeof(WAVE_HEADER) : pInfo->spAPEDescriptor->nHeaderDataBytes; + pInfo->nWAVTerminatingBytes = pInfo->spAPEDescriptor->nTerminatingDataBytes; + pInfo->nWAVDataBytes = pInfo->nTotalBlocks * pInfo->nBlockAlign; + pInfo->nWAVTotalBytes = pInfo->nWAVDataBytes + pInfo->nWAVHeaderBytes + pInfo->nWAVTerminatingBytes; + pInfo->nAPETotalBytes = m_pIO->GetSize(); + pInfo->nLengthMS = int((double(pInfo->nTotalBlocks) * double(1000)) / double(pInfo->nSampleRate)); + pInfo->nAverageBitrate = (pInfo->nLengthMS <= 0) ? 0 : int((double(pInfo->nAPETotalBytes) * double(8)) / double(pInfo->nLengthMS)); + pInfo->nDecompressedBitrate = (pInfo->nBlockAlign * pInfo->nSampleRate * 8) / 1000; + pInfo->nSeekTableElements = pInfo->spAPEDescriptor->nSeekTableBytes / 4; + + // get the seek tables (really no reason to get the whole thing if there's extra) + pInfo->spSeekByteTable.Assign(new uint32 [pInfo->nSeekTableElements], TRUE); + if (pInfo->spSeekByteTable == NULL) { return ERROR_UNDEFINED; } + + m_pIO->Read((unsigned char *) pInfo->spSeekByteTable.GetPtr(), 4 * pInfo->nSeekTableElements, &nBytesRead); + + // get the wave header + if (!(APEHeader.nFormatFlags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + { + pInfo->spWaveHeaderData.Assign(new unsigned char [pInfo->nWAVHeaderBytes], TRUE); + if (pInfo->spWaveHeaderData == NULL) { return ERROR_UNDEFINED; } + m_pIO->Read((unsigned char *) pInfo->spWaveHeaderData, pInfo->nWAVHeaderBytes, &nBytesRead); + } + + return ERROR_SUCCESS; +} + +int CAPEHeader::AnalyzeOld(APE_FILE_INFO * pInfo) +{ + // variable declares + unsigned int nBytesRead = 0; + + // read the MAC header from the file + APE_HEADER_OLD APEHeader; + m_pIO->Seek(pInfo->nJunkHeaderBytes, FILE_BEGIN); + m_pIO->Read((unsigned char *) &APEHeader, sizeof(APEHeader), &nBytesRead); + + // fail on 0 length APE files (catches non-finalized APE files) + if (APEHeader.nTotalFrames == 0) + return ERROR_UNDEFINED; + + int nPeakLevel = -1; + if (APEHeader.nFormatFlags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) + m_pIO->Read((unsigned char *) &nPeakLevel, 4, &nBytesRead); + + if (APEHeader.nFormatFlags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) + m_pIO->Read((unsigned char *) &pInfo->nSeekTableElements, 4, &nBytesRead); + else + pInfo->nSeekTableElements = APEHeader.nTotalFrames; + + // fill the APE info structure + pInfo->nVersion = int(APEHeader.nVersion); + pInfo->nCompressionLevel = int(APEHeader.nCompressionLevel); + pInfo->nFormatFlags = int(APEHeader.nFormatFlags); + pInfo->nTotalFrames = int(APEHeader.nTotalFrames); + pInfo->nFinalFrameBlocks = int(APEHeader.nFinalFrameBlocks); + pInfo->nBlocksPerFrame = ((APEHeader.nVersion >= 3900) || ((APEHeader.nVersion >= 3800) && (APEHeader.nCompressionLevel == COMPRESSION_LEVEL_EXTRA_HIGH))) ? 73728 : 9216; + if ((APEHeader.nVersion >= 3950)) pInfo->nBlocksPerFrame = 73728 * 4; + pInfo->nChannels = int(APEHeader.nChannels); + pInfo->nSampleRate = int(APEHeader.nSampleRate); + pInfo->nBitsPerSample = (pInfo->nFormatFlags & MAC_FORMAT_FLAG_8_BIT) ? 8 : ((pInfo->nFormatFlags & MAC_FORMAT_FLAG_24_BIT) ? 24 : 16); + pInfo->nBytesPerSample = pInfo->nBitsPerSample / 8; + pInfo->nBlockAlign = pInfo->nBytesPerSample * pInfo->nChannels; + pInfo->nTotalBlocks = (APEHeader.nTotalFrames == 0) ? 0 : ((APEHeader.nTotalFrames - 1) * pInfo->nBlocksPerFrame) + APEHeader.nFinalFrameBlocks; + pInfo->nWAVHeaderBytes = (APEHeader.nFormatFlags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER) ? sizeof(WAVE_HEADER) : APEHeader.nHeaderBytes; + pInfo->nWAVTerminatingBytes = int(APEHeader.nTerminatingBytes); + pInfo->nWAVDataBytes = pInfo->nTotalBlocks * pInfo->nBlockAlign; + pInfo->nWAVTotalBytes = pInfo->nWAVDataBytes + pInfo->nWAVHeaderBytes + pInfo->nWAVTerminatingBytes; + pInfo->nAPETotalBytes = m_pIO->GetSize(); + pInfo->nLengthMS = int((double(pInfo->nTotalBlocks) * double(1000)) / double(pInfo->nSampleRate)); + pInfo->nAverageBitrate = (pInfo->nLengthMS <= 0) ? 0 : int((double(pInfo->nAPETotalBytes) * double(8)) / double(pInfo->nLengthMS)); + pInfo->nDecompressedBitrate = (pInfo->nBlockAlign * pInfo->nSampleRate * 8) / 1000; + + // get the wave header + if (!(APEHeader.nFormatFlags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + { + pInfo->spWaveHeaderData.Assign(new unsigned char [APEHeader.nHeaderBytes], TRUE); + if (pInfo->spWaveHeaderData == NULL) { return ERROR_UNDEFINED; } + m_pIO->Read((unsigned char *) pInfo->spWaveHeaderData, APEHeader.nHeaderBytes, &nBytesRead); + } + + // get the seek tables (really no reason to get the whole thing if there's extra) + pInfo->spSeekByteTable.Assign(new uint32 [pInfo->nSeekTableElements], TRUE); + if (pInfo->spSeekByteTable == NULL) { return ERROR_UNDEFINED; } + + m_pIO->Read((unsigned char *) pInfo->spSeekByteTable.GetPtr(), 4 * pInfo->nSeekTableElements, &nBytesRead); + + if (APEHeader.nVersion <= 3800) + { + pInfo->spSeekBitTable.Assign(new unsigned char [pInfo->nSeekTableElements], TRUE); + if (pInfo->spSeekBitTable == NULL) { return ERROR_UNDEFINED; } + + m_pIO->Read((unsigned char *) pInfo->spSeekBitTable, pInfo->nSeekTableElements, &nBytesRead); + } + + return ERROR_SUCCESS; +} \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/APEHeader.h b/MAC_SDK/Source/MACLib/APEHeader.h new file mode 100644 index 0000000..0446cd3 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEHeader.h @@ -0,0 +1,57 @@ +#ifndef APE_HEADER_H +#define APE_HEADER_H + +/***************************************************************************************** +APE header that all APE files have in common (old and new) +*****************************************************************************************/ +struct APE_COMMON_HEADER +{ + char cID[4]; // should equal 'MAC ' + uint16 nVersion; // version number * 1000 (3.81 = 3810) +}; + +/***************************************************************************************** +APE header structure for old APE files (3.97 and earlier) +*****************************************************************************************/ +struct APE_HEADER_OLD +{ + char cID[4]; // should equal 'MAC ' + uint16 nVersion; // version number * 1000 (3.81 = 3810) + uint16 nCompressionLevel; // the compression level + uint16 nFormatFlags; // any format flags (for future use) + uint16 nChannels; // the number of channels (1 or 2) + uint32 nSampleRate; // the sample rate (typically 44100) + uint32 nHeaderBytes; // the bytes after the MAC header that compose the WAV header + uint32 nTerminatingBytes; // the bytes after that raw data (for extended info) + uint32 nTotalFrames; // the number of frames in the file + uint32 nFinalFrameBlocks; // the number of samples in the final frame +}; + +struct APE_FILE_INFO; +class CIO; + +/***************************************************************************************** +CAPEHeader - makes managing APE headers a little smoother (and the format change as of 3.98) +*****************************************************************************************/ +class CAPEHeader +{ + +public: + + CAPEHeader(CIO * pIO); + ~CAPEHeader(); + + int Analyze(APE_FILE_INFO * pInfo); + +protected: + + int AnalyzeCurrent(APE_FILE_INFO * pInfo); + int AnalyzeOld(APE_FILE_INFO * pInfo); + + int FindDescriptor(BOOL bSeek); + + CIO * m_pIO; +}; + +#endif // #ifndef APE_HEADER_H + diff --git a/MAC_SDK/Source/MACLib/APEInfo.cpp b/MAC_SDK/Source/MACLib/APEInfo.cpp new file mode 100644 index 0000000..ce3b4e9 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEInfo.cpp @@ -0,0 +1,361 @@ +/***************************************************************************************** +CAPEInfo: + -a class to make working with APE files and getting information about them simple +*****************************************************************************************/ +#include "All.h" +#include "APEInfo.h" +#include IO_HEADER_FILE +#include "APECompress.h" +#include "APEHeader.h" + +/***************************************************************************************** +Construction +*****************************************************************************************/ +CAPEInfo::CAPEInfo(int * pErrorCode, const wchar_t * pFilename, CAPETag * pTag) +{ + *pErrorCode = ERROR_SUCCESS; + CloseFile(); + + // open the file + m_spIO.Assign(new IO_CLASS_NAME); + + if (m_spIO->Open(pFilename) != 0) + { + CloseFile(); + *pErrorCode = ERROR_INVALID_INPUT_FILE; + return; + } + + // get the file information + if (GetFileInformation(TRUE) != 0) + { + CloseFile(); + *pErrorCode = ERROR_INVALID_INPUT_FILE; + return; + } + + // get the tag (do this second so that we don't do it on failure) + if (pTag == NULL) + { + // we don't want to analyze right away for non-local files + // since a single I/O object is shared, we can't tag and read at the same time (i.e. in multiple threads) + BOOL bAnalyzeNow = TRUE; + if ((wcsnicmp(pFilename, L"http://", 7) == 0) || (wcsnicmp(pFilename, L"m01p://", 7) == 0)) + bAnalyzeNow = FALSE; + + m_spAPETag.Assign(new CAPETag(m_spIO, bAnalyzeNow)); + } + else + { + m_spAPETag.Assign(pTag); + } + +} + +CAPEInfo::CAPEInfo(int * pErrorCode, CIO * pIO, CAPETag * pTag) +{ + *pErrorCode = ERROR_SUCCESS; + CloseFile(); + + m_spIO.Assign(pIO, FALSE, FALSE); + + // get the file information + if (GetFileInformation(TRUE) != 0) + { + CloseFile(); + *pErrorCode = ERROR_INVALID_INPUT_FILE; + return; + } + + // get the tag (do this second so that we don't do it on failure) + if (pTag == NULL) + m_spAPETag.Assign(new CAPETag(m_spIO, TRUE)); + else + m_spAPETag.Assign(pTag); +} + + +/***************************************************************************************** +Destruction +*****************************************************************************************/ +CAPEInfo::~CAPEInfo() +{ + CloseFile(); +} + +/***************************************************************************************** +Close the file +*****************************************************************************************/ +int CAPEInfo::CloseFile() +{ + m_spIO.Delete(); + m_APEFileInfo.spWaveHeaderData.Delete(); + m_APEFileInfo.spSeekBitTable.Delete(); + m_APEFileInfo.spSeekByteTable.Delete(); + m_APEFileInfo.spAPEDescriptor.Delete(); + + m_spAPETag.Delete(); + + // re-initialize variables + m_APEFileInfo.nSeekTableElements = 0; + m_bHasFileInformationLoaded = FALSE; + + return ERROR_SUCCESS; +} + +/***************************************************************************************** +Get the file information about the file +*****************************************************************************************/ +int CAPEInfo::GetFileInformation(BOOL bGetTagInformation) +{ + // quit if there is no simple file + if (m_spIO == NULL) { return -1; } + + // quit if the file information has already been loaded + if (m_bHasFileInformationLoaded) { return ERROR_SUCCESS; } + + // use a CAPEHeader class to help us analyze the file + CAPEHeader APEHeader(m_spIO); + int nRetVal = APEHeader.Analyze(&m_APEFileInfo); + + // update our internal state + if (nRetVal == ERROR_SUCCESS) + m_bHasFileInformationLoaded = TRUE; + + // return + return nRetVal; +} + +/***************************************************************************************** +Primary query function +*****************************************************************************************/ +int CAPEInfo::GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1, int nParam2) +{ + int nRetVal = -1; + + switch (Field) + { + case APE_INFO_FILE_VERSION: + nRetVal = m_APEFileInfo.nVersion; + break; + case APE_INFO_COMPRESSION_LEVEL: + nRetVal = m_APEFileInfo.nCompressionLevel; + break; + case APE_INFO_FORMAT_FLAGS: + nRetVal = m_APEFileInfo.nFormatFlags; + break; + case APE_INFO_SAMPLE_RATE: + nRetVal = m_APEFileInfo.nSampleRate; + break; + case APE_INFO_BITS_PER_SAMPLE: + nRetVal = m_APEFileInfo.nBitsPerSample; + break; + case APE_INFO_BYTES_PER_SAMPLE: + nRetVal = m_APEFileInfo.nBytesPerSample; + break; + case APE_INFO_CHANNELS: + nRetVal = m_APEFileInfo.nChannels; + break; + case APE_INFO_BLOCK_ALIGN: + nRetVal = m_APEFileInfo.nBlockAlign; + break; + case APE_INFO_BLOCKS_PER_FRAME: + nRetVal = m_APEFileInfo.nBlocksPerFrame; + break; + case APE_INFO_FINAL_FRAME_BLOCKS: + nRetVal = m_APEFileInfo.nFinalFrameBlocks; + break; + case APE_INFO_TOTAL_FRAMES: + nRetVal = m_APEFileInfo.nTotalFrames; + break; + case APE_INFO_WAV_HEADER_BYTES: + nRetVal = m_APEFileInfo.nWAVHeaderBytes; + break; + case APE_INFO_WAV_TERMINATING_BYTES: + nRetVal = m_APEFileInfo.nWAVTerminatingBytes; + break; + case APE_INFO_WAV_DATA_BYTES: + nRetVal = m_APEFileInfo.nWAVDataBytes; + break; + case APE_INFO_WAV_TOTAL_BYTES: + nRetVal = m_APEFileInfo.nWAVTotalBytes; + break; + case APE_INFO_APE_TOTAL_BYTES: + nRetVal = m_APEFileInfo.nAPETotalBytes; + break; + case APE_INFO_TOTAL_BLOCKS: + nRetVal = m_APEFileInfo.nTotalBlocks; + break; + case APE_INFO_LENGTH_MS: + nRetVal = m_APEFileInfo.nLengthMS; + break; + case APE_INFO_AVERAGE_BITRATE: + nRetVal = m_APEFileInfo.nAverageBitrate; + break; + case APE_INFO_FRAME_BITRATE: + { + int nFrame = nParam1; + + nRetVal = 0; + + int nFrameBytes = GetInfo(APE_INFO_FRAME_BYTES, nFrame); + int nFrameBlocks = GetInfo(APE_INFO_FRAME_BLOCKS, nFrame); + if ((nFrameBytes > 0) && (nFrameBlocks > 0) && m_APEFileInfo.nSampleRate > 0) + { + int nFrameMS = (nFrameBlocks * 1000) / m_APEFileInfo.nSampleRate; + if (nFrameMS != 0) + { + nRetVal = (nFrameBytes * 8) / nFrameMS; + } + } + break; + } + case APE_INFO_DECOMPRESSED_BITRATE: + nRetVal = m_APEFileInfo.nDecompressedBitrate; + break; + case APE_INFO_PEAK_LEVEL: + nRetVal = -1; // no longer supported + break; + case APE_INFO_SEEK_BIT: + { + int nFrame = nParam1; + if (GET_FRAMES_START_ON_BYTES_BOUNDARIES(this)) + { + nRetVal = 0; + } + else + { + if (nFrame < 0 || nFrame >= m_APEFileInfo.nTotalFrames) + nRetVal = 0; + else + nRetVal = m_APEFileInfo.spSeekBitTable[nFrame]; + } + break; + } + case APE_INFO_SEEK_BYTE: + { + int nFrame = nParam1; + if (nFrame < 0 || nFrame >= m_APEFileInfo.nTotalFrames) + nRetVal = 0; + else + nRetVal = m_APEFileInfo.spSeekByteTable[nFrame] + m_APEFileInfo.nJunkHeaderBytes; + break; + } + case APE_INFO_WAV_HEADER_DATA: + { + char * pBuffer = (char *) nParam1; + int nMaxBytes = nParam2; + + if (m_APEFileInfo.nFormatFlags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER) + { + if (sizeof(WAVE_HEADER) > nMaxBytes) + { + nRetVal = -1; + } + else + { + WAVEFORMATEX wfeFormat; GetInfo(APE_INFO_WAVEFORMATEX, (int) &wfeFormat, 0); + WAVE_HEADER WAVHeader; FillWaveHeader(&WAVHeader, m_APEFileInfo.nWAVDataBytes, &wfeFormat, + m_APEFileInfo.nWAVTerminatingBytes); + memcpy(pBuffer, &WAVHeader, sizeof(WAVE_HEADER)); + nRetVal = 0; + } + } + else + { + if (m_APEFileInfo.nWAVHeaderBytes > nMaxBytes) + { + nRetVal = -1; + } + else + { + memcpy(pBuffer, m_APEFileInfo.spWaveHeaderData, m_APEFileInfo.nWAVHeaderBytes); + nRetVal = 0; + } + } + break; + } + case APE_INFO_WAV_TERMINATING_DATA: + { + char * pBuffer = (char *) nParam1; + int nMaxBytes = nParam2; + + if (m_APEFileInfo.nWAVTerminatingBytes > nMaxBytes) + { + nRetVal = -1; + } + else + { + if (m_APEFileInfo.nWAVTerminatingBytes > 0) + { + // variables + int nOriginalFileLocation = m_spIO->GetPosition(); + unsigned int nBytesRead = 0; + + // check for a tag + m_spIO->Seek(-(m_spAPETag->GetTagBytes() + m_APEFileInfo.nWAVTerminatingBytes), FILE_END); + m_spIO->Read(pBuffer, m_APEFileInfo.nWAVTerminatingBytes, &nBytesRead); + + // restore the file pointer + m_spIO->Seek(nOriginalFileLocation, FILE_BEGIN); + } + nRetVal = 0; + } + break; + } + case APE_INFO_WAVEFORMATEX: + { + WAVEFORMATEX * pWaveFormatEx = (WAVEFORMATEX *) nParam1; + FillWaveFormatEx(pWaveFormatEx, m_APEFileInfo.nSampleRate, m_APEFileInfo.nBitsPerSample, m_APEFileInfo.nChannels); + nRetVal = 0; + break; + } + case APE_INFO_IO_SOURCE: + nRetVal = (int) m_spIO.GetPtr(); + break; + case APE_INFO_FRAME_BYTES: + { + int nFrame = nParam1; + + // bound-check the frame index + if ((nFrame < 0) || (nFrame >= m_APEFileInfo.nTotalFrames)) + { + nRetVal = -1; + } + else + { + if (nFrame != (m_APEFileInfo.nTotalFrames - 1)) + nRetVal = GetInfo(APE_INFO_SEEK_BYTE, nFrame + 1) - GetInfo(APE_INFO_SEEK_BYTE, nFrame); + else + nRetVal = m_spIO->GetSize() - m_spAPETag->GetTagBytes() - m_APEFileInfo.nWAVTerminatingBytes - GetInfo(APE_INFO_SEEK_BYTE, nFrame); + } + break; + } + case APE_INFO_FRAME_BLOCKS: + { + int nFrame = nParam1; + + // bound-check the frame index + if ((nFrame < 0) || (nFrame >= m_APEFileInfo.nTotalFrames)) + { + nRetVal = -1; + } + else + { + if (nFrame != (m_APEFileInfo.nTotalFrames - 1)) + nRetVal = m_APEFileInfo.nBlocksPerFrame; + else + nRetVal = m_APEFileInfo.nFinalFrameBlocks; + } + break; + } + case APE_INFO_TAG: + nRetVal = (int) m_spAPETag.GetPtr(); + break; + case APE_INTERNAL_INFO: + nRetVal = (int) &m_APEFileInfo; + break; + } + + return nRetVal; +} \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/APEInfo.h b/MAC_SDK/Source/MACLib/APEInfo.h new file mode 100644 index 0000000..49e5c2f --- /dev/null +++ b/MAC_SDK/Source/MACLib/APEInfo.h @@ -0,0 +1,100 @@ +/***************************************************************************************** +APEInfo.h +Copyright (C) 2000 by Matthew T. Ashland All Rights Reserved. + +Simple method for working with APE files... it encapsulates reading, writing and getting +file information. Just create a CAPEInfo class, call OpenFile(), and use the class methods +to do whatever you need... the destructor will take care of any cleanup + +Notes: + -Most all functions return 0 upon success, and some error code (other than 0) on + failure. However, all of the file functions that are wrapped from the Win32 API + return 0 on failure and some other number on success. This applies to ReadFile, + WriteFile, SetFilePointer, etc... + +WARNING: + -This class driven system for using Monkey's Audio is still in development, so + I can't make any guarantees that the classes and libraries won't change before + everything gets finalized. Use them at your own risk +*****************************************************************************************/ + +#ifndef APE_APEINFO_H +#define APE_APEINFO_H + +#include "IO.h" +#include "APETag.h" +#include "MACLib.h" + +/***************************************************************************************** +APE_FILE_INFO - structure which describes most aspects of an APE file +(used internally for speed and ease) +*****************************************************************************************/ +struct APE_FILE_INFO +{ + int nVersion; // file version number * 1000 (3.93 = 3930) + int nCompressionLevel; // the compression level + int nFormatFlags; // format flags + int nTotalFrames; // the total number frames (frames are used internally) + int nBlocksPerFrame; // the samples in a frame (frames are used internally) + int nFinalFrameBlocks; // the number of samples in the final frame + int nChannels; // audio channels + int nSampleRate; // audio samples per second + int nBitsPerSample; // audio bits per sample + int nBytesPerSample; // audio bytes per sample + int nBlockAlign; // audio block align (channels * bytes per sample) + int nWAVHeaderBytes; // header bytes of the original WAV + int nWAVDataBytes; // data bytes of the original WAV + int nWAVTerminatingBytes; // terminating bytes of the original WAV + int nWAVTotalBytes; // total bytes of the original WAV + int nAPETotalBytes; // total bytes of the APE file + int nTotalBlocks; // the total number audio blocks + int nLengthMS; // the length in milliseconds + int nAverageBitrate; // the kbps (i.e. 637 kpbs) + int nDecompressedBitrate; // the kbps of the decompressed audio (i.e. 1440 kpbs for CD audio) + int nJunkHeaderBytes; // used for ID3v2, etc. + int nSeekTableElements; // the number of elements in the seek table(s) + + CSmartPtr spSeekByteTable; // the seek table (byte) + CSmartPtr spSeekBitTable; // the seek table (bits -- legacy) + CSmartPtr spWaveHeaderData; // the pre-audio header data + CSmartPtr spAPEDescriptor; // the descriptor (only with newer files) +}; + +/***************************************************************************************** +Helper macros (sort of hacky) +*****************************************************************************************/ +#define GET_USES_CRC(APE_INFO) (((APE_INFO)->GetInfo(APE_INFO_FORMAT_FLAGS) & MAC_FORMAT_FLAG_CRC) ? TRUE : FALSE) +#define GET_FRAMES_START_ON_BYTES_BOUNDARIES(APE_INFO) (((APE_INFO)->GetInfo(APE_INFO_FILE_VERSION) > 3800) ? TRUE : FALSE) +#define GET_USES_SPECIAL_FRAMES(APE_INFO) (((APE_INFO)->GetInfo(APE_INFO_FILE_VERSION) > 3820) ? TRUE : FALSE) +#define GET_IO(APE_INFO) ((CIO *) (APE_INFO)->GetInfo(APE_INFO_IO_SOURCE)) +#define GET_TAG(APE_INFO) ((CAPETag *) (APE_INFO)->GetInfo(APE_INFO_TAG)) + +/***************************************************************************************** +CAPEInfo - use this for all work with APE files +*****************************************************************************************/ +class CAPEInfo +{ +public: + + // construction and destruction + CAPEInfo(int * pErrorCode, const wchar_t * pFilename, CAPETag * pTag = NULL); + CAPEInfo(int * pErrorCode, CIO * pIO, CAPETag * pTag = NULL); + virtual ~CAPEInfo(); + + // query for information + int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0); + +private: + + // internal functions + int GetFileInformation(BOOL bGetTagInformation = TRUE); + int CloseFile(); + + // internal variables + BOOL m_bHasFileInformationLoaded; + CSmartPtr m_spIO; + CSmartPtr m_spAPETag; + APE_FILE_INFO m_APEFileInfo; +}; + +#endif // #ifndef APE_APEINFO_H diff --git a/MAC_SDK/Source/MACLib/APELink.cpp b/MAC_SDK/Source/MACLib/APELink.cpp new file mode 100644 index 0000000..4606740 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APELink.cpp @@ -0,0 +1,120 @@ +#include "All.h" +#include "APELink.h" +#include "CharacterHelper.h" +#include IO_HEADER_FILE + +#define APE_LINK_HEADER "[Monkey's Audio Image Link File]" +#define APE_LINK_IMAGE_FILE_TAG "Image File=" +#define APE_LINK_START_BLOCK_TAG "Start Block=" +#define APE_LINK_FINISH_BLOCK_TAG "Finish Block=" + +CAPELink::CAPELink(const str_utf16 * pFilename) +{ + // empty + m_bIsLinkFile = FALSE; + m_nStartBlock = 0; + m_nFinishBlock = 0; + m_cImageFilename[0] = 0; + + // open the file + IO_CLASS_NAME ioLinkFile; + if (ioLinkFile.Open(pFilename) == ERROR_SUCCESS) + { + // create a buffer + CSmartPtr spBuffer(new char [1024], TRUE); + + // fill the buffer from the file and null terminate it + unsigned int nBytesRead = 0; + ioLinkFile.Read(spBuffer.GetPtr(), 1023, &nBytesRead); + spBuffer[nBytesRead] = 0; + + // call the other constructor (uses a buffer instead of opening the file) + ParseData(spBuffer, pFilename); + } +} + +CAPELink::CAPELink(const char * pData, const str_utf16 * pFilename) +{ + ParseData(pData, pFilename); +} + +CAPELink::~CAPELink() +{ +} + +void CAPELink::ParseData(const char * pData, const str_utf16 * pFilename) +{ + // empty + m_bIsLinkFile = FALSE; + m_nStartBlock = 0; + m_nFinishBlock = 0; + m_cImageFilename[0] = 0; + + if (pData != NULL) + { + // parse out the information + char * pHeader = (char*)strstr(pData, APE_LINK_HEADER); + char * pImageFile = (char*)strstr(pData, APE_LINK_IMAGE_FILE_TAG); + char * pStartBlock = (char*)strstr(pData, APE_LINK_START_BLOCK_TAG); + char * pFinishBlock = (char*)strstr(pData, APE_LINK_FINISH_BLOCK_TAG); + + if (pHeader && pImageFile && pStartBlock && pFinishBlock) + { + if ((_strnicmp(pHeader, APE_LINK_HEADER, strlen(APE_LINK_HEADER)) == 0) && + (_strnicmp(pImageFile, APE_LINK_IMAGE_FILE_TAG, strlen(APE_LINK_IMAGE_FILE_TAG)) == 0) && + (_strnicmp(pStartBlock, APE_LINK_START_BLOCK_TAG, strlen(APE_LINK_START_BLOCK_TAG)) == 0) && + (_strnicmp(pFinishBlock, APE_LINK_FINISH_BLOCK_TAG, strlen(APE_LINK_FINISH_BLOCK_TAG)) == 0)) + { + // get the start and finish blocks + m_nStartBlock = atoi(&pStartBlock[strlen(APE_LINK_START_BLOCK_TAG)]); + m_nFinishBlock = atoi(&pFinishBlock[strlen(APE_LINK_FINISH_BLOCK_TAG)]); + + // get the path + char cImageFile[MAX_PATH + 1]; int nIndex = 0; + char * pImageCharacter = &pImageFile[strlen(APE_LINK_IMAGE_FILE_TAG)]; + while ((*pImageCharacter != 0) && (*pImageCharacter != '\r') && (*pImageCharacter != '\n')) + cImageFile[nIndex++] = *pImageCharacter++; + cImageFile[nIndex] = 0; + + CSmartPtr spImageFileUTF16(GetUTF16FromUTF8((UCHAR *) cImageFile), TRUE); + + // process the path + if (wcsrchr(spImageFileUTF16, '\\') == NULL) + { + str_utf16 cImagePath[MAX_PATH + 1]; + wcscpy(cImagePath, pFilename); + wcscpy(wcsrchr(cImagePath, '\\') + 1, spImageFileUTF16); + wcscpy(m_cImageFilename, cImagePath); + } + else + { + wcscpy(m_cImageFilename, spImageFileUTF16); + } + + // this is a valid link file + m_bIsLinkFile = TRUE; + } + } + } +} + +int CAPELink::GetStartBlock() +{ + return m_nStartBlock; +} + +int CAPELink::GetFinishBlock() +{ + return m_nFinishBlock; +} + +const str_utf16 * CAPELink::GetImageFilename() +{ + return m_cImageFilename; +} + +BOOL CAPELink::GetIsLinkFile() +{ + return m_bIsLinkFile; +} + diff --git a/MAC_SDK/Source/MACLib/APELink.h b/MAC_SDK/Source/MACLib/APELink.h new file mode 100644 index 0000000..390b963 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APELink.h @@ -0,0 +1,30 @@ +#ifndef APE_APELINK_H +#define APE_APELINK_H + +#include "IO.h" +#include "APEInfo.h" + +class CAPELink +{ +public: + + CAPELink(const str_utf16 * pFilename); + CAPELink(const char * pData, const str_utf16 * pFilename); + ~CAPELink(); + + BOOL GetIsLinkFile(); + int GetStartBlock(); + int GetFinishBlock(); + const wchar_t * GetImageFilename(); + +protected: + + BOOL m_bIsLinkFile; + int m_nStartBlock; + int m_nFinishBlock; + str_utf16 m_cImageFilename[MAX_PATH]; + + void ParseData(const char * pData, const str_utf16 * pFilename); +}; + +#endif // #ifndef APE_APELINK_H diff --git a/MAC_SDK/Source/MACLib/APESimple.cpp b/MAC_SDK/Source/MACLib/APESimple.cpp new file mode 100644 index 0000000..a757218 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APESimple.cpp @@ -0,0 +1,426 @@ +#include "All.h" +#include "APEInfo.h" +#include "APECompress.h" +#include "APEDecompress.h" +#include "WAVInputSource.h" +#include IO_HEADER_FILE +#include "MACProgressHelper.h" +#include "GlobalFunctions.h" +#include "MD5.h" +#include "CharacterHelper.h" + +#define UNMAC_DECODER_OUTPUT_NONE 0 +#define UNMAC_DECODER_OUTPUT_WAV 1 +#define UNMAC_DECODER_OUTPUT_APE 2 + +#define BLOCKS_PER_DECODE 9216 + +int DecompressCore(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nOutputMode, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + +/***************************************************************************************** +ANSI wrappers +*****************************************************************************************/ +int __stdcall CompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + CSmartPtr spInputFile(GetUTF16FromANSI(pInputFilename), TRUE); + CSmartPtr spOutputFile(GetUTF16FromANSI(pOutputFilename), TRUE); + return CompressFileW(spInputFile, spOutputFile, nCompressionLevel, pPercentageDone, ProgressCallback, pKillFlag); +} + +int __stdcall DecompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + CSmartPtr spInputFile(GetUTF16FromANSI(pInputFilename), TRUE); + CSmartPtr spOutputFile(GetUTF16FromANSI(pOutputFilename), TRUE); + return DecompressFileW(spInputFile, pOutputFilename ? spOutputFile : NULL, pPercentageDone, ProgressCallback, pKillFlag); +} + +int __stdcall ConvertFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + CSmartPtr spInputFile(GetUTF16FromANSI(pInputFilename), TRUE); + CSmartPtr spOutputFile(GetUTF16FromANSI(pOutputFilename), TRUE); + return ConvertFileW(spInputFile, spOutputFile, nCompressionLevel, pPercentageDone, ProgressCallback, pKillFlag); +} + +int __stdcall VerifyFile(const str_ansi * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag, BOOL bQuickVerifyIfPossible) +{ + CSmartPtr spInputFile(GetUTF16FromANSI(pInputFilename), TRUE); + return VerifyFileW(spInputFile, pPercentageDone, ProgressCallback, pKillFlag, FALSE); +} + +/***************************************************************************************** +Compress file +*****************************************************************************************/ +int __stdcall CompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + // declare the variables + int nFunctionRetVal = ERROR_SUCCESS; + WAVEFORMATEX WaveFormatEx; + CSmartPtr spMACProgressHelper; + CSmartPtr spBuffer; + CSmartPtr spAPECompress; + + try + { + // create the input source + int nRetVal = ERROR_UNDEFINED; + int nAudioBlocks = 0; int nHeaderBytes = 0; int nTerminatingBytes = 0; + CSmartPtr spInputSource(CreateInputSource(pInputFilename, &WaveFormatEx, &nAudioBlocks, + &nHeaderBytes, &nTerminatingBytes, &nRetVal)); + + if ((spInputSource == NULL) || (nRetVal != ERROR_SUCCESS)) + throw nRetVal; + + // create the compressor + spAPECompress.Assign(CreateIAPECompress()); + if (spAPECompress == NULL) throw ERROR_UNDEFINED; + + // figure the audio bytes + int nAudioBytes = nAudioBlocks * WaveFormatEx.nBlockAlign; + + // start the encoder + if (nHeaderBytes > 0) spBuffer.Assign(new unsigned char [nHeaderBytes], TRUE); + THROW_ON_ERROR(spInputSource->GetHeaderData(spBuffer.GetPtr())) + THROW_ON_ERROR(spAPECompress->Start(pOutputFilename, &WaveFormatEx, nAudioBytes, + nCompressionLevel, spBuffer.GetPtr(), nHeaderBytes)); + + spBuffer.Delete(); + + // set-up the progress + spMACProgressHelper.Assign(new CMACProgressHelper(nAudioBytes, pPercentageDone, ProgressCallback, pKillFlag)); + + // master loop + int nBytesLeft = nAudioBytes; + + while (nBytesLeft > 0) + { + int nBytesAdded = 0; + THROW_ON_ERROR(spAPECompress->AddDataFromInputSource(spInputSource.GetPtr(), nBytesLeft, &nBytesAdded)) + + nBytesLeft -= nBytesAdded; + + // update the progress + spMACProgressHelper->UpdateProgress(nAudioBytes - nBytesLeft); + + // process the kill flag + if (spMACProgressHelper->ProcessKillFlag(TRUE) != ERROR_SUCCESS) + throw(ERROR_USER_STOPPED_PROCESSING); + } + + // finalize the file + if (nTerminatingBytes > 0) spBuffer.Assign(new unsigned char [nTerminatingBytes], TRUE); + THROW_ON_ERROR(spInputSource->GetTerminatingData(spBuffer.GetPtr())); + THROW_ON_ERROR(spAPECompress->Finish(spBuffer.GetPtr(), nTerminatingBytes, nTerminatingBytes)) + + // update the progress to 100% + spMACProgressHelper->UpdateProgressComplete(); + } + catch(int nErrorCode) + { + nFunctionRetVal = (nErrorCode == 0) ? ERROR_UNDEFINED : nErrorCode; + } + catch(...) + { + nFunctionRetVal = ERROR_UNDEFINED; + } + + // kill the compressor if we failed + if ((nFunctionRetVal != 0) && (spAPECompress != NULL)) + spAPECompress->Kill(); + + // return + return nFunctionRetVal; +} + + +/***************************************************************************************** +Verify file +*****************************************************************************************/ +int __stdcall VerifyFileW(const str_utf16 * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag, BOOL bQuickVerifyIfPossible) +{ + // error check the function parameters + if (pInputFilename == NULL) + { + return ERROR_INVALID_FUNCTION_PARAMETER; + } + + + // return value + int nRetVal = ERROR_UNDEFINED; + + // see if we can quick verify + if (bQuickVerifyIfPossible) + { + CSmartPtr spAPEDecompress; + try + { + int nFunctionRetVal = ERROR_SUCCESS; + + spAPEDecompress.Assign(CreateIAPEDecompress(pInputFilename, &nFunctionRetVal)); + if (spAPEDecompress == NULL || nFunctionRetVal != ERROR_SUCCESS) throw(nFunctionRetVal); + + APE_FILE_INFO * pInfo = (APE_FILE_INFO *) spAPEDecompress->GetInfo(APE_INTERNAL_INFO); + if ((pInfo->nVersion < 3980) || (pInfo->spAPEDescriptor == NULL)) + throw(ERROR_UPSUPPORTED_FILE_VERSION); + } + catch(...) + { + bQuickVerifyIfPossible = FALSE; + } + } + + // if we can and should quick verify, then do it + if (bQuickVerifyIfPossible) + { + // variable declares + int nFunctionRetVal = ERROR_SUCCESS; + unsigned int nBytesRead = 0; + CSmartPtr spAPEDecompress; + + // run the quick verify + try + { + spAPEDecompress.Assign(CreateIAPEDecompress(pInputFilename, &nFunctionRetVal)); + if (spAPEDecompress == NULL || nFunctionRetVal != ERROR_SUCCESS) throw(nFunctionRetVal); + + CMD5Helper MD5Helper; + + CIO * pIO = GET_IO(spAPEDecompress); + APE_FILE_INFO * pInfo = (APE_FILE_INFO *) spAPEDecompress->GetInfo(APE_INTERNAL_INFO); + + if ((pInfo->nVersion < 3980) || (pInfo->spAPEDescriptor == NULL)) + throw(ERROR_UPSUPPORTED_FILE_VERSION); + + int nHead = pInfo->nJunkHeaderBytes + pInfo->spAPEDescriptor->nDescriptorBytes; + int nStart = nHead + pInfo->spAPEDescriptor->nHeaderBytes + pInfo->spAPEDescriptor->nSeekTableBytes; + + pIO->Seek(nHead, FILE_BEGIN); + int nHeadBytes = nStart - nHead; + CSmartPtr spHeadBuffer(new unsigned char [nHeadBytes], TRUE); + if ((pIO->Read(spHeadBuffer, nHeadBytes, &nBytesRead) != ERROR_SUCCESS) || (nHeadBytes != int(nBytesRead))) + throw(ERROR_IO_READ); + + int nBytesLeft = pInfo->spAPEDescriptor->nHeaderDataBytes + pInfo->spAPEDescriptor->nAPEFrameDataBytes + pInfo->spAPEDescriptor->nTerminatingDataBytes; + CSmartPtr spBuffer(new unsigned char [16384], TRUE); + nBytesRead = 1; + while ((nBytesLeft > 0) && (nBytesRead > 0)) + { + int nBytesToRead = min(16384, nBytesLeft); + if (pIO->Read(spBuffer, nBytesToRead, &nBytesRead) != ERROR_SUCCESS) + throw(ERROR_IO_READ); + + MD5Helper.AddData(spBuffer, nBytesRead); + nBytesLeft -= nBytesRead; + } + + if (nBytesLeft != 0) + throw(ERROR_IO_READ); + + MD5Helper.AddData(spHeadBuffer, nHeadBytes); + + unsigned char cResult[16]; + MD5Helper.GetResult(cResult); + + if (memcmp(cResult, pInfo->spAPEDescriptor->cFileMD5, 16) != 0) + nFunctionRetVal = ERROR_INVALID_CHECKSUM; + + } + catch(int nErrorCode) + { + nFunctionRetVal = (nErrorCode == 0) ? ERROR_UNDEFINED : nErrorCode; + } + catch(...) + { + nFunctionRetVal = ERROR_UNDEFINED; + } + + // return value + nRetVal = nFunctionRetVal; + } + else + { + nRetVal = DecompressCore(pInputFilename, NULL, UNMAC_DECODER_OUTPUT_NONE, -1, pPercentageDone, ProgressCallback, pKillFlag); + } + + + return nRetVal; +} + +/***************************************************************************************** +Decompress file +*****************************************************************************************/ +int __stdcall DecompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + if (pOutputFilename == NULL) + return VerifyFileW(pInputFilename, pPercentageDone, ProgressCallback, pKillFlag); + else + return DecompressCore(pInputFilename, pOutputFilename, UNMAC_DECODER_OUTPUT_WAV, -1, pPercentageDone, ProgressCallback, pKillFlag); +} + +/***************************************************************************************** +Convert file +*****************************************************************************************/ +int __stdcall ConvertFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + return DecompressCore(pInputFilename, pOutputFilename, UNMAC_DECODER_OUTPUT_APE, nCompressionLevel, pPercentageDone, ProgressCallback, pKillFlag); +} + +/***************************************************************************************** +Decompress a file using the specified output method +*****************************************************************************************/ +int DecompressCore(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nOutputMode, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + // error check the function parameters + if (pInputFilename == NULL) + { + return ERROR_INVALID_FUNCTION_PARAMETER; + } + + // variable declares + int nFunctionRetVal = ERROR_SUCCESS; + CSmartPtr spioOutput; + CSmartPtr spAPECompress; + CSmartPtr spAPEDecompress; + CSmartPtr spTempBuffer; + CSmartPtr spMACProgressHelper; + WAVEFORMATEX wfeInput; + + try + { + // create the decoder + spAPEDecompress.Assign(CreateIAPEDecompress(pInputFilename, &nFunctionRetVal)); + if (spAPEDecompress == NULL || nFunctionRetVal != ERROR_SUCCESS) throw(nFunctionRetVal); + + // get the input format + THROW_ON_ERROR(spAPEDecompress->GetInfo(APE_INFO_WAVEFORMATEX, (int) &wfeInput)) + + // allocate space for the header + spTempBuffer.Assign(new unsigned char [spAPEDecompress->GetInfo(APE_INFO_WAV_HEADER_BYTES)], TRUE); + if (spTempBuffer == NULL) throw(ERROR_INSUFFICIENT_MEMORY); + + // get the header + THROW_ON_ERROR(spAPEDecompress->GetInfo(APE_INFO_WAV_HEADER_DATA, (int) spTempBuffer.GetPtr(), spAPEDecompress->GetInfo(APE_INFO_WAV_HEADER_BYTES))); + + // initialize the output + if (nOutputMode == UNMAC_DECODER_OUTPUT_WAV) + { + // create the file + spioOutput.Assign(new IO_CLASS_NAME); THROW_ON_ERROR(spioOutput->Create(pOutputFilename)) + + // output the header + THROW_ON_ERROR(WriteSafe(spioOutput, spTempBuffer, spAPEDecompress->GetInfo(APE_INFO_WAV_HEADER_BYTES))); + } + else if (nOutputMode == UNMAC_DECODER_OUTPUT_APE) + { + // quit if there is nothing to do + if (spAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) == MAC_VERSION_NUMBER && spAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL) == nCompressionLevel) + throw(ERROR_SKIPPED); + + // create and start the compressor + spAPECompress.Assign(CreateIAPECompress()); + THROW_ON_ERROR(spAPECompress->Start(pOutputFilename, &wfeInput, spAPEDecompress->GetInfo(APE_DECOMPRESS_TOTAL_BLOCKS) * spAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN), + nCompressionLevel, spTempBuffer, spAPEDecompress->GetInfo(APE_INFO_WAV_HEADER_BYTES))) + } + + // allocate space for decompression + spTempBuffer.Assign(new unsigned char [spAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN) * BLOCKS_PER_DECODE], TRUE); + if (spTempBuffer == NULL) throw(ERROR_INSUFFICIENT_MEMORY); + + int nBlocksLeft = spAPEDecompress->GetInfo(APE_DECOMPRESS_TOTAL_BLOCKS); + + // create the progress helper + spMACProgressHelper.Assign(new CMACProgressHelper(nBlocksLeft / BLOCKS_PER_DECODE, pPercentageDone, ProgressCallback, pKillFlag)); + + // main decoding loop + while (nBlocksLeft > 0) + { + // decode data + int nBlocksDecoded = -1; + int nRetVal = spAPEDecompress->GetData((char *) spTempBuffer.GetPtr(), BLOCKS_PER_DECODE, &nBlocksDecoded); + if (nRetVal != ERROR_SUCCESS) + throw(ERROR_INVALID_CHECKSUM); + + // handle the output + if (nOutputMode == UNMAC_DECODER_OUTPUT_WAV) + { + unsigned int nBytesToWrite = (nBlocksDecoded * spAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN)); + unsigned int nBytesWritten = 0; + int nRetVal = spioOutput->Write(spTempBuffer, nBytesToWrite, &nBytesWritten); + if ((nRetVal != 0) || (nBytesToWrite != nBytesWritten)) + throw(ERROR_IO_WRITE); + } + else if (nOutputMode == UNMAC_DECODER_OUTPUT_APE) + { + THROW_ON_ERROR(spAPECompress->AddData(spTempBuffer, nBlocksDecoded * spAPEDecompress->GetInfo(APE_INFO_BLOCK_ALIGN))) + } + + // update amount remaining + nBlocksLeft -= nBlocksDecoded; + + // update progress and kill flag + spMACProgressHelper->UpdateProgress(); + if (spMACProgressHelper->ProcessKillFlag(TRUE) != 0) + throw(ERROR_USER_STOPPED_PROCESSING); + } + + // terminate the output + if (nOutputMode == UNMAC_DECODER_OUTPUT_WAV) + { + // write any terminating WAV data + if (spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES) > 0) + { + spTempBuffer.Assign(new unsigned char[spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES)], TRUE); + if (spTempBuffer == NULL) throw(ERROR_INSUFFICIENT_MEMORY); + THROW_ON_ERROR(spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_DATA, (int) spTempBuffer.GetPtr(), spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES))) + + unsigned int nBytesToWrite = spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES); + unsigned int nBytesWritten = 0; + int nRetVal = spioOutput->Write(spTempBuffer, nBytesToWrite, &nBytesWritten); + if ((nRetVal != 0) || (nBytesToWrite != nBytesWritten)) + throw(ERROR_IO_WRITE); + } + } + else if (nOutputMode == UNMAC_DECODER_OUTPUT_APE) + { + // write the WAV data and any tag + int nTagBytes = GET_TAG(spAPEDecompress)->GetTagBytes(); + BOOL bHasTag = (nTagBytes > 0); + int nTerminatingBytes = nTagBytes; + nTerminatingBytes += spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES); + + if (nTerminatingBytes > 0) + { + spTempBuffer.Assign(new unsigned char[nTerminatingBytes], TRUE); + if (spTempBuffer == NULL) throw(ERROR_INSUFFICIENT_MEMORY); + + THROW_ON_ERROR(spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_DATA, (int) spTempBuffer.GetPtr(), nTerminatingBytes)) + + if (bHasTag) + { + unsigned int nBytesRead = 0; + THROW_ON_ERROR(GET_IO(spAPEDecompress)->Seek(-(nTagBytes), FILE_END)) + THROW_ON_ERROR(GET_IO(spAPEDecompress)->Read(&spTempBuffer[spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES)], nTagBytes, &nBytesRead)) + } + + THROW_ON_ERROR(spAPECompress->Finish(spTempBuffer, nTerminatingBytes, spAPEDecompress->GetInfo(APE_INFO_WAV_TERMINATING_BYTES))); + } + else + { + THROW_ON_ERROR(spAPECompress->Finish(NULL, 0, 0)); + } + } + + // fire the "complete" progress notification + spMACProgressHelper->UpdateProgressComplete(); + } + catch(int nErrorCode) + { + nFunctionRetVal = (nErrorCode == 0) ? ERROR_UNDEFINED : nErrorCode; + } + catch(...) + { + nFunctionRetVal = ERROR_UNDEFINED; + } + + // return + return nFunctionRetVal; +} diff --git a/MAC_SDK/Source/MACLib/APETag.cpp b/MAC_SDK/Source/MACLib/APETag.cpp new file mode 100644 index 0000000..db9a1f1 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APETag.cpp @@ -0,0 +1,743 @@ +#include "All.h" +#include "ID3Genres.h" +#include "APETag.h" +#include "CharacterHelper.h" +#include "IO.h" +#include IO_HEADER_FILE + +/***************************************************************************************** +CAPETagField +*****************************************************************************************/ + +CAPETagField::CAPETagField(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes, int nFlags) +{ + // field name + m_spFieldNameUTF16.Assign(new str_utf16 [wcslen(pFieldName) + 1], TRUE); + memcpy(m_spFieldNameUTF16, pFieldName, (wcslen(pFieldName) + 1) * sizeof(str_utf16)); + + // data (we'll always allocate two extra bytes and memset to 0 so we're safely NULL terminated) + m_nFieldValueBytes = max(nFieldBytes, 0); + m_spFieldValue.Assign(new char [m_nFieldValueBytes + 2], TRUE); + memset(m_spFieldValue, 0, m_nFieldValueBytes + 2); + if (m_nFieldValueBytes > 0) + memcpy(m_spFieldValue, pFieldValue, m_nFieldValueBytes); + + // flags + m_nFieldFlags = nFlags; +} + +CAPETagField::~CAPETagField() +{ +} + +int CAPETagField::GetFieldSize() +{ + CSmartPtr spFieldNameANSI(GetANSIFromUTF16(m_spFieldNameUTF16), TRUE); + return (strlen(spFieldNameANSI) + 1) + m_nFieldValueBytes + 4 + 4; +} + +const str_utf16 * CAPETagField::GetFieldName() +{ + return m_spFieldNameUTF16; +} + +const char * CAPETagField::GetFieldValue() +{ + return m_spFieldValue; +} + +int CAPETagField::GetFieldValueSize() +{ + return m_nFieldValueBytes; +} + +int CAPETagField::GetFieldFlags() +{ + return m_nFieldFlags; +} + +int CAPETagField::SaveField(char * pBuffer) +{ + *((int *) pBuffer) = m_nFieldValueBytes; + pBuffer += 4; + *((int *) pBuffer) = m_nFieldFlags; + pBuffer += 4; + + CSmartPtr spFieldNameANSI((char *) GetANSIFromUTF16(m_spFieldNameUTF16), TRUE); + strcpy(pBuffer, spFieldNameANSI); + pBuffer += strlen(spFieldNameANSI) + 1; + + memcpy(pBuffer, m_spFieldValue, m_nFieldValueBytes); + + return GetFieldSize(); +} + + +/***************************************************************************************** +CAPETag +*****************************************************************************************/ + +CAPETag::CAPETag(const str_utf16 * pFilename, BOOL bAnalyze) +{ + m_spIO.Assign(new IO_CLASS_NAME); + m_spIO->Open(pFilename); + + m_bAnalyzed = FALSE; + m_nFields = 0; + m_nTagBytes = 0; + m_bIgnoreReadOnly = FALSE; + + if (bAnalyze) + { + Analyze(); + } +} + +CAPETag::CAPETag(CIO * pIO, BOOL bAnalyze) +{ + m_spIO.Assign(pIO, FALSE, FALSE); // we don't own the IO source + m_bAnalyzed = FALSE; + m_nFields = 0; + m_nTagBytes = 0; + + if (bAnalyze) + { + Analyze(); + } +} + +CAPETag::~CAPETag() +{ + ClearFields(); +} + +int CAPETag::GetTagBytes() +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + + return m_nTagBytes; +} + +CAPETagField * CAPETag::GetTagField(int nIndex) +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + + if ((nIndex >= 0) && (nIndex < m_nFields)) + { + return m_aryFields[nIndex]; + } + + return NULL; +} + +int CAPETag::Save(BOOL bUseOldID3) +{ + if (Remove(FALSE) != ERROR_SUCCESS) + return -1; + + if (m_nFields == 0) { return ERROR_SUCCESS; } + + int nRetVal = -1; + + if (bUseOldID3 == FALSE) + { + int z = 0; + + // calculate the size of the whole tag + int nFieldBytes = 0; + for (z = 0; z < m_nFields; z++) + nFieldBytes += m_aryFields[z]->GetFieldSize(); + + // sort the fields + SortFields(); + + // build the footer + APE_TAG_FOOTER APETagFooter(m_nFields, nFieldBytes); + + // make a buffer for the tag + int nTotalTagBytes = APETagFooter.GetTotalTagBytes(); + CSmartPtr spRawTag(new char [nTotalTagBytes], TRUE); + + // save the fields + int nLocation = 0; + for (z = 0; z < m_nFields; z++) + nLocation += m_aryFields[z]->SaveField(&spRawTag[nLocation]); + + // add the footer to the buffer + memcpy(&spRawTag[nLocation], &APETagFooter, APE_TAG_FOOTER_BYTES); + nLocation += APE_TAG_FOOTER_BYTES; + + // dump the tag to the I/O source + nRetVal = WriteBufferToEndOfIO(spRawTag, nTotalTagBytes); + } + else + { + // build the ID3 tag + ID3_TAG ID3Tag; + CreateID3Tag(&ID3Tag); + nRetVal = WriteBufferToEndOfIO(&ID3Tag, sizeof(ID3_TAG)); + } + + return nRetVal; +} + +int CAPETag::WriteBufferToEndOfIO(void * pBuffer, int nBytes) +{ + int nOriginalPosition = m_spIO->GetPosition(); + + unsigned int nBytesWritten = 0; + m_spIO->Seek(0, FILE_END); + + int nRetVal = m_spIO->Write(pBuffer, nBytes, &nBytesWritten); + + m_spIO->Seek(nOriginalPosition, FILE_BEGIN); + + return nRetVal; +} + +int CAPETag::Analyze() +{ + // clean-up + ID3_TAG ID3Tag; + ClearFields(); + m_nTagBytes = 0; + + m_bAnalyzed = TRUE; + + // store the original location + int nOriginalPosition = m_spIO->GetPosition(); + + // check for a tag + unsigned int nBytesRead; + int nRetVal; + m_bHasID3Tag = FALSE; + m_bHasAPETag = FALSE; + m_nAPETagVersion = -1; + m_spIO->Seek(-ID3_TAG_BYTES, FILE_END); + nRetVal = m_spIO->Read((unsigned char *) &ID3Tag, sizeof(ID3_TAG), &nBytesRead); + + if ((nBytesRead == sizeof(ID3_TAG)) && (nRetVal == 0)) + { + if (ID3Tag.Header[0] == 'T' && ID3Tag.Header[1] == 'A' && ID3Tag.Header[2] == 'G') + { + m_bHasID3Tag = TRUE; + m_nTagBytes += ID3_TAG_BYTES; + } + } + + // set the fields + if (m_bHasID3Tag) + { + SetFieldID3String(APE_TAG_FIELD_ARTIST, ID3Tag.Artist, 30); + SetFieldID3String(APE_TAG_FIELD_ALBUM, ID3Tag.Album, 30); + SetFieldID3String(APE_TAG_FIELD_TITLE, ID3Tag.Title, 30); + SetFieldID3String(APE_TAG_FIELD_COMMENT, ID3Tag.Comment, 28); + SetFieldID3String(APE_TAG_FIELD_YEAR, ID3Tag.Year, 4); + + char cTemp[16]; sprintf(cTemp, "%d", ID3Tag.Track); + SetFieldString(APE_TAG_FIELD_TRACK, cTemp, FALSE); + + if ((ID3Tag.Genre == GENRE_UNDEFINED) || (ID3Tag.Genre >= GENRE_COUNT)) + SetFieldString(APE_TAG_FIELD_GENRE, APE_TAG_GENRE_UNDEFINED); + else + SetFieldString(APE_TAG_FIELD_GENRE, g_ID3Genre[ID3Tag.Genre]); + } + + // try loading the APE tag + if (m_bHasID3Tag == FALSE) + { + APE_TAG_FOOTER APETagFooter; + m_spIO->Seek(-int(APE_TAG_FOOTER_BYTES), FILE_END); + nRetVal = m_spIO->Read((unsigned char *) &APETagFooter, APE_TAG_FOOTER_BYTES, &nBytesRead); + if ((nBytesRead == APE_TAG_FOOTER_BYTES) && (nRetVal == 0)) + { + if (APETagFooter.GetIsValid(FALSE)) + { + m_bHasAPETag = TRUE; + m_nAPETagVersion = APETagFooter.GetVersion(); + + int nRawFieldBytes = APETagFooter.GetFieldBytes(); + m_nTagBytes += APETagFooter.GetTotalTagBytes(); + + CSmartPtr spRawTag(new char [nRawFieldBytes], TRUE); + m_spIO->Seek(-(APETagFooter.GetTotalTagBytes() - APETagFooter.GetFieldsOffset()), FILE_END); + nRetVal = m_spIO->Read((unsigned char *) spRawTag.GetPtr(), nRawFieldBytes, &nBytesRead); + + if ((nRetVal == 0) && (nRawFieldBytes == int(nBytesRead))) + { + // parse out the raw fields + int nLocation = 0; + for (int z = 0; z < APETagFooter.GetNumberFields(); z++) + { + int nMaximumFieldBytes = nRawFieldBytes - nLocation; + + int nBytes = 0; + if (LoadField(&spRawTag[nLocation], nMaximumFieldBytes, &nBytes) != ERROR_SUCCESS) + { + // if LoadField(...) fails, it means that the tag is corrupt (accidently or intentionally) + // we'll just bail out -- leaving the fields we've already set + break; + } + nLocation += nBytes; + } + } + } + } + } + + // restore the file pointer + m_spIO->Seek(nOriginalPosition, FILE_BEGIN); + + return ERROR_SUCCESS; +} + +int CAPETag::ClearFields() +{ + for (int z = 0; z < m_nFields; z++) + { + SAFE_DELETE(m_aryFields[z]) + } + + m_nFields = 0; + + return ERROR_SUCCESS; +} + +int CAPETag::GetTagFieldIndex(const str_utf16 * pFieldName) +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + if (pFieldName == NULL) return -1; + + for (int z = 0; z < m_nFields; z++) + { + if (wcsicmp(m_aryFields[z]->GetFieldName(), pFieldName) == 0) + return z; + } + + return -1; + +} + +CAPETagField * CAPETag::GetTagField(const str_utf16 * pFieldName) +{ + int nIndex = GetTagFieldIndex(pFieldName); + return (nIndex != -1) ? m_aryFields[nIndex] : NULL; +} + +int CAPETag::GetFieldString(const str_utf16 * pFieldName, str_ansi * pBuffer, int * pBufferCharacters, BOOL bUTF8Encode) +{ + int nOriginalCharacters = *pBufferCharacters; + str_utf16 * pUTF16 = new str_utf16 [*pBufferCharacters + 1]; + pUTF16[0] = 0; + + int nRetVal = GetFieldString(pFieldName, pUTF16, pBufferCharacters); + if (nRetVal == ERROR_SUCCESS) + { + CSmartPtr spANSI(bUTF8Encode ? (str_ansi *) GetUTF8FromUTF16(pUTF16) : GetANSIFromUTF16(pUTF16), TRUE); + if (int(strlen(spANSI)) > nOriginalCharacters) + { + memset(pBuffer, 0, nOriginalCharacters * sizeof(str_ansi)); + *pBufferCharacters = 0; + nRetVal = ERROR_UNDEFINED; + } + else + { + strcpy(pBuffer, spANSI); + *pBufferCharacters = strlen(spANSI); + } + } + + delete [] pUTF16; + + return nRetVal; +} + + +int CAPETag::GetFieldString(const str_utf16 * pFieldName, str_utf16 * pBuffer, int * pBufferCharacters) +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + + int nRetVal = ERROR_UNDEFINED; + + if (*pBufferCharacters > 0) + { + CAPETagField * pAPETagField = GetTagField(pFieldName); + if (pAPETagField == NULL) + { + // the field doesn't exist -- return an empty string + memset(pBuffer, 0, *pBufferCharacters * sizeof(str_utf16)); + *pBufferCharacters = 0; + } + else if (pAPETagField->GetIsUTF8Text() || (m_nAPETagVersion < 2000)) + { + // get the value in UTF-16 format + CSmartPtr spUTF16; + if (m_nAPETagVersion >= 2000) + spUTF16.Assign(GetUTF16FromUTF8((str_utf8 *) pAPETagField->GetFieldValue()), TRUE); + else + spUTF16.Assign(GetUTF16FromANSI(pAPETagField->GetFieldValue()), TRUE); + + // get the number of characters + int nCharacters = (wcslen(spUTF16) + 1); + if (nCharacters > *pBufferCharacters) + { + // we'll fail here, because it's not clear what would get returned (null termination, size, etc.) + // and we really don't want to cause buffer overruns on the client side + *pBufferCharacters = nCharacters; + } + else + { + // just copy in + *pBufferCharacters = nCharacters; + memcpy(pBuffer, spUTF16.GetPtr(), *pBufferCharacters * sizeof(str_utf16)); + nRetVal = ERROR_SUCCESS; + } + } + else + { + // memset the whole buffer to NULL (so everything left over is NULL terminated) + memset(pBuffer, 0, *pBufferCharacters * sizeof(str_utf16)); + + // do a binary dump (need to convert from wchar's to bytes) + int nBufferBytes = (*pBufferCharacters - 1) * sizeof(str_utf16); + nRetVal = GetFieldBinary(pFieldName, pBuffer, &nBufferBytes); + *pBufferCharacters = (nBufferBytes / sizeof(str_utf16)) + 1; + } + } + + return nRetVal; +} + +int CAPETag::GetFieldBinary(const str_utf16 * pFieldName, void * pBuffer, int * pBufferBytes) +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + + int nRetVal = ERROR_UNDEFINED; + + if (*pBufferBytes > 0) + { + CAPETagField * pAPETagField = GetTagField(pFieldName); + if (pAPETagField == NULL) + { + memset(pBuffer, 0, *pBufferBytes); + *pBufferBytes = 0; + } + else + { + if (pAPETagField->GetFieldValueSize() > *pBufferBytes) + { + // we'll fail here, because partial data may be worse than no data + memset(pBuffer, 0, *pBufferBytes); + *pBufferBytes = pAPETagField->GetFieldValueSize(); + } + else + { + // memcpy + *pBufferBytes = pAPETagField->GetFieldValueSize(); + memcpy(pBuffer, pAPETagField->GetFieldValue(), *pBufferBytes); + nRetVal = ERROR_SUCCESS; + } + } + } + + return nRetVal; +} + +int CAPETag::CreateID3Tag(ID3_TAG * pID3Tag) +{ + // error check + if (pID3Tag == NULL) { return -1; } + if (m_bAnalyzed == FALSE) { Analyze(); } + if (m_nFields == 0) { return -1; } + + // empty + ZeroMemory(pID3Tag, ID3_TAG_BYTES); + + // header + pID3Tag->Header[0] = 'T'; pID3Tag->Header[1] = 'A'; pID3Tag->Header[2] = 'G'; + + // standard fields + GetFieldID3String(APE_TAG_FIELD_ARTIST, pID3Tag->Artist, 30); + GetFieldID3String(APE_TAG_FIELD_ALBUM, pID3Tag->Album, 30); + GetFieldID3String(APE_TAG_FIELD_TITLE, pID3Tag->Title, 30); + GetFieldID3String(APE_TAG_FIELD_COMMENT, pID3Tag->Comment, 28); + GetFieldID3String(APE_TAG_FIELD_YEAR, pID3Tag->Year, 4); + + // track number + str_utf16 cBuffer[256] = { 0 }; int nBufferCharacters = 255; + GetFieldString(APE_TAG_FIELD_TRACK, cBuffer, &nBufferCharacters); + pID3Tag->Track = (unsigned char) _wtoi(cBuffer); + + // genre + cBuffer[0] = 0; nBufferCharacters = 255; + GetFieldString(APE_TAG_FIELD_GENRE, cBuffer, &nBufferCharacters); + + // convert the genre string to an index + pID3Tag->Genre = 255; + int nGenreIndex = 0; + BOOL bFound = FALSE; + while ((nGenreIndex < GENRE_COUNT) && (bFound == FALSE)) + { + if (_wcsicmp(cBuffer, g_ID3Genre[nGenreIndex]) == 0) + { + pID3Tag->Genre = nGenreIndex; + bFound = TRUE; + } + + nGenreIndex++; + } + + return ERROR_SUCCESS; +} + +int CAPETag::LoadField(const char * pBuffer, int nMaximumBytes, int * pBytes) +{ + // set bytes to 0 + if (pBytes) *pBytes = 0; + + // size and flags + int nLocation = 0; + int nFieldValueSize = *((int *) &pBuffer[nLocation]); + nLocation += 4; + int nFieldFlags = *((int *) &pBuffer[nLocation]); + nLocation += 4; + + // safety check (so we can't get buffer overflow attacked) + int nMaximumRead = nMaximumBytes - 8 - nFieldValueSize; + BOOL bSafe = TRUE; + for (int z = 0; (z < nMaximumRead) && (bSafe == TRUE); z++) + { + int nCharacter = pBuffer[nLocation + z]; + if (nCharacter == 0) + break; + if ((nCharacter < 0x20) || (nCharacter > 0x7E)) + bSafe = FALSE; + } + if (bSafe == FALSE) + return -1; + + // name + int nNameCharacters = strlen(&pBuffer[nLocation]); + CSmartPtr spNameUTF8(new str_utf8 [nNameCharacters + 1], TRUE); + memcpy(spNameUTF8, &pBuffer[nLocation], (nNameCharacters + 1) * sizeof(str_utf8)); + nLocation += nNameCharacters + 1; + CSmartPtr spNameUTF16(GetUTF16FromUTF8(spNameUTF8.GetPtr()), TRUE); + + // value + CSmartPtr spFieldBuffer(new char [nFieldValueSize], TRUE); + memcpy(spFieldBuffer, &pBuffer[nLocation], nFieldValueSize); + nLocation += nFieldValueSize; + + // update the bytes + if (pBytes) *pBytes = nLocation; + + // set + return SetFieldBinary(spNameUTF16.GetPtr(), spFieldBuffer, nFieldValueSize, nFieldFlags); +} + +int CAPETag::SetFieldString(const str_utf16 * pFieldName, const str_utf16 * pFieldValue) +{ + // remove if empty + if ((pFieldValue == NULL) || (wcslen(pFieldValue) <= 0)) + return RemoveField(pFieldName); + + // UTF-8 encode the value and call the UTF-8 SetField(...) + CSmartPtr spFieldValueUTF8(GetUTF8FromUTF16((str_utf16 *) pFieldValue), TRUE); + return SetFieldString(pFieldName, (const char *) spFieldValueUTF8.GetPtr(), TRUE); +} + +int CAPETag::SetFieldString(const str_utf16 * pFieldName, const char * pFieldValue, BOOL bAlreadyUTF8Encoded) +{ + // remove if empty + if ((pFieldValue == NULL) || (strlen(pFieldValue) <= 0)) + return RemoveField(pFieldName); + + // get the length and call the binary SetField(...) + if (bAlreadyUTF8Encoded == FALSE) + { + CSmartPtr spUTF8((char *) GetUTF8FromANSI(pFieldValue), TRUE); + int nFieldBytes = strlen(spUTF8.GetPtr()); + return SetFieldBinary(pFieldName, spUTF8.GetPtr(), nFieldBytes, TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8); + } + else + { + int nFieldBytes = strlen(pFieldValue); + return SetFieldBinary(pFieldName, pFieldValue, nFieldBytes, TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8); + } +} + +int CAPETag::SetFieldBinary(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes, int nFieldFlags) +{ + if (m_bAnalyzed == FALSE) { Analyze(); } + if (pFieldName == NULL) return -1; + + // check to see if we're trying to remove the field (by setting it to NULL or an empty string) + BOOL bRemoving = (pFieldValue == NULL) || (nFieldBytes <= 0); + + // get the index + int nFieldIndex = GetTagFieldIndex(pFieldName); + if (nFieldIndex != -1) + { + // existing field + + // fail if we're read-only (and not ignoring the read-only flag) + if ((m_bIgnoreReadOnly == FALSE) && (m_aryFields[nFieldIndex]->GetIsReadOnly())) + return -1; + + // erase the existing field + SAFE_DELETE(m_aryFields[nFieldIndex]) + + if (bRemoving) + { + return RemoveField(nFieldIndex); + } + } + else + { + if (bRemoving) + return ERROR_SUCCESS; + + nFieldIndex = m_nFields; + m_nFields++; + } + + // create the field and add it to the field array + m_aryFields[nFieldIndex] = new CAPETagField(pFieldName, pFieldValue, nFieldBytes, nFieldFlags); + + return ERROR_SUCCESS; +} + +int CAPETag::RemoveField(int nIndex) +{ + if ((nIndex >= 0) && (nIndex < m_nFields)) + { + SAFE_DELETE(m_aryFields[nIndex]) + memmove(&m_aryFields[nIndex], &m_aryFields[nIndex + 1], (256 - nIndex - 1) * sizeof(CAPETagField *)); + m_nFields--; + return ERROR_SUCCESS; + } + + return -1; +} + +int CAPETag::RemoveField(const str_utf16 * pFieldName) +{ + return RemoveField(GetTagFieldIndex(pFieldName)); +} + +int CAPETag::Remove(BOOL bUpdate) +{ + // variables + unsigned int nBytesRead = 0; + int nRetVal = 0; + int nOriginalPosition = m_spIO->GetPosition(); + + BOOL bID3Removed = TRUE; + BOOL bAPETagRemoved = TRUE; + + BOOL bFailedToRemove = FALSE; + + while (bID3Removed || bAPETagRemoved) + { + bID3Removed = FALSE; + bAPETagRemoved = FALSE; + + // ID3 tag + if (m_spIO->GetSize() > ID3_TAG_BYTES) + { + char cTagHeader[3]; + m_spIO->Seek(-ID3_TAG_BYTES, FILE_END); + nRetVal = m_spIO->Read(cTagHeader, 3, &nBytesRead); + if ((nRetVal == 0) && (nBytesRead == 3)) + { + if (strncmp(cTagHeader, "TAG", 3) == 0) + { + m_spIO->Seek(-ID3_TAG_BYTES, FILE_END); + if (m_spIO->SetEOF() != 0) + bFailedToRemove = TRUE; + else + bID3Removed = TRUE; + } + } + } + + + // APE Tag + if (m_spIO->GetSize() > APE_TAG_FOOTER_BYTES && bFailedToRemove == FALSE) + { + APE_TAG_FOOTER APETagFooter; + m_spIO->Seek(-int(APE_TAG_FOOTER_BYTES), FILE_END); + nRetVal = m_spIO->Read(&APETagFooter, APE_TAG_FOOTER_BYTES, &nBytesRead); + if ((nRetVal == 0) && (nBytesRead == APE_TAG_FOOTER_BYTES)) + { + if (APETagFooter.GetIsValid(TRUE)) + { + m_spIO->Seek(-APETagFooter.GetTotalTagBytes(), FILE_END); + + if (m_spIO->SetEOF() != 0) + bFailedToRemove = TRUE; + else + bAPETagRemoved = TRUE; + } + } + } + + } + + m_spIO->Seek(nOriginalPosition, FILE_BEGIN); + + if (bUpdate && bFailedToRemove == FALSE) + { + Analyze(); + } + + return bFailedToRemove ? -1 : 0; +} + +int CAPETag::SetFieldID3String(const str_utf16 * pFieldName, const char * pFieldValue, int nBytes) +{ + // allocate a buffer and terminate it + CSmartPtr spBuffer(new str_ansi [nBytes + 1], TRUE); + spBuffer[nBytes] = 0; + + // make a capped copy of the string + memcpy(spBuffer.GetPtr(), pFieldValue, nBytes); + + // remove trailing white-space + char * pEnd = &spBuffer[nBytes]; + while (((*pEnd == ' ') || (*pEnd == 0)) && pEnd >= &spBuffer[0]) { *pEnd-- = 0; } + + // set the field + SetFieldString(pFieldName, spBuffer, FALSE); + + return ERROR_SUCCESS; +} + +int CAPETag::GetFieldID3String(const str_utf16 * pFieldName, char * pBuffer, int nBytes) +{ + int nBufferCharacters = 255; str_utf16 cBuffer[256] = {0}; + GetFieldString(pFieldName, cBuffer, &nBufferCharacters); + + CSmartPtr spBufferANSI(GetANSIFromUTF16(cBuffer), TRUE); + + memset(pBuffer, 0, nBytes); + strncpy(pBuffer, spBufferANSI.GetPtr(), nBytes); + + return ERROR_SUCCESS; +} + +int CAPETag::SortFields() +{ + // sort the tag fields by size (so that the smallest fields are at the front of the tag) + qsort(m_aryFields, m_nFields, sizeof(CAPETagField *), CompareFields); + + return ERROR_SUCCESS; +} + +int CAPETag::CompareFields(const void * pA, const void * pB) +{ + CAPETagField * pFieldA = *((CAPETagField **) pA); + CAPETagField * pFieldB = *((CAPETagField **) pB); + + return (pFieldA->GetFieldSize() - pFieldB->GetFieldSize()); +} \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/APETag.h b/MAC_SDK/Source/MACLib/APETag.h new file mode 100644 index 0000000..eecd8b7 --- /dev/null +++ b/MAC_SDK/Source/MACLib/APETag.h @@ -0,0 +1,293 @@ +#ifndef APE_APETAG_H +#define APE_APETAG_H + +class CIO; + +/***************************************************************************************** +APETag version history / supported formats + +1.0 (1000) - Original APE tag spec. Fully supported by this code. +2.0 (2000) - Refined APE tag spec (better streaming support, UTF encoding). Fully supported by this code. + +Notes: + - also supports reading of ID3v1.1 tags + - all saving done in the APE Tag format using CURRENT_APE_TAG_VERSION +*****************************************************************************************/ + +/***************************************************************************************** +APETag layout + +1) Header - APE_TAG_FOOTER (optional) (32 bytes) +2) Fields (array): + Value Size (4 bytes) + Flags (4 bytes) + Field Name (? ANSI bytes -- requires NULL terminator -- in range of 0x20 (space) to 0x7E (tilde)) + Value ([Value Size] bytes) +3) Footer - APE_TAG_FOOTER (32 bytes) +*****************************************************************************************/ + +/***************************************************************************************** +Notes + +-When saving images, store the filename (no directory -- i.e. Cover.jpg) in UTF-8 followed +by a null terminator, followed by the image data. +*****************************************************************************************/ + +/***************************************************************************************** +The version of the APE tag +*****************************************************************************************/ +#define CURRENT_APE_TAG_VERSION 2000 + +/***************************************************************************************** +"Standard" APE tag fields +*****************************************************************************************/ +#define APE_TAG_FIELD_TITLE L"Title" +#define APE_TAG_FIELD_ARTIST L"Artist" +#define APE_TAG_FIELD_ALBUM L"Album" +#define APE_TAG_FIELD_COMMENT L"Comment" +#define APE_TAG_FIELD_YEAR L"Year" +#define APE_TAG_FIELD_TRACK L"Track" +#define APE_TAG_FIELD_GENRE L"Genre" +#define APE_TAG_FIELD_COVER_ART_FRONT L"Cover Art (front)" +#define APE_TAG_FIELD_NOTES L"Notes" +#define APE_TAG_FIELD_LYRICS L"Lyrics" +#define APE_TAG_FIELD_COPYRIGHT L"Copyright" +#define APE_TAG_FIELD_BUY_URL L"Buy URL" +#define APE_TAG_FIELD_ARTIST_URL L"Artist URL" +#define APE_TAG_FIELD_PUBLISHER_URL L"Publisher URL" +#define APE_TAG_FIELD_FILE_URL L"File URL" +#define APE_TAG_FIELD_COPYRIGHT_URL L"Copyright URL" +#define APE_TAG_FIELD_MJ_METADATA L"Media Jukebox Metadata" +#define APE_TAG_FIELD_TOOL_NAME L"Tool Name" +#define APE_TAG_FIELD_TOOL_VERSION L"Tool Version" +#define APE_TAG_FIELD_PEAK_LEVEL L"Peak Level" +#define APE_TAG_FIELD_REPLAY_GAIN_RADIO L"Replay Gain (radio)" +#define APE_TAG_FIELD_REPLAY_GAIN_ALBUM L"Replay Gain (album)" +#define APE_TAG_FIELD_COMPOSER L"Composer" +#define APE_TAG_FIELD_KEYWORDS L"Keywords" + +/***************************************************************************************** +Standard APE tag field values +*****************************************************************************************/ +#define APE_TAG_GENRE_UNDEFINED L"Undefined" + +/***************************************************************************************** +ID3 v1.1 tag +*****************************************************************************************/ +#define ID3_TAG_BYTES 128 +struct ID3_TAG +{ + char Header[3]; // should equal 'TAG' + char Title[30]; // title + char Artist[30]; // artist + char Album[30]; // album + char Year[4]; // year + char Comment[29]; // comment + unsigned char Track; // track + unsigned char Genre; // genre +}; + +/***************************************************************************************** +Footer (and header) flags +*****************************************************************************************/ +#define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31) +#define APE_TAG_FLAG_CONTAINS_FOOTER (1 << 30) +#define APE_TAG_FLAG_IS_HEADER (1 << 29) + +#define APE_TAG_FLAGS_DEFAULT (APE_TAG_FLAG_CONTAINS_FOOTER) + +/***************************************************************************************** +Tag field flags +*****************************************************************************************/ +#define TAG_FIELD_FLAG_READ_ONLY (1 << 0) + +#define TAG_FIELD_FLAG_DATA_TYPE_MASK (6) +#define TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8 (0 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_BINARY (1 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_EXTERNAL_INFO (2 << 1) +#define TAG_FIELD_FLAG_DATA_TYPE_RESERVED (3 << 1) + +/***************************************************************************************** +The footer at the end of APE tagged files (can also optionally be at the front of the tag) +*****************************************************************************************/ +#define APE_TAG_FOOTER_BYTES 32 + +class APE_TAG_FOOTER +{ +protected: + + char m_cID[8]; // should equal 'APETAGEX' + int m_nVersion; // equals CURRENT_APE_TAG_VERSION + int m_nSize; // the complete size of the tag, including this footer (excludes header) + int m_nFields; // the number of fields in the tag + int m_nFlags; // the tag flags + char m_cReserved[8]; // reserved for later use (must be zero) + +public: + + APE_TAG_FOOTER(int nFields = 0, int nFieldBytes = 0) + { + memcpy(m_cID, "APETAGEX", 8); + memset(m_cReserved, 0, 8); + m_nFields = nFields; + m_nFlags = APE_TAG_FLAGS_DEFAULT; + m_nSize = nFieldBytes + APE_TAG_FOOTER_BYTES; + m_nVersion = CURRENT_APE_TAG_VERSION; + } + + int GetTotalTagBytes() { return m_nSize + (GetHasHeader() ? APE_TAG_FOOTER_BYTES : 0); } + int GetFieldBytes() { return m_nSize - APE_TAG_FOOTER_BYTES; } + int GetFieldsOffset() { return GetHasHeader() ? APE_TAG_FOOTER_BYTES : 0; } + int GetNumberFields() { return m_nFields; } + BOOL GetHasHeader() { return (m_nFlags & APE_TAG_FLAG_CONTAINS_HEADER) ? TRUE : FALSE; } + BOOL GetIsHeader() { return (m_nFlags & APE_TAG_FLAG_IS_HEADER) ? TRUE : FALSE; } + int GetVersion() { return m_nVersion; } + + BOOL GetIsValid(BOOL bAllowHeader) + { + BOOL bValid = (strncmp(m_cID, "APETAGEX", 8) == 0) && + (m_nVersion <= CURRENT_APE_TAG_VERSION) && + (m_nFields <= 65536) && + (GetFieldBytes() <= (1024 * 1024 * 16)); + + if (bValid && (bAllowHeader == FALSE) && GetIsHeader()) + bValid = FALSE; + + return bValid ? TRUE : FALSE; + } +}; + +/***************************************************************************************** +CAPETagField class (an APE tag is an array of these) +*****************************************************************************************/ +class CAPETagField +{ +public: + + // create a tag field (use nFieldBytes = -1 for null-terminated strings) + CAPETagField(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes = -1, int nFlags = 0); + + // destructor + ~CAPETagField(); + + // gets the size of the entire field in bytes (name, value, and metadata) + int GetFieldSize(); + + // get the name of the field + const str_utf16 * GetFieldName(); + + // get the value of the field + const char * GetFieldValue(); + + // get the size of the value (in bytes) + int GetFieldValueSize(); + + // get any special flags + int GetFieldFlags(); + + // output the entire field to a buffer (GetFieldSize() bytes) + int SaveField(char * pBuffer); + + // checks to see if the field is read-only + BOOL GetIsReadOnly() { return (m_nFieldFlags & TAG_FIELD_FLAG_READ_ONLY) ? TRUE : FALSE; } + BOOL GetIsUTF8Text() { return ((m_nFieldFlags & TAG_FIELD_FLAG_DATA_TYPE_MASK) == TAG_FIELD_FLAG_DATA_TYPE_TEXT_UTF8) ? TRUE : FALSE; } + + // set helpers (use with EXTREME caution) + void SetFieldFlags(int nFlags) { m_nFieldFlags = nFlags; } + +private: + + CSmartPtr m_spFieldNameUTF16; + CSmartPtr m_spFieldValue; + int m_nFieldFlags; + int m_nFieldValueBytes; +}; + +/***************************************************************************************** +CAPETag class +*****************************************************************************************/ +class CAPETag +{ +public: + + // create an APE tag + // bAnalyze determines whether it will analyze immediately or on the first request + // be careful with multiple threads / file pointer movement if you don't analyze immediately + CAPETag(CIO * pIO, BOOL bAnalyze = TRUE); + CAPETag(const str_utf16 * pFilename, BOOL bAnalyze = TRUE); + + // destructor + ~CAPETag(); + + // save the tag to the I/O source (bUseOldID3 forces it to save as an ID3v1.1 tag instead of an APE tag) + int Save(BOOL bUseOldID3 = FALSE); + + // removes any tags from the file (bUpdate determines whether is should re-analyze after removing the tag) + int Remove(BOOL bUpdate = TRUE); + + // sets the value of a field (use nFieldBytes = -1 for null terminated strings) + // note: using NULL or "" for a string type will remove the field + int SetFieldString(const str_utf16 * pFieldName, const str_utf16 * pFieldValue); + int SetFieldString(const str_utf16 * pFieldName, const char * pFieldValue, BOOL bAlreadyUTF8Encoded); + int SetFieldBinary(const str_utf16 * pFieldName, const void * pFieldValue, int nFieldBytes, int nFieldFlags); + + // gets the value of a field (returns -1 and an empty buffer if the field doesn't exist) + int GetFieldBinary(const str_utf16 * pFieldName, void * pBuffer, int * pBufferBytes); + int GetFieldString(const str_utf16 * pFieldName, str_utf16 * pBuffer, int * pBufferCharacters); + int GetFieldString(const str_utf16 * pFieldName, str_ansi * pBuffer, int * pBufferCharacters, BOOL bUTF8Encode = FALSE); + + // remove a specific field + int RemoveField(const str_utf16 * pFieldName); + int RemoveField(int nIndex); + + // clear all the fields + int ClearFields(); + + // get the total tag bytes in the file from the last analyze + // need to call Save() then Analyze() to update any changes + int GetTagBytes(); + + // fills in an ID3_TAG using the current fields (useful for quickly converting the tag) + int CreateID3Tag(ID3_TAG * pID3Tag); + + // see whether the file has an ID3 or APE tag + BOOL GetHasID3Tag() { if (m_bAnalyzed == FALSE) { Analyze(); } return m_bHasID3Tag; } + BOOL GetHasAPETag() { if (m_bAnalyzed == FALSE) { Analyze(); } return m_bHasAPETag; } + int GetAPETagVersion() { return GetHasAPETag() ? m_nAPETagVersion : -1; } + + // gets a desired tag field (returns NULL if not found) + // again, be careful, because this a pointer to the actual field in this class + CAPETagField * GetTagField(const str_utf16 * pFieldName); + CAPETagField * GetTagField(int nIndex); + + // options + void SetIgnoreReadOnly(BOOL bIgnoreReadOnly) { m_bIgnoreReadOnly = bIgnoreReadOnly; } + +private: + + // private functions + int Analyze(); + int GetTagFieldIndex(const str_utf16 * pFieldName); + int WriteBufferToEndOfIO(void * pBuffer, int nBytes); + int LoadField(const char * pBuffer, int nMaximumBytes, int * pBytes); + int SortFields(); + static int CompareFields(const void * pA, const void * pB); + + // helper set / get field functions + int SetFieldID3String(const str_utf16 * pFieldName, const char * pFieldValue, int nBytes); + int GetFieldID3String(const str_utf16 * pFieldName, char * pBuffer, int nBytes); + + // private data + CSmartPtr m_spIO; + BOOL m_bAnalyzed; + int m_nTagBytes; + int m_nFields; + CAPETagField * m_aryFields[256]; + BOOL m_bHasAPETag; + int m_nAPETagVersion; + BOOL m_bHasID3Tag; + BOOL m_bIgnoreReadOnly; +}; + +#endif // #ifndef APE_APETAG_H + diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly.h b/MAC_SDK/Source/MACLib/Assembly/Assembly.h new file mode 100644 index 0000000..6bb1c91 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Assembly.h @@ -0,0 +1,12 @@ +#ifndef APE_ASSEMBLY_H +#define APE_ASSEMBLY_H + +extern "C" +{ + void Adapt(short * pM, const short * pAdapt, int nDirection, int nOrder); + int CalculateDotProduct(const short * pA, const short * pB, int nOrder); + BOOL GetMMXAvailable(); +}; + +#endif // #ifndef APE_ASSEMBLY_H + diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly.nas b/MAC_SDK/Source/MACLib/Assembly/Assembly.nas new file mode 100644 index 0000000..74e4eaa --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Assembly.nas @@ -0,0 +1,181 @@ + +%include "Tools.inc" + +segment_code + +; +; void Adapt ( short* pM, const short* pAdapt, int nDirection, int nOrder ) +; +; [esp+16] nOrder +; [esp+12] nDirection +; [esp+ 8] pAdapt +; [esp+ 4] pM +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop +proc Adapt + + mov eax, [esp + 4] ; pM + mov ecx, [esp + 8] ; pAdapt + mov edx, [esp + 16] ; nOrder + shr edx, 4 + + cmp dword [esp + 12], byte 0 ; nDirection + jle short AdaptSub + +AdaptAddLoop: + movq mm0, [eax] + paddw mm0, [ecx] + movq [eax], mm0 + movq mm1, [eax + 8] + paddw mm1, [ecx + 8] + movq [eax + 8], mm1 + movq mm2, [eax + 16] + paddw mm2, [ecx + 16] + movq [eax + 16], mm2 + movq mm3, [eax + 24] + paddw mm3, [ecx + 24] + movq [eax + 24], mm3 + add eax, byte 32 + add ecx, byte 32 + dec edx + jnz AdaptAddLoop + + emms + ret + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +AdaptSub: je short AdaptDone + +AdaptSubLoop: + movq mm0, [eax] + psubw mm0, [ecx] + movq [eax], mm0 + movq mm1, [eax + 8] + psubw mm1, [ecx + 8] + movq [eax + 8], mm1 + movq mm2, [eax + 16] + psubw mm2, [ecx + 16] + movq [eax + 16], mm2 + movq mm3, [eax + 24] + psubw mm3, [ecx + 24] + movq [eax + 24], mm3 + add eax, byte 32 + add ecx, byte 32 + dec edx + jnz AdaptSubLoop + + emms +AdaptDone: + +endproc + +; +; int CalculateDotProduct ( const short* pA, const short* pB, int nOrder ) +; +; [esp+12] nOrder +; [esp+ 8] pB +; [esp+ 4] pA +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +proc CalculateDotProduct + + mov eax, [esp + 4] ; pA + mov ecx, [esp + 8] ; pB + mov edx, [esp + 12] ; nOrder + shr edx, 4 + pxor mm7, mm7 + +loopDot: movq mm0, [eax] + pmaddwd mm0, [ecx] + paddd mm7, mm0 + movq mm1, [eax + 8] + pmaddwd mm1, [ecx + 8] + paddd mm7, mm1 + movq mm2, [eax + 16] + pmaddwd mm2, [ecx + 16] + paddd mm7, mm2 + movq mm3, [eax + 24] + pmaddwd mm3, [ecx + 24] + add eax, byte 32 + add ecx, byte 32 + paddd mm7, mm3 + dec edx + jnz loopDot + + movq mm6, mm7 + psrlq mm7, 32 + paddd mm6, mm7 + movd [esp + 4], mm6 + emms + mov eax, [esp + 4] +endproc + + +; +; BOOL GetMMXAvailable ( void ); +; + +proc GetMMXAvailable + pushad + pushfd + pop eax + mov ecx, eax + xor eax, 0x200000 + push eax + popfd + pushfd + pop eax + cmp eax, ecx + jz short return ; no CPUID command, so no MMX + + mov eax,1 + CPUID + test edx,0x800000 +return: popad + setnz al + and eax, byte 1 +endproc + + end diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly.obj b/MAC_SDK/Source/MACLib/Assembly/Assembly.obj new file mode 100644 index 0000000..0a8f2af Binary files /dev/null and b/MAC_SDK/Source/MACLib/Assembly/Assembly.obj differ diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly64.bak b/MAC_SDK/Source/MACLib/Assembly/Assembly64.bak new file mode 100644 index 0000000..30f8adf --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Assembly64.bak @@ -0,0 +1,180 @@ + +%include "Tools64.inc" + +segment_code + +; +; void Adapt ( short* pM, const short* pAdapt, int nDirection, int nOrder ) +; +; r9d nOrder +; r8d nDirection +; rdx pAdapt +; rcx pM +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop +proc Adapt + + shr r9d, 4 + + cmp r8d, byte 0 ; nDirection + jle short AdaptSub + +AdaptAddLoop: + movq mm0, [rcx] + paddw mm0, [rdx] + movq [rcx], mm0 + movq mm1, [rcx + 8] + paddw mm1, [rdx + 8] + movq [rcx + 8], mm1 + movq mm2, [rcx + 16] + paddw mm2, [rdx + 16] + movq [rcx + 16], mm2 + movq mm3, [rcx + 24] + paddw mm3, [rdx + 24] + movq [rcx + 24], mm3 + add rcx, byte 32 + add rdx, byte 32 + dec r9d + jnz AdaptAddLoop + + emms + ret + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +AdaptSub: je short AdaptDone + +AdaptSubLoop: + movq mm0, [rcx] + psubw mm0, [rdx] + movq [rcx], mm0 + movq mm1, [rcx + 8] + psubw mm1, [rdx + 8] + movq [rcx + 8], mm1 + movq mm2, [rcx + 16] + psubw mm2, [rdx + 16] + movq [rcx + 16], mm2 + movq mm3, [rcx + 24] + psubw mm3, [rdx + 24] + movq [rcx + 24], mm3 + add rcx, byte 32 + add rdx, byte 32 + dec r9d + jnz AdaptSubLoop + + emms +AdaptDone: + +endproc + +; +; int CalculateDotProduct ( const short* pA, const short* pB, int nOrder ) +; +; [esp+12] nOrder +; [esp+ 8] pB +; [esp+ 4] pA +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +proc CalculateDotProduct + + shr r8d, 4 + pxor mm7, mm7 + +loopDot: movq mm0, [rcx] ;pA + pmaddwd mm0, [rdx] ;pB + paddd mm7, mm0 + movq mm1, [rcx + 8] + pmaddwd mm1, [rdx + 8] + paddd mm7, mm1 + movq mm2, [rcx + 16] + pmaddwd mm2, [rdx + 16] + paddd mm7, mm2 + movq mm3, [rcx + 24] + pmaddwd mm3, [rdx + 24] + add rcx, byte 32 + add rdx, byte 32 + paddd mm7, mm3 + dec r8d + jnz loopDot + + movq mm6, mm7 + psrlq mm7, 32 + paddd mm6, mm7 + movd eax, mm6 + emms +endproc + + +; +; BOOL GetMMXAvailable ( void ); +; + +proc GetMMXAvailable + push rax + push rcx + push rdx + push rbx + pushfq + pop rax + mov rcx, rax + xor rax, 0x200000 + push rax + popfq + pushfq + pop rax + cmp rax, rcx + jz short return ; no CPUID command, so no MMX + + mov rax,1 + CPUID + test rdx,0x800000 +return: pop rbx + pop rdx + pop rcx + pop rax + setnz al + and eax, byte 1 +endproc + + end diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly64.nas b/MAC_SDK/Source/MACLib/Assembly/Assembly64.nas new file mode 100644 index 0000000..ef18cf7 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Assembly64.nas @@ -0,0 +1,240 @@ + +%include "Tools64.inc" + +segment_code + +; +; void Adapt ( short* pM, const short* pAdapt, int nDirection, int nOrder ) +; +; r9d nOrder +; r8d nDirection +; rdx pAdapt +; rcx pM +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop +proc Adapt + + shr r9d, 4 + + cmp r8d, byte 0 ; nDirection + jle short AdaptSub + +AdaptAddLoop: + movq mm0, [rcx] + paddw mm0, [rdx] + movq [rcx], mm0 + movq mm1, [rcx + 8] + paddw mm1, [rdx + 8] + movq [rcx + 8], mm1 + movq mm2, [rcx + 16] + paddw mm2, [rdx + 16] + movq [rcx + 16], mm2 + movq mm3, [rcx + 24] + paddw mm3, [rdx + 24] + movq [rcx + 24], mm3 + add rcx, byte 32 + add rdx, byte 32 + dec r9d + jnz AdaptAddLoop + + emms + ret + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +AdaptSub: je short AdaptDone + +AdaptSubLoop: + movq mm0, [rcx] + psubw mm0, [rdx] + movq [rcx], mm0 + movq mm1, [rcx + 8] + psubw mm1, [rdx + 8] + movq [rcx + 8], mm1 + movq mm2, [rcx + 16] + psubw mm2, [rdx + 16] + movq [rcx + 16], mm2 + movq mm3, [rcx + 24] + psubw mm3, [rdx + 24] + movq [rcx + 24], mm3 + add rcx, byte 32 + add rdx, byte 32 + dec r9d + jnz AdaptSubLoop + + emms +AdaptDone: + +endproc + +; +; int CalculateDotProduct ( const short* pA, const short* pB, int nOrder ) +; +; [esp+12] nOrder +; [esp+ 8] pB +; [esp+ 4] pA +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +proc CalculateDotProduct + + shr r8d, 4 + pxor mm7, mm7 + +loopDot: movq mm0, [rcx] ;pA + pmaddwd mm0, [rdx] ;pB + paddd mm7, mm0 + movq mm1, [rcx + 8] + pmaddwd mm1, [rdx + 8] + paddd mm7, mm1 + movq mm2, [rcx + 16] + pmaddwd mm2, [rdx + 16] + paddd mm7, mm2 + movq mm3, [rcx + 24] + pmaddwd mm3, [rdx + 24] + add rcx, byte 32 + add rdx, byte 32 + paddd mm7, mm3 + dec r8d + jnz loopDot + + movq mm6, mm7 + psrlq mm7, 32 + paddd mm6, mm7 + movd eax, mm6 + emms +endproc + +; +; int CalculateDotProduct ( const short* pA, const short* pB, int nOrder ) +; +; [esp+12] nOrder +; [esp+ 8] pB +; [esp+ 4] pA +; [esp+ 0] Return Address + + align 16 + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + +proc CalculateDotProductXMM + + shr r8d, 4 + pxor xmm7, xmm7 + +loopDotXMM: movdqu xmm0, [rcx] ;pA + pmaddwd xmm0, [rdx] ;pB + paddd xmm7, xmm0 + movdqu xmm1, [rcx + 16] + pmaddwd xmm1, [rdx + 16] +; paddd xmm7, xmm1 +; movq xmm2, [rcx + 32] +; pmaddwd xmm2, [rdx + 32] +; paddd xmm7, mm2 +; movq xmm3, [rcx + 48] +; pmaddwd xmm3, [rdx + 48] + add rcx, byte 32 + add rdx, byte 32 +; paddd xmm7, xmm3 + paddd xmm7, xmm1 + dec r8d + jnz loopDotXMM + + movq xmm5, xmm7 + psrldq xmm5, 16 + movq xmm4, xmm5 + psrlq xmm5, 32 + movq xmm6, xmm7 + psrlq xmm7, 32 + paddd xmm6, xmm4 + paddd xmm6, xmm5 + paddd xmm6, xmm7 + movd eax, xmm6 + emms +endproc + + +; +; BOOL GetMMXAvailable ( void ); +; + +proc GetMMXAvailable + push rax + push rcx + push rdx + push rbx + pushfq + pop rax + mov rcx, rax + xor rax, 0x200000 + push rax + popfq + pushfq + pop rax + cmp rax, rcx + jz short return ; no CPUID command, so no MMX + + mov rax,1 + CPUID + test rdx,0x800000 +return: pop rbx + pop rdx + pop rcx + pop rax + setnz al + and eax, byte 1 +endproc + +; end diff --git a/MAC_SDK/Source/MACLib/Assembly/Assembly64.obj b/MAC_SDK/Source/MACLib/Assembly/Assembly64.obj new file mode 100644 index 0000000..ebee012 Binary files /dev/null and b/MAC_SDK/Source/MACLib/Assembly/Assembly64.obj differ diff --git a/MAC_SDK/Source/MACLib/Assembly/Tools.inc b/MAC_SDK/Source/MACLib/Assembly/Tools.inc new file mode 100644 index 0000000..e1f79d9 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Tools.inc @@ -0,0 +1,117 @@ +; +; (C) Ururi 1999 +; + +BITS 32 + +%ifdef WIN32 + %define _NAMING + %define segment_code segment .text align=32 class=CODE use32 + %define segment_data segment .data align=32 class=DATA use32 + %ifdef __BORLANDC__ + %define segment_bss segment .data align=32 class=DATA use32 + %else + %define segment_bss segment .bss align=32 class=DATA use32 + %endif + +%elifdef AOUT + %define _NAMING + %define segment_code segment .text + %define segment_data segment .data + %define segment_bss segment .bss + +%else + %define segment_code segment .text align=32 class=CODE use32 + %define segment_data segment .data align=32 class=DATA use32 + %define segment_bss segment .bss align=32 class=DATA use32 +%endif + +%define pmov movq +%define pmovd movd + +%define pupldq punpckldq +%define puphdq punpckhdq +%define puplwd punpcklwd +%define puphwd punpckhwd + +%imacro globaldef 1 + %ifdef _NAMING + %define %1 _%1 + %endif + global %1 +%endmacro + +%imacro externdef 1 + %ifdef _NAMING + %define %1 _%1 + %endif + extern %1 +%endmacro + +%imacro proc 1 + %push proc + global _%1 + global %1 +_%1: +%1: + %assign %$STACK 0 + %assign %$STACKN 0 + %assign %$ARG 4 +%endmacro + +%imacro endproc 0 + %ifnctx proc + %error expected 'proc' before 'endproc'. + %else + %if %$STACK > 0 + add esp, %$STACK + %endif + + %if %$STACK <> (-%$STACKN) + %error STACKLEVEL mismatch check 'local', 'alloc', 'pushd', 'popd' + %endif + + ret + %pop + %endif +%endmacro + +%idefine sp(a) esp+%$STACK+a + +%imacro arg 1 + %00 equ %$ARG + %assign %$ARG %$ARG+%1 +%endmacro + +%imacro local 1 + %assign %$STACKN %$STACKN-%1 + %00 equ %$STACKN +%endmacro + +%imacro alloc 0 + sub esp, (-%$STACKN)-%$STACK + %assign %$STACK (-%$STACKN) +%endmacro + +%imacro pushd 1-* + %rep %0 + push %1 + %assign %$STACK %$STACK+4 + %rotate 1 + %endrep +%endmacro + +%imacro popd 1-* + %rep %0 + %rotate -1 + pop %1 + %assign %$STACK %$STACK-4 + %endrep +%endmacro + +%macro algn 1 + align 16 + %rep (65536-%1) & 15 + nop + %endrep +%endm diff --git a/MAC_SDK/Source/MACLib/Assembly/Tools64.inc b/MAC_SDK/Source/MACLib/Assembly/Tools64.inc new file mode 100644 index 0000000..4fbdf69 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/Tools64.inc @@ -0,0 +1,119 @@ +; +; (C) Ururi 1999 +; + +BITS 64 + +CPU X64 + +%ifdef WIN32 + %define _NAMING + %define segment_code segment .text align=32 class=CODE use32 + %define segment_data segment .data align=32 class=DATA use32 + %ifdef __BORLANDC__ + %define segment_bss segment .data align=32 class=DATA use32 + %else + %define segment_bss segment .bss align=32 class=DATA use32 + %endif + +%elifdef AOUT + %define _NAMING + %define segment_code segment .text + %define segment_data segment .data + %define segment_bss segment .bss + +%else + %define segment_code segment .text align=32 class=CODE use32 + %define segment_data segment .data align=32 class=DATA use32 + %define segment_bss segment .bss align=32 class=DATA use32 +%endif + +%define pmov movq +%define pmovd movd + +%define pupldq punpckldq +%define puphdq punpckhdq +%define puplwd punpcklwd +%define puphwd punpckhwd + +%imacro globaldef 1 + %ifdef _NAMING + %define %1 _%1 + %endif + global %1 +%endmacro + +%imacro externdef 1 + %ifdef _NAMING + %define %1 _%1 + %endif + extern %1 +%endmacro + +%imacro proc 1 + %push proc + global _%1 + global %1 +_%1: +%1: + %assign %$STACK 0 + %assign %$STACKN 0 + %assign %$ARG 4 +%endmacro + +%imacro endproc 0 + %ifnctx proc + %error expected 'proc' before 'endproc'. + %else + %if %$STACK > 0 + add esp, %$STACK + %endif + + %if %$STACK <> (-%$STACKN) + %error STACKLEVEL mismatch check 'local', 'alloc', 'pushd', 'popd' + %endif + + ret + %pop + %endif +%endmacro + +%idefine sp(a) esp+%$STACK+a + +%imacro arg 1 + %00 equ %$ARG + %assign %$ARG %$ARG+%1 +%endmacro + +%imacro local 1 + %assign %$STACKN %$STACKN-%1 + %00 equ %$STACKN +%endmacro + +%imacro alloc 0 + sub esp, (-%$STACKN)-%$STACK + %assign %$STACK (-%$STACKN) +%endmacro + +%imacro pushd 1-* + %rep %0 + push %1 + %assign %$STACK %$STACK+4 + %rotate 1 + %endrep +%endmacro + +%imacro popd 1-* + %rep %0 + %rotate -1 + pop %1 + %assign %$STACK %$STACK-4 + %endrep +%endmacro + +%macro algn 1 + align 16 + %rep (65536-%1) & 15 + nop + %endrep +%endm diff --git a/MAC_SDK/Source/MACLib/Assembly/hhh b/MAC_SDK/Source/MACLib/Assembly/hhh new file mode 100644 index 0000000..bad3af6 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Assembly/hhh @@ -0,0 +1,41 @@ +usage: nasm [-@ response file] [-o outfile] [-f format] [-l listfile] + [options...] [--] filename + or nasm -v for version info + + -t assemble in SciTech TASM compatible mode + -g generate debug information in selected format. + -E (or -e) preprocess only (writes output to stdout by default) + -a don't preprocess (assemble only) + -M generate Makefile dependencies on stdout + -MG d:o, missing files assumed generated + + -Z redirect error messages to file + -s redirect error messages to stdout + + -F format select a debugging format + + -I adds a pathname to the include file path + -O optimize branch offsets (-O0 disables, default) + -P pre-includes a file + -D[=] pre-defines a macro + -U undefines a macro + -X specifies error reporting format (gnu or vc) + -w+foo enables warning foo (equiv. -Wfoo) + -w-foo disable warning foo (equiv. -Wno-foo) +Warnings: + error treat warnings as errors (default off) + macro-params macro calls with wrong parameter count (default on) + macro-selfref cyclic macro references (default off) + macro-defaults macros with more default than optional parameters (default on) + orphan-labels labels alone on lines without trailing `:' (default on) + number-overflow numeric constants does not fit in 64 bits (default on) + gnu-elf-extensions using 8- or 16-bit relocation in ELF32, a GNU extension (default off) + float-overflow floating point overflow (default on) + float-denorm floating point denormal (default off) + float-underflow floating point underflow (default off) + float-toolong too many digits in floating-point number (default on) + +response files should contain command line parameters, one per line. + +For a list of valid output formats, use -hf. +For a list of debug formats, use -f
-y. diff --git a/MAC_SDK/Source/MACLib/BitArray.cpp b/MAC_SDK/Source/MACLib/BitArray.cpp new file mode 100644 index 0000000..660257a --- /dev/null +++ b/MAC_SDK/Source/MACLib/BitArray.cpp @@ -0,0 +1,434 @@ +/************************************************************************************ +Includes +************************************************************************************/ +#include "All.h" +#include "BitArray.h" +#include "MD5.h" + +/************************************************************************************ +Declares +************************************************************************************/ +#define BIT_ARRAY_ELEMENTS (4096) // the number of elements in the bit array (4 MB) +#define BIT_ARRAY_BYTES (BIT_ARRAY_ELEMENTS * 4) // the number of bytes in the bit array +#define BIT_ARRAY_BITS (BIT_ARRAY_BYTES * 8) // the number of bits in the bit array + +#define MAX_ELEMENT_BITS 128 +#define REFILL_BIT_THRESHOLD (BIT_ARRAY_BITS - MAX_ELEMENT_BITS) + +#define CODE_BITS 32 +#define TOP_VALUE ((unsigned int) 1 << (CODE_BITS - 1)) +#define SHIFT_BITS (CODE_BITS - 9) +#define EXTRA_BITS ((CODE_BITS - 2) % 8 + 1) +#define BOTTOM_VALUE (TOP_VALUE >> 8) + +/************************************************************************************ +Lookup tables +************************************************************************************/ +const uint32 K_SUM_MIN_BOUNDARY[32] = {0,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0}; + +#define MODEL_ELEMENTS 64 +#define RANGE_OVERFLOW_TOTAL_WIDTH 65536 +#define RANGE_OVERFLOW_SHIFT 16 + +const uint32 RANGE_TOTAL[64] = {0,19578,36160,48417,56323,60899,63265,64435,64971,65232,65351,65416,65447,65466,65476,65482,65485,65488,65490,65491,65492,65493,65494,65495,65496,65497,65498,65499,65500,65501,65502,65503,65504,65505,65506,65507,65508,65509,65510,65511,65512,65513,65514,65515,65516,65517,65518,65519,65520,65521,65522,65523,65524,65525,65526,65527,65528,65529,65530,65531,65532,65533,65534,65535,}; +const uint32 RANGE_WIDTH[64] = {19578,16582,12257,7906,4576,2366,1170,536,261,119,65,31,19,10,6,3,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; + +#ifdef BUILD_RANGE_TABLE + int g_aryOverflows[256] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + int g_nTotalOverflow = 0; +#endif + +/************************************************************************************ +Constructor +************************************************************************************/ +CBitArray::CBitArray(CIO *pIO) +{ + // allocate memory for the bit array + m_pBitArray = new uint32 [BIT_ARRAY_ELEMENTS]; + memset(m_pBitArray, 0, BIT_ARRAY_BYTES); + + // initialize other variables + m_nCurrentBitIndex = 0; + m_pIO = pIO; +} + +/************************************************************************************ +Destructor +************************************************************************************/ +CBitArray::~CBitArray() +{ + // free the bit array + SAFE_ARRAY_DELETE(m_pBitArray) +#ifdef BUILD_RANGE_TABLE + OutputRangeTable(); +#endif +} + +/************************************************************************************ +Output the bit array via the CIO (typically saves to disk) +************************************************************************************/ +int CBitArray::OutputBitArray(BOOL bFinalize) +{ + // write the entire file to disk + unsigned int nBytesWritten = 0; + unsigned int nBytesToWrite = 0; + unsigned int nRetVal = 0; + + if (bFinalize) + { + nBytesToWrite = ((m_nCurrentBitIndex >> 5) * 4) + 4; + + m_MD5.AddData(m_pBitArray, nBytesToWrite); + + RETURN_ON_ERROR(m_pIO->Write(m_pBitArray, nBytesToWrite, &nBytesWritten)) + + // reset the bit pointer + m_nCurrentBitIndex = 0; + } + else + { + nBytesToWrite = (m_nCurrentBitIndex >> 5) * 4; + + m_MD5.AddData(m_pBitArray, nBytesToWrite); + + RETURN_ON_ERROR(m_pIO->Write(m_pBitArray, nBytesToWrite, &nBytesWritten)) + + // move the last value to the front of the bit array + m_pBitArray[0] = m_pBitArray[m_nCurrentBitIndex >> 5]; + m_nCurrentBitIndex = (m_nCurrentBitIndex & 31); + + // zero the rest of the memory (may not need the +1 because of frame byte alignment) + memset(&m_pBitArray[1], 0, min(nBytesToWrite + 1, BIT_ARRAY_BYTES - 1)); + } + + // return a success + return ERROR_SUCCESS; +} + +/************************************************************************************ +Range coding macros -- ugly, but outperform inline's (every cycle counts here) +************************************************************************************/ +#define PUTC(VALUE) m_pBitArray[m_nCurrentBitIndex >> 5] |= ((VALUE) & 0xFF) << (24 - (m_nCurrentBitIndex & 31)); m_nCurrentBitIndex += 8; +#define PUTC_NOCAP(VALUE) m_pBitArray[m_nCurrentBitIndex >> 5] |= (VALUE) << (24 - (m_nCurrentBitIndex & 31)); m_nCurrentBitIndex += 8; + +#define NORMALIZE_RANGE_CODER \ + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) \ + { \ + if (m_RangeCoderInfo.low < (0xFF << SHIFT_BITS)) \ + { \ + PUTC(m_RangeCoderInfo.buffer); \ + for ( ; m_RangeCoderInfo.help; m_RangeCoderInfo.help--) { PUTC_NOCAP(0xFF); } \ + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.low >> SHIFT_BITS); \ + } \ + else if (m_RangeCoderInfo.low & TOP_VALUE) \ + { \ + PUTC(m_RangeCoderInfo.buffer + 1); \ + m_nCurrentBitIndex += (m_RangeCoderInfo.help * 8); \ + m_RangeCoderInfo.help = 0; \ + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.low >> SHIFT_BITS); \ + } \ + else \ + { \ + m_RangeCoderInfo.help++; \ + } \ + \ + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) & (TOP_VALUE - 1); \ + m_RangeCoderInfo.range <<= 8; \ + } + +#define ENCODE_FAST(RANGE_WIDTH, RANGE_TOTAL, SHIFT) \ + NORMALIZE_RANGE_CODER \ + const int nTemp = m_RangeCoderInfo.range >> (SHIFT); \ + m_RangeCoderInfo.range = nTemp * (RANGE_WIDTH); \ + m_RangeCoderInfo.low += nTemp * (RANGE_TOTAL); + +#define ENCODE_DIRECT(VALUE, SHIFT) \ + NORMALIZE_RANGE_CODER \ + m_RangeCoderInfo.range = m_RangeCoderInfo.range >> (SHIFT); \ + m_RangeCoderInfo.low += m_RangeCoderInfo.range * (VALUE); + +/************************************************************************************ +Directly encode bits to the bitstream +************************************************************************************/ +int CBitArray::EncodeBits(unsigned int nValue, int nBits) +{ + // make sure there is room for the data + // this is a little slower than ensuring a huge block to start with, but it's safer + if (m_nCurrentBitIndex > REFILL_BIT_THRESHOLD) + { + RETURN_ON_ERROR(OutputBitArray()) + } + + ENCODE_DIRECT(nValue, nBits); + return 0; +} + +/************************************************************************************ +Encodes an unsigned int to the bit array (no rice coding) +************************************************************************************/ +int CBitArray::EncodeUnsignedLong(unsigned int n) +{ + // make sure there are at least 8 bytes in the buffer + if (m_nCurrentBitIndex > (BIT_ARRAY_BYTES - 8)) + { + RETURN_ON_ERROR(OutputBitArray()) + } + + // encode the value + uint32 nBitArrayIndex = m_nCurrentBitIndex >> 5; + int nBitIndex = m_nCurrentBitIndex & 31; + + if (nBitIndex == 0) + { + m_pBitArray[nBitArrayIndex] = n; + } + else + { + m_pBitArray[nBitArrayIndex] |= n >> nBitIndex; + m_pBitArray[nBitArrayIndex + 1] = n << (32 - nBitIndex); + } + + m_nCurrentBitIndex += 32; + + return 0; +} + +/************************************************************************************ +Advance to a byte boundary (for frame alignment) +************************************************************************************/ +void CBitArray::AdvanceToByteBoundary() +{ + while (m_nCurrentBitIndex % 8) + m_nCurrentBitIndex++; +} + +/************************************************************************************ +Encode a value +************************************************************************************/ +int CBitArray::EncodeValue(int nEncode, BIT_ARRAY_STATE & BitArrayState) +{ + // make sure there is room for the data + // this is a little slower than ensuring a huge block to start with, but it's safer + if (m_nCurrentBitIndex > REFILL_BIT_THRESHOLD) + { + RETURN_ON_ERROR(OutputBitArray()) + } + + // convert to unsigned + nEncode = (nEncode > 0) ? nEncode * 2 - 1 : -nEncode * 2; + + int nOriginalKSum = BitArrayState.nKSum; + + // get the working k + int nTempK = (BitArrayState.k) ? BitArrayState.k - 1 : 0; + + // update nKSum + BitArrayState.nKSum += ((nEncode + 1) / 2) - ((BitArrayState.nKSum + 16) >> 5); + + // update k + if (BitArrayState.nKSum < K_SUM_MIN_BOUNDARY[BitArrayState.k]) + BitArrayState.k--; + else if (BitArrayState.nKSum >= K_SUM_MIN_BOUNDARY[BitArrayState.k + 1]) + BitArrayState.k++; + + // figure the pivot value + int nPivotValue = max(nOriginalKSum / 32, 1); + int nOverflow = nEncode / nPivotValue; + int nBase = nEncode - (nOverflow * nPivotValue); + + // store the overflow + if (nOverflow < (MODEL_ELEMENTS - 1)) + { + ENCODE_FAST(RANGE_WIDTH[nOverflow], RANGE_TOTAL[nOverflow], RANGE_OVERFLOW_SHIFT); + + #ifdef BUILD_RANGE_TABLE + g_aryOverflows[nOverflow]++; + g_nTotalOverflow++; + #endif + } + else + { + // store the "special" overflow (tells that perfect k is encoded next) + ENCODE_FAST(RANGE_WIDTH[MODEL_ELEMENTS - 1], RANGE_TOTAL[MODEL_ELEMENTS - 1], RANGE_OVERFLOW_SHIFT); + + #ifdef BUILD_RANGE_TABLE + g_aryOverflows[MODEL_ELEMENTS - 1]++; + g_nTotalOverflow++; + #endif + + // code the overflow using straight bits + ENCODE_DIRECT((nOverflow >> 16) & 0xFFFF, 16); + ENCODE_DIRECT(nOverflow & 0xFFFF, 16); + } + + // code the base + { + if (nPivotValue >= (1 << 16)) + { + int nPivotValueBits = 0; + while ((nPivotValue >> nPivotValueBits) > 0) { nPivotValueBits++; } + int nSplitFactor = 1 << (nPivotValueBits - 16); + + // we know that base is smaller than pivot coming into this + // however, after we divide both by an integer, they could be the same + // we account by adding one to the pivot, but this hurts compression + // by (1 / nSplitFactor) -- therefore we maximize the split factor + // that gets one added to it + + // encode the pivot as two pieces + int nPivotValueA = (nPivotValue / nSplitFactor) + 1; + int nPivotValueB = nSplitFactor; + + int nBaseA = nBase / nSplitFactor; + int nBaseB = nBase % nSplitFactor; + + { + NORMALIZE_RANGE_CODER + const int nTemp = m_RangeCoderInfo.range / nPivotValueA; + m_RangeCoderInfo.range = nTemp; + m_RangeCoderInfo.low += nTemp * nBaseA; + } + + { + NORMALIZE_RANGE_CODER + const int nTemp = m_RangeCoderInfo.range / nPivotValueB; + m_RangeCoderInfo.range = nTemp; + m_RangeCoderInfo.low += nTemp * nBaseB; + } + } + else + { + + NORMALIZE_RANGE_CODER + const int nTemp = m_RangeCoderInfo.range / nPivotValue; + m_RangeCoderInfo.range = nTemp; + m_RangeCoderInfo.low += nTemp * nBase; + } + } + + return 0; +} + +/************************************************************************************ +Flush +************************************************************************************/ +void CBitArray::FlushBitArray() +{ + // advance to a byte boundary (for alignment) + AdvanceToByteBoundary(); + + // the range coder + m_RangeCoderInfo.low = 0; // full code range + m_RangeCoderInfo.range = TOP_VALUE; + m_RangeCoderInfo.buffer = 0; + m_RangeCoderInfo.help = 0; // no bytes to follow +} + +void CBitArray::FlushState(BIT_ARRAY_STATE & BitArrayState) +{ + // k and ksum + BitArrayState.k = 10; + BitArrayState.nKSum = (1 << BitArrayState.k) * 16; +} + +/************************************************************************************ +Finalize +************************************************************************************/ +void CBitArray::Finalize() +{ + NORMALIZE_RANGE_CODER + + unsigned int nTemp = (m_RangeCoderInfo.low >> SHIFT_BITS) + 1; + + if (nTemp > 0xFF) // we have a carry + { + PUTC(m_RangeCoderInfo.buffer + 1); + for ( ; m_RangeCoderInfo.help; m_RangeCoderInfo.help--) + { + PUTC(0); + } + } + else // no carry + { + PUTC(m_RangeCoderInfo.buffer); + for ( ; m_RangeCoderInfo.help; m_RangeCoderInfo.help--) + { + PUTC(((unsigned char) 0xFF)); + } + } + + // we must output these bytes so the decoder can properly work at the end of the stream + PUTC(nTemp & 0xFF); + PUTC(0); + PUTC(0); + PUTC(0); +} + +/************************************************************************************ +Build a range table (for development / debugging) +************************************************************************************/ +#ifdef BUILD_RANGE_TABLE +void CBitArray::OutputRangeTable() +{ + int z; + + if (g_nTotalOverflow == 0) return; + + int nTotal = 0; + int aryWidth[256]; ZeroMemory(aryWidth, 256 * 4); + for (z = 0; z < MODEL_ELEMENTS; z++) + { + aryWidth[z] = int(((float(g_aryOverflows[z]) * float(65536)) + (g_nTotalOverflow / 2)) / float(g_nTotalOverflow)); + if (aryWidth[z] == 0) aryWidth[z] = 1; + nTotal += aryWidth[z]; + } + + z = 0; + while (nTotal > 65536) + { + if (aryWidth[z] != 1) + { + aryWidth[z]--; + nTotal--; + } + z++; + if (z == MODEL_ELEMENTS) z = 0; + } + + z = 0; + while (nTotal < 65536) + { + aryWidth[z++]++; + nTotal++; + if (z == MODEL_ELEMENTS) z = 0; + } + + int aryTotal[256]; ZeroMemory(aryTotal, 256 * 4); + for (z = 0; z < MODEL_ELEMENTS; z++) + { + for (int q = 0; q < z; q++) + { + aryTotal[z] += aryWidth[q]; + } + } + + TCHAR buf[1024]; + _stprintf(buf, _T("const uint32 RANGE_TOTAL[%d] = {"), MODEL_ELEMENTS); + ODS(buf); + for (z = 0; z < MODEL_ELEMENTS; z++) + { + _stprintf(buf, _T("%d,"), aryTotal[z]); + OutputDebugString(buf); + } + ODS(_T("};\n")); + + _stprintf(buf, _T("const uint32 RANGE_WIDTH[%d] = {"), MODEL_ELEMENTS); + ODS(buf); + for (z = 0; z < MODEL_ELEMENTS; z++) + { + _stprintf(buf, _T("%d,"), aryWidth[z]); + OutputDebugString(buf); + } + ODS(_T("};\n\n")); +} +#endif // #ifdef BUILD_RANGE_TABLE diff --git a/MAC_SDK/Source/MACLib/BitArray.h b/MAC_SDK/Source/MACLib/BitArray.h new file mode 100644 index 0000000..2f4cde7 --- /dev/null +++ b/MAC_SDK/Source/MACLib/BitArray.h @@ -0,0 +1,62 @@ +#ifndef APE_BITARRAY_H +#define APE_BITARRAY_H + +#include "IO.h" +#include "MD5.h" + +//#define BUILD_RANGE_TABLE + +struct RANGE_CODER_STRUCT_COMPRESS +{ + unsigned int low; // low end of interval + unsigned int range; // length of interval + unsigned int help; // bytes_to_follow resp. intermediate value + unsigned char buffer; // buffer for input / output +}; + +struct BIT_ARRAY_STATE +{ + uint32 k; + uint32 nKSum; +}; + +class CBitArray +{ +public: + + // construction / destruction + CBitArray(CIO *pIO); + ~CBitArray(); + + // encoding + int EncodeUnsignedLong(unsigned int n); + int EncodeValue(int nEncode, BIT_ARRAY_STATE & BitArrayState); + int EncodeBits(unsigned int nValue, int nBits); + + // output (saving) + int OutputBitArray(BOOL bFinalize = FALSE); + + // other functions + void Finalize(); + void AdvanceToByteBoundary(); + inline uint32 GetCurrentBitIndex() { return m_nCurrentBitIndex; } + void FlushState(BIT_ARRAY_STATE & BitArrayState); + void FlushBitArray(); + inline CMD5Helper & GetMD5Helper() { return m_MD5; } + +private: + + // data members + uint32 * m_pBitArray; + CIO * m_pIO; + uint32 m_nCurrentBitIndex; + RANGE_CODER_STRUCT_COMPRESS m_RangeCoderInfo; + CMD5Helper m_MD5; + +#ifdef BUILD_RANGE_TABLE + void OutputRangeTable(); +#endif + +}; + +#endif // #ifndef APE_BITARRAY_H diff --git a/MAC_SDK/Source/MACLib/MACLib.cpp b/MAC_SDK/Source/MACLib/MACLib.cpp new file mode 100644 index 0000000..19a5acb --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.cpp @@ -0,0 +1,157 @@ +#include "All.h" +#include "MACLib.h" + +#include "APECompress.h" +#include "APECompressCreate.h" +#include "APECompressCore.h" +#include "APECompress.h" +#include "APEDecompress.h" +#include "APEInfo.h" +#include "APELink.h" + +#ifdef BACKWARDS_COMPATIBILITY + #include "Old/APEDecompressOld.h" +#endif + +IAPEDecompress * CreateIAPEDecompressCore(CAPEInfo * pAPEInfo, int nStartBlock, int nFinishBlock, int * pErrorCode) +{ + IAPEDecompress * pAPEDecompress = NULL; + if (pAPEInfo != NULL && *pErrorCode == ERROR_SUCCESS) + { + try + { + if (pAPEInfo->GetInfo(APE_INFO_FILE_VERSION) >= 3930) + pAPEDecompress = new CAPEDecompress(pErrorCode, pAPEInfo, nStartBlock, nFinishBlock); +#ifdef BACKWARDS_COMPATIBILITY + else + pAPEDecompress = new CAPEDecompressOld(pErrorCode, pAPEInfo, nStartBlock, nFinishBlock); +#endif + + if (pAPEDecompress == NULL || *pErrorCode != ERROR_SUCCESS) + { + SAFE_DELETE(pAPEDecompress) + } + } + catch(...) + { + SAFE_DELETE(pAPEDecompress) + *pErrorCode = ERROR_UNDEFINED; + } + } + + return pAPEDecompress; +} + +IAPEDecompress * __stdcall CreateIAPEDecompress(const str_utf16 * pFilename, int * pErrorCode) +{ + // error check the parameters + if ((pFilename == NULL) || (wcslen(pFilename) == 0)) + { + if (pErrorCode) *pErrorCode = ERROR_BAD_PARAMETER; + return NULL; + } + + // variables + int nErrorCode = ERROR_UNDEFINED; + CAPEInfo * pAPEInfo = NULL; + int nStartBlock = -1; int nFinishBlock = -1; + + // get the extension + const str_utf16 * pExtension = &pFilename[wcslen(pFilename)]; + while ((pExtension > pFilename) && (*pExtension != '.')) + pExtension--; + + // take the appropriate action (based on the extension) + if (wcsicmp(pExtension, L".apl") == 0) + { + // "link" file (.apl linked large APE file) + CAPELink APELink(pFilename); + if (APELink.GetIsLinkFile()) + { + pAPEInfo = new CAPEInfo(&nErrorCode, APELink.GetImageFilename(), new CAPETag(pFilename, TRUE)); + nStartBlock = APELink.GetStartBlock(); nFinishBlock = APELink.GetFinishBlock(); + } + } + else if ((wcsicmp(pExtension, L".mac") == 0) || (wcsicmp(pExtension, L".ape") == 0)) + { + // plain .ape file + pAPEInfo = new CAPEInfo(&nErrorCode, pFilename); + } + + // fail if we couldn't get the file information + if (pAPEInfo == NULL) + { + if (pErrorCode) *pErrorCode = ERROR_INVALID_INPUT_FILE; + return NULL; + } + + // create and return + IAPEDecompress * pAPEDecompress = CreateIAPEDecompressCore(pAPEInfo, nStartBlock, nFinishBlock, &nErrorCode); + if (pErrorCode) *pErrorCode = nErrorCode; + return pAPEDecompress; +} + +IAPEDecompress * __stdcall CreateIAPEDecompressEx(CIO * pIO, int * pErrorCode) +{ + int nErrorCode = ERROR_UNDEFINED; + CAPEInfo * pAPEInfo = new CAPEInfo(&nErrorCode, pIO); + IAPEDecompress * pAPEDecompress = CreateIAPEDecompressCore(pAPEInfo, -1, -1, &nErrorCode); + if (pErrorCode) *pErrorCode = nErrorCode; + return pAPEDecompress; +} + + +IAPEDecompress * __stdcall CreateIAPEDecompressEx2(CAPEInfo * pAPEInfo, int nStartBlock, int nFinishBlock, int * pErrorCode) +{ + int nErrorCode = ERROR_SUCCESS; + IAPEDecompress * pAPEDecompress = CreateIAPEDecompressCore(pAPEInfo, nStartBlock, nFinishBlock, &nErrorCode); + if (pErrorCode) *pErrorCode = nErrorCode; + return pAPEDecompress; +} + +IAPECompress * __stdcall CreateIAPECompress(int * pErrorCode) +{ + if (pErrorCode) + *pErrorCode = ERROR_SUCCESS; + + return new CAPECompress(); +} + +int __stdcall FillWaveFormatEx(WAVEFORMATEX * pWaveFormatEx, int nSampleRate, int nBitsPerSample, int nChannels) +{ + pWaveFormatEx->cbSize = 0; + pWaveFormatEx->nSamplesPerSec = nSampleRate; + pWaveFormatEx->wBitsPerSample = nBitsPerSample; + pWaveFormatEx->nChannels = nChannels; + pWaveFormatEx->wFormatTag = 1; + + pWaveFormatEx->nBlockAlign = (pWaveFormatEx->wBitsPerSample / 8) * pWaveFormatEx->nChannels; + pWaveFormatEx->nAvgBytesPerSec = pWaveFormatEx->nBlockAlign * pWaveFormatEx->nSamplesPerSec; + + return ERROR_SUCCESS; +} + +int __stdcall FillWaveHeader(WAVE_HEADER * pWAVHeader, int nAudioBytes, WAVEFORMATEX * pWaveFormatEx, int nTerminatingBytes) +{ + try + { + // RIFF header + memcpy(pWAVHeader->cRIFFHeader, "RIFF", 4); + pWAVHeader->nRIFFBytes = (nAudioBytes + 44) - 8 + nTerminatingBytes; + + // format header + memcpy(pWAVHeader->cDataTypeID, "WAVE", 4); + memcpy(pWAVHeader->cFormatHeader, "fmt ", 4); + + // the format chunk is the first 16 bytes of a waveformatex + pWAVHeader->nFormatBytes = 16; + memcpy(&pWAVHeader->nFormatTag, pWaveFormatEx, 16); + + // the data header + memcpy(pWAVHeader->cDataHeader, "data", 4); + pWAVHeader->nDataBytes = nAudioBytes; + + return ERROR_SUCCESS; + } + catch(...) { return ERROR_UNDEFINED; } +} \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/MACLib.dsp b/MAC_SDK/Source/MACLib/MACLib.dsp new file mode 100644 index 0000000..0edca6e --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.dsp @@ -0,0 +1,462 @@ +# Microsoft Developer Studio Project File - Name="MACLib" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=MACLib - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "MACLib.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "MACLib.mak" CFG="MACLib - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "MACLib - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "MACLib - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName ""$/Monkey's Audio/MACLib", SCAAAAAA" +# PROP Scc_LocalPath "." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "MACLib - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Ot /Og /Oi /Ob2 /I "..\Shared" /D "WIN32" /D "NDEBUG" /D "_LIB" /D "_UNICODE" /D "UNICODE" /FR /YX"all.h" /FD /c +# SUBTRACT CPP /Oa +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo +# Begin Special Build Tool +ProjDir=. +SOURCE="$(InputPath)" +PreLink_Desc=Building assembly... +PreLink_Cmds=cd $(ProjDir)\Assembly nasmw -d WIN32 -f win32 -o Assembly.obj Assembly.nas +# End Special Build Tool + +!ELSEIF "$(CFG)" == "MACLib - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\Shared" /D "WIN32" /D "_DEBUG" /D "_LIB" /D "_UNICODE" /D "UNICODE" /FD /GZ /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo +# Begin Special Build Tool +ProjDir=. +SOURCE="$(InputPath)" +PreLink_Desc=Building assembly... +PreLink_Cmds=cd $(ProjDir)\Assembly nasmw -d WIN32 -f win32 -o Assembly.obj Assembly.nas +# End Special Build Tool + +!ENDIF + +# Begin Target + +# Name "MACLib - Win32 Release" +# Name "MACLib - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Group "Compress" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\APECompress.cpp +# End Source File +# Begin Source File + +SOURCE=.\APECompressCore.cpp +# End Source File +# Begin Source File + +SOURCE=.\APECompressCreate.cpp +# End Source File +# Begin Source File + +SOURCE=.\BitArray.cpp +# End Source File +# End Group +# Begin Group "Decompress" + +# PROP Default_Filter "" +# Begin Group "Old" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=".\Old\Anti-Predictor.cpp" +# End Source File +# Begin Source File + +SOURCE=.\Old\AntiPredictorExtraHigh.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\AntiPredictorFast.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\AntiPredictorHigh.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\AntiPredictorNormal.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\APEDecompressCore.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\APEDecompressOld.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\UnBitArrayOld.cpp +# End Source File +# Begin Source File + +SOURCE=.\Old\UnMAC.cpp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\APEDecompress.cpp +# End Source File +# Begin Source File + +SOURCE=.\UnBitArray.cpp +# End Source File +# Begin Source File + +SOURCE=.\UnBitArrayBase.cpp +# End Source File +# End Group +# Begin Group "Info" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\APEHeader.cpp +# End Source File +# Begin Source File + +SOURCE=.\APEInfo.cpp +# End Source File +# Begin Source File + +SOURCE=.\APELink.cpp +# End Source File +# Begin Source File + +SOURCE=.\APETag.cpp +# End Source File +# Begin Source File + +SOURCE=.\WAVInputSource.cpp +# End Source File +# End Group +# Begin Group "Tools" + +# PROP Default_Filter "" +# Begin Group "IO" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\Shared\StdLibFileIO.cpp +# End Source File +# Begin Source File + +SOURCE=..\Shared\WinFileIO.cpp +# End Source File +# End Group +# Begin Source File + +SOURCE=..\Shared\CharacterHelper.cpp +# End Source File +# Begin Source File + +SOURCE=..\Shared\CircleBuffer.cpp +# End Source File +# Begin Source File + +SOURCE=..\Shared\GlobalFunctions.cpp +# End Source File +# Begin Source File + +SOURCE=.\MACProgressHelper.cpp +# End Source File +# Begin Source File + +SOURCE=.\MD5.cpp +# End Source File +# Begin Source File + +SOURCE=.\Prepare.cpp +# End Source File +# End Group +# Begin Group "Prediction" + +# PROP Default_Filter "" +# Begin Group "Filters" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\NNFilter.cpp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\NewPredictor.cpp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\APESimple.cpp +# End Source File +# Begin Source File + +SOURCE=.\MACLib.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Group "Compress (h)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\APECompress.h +# End Source File +# Begin Source File + +SOURCE=.\APECompressCore.h +# End Source File +# Begin Source File + +SOURCE=.\APECompressCreate.h +# End Source File +# Begin Source File + +SOURCE=.\BitArray.h +# End Source File +# End Group +# Begin Group "Decompress (h)" + +# PROP Default_Filter "" +# Begin Group "Old (h)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=".\Old\Anti-Predictor.h" +# End Source File +# Begin Source File + +SOURCE=.\Old\APEDecompressCore.h +# End Source File +# Begin Source File + +SOURCE=.\Old\APEDecompressOld.h +# End Source File +# Begin Source File + +SOURCE=.\Old\UnBitArrayOld.h +# End Source File +# Begin Source File + +SOURCE=.\Old\UnMAC.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\APEDecompress.h +# End Source File +# Begin Source File + +SOURCE=.\UnBitArray.h +# End Source File +# Begin Source File + +SOURCE=.\UnBitArrayBase.h +# End Source File +# End Group +# Begin Group "Info (h)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\APEHeader.h +# End Source File +# Begin Source File + +SOURCE=.\APEInfo.h +# End Source File +# Begin Source File + +SOURCE=.\APELink.h +# End Source File +# Begin Source File + +SOURCE=.\APETag.h +# End Source File +# Begin Source File + +SOURCE=.\WAVInputSource.h +# End Source File +# End Group +# Begin Group "Tools (h)" + +# PROP Default_Filter "" +# Begin Group "IO (h)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\Shared\IO.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\StdLibFileIO.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\WinFileIO.h +# End Source File +# End Group +# Begin Source File + +SOURCE=..\Shared\CharacterHelper.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\CircleBuffer.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\GlobalFunctions.h +# End Source File +# Begin Source File + +SOURCE=.\MACProgressHelper.h +# End Source File +# Begin Source File + +SOURCE=.\md5.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\NoWindows.h +# End Source File +# Begin Source File + +SOURCE=.\Prepare.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\SmartPtr.h +# End Source File +# End Group +# Begin Group "Prediction (h)" + +# PROP Default_Filter "" +# Begin Group "Filters (h)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\NNFilter.h +# End Source File +# Begin Source File + +SOURCE=..\Shared\RollBuffer.h +# End Source File +# Begin Source File + +SOURCE=.\ScaledFirstOrderFilter.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\NewPredictor.h +# End Source File +# Begin Source File + +SOURCE=.\Predictor.h +# End Source File +# End Group +# Begin Source File + +SOURCE=..\Shared\All.h +# End Source File +# Begin Source File + +SOURCE=.\Assembly\Assembly.h +# End Source File +# Begin Source File + +SOURCE=.\MACLib.h +# End Source File +# End Group +# Begin Source File + +SOURCE=..\Credits.txt +# End Source File +# Begin Source File + +SOURCE=..\History.txt +# End Source File +# Begin Source File + +SOURCE="..\To Do.txt" +# End Source File +# Begin Source File + +SOURCE=.\Assembly\Assembly.obj +# End Source File +# End Target +# End Project diff --git a/MAC_SDK/Source/MACLib/MACLib.h b/MAC_SDK/Source/MACLib/MACLib.h new file mode 100644 index 0000000..af0cbcd --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.h @@ -0,0 +1,450 @@ +/***************************************************************************************** +Monkey's Audio MACLib.h (include for using MACLib.lib in your projects) +Copyright (C) 2000-2003 by Matthew T. Ashland All Rights Reserved. + +Overview: + +There are two main interfaces... create one (using CreateIAPExxx) and go to town: + + IAPECompress - for creating APE files + IAPEDecompress - for decompressing and analyzing APE files + +Note(s): + +Unless otherwise specified, functions return ERROR_SUCCESS (0) on success and an +error code on failure. + +The terminology "Sample" refers to a single sample value, and "Block" refers +to a collection of "Channel" samples. For simplicity, MAC typically uses blocks +everywhere so that channel mis-alignment cannot happen. (i.e. on a CD, a sample is +2 bytes and a block is 4 bytes ([2 bytes per sample] * [2 channels] = 4 bytes)) + +Questions / Suggestions: + +Please direct questions or comments to the Monkey's Audio developers board: +http://www.monkeysaudio.com/cgi-bin/YaBB/YaBB.cgi -> Developers +or, if necessary, matt @ monkeysaudio.com +*****************************************************************************************/ + +#ifndef APE_MACLIB_H +#define APE_MACLIB_H + +/************************************************************************************************* +APE File Format Overview: (pieces in order -- only valid for the latest version APE files) + + JUNK - any amount of "junk" before the APE_DESCRIPTOR (so people that put ID3v2 tags on the files aren't hosed) + APE_DESCRIPTOR - defines the sizes (and offsets) of all the pieces, as well as the MD5 checksum + APE_HEADER - describes all of the necessary information about the APE file + SEEK TABLE - the table that represents seek offsets [optional] + HEADER DATA - the pre-audio data from the original file [optional] + APE FRAMES - the actual compressed audio (broken into frames for seekability) + TERMINATING DATA - the post-audio data from the original file [optional] + TAG - describes all the properties of the file [optional] + +Notes: + + Junk: + + This block may not be supported in the future, so don't write any software that adds meta data + before the APE_DESCRIPTOR. Please use the APE Tag for any meta data. + + Seek Table: + + A 32-bit unsigned integer array of offsets from the header to the frame data. May become "delta" + values someday to better suit huge files. + + MD5 Hash: + + Since the header is the last part written to an APE file, you must calculate the MD5 checksum out of order. + So, you first calculate from the tail of the seek table to the end of the terminating data. + Then, go back and do from the end of the descriptor to the tail of the seek table. + You may wish to just cache the header data when starting and run it last, so you don't + need to seek back in the I/O. +*************************************************************************************************/ + +/***************************************************************************************** +Defines +*****************************************************************************************/ +#define COMPRESSION_LEVEL_FAST 1000 +#define COMPRESSION_LEVEL_NORMAL 2000 +#define COMPRESSION_LEVEL_HIGH 3000 +#define COMPRESSION_LEVEL_EXTRA_HIGH 4000 +#define COMPRESSION_LEVEL_INSANE 5000 + +#define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE] +#define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE] +#define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE] +#define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE] +#define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level +#define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored) + +#define CREATE_WAV_HEADER_ON_DECOMPRESSION -1 +#define MAX_AUDIO_BYTES_UNKNOWN -1 + +typedef void (__stdcall * APE_PROGRESS_CALLBACK) (int); + +/***************************************************************************************** +WAV header structure +*****************************************************************************************/ +struct WAVE_HEADER +{ + // RIFF header + char cRIFFHeader[4]; + unsigned int nRIFFBytes; + + // data type + char cDataTypeID[4]; + + // wave format + char cFormatHeader[4]; + unsigned int nFormatBytes; + + unsigned short nFormatTag; + unsigned short nChannels; + unsigned int nSamplesPerSec; + unsigned int nAvgBytesPerSec; + unsigned short nBlockAlign; + unsigned short nBitsPerSample; + + // data chunk header + char cDataHeader[4]; + unsigned int nDataBytes; +}; + +/***************************************************************************************** +APE_DESCRIPTOR structure (file header that describes lengths, offsets, etc.) +*****************************************************************************************/ +struct APE_DESCRIPTOR +{ + char cID[4]; // should equal 'MAC ' + uint16 nVersion; // version number * 1000 (3.81 = 3810) + + uint32 nDescriptorBytes; // the number of descriptor bytes (allows later expansion of this header) + uint32 nHeaderBytes; // the number of header APE_HEADER bytes + uint32 nSeekTableBytes; // the number of bytes of the seek table + uint32 nHeaderDataBytes; // the number of header data bytes (from original file) + uint32 nAPEFrameDataBytes; // the number of bytes of APE frame data + uint32 nAPEFrameDataBytesHigh; // the high order number of APE frame data bytes + uint32 nTerminatingDataBytes; // the terminating data of the file (not including tag data) + + uint8 cFileMD5[16]; // the MD5 hash of the file (see notes for usage... it's a littly tricky) +}; + +/***************************************************************************************** +APE_HEADER structure (describes the format, duration, etc. of the APE file) +*****************************************************************************************/ +struct APE_HEADER +{ + uint16 nCompressionLevel; // the compression level (see defines I.E. COMPRESSION_LEVEL_FAST) + uint16 nFormatFlags; // any format flags (for future use) + + uint32 nBlocksPerFrame; // the number of audio blocks in one frame + uint32 nFinalFrameBlocks; // the number of audio blocks in the final frame + uint32 nTotalFrames; // the total number of frames + + uint16 nBitsPerSample; // the bits per sample (typically 16) + uint16 nChannels; // the number of channels (1 or 2) + uint32 nSampleRate; // the sample rate (typically 44100) +}; + +/************************************************************************************************* +Classes (fully defined elsewhere) +*************************************************************************************************/ +class CIO; +class CInputSource; +class CAPEInfo; + +/************************************************************************************************* +IAPEDecompress fields - used when querying for information + +Note(s): +-the distinction between APE_INFO_XXXX and APE_DECOMPRESS_XXXX is that the first is querying the APE +information engine, and the other is querying the decompressor, and since the decompressor can be +a range of an APE file (for APL), differences will arise. Typically, use the APE_DECOMPRESS_XXXX +fields when querying for info about the length, etc. so APL will work properly. +(i.e. (APE_INFO_TOTAL_BLOCKS != APE_DECOMPRESS_TOTAL_BLOCKS) for APL files) +*************************************************************************************************/ +enum APE_DECOMPRESS_FIELDS +{ + APE_INFO_FILE_VERSION = 1000, // version of the APE file * 1000 (3.93 = 3930) [ignored, ignored] + APE_INFO_COMPRESSION_LEVEL = 1001, // compression level of the APE file [ignored, ignored] + APE_INFO_FORMAT_FLAGS = 1002, // format flags of the APE file [ignored, ignored] + APE_INFO_SAMPLE_RATE = 1003, // sample rate (Hz) [ignored, ignored] + APE_INFO_BITS_PER_SAMPLE = 1004, // bits per sample [ignored, ignored] + APE_INFO_BYTES_PER_SAMPLE = 1005, // number of bytes per sample [ignored, ignored] + APE_INFO_CHANNELS = 1006, // channels [ignored, ignored] + APE_INFO_BLOCK_ALIGN = 1007, // block alignment [ignored, ignored] + APE_INFO_BLOCKS_PER_FRAME = 1008, // number of blocks in a frame (frames are used internally) [ignored, ignored] + APE_INFO_FINAL_FRAME_BLOCKS = 1009, // blocks in the final frame (frames are used internally) [ignored, ignored] + APE_INFO_TOTAL_FRAMES = 1010, // total number frames (frames are used internally) [ignored, ignored] + APE_INFO_WAV_HEADER_BYTES = 1011, // header bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_TERMINATING_BYTES = 1012, // terminating bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_DATA_BYTES = 1013, // data bytes of the decompressed WAV [ignored, ignored] + APE_INFO_WAV_TOTAL_BYTES = 1014, // total bytes of the decompressed WAV [ignored, ignored] + APE_INFO_APE_TOTAL_BYTES = 1015, // total bytes of the APE file [ignored, ignored] + APE_INFO_TOTAL_BLOCKS = 1016, // total blocks of audio data [ignored, ignored] + APE_INFO_LENGTH_MS = 1017, // length in ms (1 sec = 1000 ms) [ignored, ignored] + APE_INFO_AVERAGE_BITRATE = 1018, // average bitrate of the APE [ignored, ignored] + APE_INFO_FRAME_BITRATE = 1019, // bitrate of specified APE frame [frame index, ignored] + APE_INFO_DECOMPRESSED_BITRATE = 1020, // bitrate of the decompressed WAV [ignored, ignored] + APE_INFO_PEAK_LEVEL = 1021, // peak audio level (obsolete) (-1 is unknown) [ignored, ignored] + APE_INFO_SEEK_BIT = 1022, // bit offset [frame index, ignored] + APE_INFO_SEEK_BYTE = 1023, // byte offset [frame index, ignored] + APE_INFO_WAV_HEADER_DATA = 1024, // error code [buffer *, max bytes] + APE_INFO_WAV_TERMINATING_DATA = 1025, // error code [buffer *, max bytes] + APE_INFO_WAVEFORMATEX = 1026, // error code [waveformatex *, ignored] + APE_INFO_IO_SOURCE = 1027, // I/O source (CIO *) [ignored, ignored] + APE_INFO_FRAME_BYTES = 1028, // bytes (compressed) of the frame [frame index, ignored] + APE_INFO_FRAME_BLOCKS = 1029, // blocks in a given frame [frame index, ignored] + APE_INFO_TAG = 1030, // point to tag (CAPETag *) [ignored, ignored] + + APE_DECOMPRESS_CURRENT_BLOCK = 2000, // current block location [ignored, ignored] + APE_DECOMPRESS_CURRENT_MS = 2001, // current millisecond location [ignored, ignored] + APE_DECOMPRESS_TOTAL_BLOCKS = 2002, // total blocks in the decompressors range [ignored, ignored] + APE_DECOMPRESS_LENGTH_MS = 2003, // total blocks in the decompressors range [ignored, ignored] + APE_DECOMPRESS_CURRENT_BITRATE = 2004, // current bitrate [ignored, ignored] + APE_DECOMPRESS_AVERAGE_BITRATE = 2005, // average bitrate (works with ranges) [ignored, ignored] + + APE_INTERNAL_INFO = 3000, // for internal use -- don't use (returns APE_FILE_INFO *) [ignored, ignored] +}; + +/************************************************************************************************* +IAPEDecompress - interface for working with existing APE files (decoding, seeking, analyzing, etc.) +*************************************************************************************************/ +class IAPEDecompress +{ +public: + + // destructor (needed so implementation's destructor will be called) + virtual ~IAPEDecompress() {} + + /********************************************************************************************* + * Decompress / Seek + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetData(...) - gets raw decompressed audio + // + // Parameters: + // char * pBuffer + // a pointer to a buffer to put the data into + // int nBlocks + // the number of audio blocks desired (see note at intro about blocks vs. samples) + // int * pBlocksRetrieved + // the number of blocks actually retrieved (could be less at end of file or on critical failure) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Seek(...) - seeks + // + // Parameters: + // int nBlockOffset + // the block to seek to (see note at intro about blocks vs. samples) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Seek(int nBlockOffset) = 0; + + /********************************************************************************************* + * Get Information + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetInfo(...) - get information about the APE file or the state of the decompressor + // + // Parameters: + // APE_DECOMPRESS_FIELDS Field + // the field we're querying (see APE_DECOMPRESS_FIELDS above for more info) + // int nParam1 + // generic parameter... usage is listed in APE_DECOMPRESS_FIELDS + // int nParam2 + // generic parameter... usage is listed in APE_DECOMPRESS_FIELDS + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0) = 0; +}; + +/************************************************************************************************* +IAPECompress - interface for creating APE files + +Usage: + + To create an APE file, you Start(...), then add data (in a variety of ways), then Finish(...) +*************************************************************************************************/ +class IAPECompress +{ +public: + + // destructor (needed so implementation's destructor will be called) + virtual ~IAPECompress() {} + + /********************************************************************************************* + * Start + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Start(...) / StartEx(...) - starts encoding + // + // Parameters: + // CIO * pioOutput / const str_utf16 * pFilename + // the output... either a filename or an I/O source + // WAVEFORMATEX * pwfeInput + // format of the audio to encode (use FillWaveFormatEx() if necessary) + // int nMaxAudioBytes + // the absolute maximum audio bytes that will be encoded... encoding fails with a + // ERROR_APE_COMPRESS_TOO_MUCH_DATA if you attempt to encode more than specified here + // (if unknown, use MAX_AUDIO_BYTES_UNKNOWN to allocate as much storage in the seek table as + // possible... limit is then 2 GB of data (~4 hours of CD music)... this wastes around + // 30kb, so only do it if completely necessary) + // int nCompressionLevel + // the compression level for the APE file (fast - extra high) + // (note: extra-high is much slower for little gain) + // const void * pHeaderData + // a pointer to a buffer containing the WAV header (data before the data block in the WAV) + // (note: use NULL for on-the-fly encoding... see next parameter) + // int nHeaderBytes + // number of bytes in the header data buffer (use CREATE_WAV_HEADER_ON_DECOMPRESSION and + // NULL for the pHeaderData and MAC will automatically create the appropriate WAV header + // on decompression) + ////////////////////////////////////////////////////////////////////////////////////////////// + + virtual int Start(const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput, + int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, + const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0; + + virtual int StartEx(CIO * pioOutput, const WAVEFORMATEX * pwfeInput, + int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, + const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0; + + /********************************************************************************************* + * Add / Compress Data + * - there are 3 ways to add data: + * 1) simple call AddData(...) + * 2) lock MAC's buffer, copy into it, and unlock (LockBuffer(...) / UnlockBuffer(...)) + * 3) from an I/O source (AddDataFromInputSource(...)) + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // AddData(...) - adds data to the encoder + // + // Parameters: + // unsigned char * pData + // a pointer to a buffer containing the raw audio data + // int nBytes + // the number of bytes in the buffer + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int AddData(unsigned char * pData, int nBytes) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // GetBufferBytesAvailable(...) - returns the number of bytes available in the buffer + // (helpful when locking) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int GetBufferBytesAvailable() = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // LockBuffer(...) - locks MAC's buffer so we can copy into it + // + // Parameters: + // int * pBytesAvailable + // returns the number of bytes available in the buffer (DO NOT COPY MORE THAN THIS IN) + // + // Return: + // pointer to the buffer (add at that location) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual unsigned char * LockBuffer(int * pBytesAvailable) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // UnlockBuffer(...) - releases the buffer + // + // Parameters: + // int nBytesAdded + // the number of bytes copied into the buffer + // BOOL bProcess + // whether MAC should process as much as possible of the buffer + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int UnlockBuffer(int nBytesAdded, BOOL bProcess = TRUE) = 0; + + + ////////////////////////////////////////////////////////////////////////////////////////////// + // AddDataFromInputSource(...) - use a CInputSource (input source) to add data + // + // Parameters: + // CInputSource * pInputSource + // a pointer to the input source + // int nMaxBytes + // the maximum number of bytes to let MAC add (-1 if MAC can add any amount) + // int * pBytesAdded + // returns the number of bytes added from the I/O source + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int AddDataFromInputSource(CInputSource * pInputSource, int nMaxBytes = -1, int * pBytesAdded = NULL) = 0; + + /********************************************************************************************* + * Finish / Kill + *********************************************************************************************/ + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Finish(...) - ends encoding and finalizes the file + // + // Parameters: + // unsigned char * pTerminatingData + // a pointer to a buffer containing the information to place at the end of the APE file + // (comprised of the WAV terminating data (data after the data block in the WAV) followed + // by any tag information) + // int nTerminatingBytes + // number of bytes in the terminating data buffer + // int nWAVTerminatingBytes + // the number of bytes of the terminating data buffer that should be appended to a decoded + // WAV file (it's basically nTerminatingBytes - the bytes that make up the tag) + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Finish(unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) = 0; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Kill(...) - stops encoding and deletes the output file + // --- NOT CURRENTLY IMPLEMENTED --- + ////////////////////////////////////////////////////////////////////////////////////////////// + virtual int Kill() = 0; +}; + +/************************************************************************************************* +Functions to create the interfaces + +Usage: + Interface creation returns a NULL pointer on failure (and fills error code if it was passed in) + +Usage example: + int nErrorCode; + IAPEDecompress * pAPEDecompress = CreateIAPEDecompress("c:\\1.ape", &nErrorCode); + if (pAPEDecompress == NULL) + { + // failure... nErrorCode will have specific code + } + +*************************************************************************************************/ +extern "C" +{ + IAPEDecompress * __stdcall CreateIAPEDecompress(const str_utf16 * pFilename, int * pErrorCode = NULL); + IAPEDecompress * __stdcall CreateIAPEDecompressEx(CIO * pIO, int * pErrorCode = NULL); + IAPEDecompress * __stdcall CreateIAPEDecompressEx2(CAPEInfo * pAPEInfo, int nStartBlock = -1, int nFinishBlock = -1, int * pErrorCode = NULL); + IAPECompress * __stdcall CreateIAPECompress(int * pErrorCode = NULL); +} + +/************************************************************************************************* +Simple functions - see the SDK sample projects for usage examples +*************************************************************************************************/ +extern "C" +{ + // process whole files + DLLEXPORT int __stdcall CompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL); + DLLEXPORT int __stdcall DecompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall ConvertFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall VerifyFile(const str_ansi * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + + DLLEXPORT int __stdcall CompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL); + DLLEXPORT int __stdcall DecompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall ConvertFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag); + DLLEXPORT int __stdcall VerifyFileW(const str_utf16 * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag, BOOL bQuickVerifyIfPossible = FALSE); + + // helper functions + DLLEXPORT int __stdcall FillWaveFormatEx(WAVEFORMATEX * pWaveFormatEx, int nSampleRate = 44100, int nBitsPerSample = 16, int nChannels = 2); + DLLEXPORT int __stdcall FillWaveHeader(WAVE_HEADER * pWAVHeader, int nAudioBytes, WAVEFORMATEX * pWaveFormatEx, int nTerminatingBytes = 0); +} + +#endif // #ifndef APE_MACLIB_H diff --git a/MAC_SDK/Source/MACLib/MACLib.sln b/MAC_SDK/Source/MACLib/MACLib.sln new file mode 100644 index 0000000..c939473 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MACLib", "MACLib.vcproj", "{0B9C97D4-61B8-4294-A1DF-BA90752A1779}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Sample 2", "..\..\Decompress\Sample 2\Sample 2.vcproj", "{E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|Win32.ActiveCfg = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|Win32.Build.0 = Debug|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x64.ActiveCfg = Debug|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Debug|x64.Build.0 = Debug|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|Win32.ActiveCfg = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|Win32.Build.0 = Release|Win32 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x64.ActiveCfg = Release|x64 + {0B9C97D4-61B8-4294-A1DF-BA90752A1779}.Release|x64.Build.0 = Release|x64 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Debug|Win32.ActiveCfg = Debug|Win32 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Debug|Win32.Build.0 = Debug|Win32 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Debug|x64.ActiveCfg = Debug|x64 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Release|Win32.ActiveCfg = Release|Win32 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Release|Win32.Build.0 = Release|Win32 + {E7B72EF2-1C5A-45EF-BA35-6094BCF560B1}.Release|x64.ActiveCfg = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/MAC_SDK/Source/MACLib/MACLib.vcproj b/MAC_SDK/Source/MACLib/MACLib.vcproj new file mode 100644 index 0000000..d5c11a0 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.vcproj @@ -0,0 +1,2183 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Source/MACLib/MACLib.vcproj.7.10.old b/MAC_SDK/Source/MACLib/MACLib.vcproj.7.10.old new file mode 100644 index 0000000..4bdb285 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACLib.vcproj.7.10.old @@ -0,0 +1,1019 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MAC_SDK/Source/MACLib/MACProgressHelper.cpp b/MAC_SDK/Source/MACLib/MACProgressHelper.cpp new file mode 100644 index 0000000..410dd96 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACProgressHelper.cpp @@ -0,0 +1,82 @@ +#include "All.h" +#include "MACProgressHelper.h" + +CMACProgressHelper::CMACProgressHelper(int nTotalSteps, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag) +{ + m_pKillFlag = pKillFlag; + + m_bUseCallback = FALSE; + if (ProgressCallback != NULL) + { + m_bUseCallback = TRUE; + m_CallbackFunction = ProgressCallback; + } + + m_pPercentageDone = pPercentageDone; + + m_nTotalSteps = nTotalSteps; + m_nCurrentStep = 0; + m_nLastCallbackFiredPercentageDone = 0; + + UpdateProgress(0); +} + +CMACProgressHelper::~CMACProgressHelper() +{ + +} + +void CMACProgressHelper::UpdateProgress(int nCurrentStep, BOOL bForceUpdate) +{ + // update the step + if (nCurrentStep == -1) + m_nCurrentStep++; + else + m_nCurrentStep = nCurrentStep; + + // figure the percentage done + float fPercentageDone = float(m_nCurrentStep) / float(max(m_nTotalSteps, 1)); + int nPercentageDone = (int) (fPercentageDone * 1000 * 100); + if (nPercentageDone > 100000) nPercentageDone = 100000; + + // update the percent done pointer + if (m_pPercentageDone) + { + *m_pPercentageDone = nPercentageDone; + } + + // fire the callback + if (m_bUseCallback) + { + if (bForceUpdate || (nPercentageDone - m_nLastCallbackFiredPercentageDone) >= 1000) + { + m_CallbackFunction(nPercentageDone); + m_nLastCallbackFiredPercentageDone = nPercentageDone; + } + } +} + +int CMACProgressHelper::ProcessKillFlag(BOOL bSleep) +{ + // process any messages (allows repaint, etc.) + if (bSleep) + { + PUMP_MESSAGE_LOOP + } + + if (m_pKillFlag) + { + while (*m_pKillFlag == KILL_FLAG_PAUSE) + { + SLEEP(50); + PUMP_MESSAGE_LOOP + } + + if ((*m_pKillFlag != KILL_FLAG_CONTINUE) && (*m_pKillFlag != KILL_FLAG_PAUSE)) + { + return -1; + } + } + + return ERROR_SUCCESS; +} diff --git a/MAC_SDK/Source/MACLib/MACProgressHelper.h b/MAC_SDK/Source/MACLib/MACProgressHelper.h new file mode 100644 index 0000000..48c08d5 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MACProgressHelper.h @@ -0,0 +1,37 @@ +#ifndef APE_MACPROGRESSHELPER_H +#define APE_MACPROGRESSHELPER_H + +#define KILL_FLAG_CONTINUE 0 +#define KILL_FLAG_PAUSE -1 +#define KILL_FLAG_STOP 1 + +typedef void (__stdcall * APE_PROGRESS_CALLBACK) (int); + +class CMACProgressHelper +{ +public: + + CMACProgressHelper(int nTotalSteps, int *pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int *pKillFlag); + virtual ~CMACProgressHelper(); + + void UpdateProgress(int nCurrentStep = -1, BOOL bForceUpdate = FALSE); + void UpdateProgressComplete() { UpdateProgress(m_nTotalSteps, TRUE); } + + int ProcessKillFlag(BOOL bSleep = TRUE); + +private: + + BOOL m_bUseCallback; + APE_PROGRESS_CALLBACK m_CallbackFunction; + + int *m_pPercentageDone; + + int m_nTotalSteps; + int m_nCurrentStep; + int m_nLastCallbackFiredPercentageDone; + + int *m_pKillFlag; +}; + +#endif // #ifndef APE_MACPROGRESSHELPER_H + diff --git a/MAC_SDK/Source/MACLib/MD5.cpp b/MAC_SDK/Source/MACLib/MD5.cpp new file mode 100644 index 0000000..afd6be6 --- /dev/null +++ b/MAC_SDK/Source/MACLib/MD5.cpp @@ -0,0 +1,264 @@ +/***************************************************************************** +* +* "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm". +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +*****************************************************************************/ + +#include "All.h" +#include +#include "MD5.h" + + +#if __BYTE_ORDER == __BIG_ENDIAN +/* + * Block copy and convert byte order to little-endian. + * dst must be 32bit aligned. + * Length is the number of 32bit words + */ +static void +CopyToLittleEndian ( uint32_t* dst, + const uint8_t* src, + size_t length ) +{ + for ( ; length--; src += 4; dst++ ) { + *dst = (( (uint32_t) src [3] ) << 24) | + (( (uint32_t) src [2] ) << 16) | + (( (uint32_t) src [1] ) << 8) | + (( (uint32_t) src [0] ) << 0); + + + } +} +#endif + + +/* + Assembler versions of __MD5Transform, MD5Init and MD5Update + currently exist for x86 and little-endian ARM. + For other targets, we need to use the C versions below. +*/ + +#if !(defined (__i386__) || ((defined (__arm__) && (__BYTE_ORDER == __LITTLE_ENDIAN)))) + +/* + Initialise the MD5 context. +*/ +void +MD5Init ( MD5_CTX* context ) +{ + context -> count [0] = 0; + context -> count [1] = 0; + + context -> state [0] = 0x67452301; /* Load magic constants. */ + context -> state [1] = 0xefcdab89; + context -> state [2] = 0x98badcfe; + context -> state [3] = 0x10325476; +} + +#define ROTATE_LEFT(x, n) ((x << n) | (x >> (32-n))) + +#define F(x, y, z) (z ^ (x & (y ^ z))) +#define G(x, y, z) (y ^ (z & (x ^ y))) +#define H(x, y, z) (x ^ y ^ z) +#define I(x, y, z) (y ^ (x | ~z)) + +#define FF(a, b, c, d, x, s, ac) { (a) += F (b, c, d) + (x) + (uint32_t)(ac); (a) = ROTATE_LEFT (a, s); (a) += (b); } +#define GG(a, b, c, d, x, s, ac) { (a) += G (b, c, d) + (x) + (uint32_t)(ac); (a) = ROTATE_LEFT (a, s); (a) += (b); } +#define HH(a, b, c, d, x, s, ac) { (a) += H (b, c, d) + (x) + (uint32_t)(ac); (a) = ROTATE_LEFT (a, s); (a) += (b); } +#define II(a, b, c, d, x, s, ac) { (a) += I (b, c, d) + (x) + (uint32_t)(ac); (a) = ROTATE_LEFT (a, s); (a) += (b); } + +static void +__MD5Transform ( uint32_t state [4], + const uint8_t* in, + int repeat ) +{ + const uint32_t* x; + uint32_t a = state [0]; + uint32_t b = state [1]; + uint32_t c = state [2]; + uint32_t d = state [3]; + + for ( ; repeat; repeat-- ) { + uint32_t tempBuffer [16]; +#if __BYTE_ORDER == __BIG_ENDIAN + + CopyToLittleEndian (tempBuffer, in, 16); + x = tempBuffer; +#else + if ( (unsigned int)in & 3 ) { + memcpy ( tempBuffer, in, 64 ); + x = tempBuffer; + } + else { + x = (const uint32_t*) in; + } +#endif + + FF (a, b, c, d, x[ 0], 7, 0xd76aa478); /* 1 */ /* Round 1 */ + FF (d, a, b, c, x[ 1], 12, 0xe8c7b756); /* 2 */ + FF (c, d, a, b, x[ 2], 17, 0x242070db); /* 3 */ + FF (b, c, d, a, x[ 3], 22, 0xc1bdceee); /* 4 */ + FF (a, b, c, d, x[ 4], 7, 0xf57c0faf); /* 5 */ + FF (d, a, b, c, x[ 5], 12, 0x4787c62a); /* 6 */ + FF (c, d, a, b, x[ 6], 17, 0xa8304613); /* 7 */ + FF (b, c, d, a, x[ 7], 22, 0xfd469501); /* 8 */ + FF (a, b, c, d, x[ 8], 7, 0x698098d8); /* 9 */ + FF (d, a, b, c, x[ 9], 12, 0x8b44f7af); /* 10 */ + FF (c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */ + FF (b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */ + FF (a, b, c, d, x[12], 7, 0x6b901122); /* 13 */ + FF (d, a, b, c, x[13], 12, 0xfd987193); /* 14 */ + FF (c, d, a, b, x[14], 17, 0xa679438e); /* 15 */ + FF (b, c, d, a, x[15], 22, 0x49b40821); /* 16 */ + + GG (a, b, c, d, x[ 1], 5, 0xf61e2562); /* 17 */ /* Round 2 */ + GG (d, a, b, c, x[ 6], 9, 0xc040b340); /* 18 */ + GG (c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */ + GG (b, c, d, a, x[ 0], 20, 0xe9b6c7aa); /* 20 */ + GG (a, b, c, d, x[ 5], 5, 0xd62f105d); /* 21 */ + GG (d, a, b, c, x[10], 9, 0x02441453); /* 22 */ + GG (c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */ + GG (b, c, d, a, x[ 4], 20, 0xe7d3fbc8); /* 24 */ + GG (a, b, c, d, x[ 9], 5, 0x21e1cde6); /* 25 */ + GG (d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */ + GG (c, d, a, b, x[ 3], 14, 0xf4d50d87); /* 27 */ + GG (b, c, d, a, x[ 8], 20, 0x455a14ed); /* 28 */ + GG (a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */ + GG (d, a, b, c, x[ 2], 9, 0xfcefa3f8); /* 30 */ + GG (c, d, a, b, x[ 7], 14, 0x676f02d9); /* 31 */ + GG (b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */ + + HH (a, b, c, d, x[ 5], 4, 0xfffa3942); /* 33 */ /* Round 3 */ + HH (d, a, b, c, x[ 8], 11, 0x8771f681); /* 34 */ + HH (c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */ + HH (b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */ + HH (a, b, c, d, x[ 1], 4, 0xa4beea44); /* 37 */ + HH (d, a, b, c, x[ 4], 11, 0x4bdecfa9); /* 38 */ + HH (c, d, a, b, x[ 7], 16, 0xf6bb4b60); /* 39 */ + HH (b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */ + HH (a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */ + HH (d, a, b, c, x[ 0], 11, 0xeaa127fa); /* 42 */ + HH (c, d, a, b, x[ 3], 16, 0xd4ef3085); /* 43 */ + HH (b, c, d, a, x[ 6], 23, 0x04881d05); /* 44 */ + HH (a, b, c, d, x[ 9], 4, 0xd9d4d039); /* 45 */ + HH (d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */ + HH (c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */ + HH (b, c, d, a, x[ 2], 23, 0xc4ac5665); /* 48 */ + + II (a, b, c, d, x[ 0], 6, 0xf4292244); /* 49 */ /* Round 4 */ + II (d, a, b, c, x[ 7], 10, 0x432aff97); /* 50 */ + II (c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */ + II (b, c, d, a, x[ 5], 21, 0xfc93a039); /* 52 */ + II (a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */ + II (d, a, b, c, x[ 3], 10, 0x8f0ccc92); /* 54 */ + II (c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */ + II (b, c, d, a, x[ 1], 21, 0x85845dd1); /* 56 */ + II (a, b, c, d, x[ 8], 6, 0x6fa87e4f); /* 57 */ + II (d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */ + II (c, d, a, b, x[ 6], 15, 0xa3014314); /* 59 */ + II (b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */ + II (a, b, c, d, x[ 4], 6, 0xf7537e82); /* 61 */ + II (d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */ + II (c, d, a, b, x[ 2], 15, 0x2ad7d2bb); /* 63 */ + II (b, c, d, a, x[ 9], 21, 0xeb86d391); /* 64 */ + + state [0] = a = a + state [0]; + state [1] = b = b + state [1]; + state [2] = c = c + state [2]; + state [3] = d = d + state [3]; + + in += 64; + } +} + + +/* + MD5 block update operation: + Process another sub-string of the message and update the context. +*/ + +void +MD5Update ( MD5_CTX* context, + const uint8_t* input, + size_t inputBytes ) +{ + int byteIndex; + unsigned int partLen; + int len; + int i; + + /* Compute number of bytes mod 64 */ + byteIndex = (context -> count[0] >> 3) & 0x3F; + + /* Update number of bits: count += 8 * inputBytes */ + if ( (context -> count [0] += inputBytes << 3) < (inputBytes << 3) ) + context -> count [1]++; + context -> count [1] += inputBytes >> (32 - 3); + + partLen = (64 - byteIndex); + + /* Transform as many times as possible. */ + if ( inputBytes >= partLen ) { + memcpy ( context -> buffer + byteIndex, input, partLen ); + __MD5Transform ( context -> state, (const uint8_t*) context -> buffer, 1 ); + len = ( inputBytes - partLen ) >> 6; + __MD5Transform ( context -> state, input + partLen, len ); + i = partLen + (len << 6); + byteIndex = 0; + } + else { + i = 0; + } + + /* Buffer remaining input */ + memcpy ( (context -> buffer) + byteIndex, input + i, inputBytes - i ); +} + +#endif + + +void +MD5Final ( uint8_t digest [16], + MD5_CTX* context ) +{ + static uint8_t finalBlock [64]; + uint32_t bits [2]; + int byteIndex; + int finalBlockLength; + + byteIndex = (context -> count[0] >> 3) & 0x3F; + finalBlockLength = (byteIndex < 56 ? 56 : 120) - byteIndex; + finalBlock[0] = 0x80; + +#if __BYTE_ORDER == __BIG_ENDIAN + CopyToLittleEndian ( bits, (const uint8_t*) context -> count, 2 ); +#else + memcpy ( bits, context->count, 8 ); +#endif + + MD5Update ( context, finalBlock, finalBlockLength ); + MD5Update ( context, (const uint8_t*) bits, 8 ); + +#if __BYTE_ORDER == __BIG_ENDIAN + CopyToLittleEndian ( (uint32_t*) digest, (const uint8_t*) context -> state, 4 ); +#else + memcpy ( digest, context -> state, 16 ); +#endif + + memset ( context, 0, sizeof (*context) ); +} + diff --git a/MAC_SDK/Source/MACLib/MultichannelNNFilter.h b/MAC_SDK/Source/MACLib/MultichannelNNFilter.h new file mode 100644 index 0000000..df66c3f --- /dev/null +++ b/MAC_SDK/Source/MACLib/MultichannelNNFilter.h @@ -0,0 +1,95 @@ +#ifndef APE_MULTICHANNEL_NNFILTER_H +#define APE_MULTICHANNEL_NNFILTER_H + +#include "NNFilter.h" + +class CMultichannelNNFilter +{ +public: + + CMultichannelNNFilter(int nOrder1, int nOrder2, int nShift) + { + m_pNNFilterA = new CNNFilter(nOrder1 + nOrder2, 11, 3980); + m_pNNFilterB = new CNNFilter(nOrder1 + nOrder2, 11, 3980); + + m_rbA.Create(NN_WINDOW_ELEMENTS, nOrder1 + nOrder2 + 1); + m_rbB.Create(NN_WINDOW_ELEMENTS, nOrder1 + nOrder2 + 1); + + m_nShift = nShift; + + m_nOrder1 = nOrder1; + } + + + ~CMultichannelNNFilter() + { + SAFE_DELETE(m_pNNFilterA) + SAFE_DELETE(m_pNNFilterB) + } + + void Flush() + { + m_pNNFilterA->Flush(); + m_pNNFilterB->Flush(); + + m_rbA.Flush(); + m_rbB.Flush(); + + } + + inline void Compress(int & nA, int & nB) + { + if (m_nShift <= 0) + return; + + m_rbA[0] = GetSaturatedShortFromInt(nA); m_rbB[0] = GetSaturatedShortFromInt(nB); + m_rbA[-m_nOrder1 - 1] = m_rbB[-1]; m_rbB[-m_nOrder1 - 1] = m_rbA[0]; + + nA -= (m_pNNFilterA->GetPrediction(&m_rbA[-1]) >> m_nShift); + nB -= (m_pNNFilterB->GetPrediction(&m_rbB[-1]) >> m_nShift); + + m_pNNFilterA->AdaptAfterPrediction(&m_rbA[-1], -m_nOrder1, nA); + m_pNNFilterB->AdaptAfterPrediction(&m_rbB[-1], -m_nOrder1, nB); + + m_rbA.IncrementSafe(); m_rbB.IncrementSafe(); + } + + inline void Decompress(int & nA, int & nB) + { + if (m_nShift <= 0) + return; + + m_rbA[-m_nOrder1 - 1] = m_rbB[-1]; + int nOutputA = nA + (m_pNNFilterA->GetPrediction(&m_rbA[-1]) >> m_nShift); + m_rbA[0] = GetSaturatedShortFromInt(nOutputA); + + m_rbB[-m_nOrder1 - 1] = m_rbA[0]; + int nOutputB = nB + (m_pNNFilterB->GetPrediction(&m_rbB[-1]) >> m_nShift); + m_rbB[0] = GetSaturatedShortFromInt(nOutputB); + + m_pNNFilterA->AdaptAfterPrediction(&m_rbA[-1], -m_nOrder1, nA); + m_pNNFilterB->AdaptAfterPrediction(&m_rbB[-1], -m_nOrder1, nB); + + m_rbA.IncrementSafe(); m_rbB.IncrementSafe(); + + nA = nOutputA; nB = nOutputB; + } + +protected: + + CNNFilter * m_pNNFilterA; + CNNFilter * m_pNNFilterB; + + int m_nShift; + int m_nOrder1; + + CRollBuffer m_rbA; + CRollBuffer m_rbB; + + inline short GetSaturatedShortFromInt(int nValue) const + { + return short((nValue == short(nValue)) ? nValue : (nValue >> 31) ^ 0x7FFF); + } +}; + +#endif // #ifndef APE_MULTICHANNEL_NNFILTER_H diff --git a/MAC_SDK/Source/MACLib/NNFilter.cpp b/MAC_SDK/Source/MACLib/NNFilter.cpp new file mode 100644 index 0000000..f72b650 --- /dev/null +++ b/MAC_SDK/Source/MACLib/NNFilter.cpp @@ -0,0 +1,168 @@ +#include "All.h" +#include "GlobalFunctions.h" +#include "NNFilter.h" +#include "Assembly/Assembly.h" + +CNNFilter::CNNFilter(int nOrder, int nShift, int nVersion) +{ + if ((nOrder <= 0) || ((nOrder % 16) != 0)) throw(1); + m_nOrder = nOrder; + m_nShift = nShift; + m_nVersion = nVersion; + + m_bMMXAvailable = GetMMXAvailable(); + + m_rbInput.Create(NN_WINDOW_ELEMENTS, m_nOrder); + m_rbDeltaM.Create(NN_WINDOW_ELEMENTS, m_nOrder); + m_paryM = new short [m_nOrder]; + +#ifdef NN_TEST_MMX + srand(GetTickCount()); +#endif +} + +CNNFilter::~CNNFilter() +{ + SAFE_ARRAY_DELETE(m_paryM) +} + +void CNNFilter::Flush() +{ + memset(&m_paryM[0], 0, m_nOrder * sizeof(short)); + m_rbInput.Flush(); + m_rbDeltaM.Flush(); + m_nRunningAverage = 0; +} + +int CNNFilter::Compress(int nInput) +{ + // convert the input to a short and store it + m_rbInput[0] = GetSaturatedShortFromInt(nInput); + + // figure a dot product + int nDotProduct; + if (m_bMMXAvailable) + nDotProduct = CalculateDotProduct(&m_rbInput[-m_nOrder], &m_paryM[0], m_nOrder); + else + nDotProduct = CalculateDotProductNoMMX(&m_rbInput[-m_nOrder], &m_paryM[0], m_nOrder); + + // calculate the output + int nOutput = nInput - ((nDotProduct + (1 << (m_nShift - 1))) >> m_nShift); + + // adapt + if (m_bMMXAvailable) + Adapt(&m_paryM[0], &m_rbDeltaM[-m_nOrder], -nOutput, m_nOrder); + else + AdaptNoMMX(&m_paryM[0], &m_rbDeltaM[-m_nOrder], nOutput, m_nOrder); + + int nTempABS = abs(nInput); + + if (nTempABS > (m_nRunningAverage * 3)) + m_rbDeltaM[0] = ((nInput >> 25) & 64) - 32; + else if (nTempABS > (m_nRunningAverage * 4) / 3) + m_rbDeltaM[0] = ((nInput >> 26) & 32) - 16; + else if (nTempABS > 0) + m_rbDeltaM[0] = ((nInput >> 27) & 16) - 8; + else + m_rbDeltaM[0] = 0; + + m_nRunningAverage += (nTempABS - m_nRunningAverage) / 16; + + m_rbDeltaM[-1] >>= 1; + m_rbDeltaM[-2] >>= 1; + m_rbDeltaM[-8] >>= 1; + + // increment and roll if necessary + m_rbInput.IncrementSafe(); + m_rbDeltaM.IncrementSafe(); + + return nOutput; +} + +int CNNFilter::Decompress(int nInput) +{ + // figure a dot product + int nDotProduct; + + if (m_bMMXAvailable) + nDotProduct = CalculateDotProduct(&m_rbInput[-m_nOrder], &m_paryM[0], m_nOrder); + else + nDotProduct = CalculateDotProductNoMMX(&m_rbInput[-m_nOrder], &m_paryM[0], m_nOrder); + + // adapt + if (m_bMMXAvailable) + Adapt(&m_paryM[0], &m_rbDeltaM[-m_nOrder], -nInput, m_nOrder); + else + AdaptNoMMX(&m_paryM[0], &m_rbDeltaM[-m_nOrder], nInput, m_nOrder); + + // store the output value + int nOutput = nInput + ((nDotProduct + (1 << (m_nShift - 1))) >> m_nShift); + + // update the input buffer + m_rbInput[0] = GetSaturatedShortFromInt(nOutput); + + if (m_nVersion >= 3980) + { + int nTempABS = abs(nOutput); + + if (nTempABS > (m_nRunningAverage * 3)) + m_rbDeltaM[0] = ((nOutput >> 25) & 64) - 32; + else if (nTempABS > (m_nRunningAverage * 4) / 3) + m_rbDeltaM[0] = ((nOutput >> 26) & 32) - 16; + else if (nTempABS > 0) + m_rbDeltaM[0] = ((nOutput >> 27) & 16) - 8; + else + m_rbDeltaM[0] = 0; + + m_nRunningAverage += (nTempABS - m_nRunningAverage) / 16; + + m_rbDeltaM[-1] >>= 1; + m_rbDeltaM[-2] >>= 1; + m_rbDeltaM[-8] >>= 1; + } + else + { + m_rbDeltaM[0] = (nOutput == 0) ? 0 : ((nOutput >> 28) & 8) - 4; + m_rbDeltaM[-4] >>= 1; + m_rbDeltaM[-8] >>= 1; + } + + // increment and roll if necessary + m_rbInput.IncrementSafe(); + m_rbDeltaM.IncrementSafe(); + + return nOutput; +} + +void CNNFilter::AdaptNoMMX(short * pM, short * pAdapt, int nDirection, int nOrder) +{ + nOrder >>= 4; + + if (nDirection < 0) + { + while (nOrder--) + { + EXPAND_16_TIMES(*pM++ += *pAdapt++;) + } + } + else if (nDirection > 0) + { + while (nOrder--) + { + EXPAND_16_TIMES(*pM++ -= *pAdapt++;) + } + } +} + +int CNNFilter::CalculateDotProductNoMMX(short * pA, short * pB, int nOrder) +{ + int nDotProduct = 0; + nOrder >>= 4; + + while (nOrder--) + { + EXPAND_16_TIMES(nDotProduct += *pA++ * *pB++;) + } + + return nDotProduct; +} diff --git a/MAC_SDK/Source/MACLib/NNFilter.h b/MAC_SDK/Source/MACLib/NNFilter.h new file mode 100644 index 0000000..0f79aeb --- /dev/null +++ b/MAC_SDK/Source/MACLib/NNFilter.h @@ -0,0 +1,42 @@ +#ifndef APE_NNFILTER_H +#define APE_NNFILTER_H + +#include "RollBuffer.h" +#define NN_WINDOW_ELEMENTS 512 +//#define NN_TEST_MMX + +class CNNFilter +{ +public: + + CNNFilter(int nOrder, int nShift, int nVersion); + ~CNNFilter(); + + int Compress(int nInput); + int Decompress(int nInput); + void Flush(); + +private: + + int m_nOrder; + int m_nShift; + int m_nVersion; + BOOL m_bMMXAvailable; + int m_nRunningAverage; + + CRollBuffer m_rbInput; + CRollBuffer m_rbDeltaM; + + short * m_paryM; +// short * m_paryM_ptr; + + inline short GetSaturatedShortFromInt(int nValue) const + { + return short((nValue == short(nValue)) ? nValue : (nValue >> 31) ^ 0x7FFF); + } + + inline int CalculateDotProductNoMMX(short * pA, short * pB, int nOrder); + inline void AdaptNoMMX(short * pM, short * pAdapt, int nDirection, int nOrder); +}; + +#endif // #ifndef APE_NNFILTER_H diff --git a/MAC_SDK/Source/MACLib/NewPredictor.cpp b/MAC_SDK/Source/MACLib/NewPredictor.cpp new file mode 100644 index 0000000..f9b6e86 --- /dev/null +++ b/MAC_SDK/Source/MACLib/NewPredictor.cpp @@ -0,0 +1,408 @@ +#include "All.h" +#include "APECompress.h" +#include "NewPredictor.h" + +/***************************************************************************************** +CPredictorCompressNormal +*****************************************************************************************/ +CPredictorCompressNormal::CPredictorCompressNormal(int nCompressionLevel) + : IPredictorCompress(nCompressionLevel) +{ + if (nCompressionLevel == COMPRESSION_LEVEL_FAST) + { + m_pNNFilter = NULL; + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_NORMAL) + { + m_pNNFilter = new CNNFilter(16, 11, MAC_VERSION_NUMBER); + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_HIGH) + { + m_pNNFilter = new CNNFilter(64, 11, MAC_VERSION_NUMBER); + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_EXTRA_HIGH) + { + m_pNNFilter = new CNNFilter(256, 13, MAC_VERSION_NUMBER); + m_pNNFilter1 = new CNNFilter(32, 10, MAC_VERSION_NUMBER); + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_INSANE) + { + m_pNNFilter = new CNNFilter(1024 + 256, 15, MAC_VERSION_NUMBER); + m_pNNFilter1 = new CNNFilter(256, 13, MAC_VERSION_NUMBER); + m_pNNFilter2 = new CNNFilter(16, 11, MAC_VERSION_NUMBER); + + } + else + { + throw(1); + } +} + +CPredictorCompressNormal::~CPredictorCompressNormal() +{ + SAFE_DELETE(m_pNNFilter) + SAFE_DELETE(m_pNNFilter1) + SAFE_DELETE(m_pNNFilter2) +} + +int CPredictorCompressNormal::Flush() +{ + if (m_pNNFilter) m_pNNFilter->Flush(); + if (m_pNNFilter1) m_pNNFilter1->Flush(); + if (m_pNNFilter2) m_pNNFilter2->Flush(); + + m_rbPrediction.Flush(); + m_rbAdapt.Flush(); + m_Stage1FilterA.Flush(); m_Stage1FilterB.Flush(); + + memset(m_aryM, 0, sizeof(m_aryM)); + + int * paryM = &m_aryM[8]; + paryM[0] = 360; + paryM[-1] = 317; + paryM[-2] = -109; + paryM[-3] = 98; + + m_nCurrentIndex = 0; + + return ERROR_SUCCESS; +} + +int CPredictorCompressNormal::CompressValue(int nA, int nB) +{ + // roll the buffers if necessary + if (m_nCurrentIndex == WINDOW_BLOCKS) + { + m_rbPrediction.Roll(); m_rbAdapt.Roll(); + m_nCurrentIndex = 0; + } + + // stage 1: simple, non-adaptive order 1 prediction + nA = m_Stage1FilterA.Compress(nA); + nB = m_Stage1FilterB.Compress(nB); + + // stage 2: adaptive offset filter(s) + m_rbPrediction[0] = nA; + m_rbPrediction[-2] = m_rbPrediction[-1] - m_rbPrediction[-2]; + + m_rbPrediction[-5] = nB; + m_rbPrediction[-6] = m_rbPrediction[-5] - m_rbPrediction[-6]; + + int * paryM = &m_aryM[8]; + + int nPredictionA = (m_rbPrediction[-1] * paryM[0]) + (m_rbPrediction[-2] * paryM[-1]) + (m_rbPrediction[-3] * paryM[-2]) + (m_rbPrediction[-4] * paryM[-3]); + int nPredictionB = (m_rbPrediction[-5] * paryM[-4]) + (m_rbPrediction[-6] * paryM[-5]) + (m_rbPrediction[-7] * paryM[-6]) + (m_rbPrediction[-8] * paryM[-7]) + (m_rbPrediction[-9] * paryM[-8]); + + int nOutput = nA - ((nPredictionA + (nPredictionB >> 1)) >> 10); + + // adapt + m_rbAdapt[0] = (m_rbPrediction[-1]) ? ((m_rbPrediction[-1] >> 30) & 2) - 1 : 0; + m_rbAdapt[-1] = (m_rbPrediction[-2]) ? ((m_rbPrediction[-2] >> 30) & 2) - 1 : 0; + m_rbAdapt[-4] = (m_rbPrediction[-5]) ? ((m_rbPrediction[-5] >> 30) & 2) - 1 : 0; + m_rbAdapt[-5] = (m_rbPrediction[-6]) ? ((m_rbPrediction[-6] >> 30) & 2) - 1 : 0; + + if (nOutput > 0) + { + int * pM = &paryM[-8]; int * pAdapt = &m_rbAdapt[-8]; + EXPAND_9_TIMES(*pM++ -= *pAdapt++;) + } + else if (nOutput < 0) + { + int * pM = &paryM[-8]; int * pAdapt = &m_rbAdapt[-8]; + EXPAND_9_TIMES(*pM++ += *pAdapt++;) + } + + // stage 3: NNFilters + if (m_pNNFilter) + { + nOutput = m_pNNFilter->Compress(nOutput); + + if (m_pNNFilter1) + { + nOutput = m_pNNFilter1->Compress(nOutput); + + if (m_pNNFilter2) + nOutput = m_pNNFilter2->Compress(nOutput); + } + } + + m_rbPrediction.IncrementFast(); m_rbAdapt.IncrementFast(); + m_nCurrentIndex++; + + return nOutput; +} + +/***************************************************************************************** +CPredictorDecompressNormal3930to3950 +*****************************************************************************************/ +CPredictorDecompressNormal3930to3950::CPredictorDecompressNormal3930to3950(int nCompressionLevel, int nVersion) + : IPredictorDecompress(nCompressionLevel, nVersion) +{ + m_pBuffer[0] = new int [HISTORY_ELEMENTS + WINDOW_BLOCKS]; + + if (nCompressionLevel == COMPRESSION_LEVEL_FAST) + { + m_pNNFilter = NULL; + m_pNNFilter1 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_NORMAL) + { + m_pNNFilter = new CNNFilter(16, 11, nVersion); + m_pNNFilter1 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_HIGH) + { + m_pNNFilter = new CNNFilter(64, 11, nVersion); + m_pNNFilter1 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_EXTRA_HIGH) + { + m_pNNFilter = new CNNFilter(256, 13, nVersion); + m_pNNFilter1 = new CNNFilter(32, 10, nVersion); + } + else + { + throw(1); + } +} + +CPredictorDecompressNormal3930to3950::~CPredictorDecompressNormal3930to3950() +{ + SAFE_DELETE(m_pNNFilter) + SAFE_DELETE(m_pNNFilter1) + SAFE_ARRAY_DELETE(m_pBuffer[0]) +} + +int CPredictorDecompressNormal3930to3950::Flush() +{ + if (m_pNNFilter) m_pNNFilter->Flush(); + if (m_pNNFilter1) m_pNNFilter1->Flush(); + + ZeroMemory(m_pBuffer[0], (HISTORY_ELEMENTS + 1) * sizeof(int)); + ZeroMemory(&m_aryM[0], M_COUNT * sizeof(int)); + + m_aryM[0] = 360; + m_aryM[1] = 317; + m_aryM[2] = -109; + m_aryM[3] = 98; + + m_pInputBuffer = &m_pBuffer[0][HISTORY_ELEMENTS]; + + m_nLastValue = 0; + m_nCurrentIndex = 0; + + return ERROR_SUCCESS; +} + +int CPredictorDecompressNormal3930to3950::DecompressValue(int nInput, int) +{ + if (m_nCurrentIndex == WINDOW_BLOCKS) + { + // copy forward and adjust pointers + memcpy(&m_pBuffer[0][0], &m_pBuffer[0][WINDOW_BLOCKS], HISTORY_ELEMENTS * sizeof(int)); + m_pInputBuffer = &m_pBuffer[0][HISTORY_ELEMENTS]; + + m_nCurrentIndex = 0; + } + + // stage 2: NNFilter + if (m_pNNFilter1) + nInput = m_pNNFilter1->Decompress(nInput); + if (m_pNNFilter) + nInput = m_pNNFilter->Decompress(nInput); + + // stage 1: multiple predictors (order 2 and offset 1) + + int p1 = m_pInputBuffer[-1]; + int p2 = m_pInputBuffer[-1] - m_pInputBuffer[-2]; + int p3 = m_pInputBuffer[-2] - m_pInputBuffer[-3]; + int p4 = m_pInputBuffer[-3] - m_pInputBuffer[-4]; + + m_pInputBuffer[0] = nInput + (((p1 * m_aryM[0]) + (p2 * m_aryM[1]) + (p3 * m_aryM[2]) + (p4 * m_aryM[3])) >> 9); + + if (nInput > 0) + { + m_aryM[0] -= ((p1 >> 30) & 2) - 1; + m_aryM[1] -= ((p2 >> 30) & 2) - 1; + m_aryM[2] -= ((p3 >> 30) & 2) - 1; + m_aryM[3] -= ((p4 >> 30) & 2) - 1; + } + else if (nInput < 0) + { + m_aryM[0] += ((p1 >> 30) & 2) - 1; + m_aryM[1] += ((p2 >> 30) & 2) - 1; + m_aryM[2] += ((p3 >> 30) & 2) - 1; + m_aryM[3] += ((p4 >> 30) & 2) - 1; + } + + int nRetVal = m_pInputBuffer[0] + ((m_nLastValue * 31) >> 5); + m_nLastValue = nRetVal; + + m_nCurrentIndex++; + m_pInputBuffer++; + + return nRetVal; +} + +/***************************************************************************************** +CPredictorDecompress3950toCurrent +*****************************************************************************************/ +CPredictorDecompress3950toCurrent::CPredictorDecompress3950toCurrent(int nCompressionLevel, int nVersion) + : IPredictorDecompress(nCompressionLevel, nVersion) +{ + m_nVersion = nVersion; + + if (nCompressionLevel == COMPRESSION_LEVEL_FAST) + { + m_pNNFilter = NULL; + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_NORMAL) + { + m_pNNFilter = new CNNFilter(16, 11, nVersion); + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_HIGH) + { + m_pNNFilter = new CNNFilter(64, 11, nVersion); + m_pNNFilter1 = NULL; + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_EXTRA_HIGH) + { + m_pNNFilter = new CNNFilter(256, 13, nVersion); + m_pNNFilter1 = new CNNFilter(32, 10, nVersion); + m_pNNFilter2 = NULL; + } + else if (nCompressionLevel == COMPRESSION_LEVEL_INSANE) + { + m_pNNFilter = new CNNFilter(1024 + 256, 15, MAC_VERSION_NUMBER); + m_pNNFilter1 = new CNNFilter(256, 13, MAC_VERSION_NUMBER); + m_pNNFilter2 = new CNNFilter(16, 11, MAC_VERSION_NUMBER); + + } + else + { + throw(1); + } +} + +CPredictorDecompress3950toCurrent::~CPredictorDecompress3950toCurrent() +{ + SAFE_DELETE(m_pNNFilter) + SAFE_DELETE(m_pNNFilter1) + SAFE_DELETE(m_pNNFilter2) +} + +int CPredictorDecompress3950toCurrent::Flush() +{ + if (m_pNNFilter) m_pNNFilter->Flush(); + if (m_pNNFilter1) m_pNNFilter1->Flush(); + if (m_pNNFilter2) m_pNNFilter2->Flush(); + + ZeroMemory(m_aryMA, sizeof(m_aryMA)); + ZeroMemory(m_aryMB, sizeof(m_aryMB)); + + m_rbPredictionA.Flush(); + m_rbPredictionB.Flush(); + m_rbAdaptA.Flush(); + m_rbAdaptB.Flush(); + + m_aryMA[0] = 360; + m_aryMA[1] = 317; + m_aryMA[2] = -109; + m_aryMA[3] = 98; + + m_Stage1FilterA.Flush(); + m_Stage1FilterB.Flush(); + + m_nLastValueA = 0; + + m_nCurrentIndex = 0; + + return ERROR_SUCCESS; +} + +int CPredictorDecompress3950toCurrent::DecompressValue(int nA, int nB) +{ + if (m_nCurrentIndex == WINDOW_BLOCKS) + { + // copy forward and adjust pointers + m_rbPredictionA.Roll(); m_rbPredictionB.Roll(); + m_rbAdaptA.Roll(); m_rbAdaptB.Roll(); + + m_nCurrentIndex = 0; + } + + // stage 2: NNFilter + if (m_pNNFilter2) + nA = m_pNNFilter2->Decompress(nA); + if (m_pNNFilter1) + nA = m_pNNFilter1->Decompress(nA); + if (m_pNNFilter) + nA = m_pNNFilter->Decompress(nA); + + // stage 1: multiple predictors (order 2 and offset 1) + m_rbPredictionA[0] = m_nLastValueA; + m_rbPredictionA[-1] = m_rbPredictionA[0] - m_rbPredictionA[-1]; + + m_rbPredictionB[0] = m_Stage1FilterB.Compress(nB); + m_rbPredictionB[-1] = m_rbPredictionB[0] - m_rbPredictionB[-1]; + + int nPredictionA = (m_rbPredictionA[0] * m_aryMA[0]) + (m_rbPredictionA[-1] * m_aryMA[1]) + (m_rbPredictionA[-2] * m_aryMA[2]) + (m_rbPredictionA[-3] * m_aryMA[3]); + int nPredictionB = (m_rbPredictionB[0] * m_aryMB[0]) + (m_rbPredictionB[-1] * m_aryMB[1]) + (m_rbPredictionB[-2] * m_aryMB[2]) + (m_rbPredictionB[-3] * m_aryMB[3]) + (m_rbPredictionB[-4] * m_aryMB[4]); + + int nCurrentA = nA + ((nPredictionA + (nPredictionB >> 1)) >> 10); + + m_rbAdaptA[0] = (m_rbPredictionA[0]) ? ((m_rbPredictionA[0] >> 30) & 2) - 1 : 0; + m_rbAdaptA[-1] = (m_rbPredictionA[-1]) ? ((m_rbPredictionA[-1] >> 30) & 2) - 1 : 0; + + m_rbAdaptB[0] = (m_rbPredictionB[0]) ? ((m_rbPredictionB[0] >> 30) & 2) - 1 : 0; + m_rbAdaptB[-1] = (m_rbPredictionB[-1]) ? ((m_rbPredictionB[-1] >> 30) & 2) - 1 : 0; + + if (nA > 0) + { + m_aryMA[0] -= m_rbAdaptA[0]; + m_aryMA[1] -= m_rbAdaptA[-1]; + m_aryMA[2] -= m_rbAdaptA[-2]; + m_aryMA[3] -= m_rbAdaptA[-3]; + + m_aryMB[0] -= m_rbAdaptB[0]; + m_aryMB[1] -= m_rbAdaptB[-1]; + m_aryMB[2] -= m_rbAdaptB[-2]; + m_aryMB[3] -= m_rbAdaptB[-3]; + m_aryMB[4] -= m_rbAdaptB[-4]; + } + else if (nA < 0) + { + m_aryMA[0] += m_rbAdaptA[0]; + m_aryMA[1] += m_rbAdaptA[-1]; + m_aryMA[2] += m_rbAdaptA[-2]; + m_aryMA[3] += m_rbAdaptA[-3]; + + m_aryMB[0] += m_rbAdaptB[0]; + m_aryMB[1] += m_rbAdaptB[-1]; + m_aryMB[2] += m_rbAdaptB[-2]; + m_aryMB[3] += m_rbAdaptB[-3]; + m_aryMB[4] += m_rbAdaptB[-4]; + } + + int nRetVal = m_Stage1FilterA.Decompress(nCurrentA); + m_nLastValueA = nCurrentA; + + m_rbPredictionA.IncrementFast(); m_rbPredictionB.IncrementFast(); + m_rbAdaptA.IncrementFast(); m_rbAdaptB.IncrementFast(); + + m_nCurrentIndex++; + + return nRetVal; +} diff --git a/MAC_SDK/Source/MACLib/NewPredictor.h b/MAC_SDK/Source/MACLib/NewPredictor.h new file mode 100644 index 0000000..eedb28e --- /dev/null +++ b/MAC_SDK/Source/MACLib/NewPredictor.h @@ -0,0 +1,111 @@ +#ifndef APE_NEWPREDICTOR_H +#define APE_NEWPREDICTOR_H + +#include "Predictor.h" + +#include "RollBuffer.h" +#include "NNFilter.h" +#include "ScaledFirstOrderFilter.h" + +/************************************************************************************************* +Functions to create the interfaces +*************************************************************************************************/ +IPredictorCompress * __stdcall CreateIPredictorCompress(); +IPredictorDecompress * __stdcall CreateIPredictorDecompress(); + +#define WINDOW_BLOCKS 512 + +#define BUFFER_COUNT 1 +#define HISTORY_ELEMENTS 8 +#define M_COUNT 8 + +class CPredictorCompressNormal : public IPredictorCompress +{ +public: + CPredictorCompressNormal(int nCompressionLevel); + virtual ~CPredictorCompressNormal(); + + int CompressValue(int nA, int nB = 0); + int Flush(); + +protected: + + // buffer information + CRollBufferFast m_rbPrediction; + CRollBufferFast m_rbAdapt; + + CScaledFirstOrderFilter<31, 5> m_Stage1FilterA; + CScaledFirstOrderFilter<31, 5> m_Stage1FilterB; + + // adaption + int m_aryM[9]; + + // other + int m_nCurrentIndex; + CNNFilter * m_pNNFilter; + CNNFilter * m_pNNFilter1; + CNNFilter * m_pNNFilter2; +}; + +class CPredictorDecompressNormal3930to3950 : public IPredictorDecompress +{ +public: + CPredictorDecompressNormal3930to3950(int nCompressionLevel, int nVersion); + virtual ~CPredictorDecompressNormal3930to3950(); + + int DecompressValue(int nInput, int); + int Flush(); + +protected: + + // buffer information + int * m_pBuffer[BUFFER_COUNT]; + + // adaption + int m_aryM[M_COUNT]; + + // buffer pointers + int * m_pInputBuffer; + + // other + int m_nCurrentIndex; + int m_nLastValue; + CNNFilter * m_pNNFilter; + CNNFilter * m_pNNFilter1; +}; + +class CPredictorDecompress3950toCurrent : public IPredictorDecompress +{ +public: + CPredictorDecompress3950toCurrent(int nCompressionLevel, int nVersion); + virtual ~CPredictorDecompress3950toCurrent(); + + int DecompressValue(int nA, int nB = 0); + int Flush(); + +protected: + + // adaption + int m_aryMA[M_COUNT]; + int m_aryMB[M_COUNT]; + + // buffer pointers + CRollBufferFast m_rbPredictionA; + CRollBufferFast m_rbPredictionB; + + CRollBufferFast m_rbAdaptA; + CRollBufferFast m_rbAdaptB; + + CScaledFirstOrderFilter<31, 5> m_Stage1FilterA; + CScaledFirstOrderFilter<31, 5> m_Stage1FilterB; + + // other + int m_nCurrentIndex; + int m_nLastValueA; + int m_nVersion; + CNNFilter * m_pNNFilter; + CNNFilter * m_pNNFilter1; + CNNFilter * m_pNNFilter2; +}; + +#endif // #ifndef APE_NEWPREDICTOR_H diff --git a/MAC_SDK/Source/MACLib/Old/APEDecompressCore.cpp b/MAC_SDK/Source/MACLib/Old/APEDecompressCore.cpp new file mode 100644 index 0000000..84ad6a1 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/APEDecompressCore.cpp @@ -0,0 +1,178 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "UnMAC.h" +#include "APEDecompressCore.h" +#include "../APEInfo.h" +#include "GlobalFunctions.h" +#include "../UnBitArrayBase.h" +#include "Anti-Predictor.h" +#include "UnMAC.h" +#include "../Prepare.h" +#include "../UnBitArray.h" +#include "../Assembly/Assembly.h" + +CAPEDecompressCore::CAPEDecompressCore(CIO * pIO, IAPEDecompress * pAPEDecompress) +{ + m_pAPEDecompress = pAPEDecompress; + + // initialize the bit array + m_pUnBitArray = CreateUnBitArray(pAPEDecompress, pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + + if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) >= 3930) + throw(0); + + m_pAntiPredictorX = CreateAntiPredictor(pAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL), pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + m_pAntiPredictorY = CreateAntiPredictor(pAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL), pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + + m_pDataX = new int [pAPEDecompress->GetInfo(APE_INFO_BLOCKS_PER_FRAME) + 16]; + m_pDataY = new int [pAPEDecompress->GetInfo(APE_INFO_BLOCKS_PER_FRAME) + 16]; + m_pTempData = new int [pAPEDecompress->GetInfo(APE_INFO_BLOCKS_PER_FRAME) + 16]; + + m_nBlocksProcessed = 0; + + // check to see if MMX is available + m_bMMXAvailable = GetMMXAvailable(); +} + +CAPEDecompressCore::~CAPEDecompressCore() +{ + SAFE_DELETE(m_pUnBitArray) + + SAFE_DELETE(m_pAntiPredictorX) + SAFE_DELETE(m_pAntiPredictorY) + + SAFE_ARRAY_DELETE(m_pDataX) + SAFE_ARRAY_DELETE(m_pDataY) + SAFE_ARRAY_DELETE(m_pTempData) +} + +void CAPEDecompressCore::GenerateDecodedArrays(int nBlocks, int nSpecialCodes, int nFrameIndex, int nCPULoadBalancingFactor) +{ + CUnBitArray * pBitArray = (CUnBitArray *) m_pUnBitArray; + + if (m_pAPEDecompress->GetInfo(APE_INFO_CHANNELS) == 2) + { + if ((nSpecialCodes & SPECIAL_FRAME_LEFT_SILENCE) && (nSpecialCodes & SPECIAL_FRAME_RIGHT_SILENCE)) + { + memset(m_pDataX, 0, nBlocks * 4); + memset(m_pDataY, 0, nBlocks * 4); + } + else if (nSpecialCodes & SPECIAL_FRAME_PSEUDO_STEREO) + { + GenerateDecodedArray(m_pDataX, nBlocks, nFrameIndex, m_pAntiPredictorX, nCPULoadBalancingFactor); + memset(m_pDataY, 0, nBlocks * 4); + } + else + { + GenerateDecodedArray(m_pDataX, nBlocks, nFrameIndex, m_pAntiPredictorX, nCPULoadBalancingFactor); + GenerateDecodedArray(m_pDataY, nBlocks, nFrameIndex, m_pAntiPredictorY, nCPULoadBalancingFactor); + } + } + else + { + if (nSpecialCodes & SPECIAL_FRAME_LEFT_SILENCE) + { + memset(m_pDataX, 0, nBlocks * 4); + } + else + { + GenerateDecodedArray(m_pDataX, nBlocks, nFrameIndex, m_pAntiPredictorX, nCPULoadBalancingFactor); + } + } +} + + +void CAPEDecompressCore::GenerateDecodedArray(int * Input_Array, uint32 Number_of_Elements, int Frame_Index, CAntiPredictor *pAntiPredictor, int CPULoadBalancingFactor) +{ + const int nFrameBytes = m_pAPEDecompress->GetInfo(APE_INFO_FRAME_BYTES, Frame_Index); + + // run the prediction sequence + switch (m_pAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL)) + { + +#ifdef ENABLE_COMPRESSION_MODE_FAST + case COMPRESSION_LEVEL_FAST: + if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) < 3320) + { + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + pAntiPredictor->AntiPredict(m_pTempData, Input_Array, Number_of_Elements); + } + else + { + m_pUnBitArray->GenerateArray(Input_Array, Number_of_Elements, nFrameBytes); + pAntiPredictor->AntiPredict(Input_Array, NULL, Number_of_Elements); + } + + break; +#endif // #ifdef ENABLE_COMPRESSION_MODE_FAST + +#ifdef ENABLE_COMPRESSION_MODE_NORMAL + + case COMPRESSION_LEVEL_NORMAL: + { + // get the array from the bitstream + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + pAntiPredictor->AntiPredict(m_pTempData, Input_Array, Number_of_Elements); + break; + } + +#endif // #ifdef ENABLE_COMPRESSION_MODE_NORMAL + +#ifdef ENABLE_COMPRESSION_MODE_HIGH + case COMPRESSION_LEVEL_HIGH: + // get the array from the bitstream + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + pAntiPredictor->AntiPredict(m_pTempData, Input_Array, Number_of_Elements); + break; +#endif // #ifdef ENABLE_COMPRESSION_MODE_HIGH + +#ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + case COMPRESSION_LEVEL_EXTRA_HIGH: + + unsigned int aryCoefficientsA[64], aryCoefficientsB[64], nNumberOfCoefficients; + + #define GET_COEFFICIENTS(NumberOfCoefficientsBits, ValueBits) \ + nNumberOfCoefficients = m_pUnBitArray->DecodeValue(DECODE_VALUE_METHOD_X_BITS, NumberOfCoefficientsBits); \ + for (unsigned int z = 0; z <= nNumberOfCoefficients; z++) \ + { \ + aryCoefficientsA[z] = m_pUnBitArray->DecodeValue(DECODE_VALUE_METHOD_X_BITS, ValueBits); \ + aryCoefficientsB[z] = m_pUnBitArray->DecodeValue(DECODE_VALUE_METHOD_X_BITS, ValueBits); \ + } \ + + if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) < 3320) + { + GET_COEFFICIENTS(4, 6) + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + ((CAntiPredictorExtraHigh0000To3320 *) pAntiPredictor)->AntiPredict(m_pTempData, Input_Array, Number_of_Elements, nNumberOfCoefficients, &aryCoefficientsA[0], &aryCoefficientsB[0]); + } + else if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) < 3600) + { + GET_COEFFICIENTS(3, 5) + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + ((CAntiPredictorExtraHigh3320To3600 *) pAntiPredictor)->AntiPredict(m_pTempData, Input_Array, Number_of_Elements, nNumberOfCoefficients, &aryCoefficientsA[0], &aryCoefficientsB[0]); + } + else if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) < 3700) + { + GET_COEFFICIENTS(3, 6) + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + ((CAntiPredictorExtraHigh3600To3700 *) pAntiPredictor)->AntiPredict(m_pTempData, Input_Array, Number_of_Elements, nNumberOfCoefficients, &aryCoefficientsA[0], &aryCoefficientsB[0]); + } + else if (m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION) < 3800) + { + GET_COEFFICIENTS(3, 6) + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + ((CAntiPredictorExtraHigh3700To3800 *) pAntiPredictor)->AntiPredict(m_pTempData, Input_Array, Number_of_Elements, nNumberOfCoefficients, &aryCoefficientsA[0], &aryCoefficientsB[0]); + } + else + { + m_pUnBitArray->GenerateArray(m_pTempData, Number_of_Elements, nFrameBytes); + ((CAntiPredictorExtraHigh3800ToCurrent *) pAntiPredictor)->AntiPredict(m_pTempData, Input_Array, Number_of_Elements, m_bMMXAvailable, CPULoadBalancingFactor, m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + } + + break; +#endif // #ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + } +} + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/APEDecompressCore.h b/MAC_SDK/Source/MACLib/Old/APEDecompressCore.h new file mode 100644 index 0000000..d0b770f --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/APEDecompressCore.h @@ -0,0 +1,37 @@ +#ifndef APE_DECOMPRESS_CORE_H +#define APE_DECOMPRESS_CORE_H + +class CAPEDecompressCore +{ +public: + + CAPEDecompressCore(CIO * pIO, IAPEDecompress * pAPEDecompress); + ~CAPEDecompressCore(); + + void GenerateDecodedArrays(int nBlocks, int nSpecialCodes, int nFrameIndex, int nCPULoadBalancingFactor); + void GenerateDecodedArray(int *Input_Array, uint32 Number_of_Elements, int Frame_Index, CAntiPredictor *pAntiPredictor, int CPULoadBalancingFactor = 0); + + int * GetDataX() { return m_pDataX; } + int * GetDataY() { return m_pDataY; } + + CUnBitArrayBase * GetUnBitArrray() { return m_pUnBitArray; } + + int * m_pTempData; + int * m_pDataX; + int * m_pDataY; + + CAntiPredictor * m_pAntiPredictorX; + CAntiPredictor * m_pAntiPredictorY; + + CUnBitArrayBase * m_pUnBitArray; + BIT_ARRAY_STATE m_BitArrayStateX; + BIT_ARRAY_STATE m_BitArrayStateY; + + IAPEDecompress * m_pAPEDecompress; + + BOOL m_bMMXAvailable; + int m_nBlocksProcessed; +}; + + +#endif // #ifndef APE_DECOMPRESS_CORE_H \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/Old/APEDecompressOld.cpp b/MAC_SDK/Source/MACLib/Old/APEDecompressOld.cpp new file mode 100644 index 0000000..27b3177 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/APEDecompressOld.cpp @@ -0,0 +1,279 @@ +#include "All.h" + +#ifdef BACKWARDS_COMPATIBILITY + +#include "UnMAC.h" +#include "APEDecompressOld.h" +#include "../APEInfo.h" + +CAPEDecompressOld::CAPEDecompressOld(int * pErrorCode, CAPEInfo * pAPEInfo, int nStartBlock, int nFinishBlock) +{ + *pErrorCode = ERROR_SUCCESS; + + // open / analyze the file + m_spAPEInfo.Assign(pAPEInfo); + + // version check (this implementation only works with 3.92 and earlier files) + if (GetInfo(APE_INFO_FILE_VERSION) > 3920) + { + *pErrorCode = ERROR_UNDEFINED; + return; + } + + // create the buffer + m_nBlockAlign = GetInfo(APE_INFO_BLOCK_ALIGN); + + // initialize other stuff + m_nBufferTail = 0; + m_bDecompressorInitialized = FALSE; + m_nCurrentFrame = 0; + m_nCurrentBlock = 0; + + // set the "real" start and finish blocks + m_nStartBlock = (nStartBlock < 0) ? 0 : min(nStartBlock, GetInfo(APE_INFO_TOTAL_BLOCKS)); + m_nFinishBlock = (nFinishBlock < 0) ? GetInfo(APE_INFO_TOTAL_BLOCKS) : min(nFinishBlock, GetInfo(APE_INFO_TOTAL_BLOCKS)); + m_bIsRanged = (m_nStartBlock != 0) || (m_nFinishBlock != GetInfo(APE_INFO_TOTAL_BLOCKS)); +} + +CAPEDecompressOld::~CAPEDecompressOld() +{ + +} + +int CAPEDecompressOld::InitializeDecompressor() +{ + // check if we have anything to do + if (m_bDecompressorInitialized) + return ERROR_SUCCESS; + + // initialize the decoder + RETURN_ON_ERROR(m_UnMAC.Initialize(this)) + + int nMaximumDecompressedFrameBytes = m_nBlockAlign * GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nTotalBufferBytes = max(65536, (nMaximumDecompressedFrameBytes + 16) * 2); + m_spBuffer.Assign(new char [nTotalBufferBytes], TRUE); + if (m_spBuffer == NULL) + return ERROR_INSUFFICIENT_MEMORY; + + // update the initialized flag + m_bDecompressorInitialized = TRUE; + + // seek to the beginning + return Seek(0); +} + +int CAPEDecompressOld::GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved) +{ + if (pBlocksRetrieved) *pBlocksRetrieved = 0; + + RETURN_ON_ERROR(InitializeDecompressor()) + + // cap + int nBlocksUntilFinish = m_nFinishBlock - m_nCurrentBlock; + nBlocks = min(nBlocks, nBlocksUntilFinish); + + int nBlocksRetrieved = 0; + + // fulfill as much of the request as possible + int nTotalBytesNeeded = nBlocks * m_nBlockAlign; + int nBytesLeft = nTotalBytesNeeded; + int nBlocksDecoded = 1; + + while (nBytesLeft > 0 && nBlocksDecoded > 0) + { + // empty the buffer + int nBytesAvailable = m_nBufferTail; + int nIntialBytes = min(nBytesLeft, nBytesAvailable); + if (nIntialBytes > 0) + { + memcpy(&pBuffer[nTotalBytesNeeded - nBytesLeft], &m_spBuffer[0], nIntialBytes); + + if ((m_nBufferTail - nIntialBytes) > 0) + memmove(&m_spBuffer[0], &m_spBuffer[nIntialBytes], m_nBufferTail - nIntialBytes); + + nBytesLeft -= nIntialBytes; + m_nBufferTail -= nIntialBytes; + + } + + // decode more + if (nBytesLeft > 0) + { + nBlocksDecoded = m_UnMAC.DecompressFrame((unsigned char *) &m_spBuffer[m_nBufferTail], m_nCurrentFrame++, 0); + if (nBlocksDecoded == -1) + { + return -1; + } + m_nBufferTail += (nBlocksDecoded * m_nBlockAlign); + } + } + + nBlocksRetrieved = (nTotalBytesNeeded - nBytesLeft) / m_nBlockAlign; + + // update the position + m_nCurrentBlock += nBlocksRetrieved; + + if (pBlocksRetrieved) *pBlocksRetrieved = nBlocksRetrieved; + + return ERROR_SUCCESS; +} + +int CAPEDecompressOld::Seek(int nBlockOffset) +{ + RETURN_ON_ERROR(InitializeDecompressor()) + + // use the offset + nBlockOffset += m_nStartBlock; + + // cap (to prevent seeking too far) + if (nBlockOffset >= m_nFinishBlock) + nBlockOffset = m_nFinishBlock - 1; + if (nBlockOffset < m_nStartBlock) + nBlockOffset = m_nStartBlock; + + // flush the buffer + m_nBufferTail = 0; + + // seek to the perfect location + int nBaseFrame = nBlockOffset / GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nBlocksToSkip = nBlockOffset % GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nBytesToSkip = nBlocksToSkip * m_nBlockAlign; + + // skip necessary blocks + int nMaximumDecompressedFrameBytes = m_nBlockAlign * GetInfo(APE_INFO_BLOCKS_PER_FRAME); + char *pTempBuffer = new char [nMaximumDecompressedFrameBytes + 16]; + ZeroMemory(pTempBuffer, nMaximumDecompressedFrameBytes + 16); + + m_nCurrentFrame = nBaseFrame; + + int nBlocksDecoded = m_UnMAC.DecompressFrame((unsigned char *) pTempBuffer, m_nCurrentFrame++, 0); + + if (nBlocksDecoded == -1) + { + return -1; + } + + int nBytesToKeep = (nBlocksDecoded * m_nBlockAlign) - nBytesToSkip; + memcpy(&m_spBuffer[m_nBufferTail], &pTempBuffer[nBytesToSkip], nBytesToKeep); + m_nBufferTail += nBytesToKeep; + + delete [] pTempBuffer; + + + m_nCurrentBlock = nBlockOffset; + + return ERROR_SUCCESS; +} + +int CAPEDecompressOld::GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1, int nParam2) +{ + int nRetVal = 0; + BOOL bHandled = TRUE; + + switch (Field) + { + case APE_DECOMPRESS_CURRENT_BLOCK: + nRetVal = m_nCurrentBlock - m_nStartBlock; + break; + case APE_DECOMPRESS_CURRENT_MS: + { + int nSampleRate = m_spAPEInfo->GetInfo(APE_INFO_SAMPLE_RATE, 0, 0); + if (nSampleRate > 0) + nRetVal = int((double(m_nCurrentBlock) * double(1000)) / double(nSampleRate)); + break; + } + case APE_DECOMPRESS_TOTAL_BLOCKS: + nRetVal = m_nFinishBlock - m_nStartBlock; + break; + case APE_DECOMPRESS_LENGTH_MS: + { + int nSampleRate = m_spAPEInfo->GetInfo(APE_INFO_SAMPLE_RATE, 0, 0); + if (nSampleRate > 0) + nRetVal = int((double(m_nFinishBlock - m_nStartBlock) * double(1000)) / double(nSampleRate)); + break; + } + case APE_DECOMPRESS_CURRENT_BITRATE: + nRetVal = GetInfo(APE_INFO_FRAME_BITRATE, m_nCurrentFrame); + break; + case APE_DECOMPRESS_AVERAGE_BITRATE: + { + if (m_bIsRanged) + { + // figure the frame range + const int nBlocksPerFrame = GetInfo(APE_INFO_BLOCKS_PER_FRAME); + int nStartFrame = m_nStartBlock / nBlocksPerFrame; + int nFinishFrame = (m_nFinishBlock + nBlocksPerFrame - 1) / nBlocksPerFrame; + + // get the number of bytes in the first and last frame + int nTotalBytes = (GetInfo(APE_INFO_FRAME_BYTES, nStartFrame) * (m_nStartBlock % nBlocksPerFrame)) / nBlocksPerFrame; + if (nFinishFrame != nStartFrame) + nTotalBytes += (GetInfo(APE_INFO_FRAME_BYTES, nFinishFrame) * (m_nFinishBlock % nBlocksPerFrame)) / nBlocksPerFrame; + + // get the number of bytes in between + const int nTotalFrames = GetInfo(APE_INFO_TOTAL_FRAMES); + for (int nFrame = nStartFrame + 1; (nFrame < nFinishFrame) && (nFrame < nTotalFrames); nFrame++) + nTotalBytes += GetInfo(APE_INFO_FRAME_BYTES, nFrame); + + // figure the bitrate + int nTotalMS = int((double(m_nFinishBlock - m_nStartBlock) * double(1000)) / double(GetInfo(APE_INFO_SAMPLE_RATE))); + if (nTotalMS != 0) + nRetVal = (nTotalBytes * 8) / nTotalMS; + } + else + { + nRetVal = GetInfo(APE_INFO_AVERAGE_BITRATE); + } + + break; + } + default: + bHandled = FALSE; + } + + if (!bHandled && m_bIsRanged) + { + bHandled = TRUE; + + switch (Field) + { + case APE_INFO_WAV_HEADER_BYTES: + nRetVal = sizeof(WAVE_HEADER); + break; + case APE_INFO_WAV_HEADER_DATA: + { + char * pBuffer = (char *) nParam1; + int nMaxBytes = nParam2; + + if (sizeof(WAVE_HEADER) > nMaxBytes) + { + nRetVal = -1; + } + else + { + WAVEFORMATEX wfeFormat; GetInfo(APE_INFO_WAVEFORMATEX, (int) &wfeFormat, 0); + WAVE_HEADER WAVHeader; FillWaveHeader(&WAVHeader, + (m_nFinishBlock - m_nStartBlock) * GetInfo(APE_INFO_BLOCK_ALIGN), + &wfeFormat, 0); + memcpy(pBuffer, &WAVHeader, sizeof(WAVE_HEADER)); + nRetVal = 0; + } + break; + } + case APE_INFO_WAV_TERMINATING_BYTES: + nRetVal = 0; + break; + case APE_INFO_WAV_TERMINATING_DATA: + nRetVal = 0; + break; + default: + bHandled = FALSE; + } + } + + if (bHandled == FALSE) + nRetVal = m_spAPEInfo->GetInfo(Field, nParam1, nParam2); + + return nRetVal; +} + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/APEDecompressOld.h b/MAC_SDK/Source/MACLib/Old/APEDecompressOld.h new file mode 100644 index 0000000..c3b3b61 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/APEDecompressOld.h @@ -0,0 +1,43 @@ +#ifndef _apedecompressold_h_ +#define _apedecompressold_h_ + +#include "../APEDecompress.h" +#include "UnMAC.h" + +class CAPEDecompressOld : public IAPEDecompress +{ +public: + CAPEDecompressOld(int * pErrorCode, CAPEInfo * pAPEInfo, int nStartBlock = -1, int nFinishBlock = -1); + ~CAPEDecompressOld(); + + int GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved); + int Seek(int nBlockOffset); + + int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0); + +protected: + + // buffer + CSmartPtr m_spBuffer; + int m_nBufferTail; + + // file info + int m_nBlockAlign; + int m_nCurrentFrame; + + // start / finish information + int m_nStartBlock; + int m_nFinishBlock; + int m_nCurrentBlock; + BOOL m_bIsRanged; + + // decoding tools + CUnMAC m_UnMAC; + CSmartPtr m_spAPEInfo; + + BOOL m_bDecompressorInitialized; + int InitializeDecompressor(); +}; + +#endif //_apedecompressold_h_ + diff --git a/MAC_SDK/Source/MACLib/Old/Anti-Predictor.cpp b/MAC_SDK/Source/MACLib/Old/Anti-Predictor.cpp new file mode 100644 index 0000000..302e808 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/Anti-Predictor.cpp @@ -0,0 +1,394 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "../MACLib.h" +#include "Anti-Predictor.h" + +CAntiPredictor * CreateAntiPredictor(int nCompressionLevel, int nVersion) +{ + CAntiPredictor *pAntiPredictor = NULL; + + switch (nCompressionLevel) + { +#ifdef ENABLE_COMPRESSION_MODE_FAST + case COMPRESSION_LEVEL_FAST: + if (nVersion < 3320) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorFast0000To3320; + } + else + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorFast3320ToCurrent; + } + break; +#endif //ENABLE_COMPRESSION_MODE_FAST + +#ifdef ENABLE_COMPRESSION_MODE_NORMAL + + case COMPRESSION_LEVEL_NORMAL: + if (nVersion < 3320) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorNormal0000To3320; + } + else if (nVersion < 3800) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorNormal3320To3800; + } + else + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorNormal3800ToCurrent; + } + break; + +#endif //ENABLE_COMPRESSION_MODE_NORMAL + +#ifdef ENABLE_COMPRESSION_MODE_HIGH + case COMPRESSION_LEVEL_HIGH: + if (nVersion < 3320) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorHigh0000To3320; + } + else if (nVersion < 3600) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorHigh3320To3600; + } + else if (nVersion < 3700) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorHigh3600To3700; + } + else if (nVersion < 3800) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorHigh3700To3800; + } + else + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorHigh3800ToCurrent; + } + break; +#endif //ENABLE_COMPRESSION_MODE_HIGH + +#ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + case COMPRESSION_LEVEL_EXTRA_HIGH: + if (nVersion < 3320) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorExtraHigh0000To3320; + } + else if (nVersion < 3600) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorExtraHigh3320To3600; + } + else if (nVersion < 3700) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorExtraHigh3600To3700; + } + else if (nVersion < 3800) + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorExtraHigh3700To3800; + } + else + { + pAntiPredictor = (CAntiPredictor *) new CAntiPredictorExtraHigh3800ToCurrent; + } + break; +#endif //ENABLE_COMPRESSION_MODE_EXTRA_HIGH + } + + return pAntiPredictor; +} + + + +CAntiPredictor::CAntiPredictor() +{ +} + +CAntiPredictor::~CAntiPredictor() +{ +} + +void CAntiPredictor::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + return; +} + +void CAntiPredictorOffset::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Offset, int DeltaM) +{ + + memcpy(pOutputArray, pInputArray, Offset * 4); + + int *ip = &pInputArray[Offset]; + int *ipo = &pOutputArray[0]; + int *op = &pOutputArray[Offset]; + int m = 0; + + for (; op < &pOutputArray[NumberOfElements]; ip++, ipo++, op++) + { + *op = *ip + ((*ipo * m) >> 12); + + (*ipo ^ *ip) > 0 ? m += DeltaM : m -= DeltaM; + } +} + +#ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +int CAntiPredictorExtraHighHelper::ConventionalDotProduct(short *bip, short *bbm, short *pIPAdaptFactor, int op, int nNumberOfIterations) +{ + // dot product + int nDotProduct = 0; + short *pMaxBBM = &bbm[nNumberOfIterations]; + + if (op == 0) + { + while(bbm < pMaxBBM) + { + EXPAND_32_TIMES(nDotProduct += *bip++ * *bbm++;) + } + } + else if (op > 0) + { + while(bbm < pMaxBBM) + { + EXPAND_32_TIMES(nDotProduct += *bip++ * *bbm; *bbm++ += *pIPAdaptFactor++;) + } + } + else + { + while(bbm < pMaxBBM) + { + EXPAND_32_TIMES(nDotProduct += *bip++ * *bbm; *bbm++ -= *pIPAdaptFactor++;) + } + } + + // use the dot product + return nDotProduct; +} + +#ifdef ENABLE_ASSEMBLY + +#define MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_HEAD \ + __asm movq mm0, [esi] \ + __asm add esi, 8 \ + __asm movq mm1, [esi] \ + __asm add esi, 8 \ + __asm movq mm2, [esi] \ + __asm add esi, 8 \ + \ + __asm movq mm3, [edi] \ + __asm add edi, 8 \ + __asm movq mm4, [edi] \ + __asm add edi, 8 \ + __asm movq mm5, [edi] \ + __asm sub edi, 16 \ + \ + __asm pmaddwd mm0, mm3 \ + __asm pmaddwd mm1, mm4 \ + __asm pmaddwd mm2, mm5 \ + \ + __asm paddd mm7, mm0 \ + __asm paddd mm7, mm1 \ + __asm paddd mm7, mm2 \ + + +#define MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD \ + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_HEAD \ + \ + __asm paddw mm3, DWORD PTR [eax] \ + __asm movq [edi], mm3 \ + __asm add eax, 8 \ + __asm add edi, 8 \ + __asm paddw mm4, DWORD PTR [eax] \ + __asm movq [edi], mm4 \ + __asm add eax, 8 \ + __asm add edi, 8 \ + __asm paddw mm5, DWORD PTR [eax] \ + __asm movq [edi], mm5 \ + __asm add eax, 8 \ + __asm add edi, 8 + +#define MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT \ + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_HEAD \ + \ + __asm psubw mm3, DWORD PTR [eax] \ + __asm movq [edi], mm3 \ + __asm add eax, 8 \ + __asm add edi, 8 \ + __asm psubw mm4, DWORD PTR [eax] \ + __asm movq [edi], mm4 \ + __asm add eax, 8 \ + __asm add edi, 8 \ + __asm psubw mm5, DWORD PTR [eax] \ + __asm movq [edi], mm5 \ + __asm add eax, 8 \ + __asm add edi, 8 + +int CAntiPredictorExtraHighHelper::MMXDotProduct(short *bip, short *bbm, short *pIPAdaptFactor, int op, int nNumberOfIterations) +{ + int nDotProduct; + nNumberOfIterations = (nNumberOfIterations / 128); + + if (op > 0) + { + __asm + { + push eax + + mov eax, DWORD PTR [pIPAdaptFactor] + + push esi + push edi + + mov esi, DWORD PTR bip[0] + mov edi, DWORD PTR bbm[0] + + pxor mm7, mm7 + +LBL_ADD_AGAIN: + + ///////////////////////////////////////////////////////// + // process 8 mm registers full + ///////////////////////////////////////////////////////// + + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_ADD + + // fill the registers + movq mm0, [esi] + add esi, 8 + movq mm1, [esi] + add esi, 8 + + movq mm3, [edi] + add edi, 8 + movq mm4, [edi] + sub edi, 8 + + pmaddwd mm0, mm3 + pmaddwd mm1, mm4 + + paddd mm7, mm0 + paddd mm7, mm1 + + paddw mm3, DWORD PTR [eax] + movq [edi], mm3 + add eax, 8 + add edi, 8 + paddw mm4, DWORD PTR [eax] + movq [edi], mm4 + add eax, 8 + add edi, 8 + + sub nNumberOfIterations, 1 + cmp nNumberOfIterations, 0 + jg LBL_ADD_AGAIN + + /////////////////////////////////////////////////////////////// + // clean-up + /////////////////////////////////////////////////////////////// + // mm7 has the final dot-product (split into two dwords) + movq mm6, mm7 + psrlq mm7, 32 + paddd mm6, mm7 + movd nDotProduct, mm6 + + pop edi + pop esi + pop eax + emms + + } + } + else + { + __asm + { + push eax + + mov eax, DWORD PTR [pIPAdaptFactor] + + push esi + push edi + + mov esi, DWORD PTR bip[0] + mov edi, DWORD PTR bbm[0] + + pxor mm7, mm7 + +LBL_SUBTRACT_AGAIN: + + ///////////////////////////////////////////////////////// + // process 8 mm registers full + ///////////////////////////////////////////////////////// + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + MMX_DOT_PRODUCT_3800_TO_CURRENT_PROCESS_CHUNK_SUBTRACT + + // fill the registers + movq mm0, [esi] + add esi, 8 + movq mm1, [esi] + add esi, 8 + + movq mm3, [edi] + add edi, 8 + movq mm4, [edi] + sub edi, 8 + + pmaddwd mm0, mm3 + pmaddwd mm1, mm4 + + paddd mm7, mm0 + paddd mm7, mm1 + + psubw mm3, DWORD PTR [eax] + movq [edi], mm3 + add eax, 8 + add edi, 8 + psubw mm4, DWORD PTR [eax] + movq [edi], mm4 + add eax, 8 + add edi, 8 + + sub nNumberOfIterations, 1 + cmp nNumberOfIterations, 0 + jg LBL_SUBTRACT_AGAIN + + /////////////////////////////////////////////////////////////// + // clean-up + /////////////////////////////////////////////////////////////// + // mm7 has the final dot-product (split into two dwords) + movq mm6, mm7 + psrlq mm7, 32 + paddd mm6, mm7 + movd nDotProduct, mm6 + + pop edi + pop esi + pop eax + emms + + } + } + + return nDotProduct; +} + +#endif // #ifdef ENABLE_ASSEMBLY + +#endif // #ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/Anti-Predictor.h b/MAC_SDK/Source/MACLib/Old/Anti-Predictor.h new file mode 100644 index 0000000..fc72ac4 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/Anti-Predictor.h @@ -0,0 +1,253 @@ +#ifndef APE_ANTIPREDICTOR_H +#define APE_ANTIPREDICTOR_H + +class CAntiPredictor; + +CAntiPredictor * CreateAntiPredictor(int nCompressionLevel, int nVersion); + +/***************************************************************************************** +Base class for all anti-predictors +*****************************************************************************************/ +class CAntiPredictor +{ +public: + + // construction/destruction + CAntiPredictor(); + ~CAntiPredictor(); + + // functions + virtual void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +Offset anti-predictor +*****************************************************************************************/ +class CAntiPredictorOffset : public CAntiPredictor +{ +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Offset, int DeltaM); +}; + +#ifdef ENABLE_COMPRESSION_MODE_FAST + +/***************************************************************************************** +Fast anti-predictor (from original 'fast' mode...updated for version 3.32) +*****************************************************************************************/ +class CAntiPredictorFast0000To3320 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +Fast anti-predictor (new 'fast' mode release with version 3.32) +*****************************************************************************************/ +class CAntiPredictorFast3320ToCurrent : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +#endif // #ifdef ENABLE_COMPRESSION_MODE_FAST + +#ifdef ENABLE_COMPRESSION_MODE_NORMAL +/***************************************************************************************** +Normal anti-predictor +*****************************************************************************************/ +class CAntiPredictorNormal0000To3320 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +Normal anti-predictor +*****************************************************************************************/ +class CAntiPredictorNormal3320To3800 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +Normal anti-predictor +*****************************************************************************************/ +class CAntiPredictorNormal3800ToCurrent : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +#endif // #ifdef ENABLE_COMPRESSION_MODE_NORMAL + +#ifdef ENABLE_COMPRESSION_MODE_HIGH + +/***************************************************************************************** +High anti-predictor +*****************************************************************************************/ +class CAntiPredictorHigh0000To3320 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +High anti-predictor +*****************************************************************************************/ +class CAntiPredictorHigh3320To3600 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +High anti-predictor +*****************************************************************************************/ +class CAntiPredictorHigh3600To3700 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +High anti-predictor +*****************************************************************************************/ +class CAntiPredictorHigh3700To3800 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +/***************************************************************************************** +High anti-predictor +*****************************************************************************************/ +class CAntiPredictorHigh3800ToCurrent : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements); + +}; + +#endif // #ifdef ENABLE_COMPRESSION_MODE_HIGH + +#ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +/***************************************************************************************** +Extra high helper +*****************************************************************************************/ +class CAntiPredictorExtraHighHelper +{ +public: + int ConventionalDotProduct(short *bip, short *bbm, short *pIPAdaptFactor, int op, int nNumberOfIterations); + +#ifdef ENABLE_ASSEMBLY + int MMXDotProduct(short *bip, short *bbm, short *pIPAdaptFactor, int op, int nNumberOfIterations); +#endif // #ifdef ENABLE_ASSEMBLY +}; + + +/***************************************************************************************** +Extra high anti-predictor +*****************************************************************************************/ +class CAntiPredictorExtraHigh0000To3320 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB); + +private: + void AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g, int dm, int Max_Order); + +}; + +/***************************************************************************************** +Extra high anti-predictor +*****************************************************************************************/ +class CAntiPredictorExtraHigh3320To3600 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB); + +private: + void AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g, int dm, int Max_Order); +}; + +/***************************************************************************************** +Extra high anti-predictor +*****************************************************************************************/ +class CAntiPredictorExtraHigh3600To3700 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB); + +private: + void AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g1, int g2, int Max_Order); + +}; + +/***************************************************************************************** +Extra high anti-predictor +*****************************************************************************************/ +class CAntiPredictorExtraHigh3700To3800 : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB); + +private: + void AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g1, int g2, int Max_Order); +}; + +/***************************************************************************************** +Extra high anti-predictor +*****************************************************************************************/ +class CAntiPredictorExtraHigh3800ToCurrent : public CAntiPredictor { + +public: + + // functions + void AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, BOOL bMMXAvailable, int CPULoadBalancingFactor, int nVersion); +}; + +#endif // #ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +#endif // #ifndef APE_ANTIPREDICTOR_H \ No newline at end of file diff --git a/MAC_SDK/Source/MACLib/Old/AntiPredictorExtraHigh.cpp b/MAC_SDK/Source/MACLib/Old/AntiPredictorExtraHigh.cpp new file mode 100644 index 0000000..7200fae --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/AntiPredictorExtraHigh.cpp @@ -0,0 +1,330 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "Anti-Predictor.h" + +#ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +/***************************************************************************************** +Extra high 0000 to 3320 implementation +*****************************************************************************************/ +void CAntiPredictorExtraHigh0000To3320::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB) { + for (int z = Iterations; z >= 0; z--){ + AntiPredictorOffset(pInputArray, pOutputArray, NumberOfElements, pOffsetValueArrayB[z], -1, 64); + AntiPredictorOffset(pOutputArray, pInputArray, NumberOfElements, pOffsetValueArrayA[z], 1, 64); + } + + CAntiPredictorHigh0000To3320 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); +} + +void CAntiPredictorExtraHigh0000To3320::AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g, int dm, int Max_Order) +{ + int q; + + if ((g==0) || (Number_of_Elements <= Max_Order)) { + memcpy(Output_Array, Input_Array, Number_of_Elements * 4); + return; + } + + memcpy(Output_Array, Input_Array, Max_Order * 4); + + int m = 512; + + if (dm > 0) + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] + (Output_Array[q - g] >> 3); + } + + else + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] - (Output_Array[q - g] >> 3); + } +} + + +/***************************************************************************************** +Extra high 3320 to 3600 implementation +*****************************************************************************************/ +void CAntiPredictorExtraHigh3320To3600::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB) +{ + for (int z = Iterations; z >= 0; z--) + { + AntiPredictorOffset(pInputArray, pOutputArray, NumberOfElements, pOffsetValueArrayB[z], -1, 32); + AntiPredictorOffset(pOutputArray, pInputArray, NumberOfElements, pOffsetValueArrayA[z], 1, 32); + } + + CAntiPredictorHigh0000To3320 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); +} + + +void CAntiPredictorExtraHigh3320To3600::AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g, int dm, int Max_Order) +{ + + int q; + + if ((g==0) || (Number_of_Elements <= Max_Order)) { + memcpy(Output_Array, Input_Array, Number_of_Elements * 4); + return; + } + + memcpy(Output_Array, Input_Array, Max_Order * 4); + + int m = 512; + + if (dm > 0) + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] + ((Output_Array[q - g] * m) >> 12); + (Input_Array[q] ^ Output_Array[q - g]) > 0 ? m += 8 : m -= 8; + } + + else + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] - ((Output_Array[q - g] * m) >> 12); + (Input_Array[q] ^ Output_Array[q - g]) > 0 ? m -= 8 : m += 8; + } +} + + +/***************************************************************************************** +Extra high 3600 to 3700 implementation +*****************************************************************************************/ +void CAntiPredictorExtraHigh3600To3700::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB) { + for (int z = Iterations; z >= 0; ){ + + AntiPredictorOffset(pInputArray, pOutputArray, NumberOfElements, pOffsetValueArrayA[z], pOffsetValueArrayB[z], 64); + z--; + + if (z >= 0) { + AntiPredictorOffset(pOutputArray, pInputArray, NumberOfElements, pOffsetValueArrayA[z], pOffsetValueArrayB[z], 64); + z--; + } + else { + memcpy(pInputArray, pOutputArray, NumberOfElements * 4); + goto Exit_Loop; + z--; + } + } + +Exit_Loop: + CAntiPredictorHigh3600To3700 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); +} + +void CAntiPredictorExtraHigh3600To3700::AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g1, int g2, int Max_Order) { + int q; + + if ((g1==0) || (g2==0) || (Number_of_Elements <= Max_Order)) { + memcpy(Output_Array, Input_Array, Number_of_Elements * 4); + return; + } + + memcpy(Output_Array, Input_Array, Max_Order * 4); + + int m = 64; + int m2 = 64; + + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] + ((Output_Array[q - g1] * m) >> 9) - ((Output_Array[q - g2] * m2) >> 9); + (Input_Array[q] ^ Output_Array[q - g1]) > 0 ? m++ : m--; + (Input_Array[q] ^ Output_Array[q - g2]) > 0 ? m2-- : m2++; + } +} + +/***************************************************************************************** +Extra high 3700 to 3800 implementation +*****************************************************************************************/ +void CAntiPredictorExtraHigh3700To3800::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, int Iterations, unsigned int *pOffsetValueArrayA, unsigned int *pOffsetValueArrayB) { + for (int z = Iterations; z >= 0; ) { + + AntiPredictorOffset(pInputArray, pOutputArray, NumberOfElements, pOffsetValueArrayA[z], pOffsetValueArrayB[z], 64); + z--; + + if (z >= 0) { + AntiPredictorOffset(pOutputArray, pInputArray, NumberOfElements, pOffsetValueArrayA[z], pOffsetValueArrayB[z], 64); + z--; + } + else { + memcpy(pInputArray, pOutputArray, NumberOfElements * 4); + goto Exit_Loop; + z--; + } + } + +Exit_Loop: + CAntiPredictorHigh3700To3800 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); + +} + +void CAntiPredictorExtraHigh3700To3800::AntiPredictorOffset(int* Input_Array, int* Output_Array, int Number_of_Elements, int g1, int g2, int Max_Order) { + int q; + + if ((g1==0) || (g2==0) || (Number_of_Elements <= Max_Order)) { + memcpy(Output_Array, Input_Array, Number_of_Elements * 4); + return; + } + + memcpy(Output_Array, Input_Array, Max_Order * 4); + + int m = 64; + int m2 = 64; + + for (q = Max_Order; q < Number_of_Elements; q++) { + Output_Array[q] = Input_Array[q] + ((Output_Array[q - g1] * m) >> 9) - ((Output_Array[q - g2] * m2) >> 9); + (Input_Array[q] ^ Output_Array[q - g1]) > 0 ? m++ : m--; + (Input_Array[q] ^ Output_Array[q - g2]) > 0 ? m2-- : m2++; + } +} + +/***************************************************************************************** +Extra high 3800 to Current +*****************************************************************************************/ +void CAntiPredictorExtraHigh3800ToCurrent::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements, BOOL bMMXAvailable, int CPULoadBalancingFactor, int nVersion) +{ + const int nFilterStageElements = (nVersion < 3830) ? 128 : 256; + const int nFilterStageShift = (nVersion < 3830) ? 11 : 12; + const int nMaxElements = (nVersion < 3830) ? 134 : 262; + const int nFirstElement = (nVersion < 3830) ? 128 : 256; + const int nStageCShift = (nVersion < 3830) ? 10 : 11; + + //short frame handling + if (NumberOfElements < nMaxElements) { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + //make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, nFirstElement * 4); + + //variable declares and initializations + //short bm[nFirstElement]; memset(bm, 0, nFirstElement * 2); + short bm[256]; memset(bm, 0, 256 * 2); + int m2 = 64, m3 = 115, m4 = 64, m5 = 740, m6 = 0; + int p4 = pInputArray[nFirstElement - 1]; + int p3 = (pInputArray[nFirstElement - 1] - pInputArray[nFirstElement - 2]) << 1; + int p2 = pInputArray[nFirstElement - 1] + ((pInputArray[nFirstElement - 3] - pInputArray[nFirstElement - 2]) << 3);// - pInputArray[3] + pInputArray[2]; + int *op = &pOutputArray[nFirstElement]; + int *ip = &pInputArray[nFirstElement]; + int IPP2 = ip[-2]; + int IPP1 = ip[-1]; + int p7 = 2 * ip[-1] - ip[-2]; + int opp = op[-1]; + int Original; + CAntiPredictorExtraHighHelper Helper; + + //undo the initial prediction stuff + int q; // loop variable + for (q = 1; q < nFirstElement; q++) { + pOutputArray[q] += pOutputArray[q - 1]; + } + + //pump the primary loop + short *IPAdaptFactor = (short *) calloc(NumberOfElements, 2); + short *IPShort = (short *) calloc(NumberOfElements, 2); + for (q = 0; q < nFirstElement; q++) { + IPAdaptFactor[q] = ((pInputArray[q] >> 30) & 2) - 1; + IPShort[q] = short(pInputArray[q]); + } + + int FM[9]; memset(&FM[0], 0, 9 * 4); + int FP[9]; memset(&FP[0], 0, 9 * 4); + + for (q = nFirstElement; op < &pOutputArray[NumberOfElements]; op++, ip++, q++) { + //CPU load-balancing + if (CPULoadBalancingFactor > 0) { + if ((q % CPULoadBalancingFactor) == 0) { SLEEP(1); } + } + + if (nVersion >= 3830) + { + int *pFP = &FP[8]; + int *pFM = &FM[8]; + int nDotProduct = 0; + FP[0] = ip[0]; + + if (FP[0] == 0) + { + EXPAND_8_TIMES(nDotProduct += *pFP * *pFM--; *pFP-- = *(pFP - 1);) + } + else if (FP[0] > 0) + { + EXPAND_8_TIMES(nDotProduct += *pFP * *pFM; *pFM-- += ((*pFP >> 30) & 2) - 1; *pFP-- = *(pFP - 1);) + } + else + { + EXPAND_8_TIMES(nDotProduct += *pFP * *pFM; *pFM-- -= ((*pFP >> 30) & 2) - 1; *pFP-- = *(pFP - 1);) + } + + *ip -= nDotProduct >> 9; + } + + Original = *ip; + + IPShort[q] = short(*ip); + IPAdaptFactor[q] = ((ip[0] >> 30) & 2) - 1; + +#ifdef ENABLE_ASSEMBLY + if (bMMXAvailable && (Original != 0)) + { + *ip -= (Helper.MMXDotProduct(&IPShort[q-nFirstElement], &bm[0], &IPAdaptFactor[q-nFirstElement], Original, nFilterStageElements) >> nFilterStageShift); + } + else + { + *ip -= (Helper.ConventionalDotProduct(&IPShort[q-nFirstElement], &bm[0], &IPAdaptFactor[q-nFirstElement], Original, nFilterStageElements) >> nFilterStageShift); + } +#else + *ip -= (Helper.ConventionalDotProduct(&IPShort[q-nFirstElement], &bm[0], &IPAdaptFactor[q-nFirstElement], Original, nFilterStageElements) >> nFilterStageShift); +#endif + + IPShort[q] = short(*ip); + IPAdaptFactor[q] = ((ip[0] >> 30) & 2) - 1; + + ///////////////////////////////////////////// + *op = *ip + (((p2 * m2) + (p3 * m3) + (p4 * m4)) >> 11); + + if (*ip > 0) { + m2 -= ((p2 >> 30) & 2) - 1; + m3 -= ((p3 >> 28) & 8) - 4; + m4 -= ((p4 >> 28) & 8) - 4; + } + else if (*ip < 0) { + m2 += ((p2 >> 30) & 2) - 1; + m3 += ((p3 >> 28) & 8) - 4; + m4 += ((p4 >> 28) & 8) - 4; + } + + + p2 = *op + ((IPP2 - p4) << 3); + p3 = (*op - p4) << 1; + IPP2 = p4; + p4 = *op; + + ///////////////////////////////////////////// + *op += (((p7 * m5) - (opp * m6)) >> nStageCShift); + + if (p4 > 0) { + m5 -= ((p7 >> 29) & 4) - 2; + m6 += ((opp >> 30) & 2) - 1; + } + else if (p4 < 0) { + m5 += ((p7 >> 29) & 4) - 2; + m6 -= ((opp >> 30) & 2) - 1; + } + + p7 = 2 * *op - opp; + opp = *op; + + ///////////////////////////////////////////// + *op += ((op[-1] * 31) >> 5); + + } + + free(IPAdaptFactor); + free(IPShort); +} + +#endif // #ifdef ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/AntiPredictorFast.cpp b/MAC_SDK/Source/MACLib/Old/AntiPredictorFast.cpp new file mode 100644 index 0000000..2855a3f --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/AntiPredictorFast.cpp @@ -0,0 +1,88 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "Anti-Predictor.h" + +#ifdef ENABLE_COMPRESSION_MODE_FAST + +void CAntiPredictorFast0000To3320::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) { + + //short frame handling + if (NumberOfElements < 32) { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + //the initial + pOutputArray[0] = pInputArray[0]; + pOutputArray[1] = pInputArray[1] + pOutputArray[0]; + pOutputArray[2] = pInputArray[2] + pOutputArray[1]; + pOutputArray[3] = pInputArray[3] + pOutputArray[2]; + pOutputArray[4] = pInputArray[4] + pOutputArray[3]; + pOutputArray[5] = pInputArray[5] + pOutputArray[4]; + pOutputArray[6] = pInputArray[6] + pOutputArray[5]; + pOutputArray[7] = pInputArray[7] + pOutputArray[6]; + + //the rest + int p, pw; + int m = 4000; + int *ip, *op, *op1; + + op1 = &pOutputArray[7]; + p = (*op1 * 2) - pOutputArray[6]; + pw = (p * m) >> 12; + + for (op = &pOutputArray[8], ip = &pInputArray[8]; ip < &pInputArray[NumberOfElements]; ip++, op++, op1++) { + *op = *ip + pw; + + + //adjust m + if (*ip > 0) + m += (p > 0) ? 4 : -4; + else if (*ip < 0) + m += (p > 0) ? -4 : 4; + + p = (*op * 2) - *op1; + pw = (p * m) >> 12; + + } +} + +///////note: no output - overwrites input///////////////// +void CAntiPredictorFast3320ToCurrent::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) { + + //short frame handling + if (NumberOfElements < 3) { + return; + } + + //variable declares + int p; + int m = 375; + int *ip; + int IP2 = pInputArray[1]; + int IP3 = pInputArray[0]; + int OP1 = pInputArray[1]; + + //the decompression loop (order 2 followed by order 1) + for (ip = &pInputArray[2]; ip < &pInputArray[NumberOfElements]; ip++) { + + //make a prediction for order 2 + p = IP2 + IP2 - IP3; + + //rollback the values + IP3 = IP2; + IP2 = *ip + ((p * m) >> 9); + + //adjust m for the order 2 + (*ip ^ p) > 0 ? m++ : m--; + + //set the output value + *ip = IP2 + OP1; + OP1 = *ip; + } +} + +#endif // #ifdef ENABLE_COMPRESSION_MODE_FAST + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/AntiPredictorHigh.cpp b/MAC_SDK/Source/MACLib/Old/AntiPredictorHigh.cpp new file mode 100644 index 0000000..b0cc5a0 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/AntiPredictorHigh.cpp @@ -0,0 +1,484 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "Anti-Predictor.h" + +#ifdef ENABLE_COMPRESSION_MODE_HIGH + +void CAntiPredictorHigh0000To3320::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // variable declares + int p, pw; + int q; + int m; + + // short frame handling + if (NumberOfElements < 32) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + //////////////////////////////////////// + // order 5 + //////////////////////////////////////// + memcpy(pOutputArray, pInputArray, 32); + + // initialize values + m = 0; + + for (q = 8; q < NumberOfElements; q++) + { + p = (5 * pOutputArray[q - 1]) - (10 * pOutputArray[q - 2]) + (12 * pOutputArray[q - 3]) - (7 * pOutputArray[q - 4]) + pOutputArray[q - 5]; + + pw = (p * m) >> 12; + + pOutputArray[q] = pInputArray[q] + pw; + + // adjust m + if (pInputArray[q] > 0) + (p > 0) ? m += 1 : m -= 1; + else if (pInputArray[q] < 0) + (p > 0) ? m -= 1 : m += 1; + + } + + /////////////////////////////////////// + // order 4 + /////////////////////////////////////// + memcpy(pInputArray, pOutputArray, 32); + m = 0; + + for (q = 8; q < NumberOfElements; q++) + { + p = (4 * pInputArray[q - 1]) - (6 * pInputArray[q - 2]) + (4 * pInputArray[q - 3]) - pInputArray[q - 4]; + pw = (p * m) >> 12; + + pInputArray[q] = pOutputArray[q] + pw; + + // adjust m + if (pOutputArray[q] > 0) + (p > 0) ? m += 2 : m -= 2; + else if (pOutputArray[q] < 0) + (p > 0) ? m -= 2 : m += 2; + } + + CAntiPredictorNormal0000To3320 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); +} + +void CAntiPredictorHigh3320To3600::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // short frame handling + if (NumberOfElements < 8) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // do the offset anti-prediction + CAntiPredictorOffset AntiPredictorOffset; + AntiPredictorOffset.AntiPredict(pInputArray, pOutputArray, NumberOfElements, 2, 12); + AntiPredictorOffset.AntiPredict(pOutputArray, pInputArray, NumberOfElements, 3, 12); + + AntiPredictorOffset.AntiPredict(pInputArray, pOutputArray, NumberOfElements, 4, 12); + AntiPredictorOffset.AntiPredict(pOutputArray, pInputArray, NumberOfElements, 5, 12); + + AntiPredictorOffset.AntiPredict(pInputArray, pOutputArray, NumberOfElements, 6, 12); + AntiPredictorOffset.AntiPredict(pOutputArray, pInputArray, NumberOfElements, 7, 12); + + // use the normal mode + CAntiPredictorNormal3320To3800 AntiPredictor; + AntiPredictor.AntiPredict(pInputArray, pOutputArray, NumberOfElements); +} + +void CAntiPredictorHigh3600To3700::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // variable declares + int q; + + // short frame handling + if (NumberOfElements < 16) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, 13 * 4); + + // initialize values + int bm1 = 0; + int bm2 = 0; + int bm3 = 0; + int bm4 = 0; + int bm5 = 0; + int bm6 = 0; + int bm7 = 0; + int bm8 = 0; + int bm9 = 0; + int bm10 = 0; + int bm11 = 0; + int bm12 = 0; + int bm13 = 0; + + int m2 = 64; + + int m3 = 28; + int m4 = 16; + int OP0; + int OP1 = pOutputArray[12]; + int p4 = pInputArray[12]; + int p3 = (pInputArray[12] - pInputArray[11]) << 1; + int p2 = pInputArray[12] + ((pInputArray[10] - pInputArray[11]) << 3);// - pInputArray[3] + pInputArray[2]; + int bp1 = pOutputArray[12]; + int bp2 = pOutputArray[11]; + int bp3 = pOutputArray[10]; + int bp4 = pOutputArray[9]; + int bp5 = pOutputArray[8]; + int bp6 = pOutputArray[7]; + int bp7 = pOutputArray[6]; + int bp8 = pOutputArray[5]; + int bp9 = pOutputArray[4]; + int bp10 = pOutputArray[3]; + int bp11 = pOutputArray[2]; + int bp12 = pOutputArray[1]; + int bp13 = pOutputArray[0]; + + for (q = 13; q < NumberOfElements; q++) + { + pInputArray[q] = pInputArray[q] - 1; + OP0 = (pInputArray[q] - ((bp1 * bm1) >> 8) + ((bp2 * bm2) >> 8) - ((bp3 * bm3) >> 8) - ((bp4 * bm4) >> 8) - ((bp5 * bm5) >> 8) - ((bp6 * bm6) >> 8) - ((bp7 * bm7) >> 8) - ((bp8 * bm8) >> 8) - ((bp9 * bm9) >> 8) + ((bp10 * bm10) >> 8) + ((bp11 * bm11) >> 8) + ((bp12 * bm12) >> 8) + ((bp13 * bm13) >> 8)); + + if (pInputArray[q] > 0) + { + bm1 -= bp1 > 0 ? 1 : -1; + bm2 += bp2 >= 0 ? 1 : -1; + bm3 -= bp3 > 0 ? 1 : -1; + bm4 -= bp4 >= 0 ? 1 : -1; + bm5 -= bp5 > 0 ? 1 : -1; + bm6 -= bp6 >= 0 ? 1 : -1; + bm7 -= bp7 > 0 ? 1 : -1; + bm8 -= bp8 >= 0 ? 1 : -1; + bm9 -= bp9 > 0 ? 1 : -1; + bm10 += bp10 >= 0 ? 1 : -1; + bm11 += bp11 > 0 ? 1 : -1; + bm12 += bp12 >= 0 ? 1 : -1; + bm13 += bp13 > 0 ? 1 : -1; + } + else if (pInputArray[q] < 0) + { + bm1 -= bp1 <= 0 ? 1 : -1; + bm2 += bp2 < 0 ? 1 : -1; + bm3 -= bp3 <= 0 ? 1 : -1; + bm4 -= bp4 < 0 ? 1 : -1; + bm5 -= bp5 <= 0 ? 1 : -1; + bm6 -= bp6 < 0 ? 1 : -1; + bm7 -= bp7 <= 0 ? 1 : -1; + bm8 -= bp8 < 0 ? 1 : -1; + bm9 -= bp9 <= 0 ? 1 : -1; + bm10 += bp10 < 0 ? 1 : -1; + bm11 += bp11 <= 0 ? 1 : -1; + bm12 += bp12 < 0 ? 1 : -1; + bm13 += bp13 <= 0 ? 1 : -1; + } + + bp13 = bp12; + bp12 = bp11; + bp11 = bp10; + bp10 = bp9; + bp9 = bp8; + bp8 = bp7; + bp7 = bp6; + bp6 = bp5; + bp5 = bp4; + bp4 = bp3; + bp3 = bp2; + bp2 = bp1; + bp1 = OP0; + + pInputArray[q] = OP0 + ((p2 * m2) >> 11) + ((p3 * m3) >> 9) + ((p4 * m4) >> 9); + + if (OP0 > 0) + { + m2 -= p2 > 0 ? -1 : 1; + m3 -= p3 > 0 ? -1 : 1; + m4 -= p4 > 0 ? -1 : 1; + } + else if (OP0 < 0) + { + m2 -= p2 > 0 ? 1 : -1; + m3 -= p3 > 0 ? 1 : -1; + m4 -= p4 > 0 ? 1 : -1; + } + + p2 = pInputArray[q] + ((pInputArray[q - 2] - pInputArray[q - 1]) << 3); + p3 = (pInputArray[q] - pInputArray[q - 1]) << 1; + p4 = pInputArray[q]; + pOutputArray[q] = pInputArray[q];// + ((p3 * m3) >> 9); + } + + m4 = 370; + int m5 = 3900; + + pOutputArray[1] = pInputArray[1] + pOutputArray[0]; + pOutputArray[2] = pInputArray[2] + pOutputArray[1]; + pOutputArray[3] = pInputArray[3] + pOutputArray[2]; + pOutputArray[4] = pInputArray[4] + pOutputArray[3]; + pOutputArray[5] = pInputArray[5] + pOutputArray[4]; + pOutputArray[6] = pInputArray[6] + pOutputArray[5]; + pOutputArray[7] = pInputArray[7] + pOutputArray[6]; + pOutputArray[8] = pInputArray[8] + pOutputArray[7]; + pOutputArray[9] = pInputArray[9] + pOutputArray[8]; + pOutputArray[10] = pInputArray[10] + pOutputArray[9]; + pOutputArray[11] = pInputArray[11] + pOutputArray[10]; + pOutputArray[12] = pInputArray[12] + pOutputArray[11]; + + p4 = (2 * pInputArray[12]) - pInputArray[11]; + int p6 = 0; + int p5 = pOutputArray[12]; + int IP0, IP1; + int m6 = 0; + + IP1 = pInputArray[12]; + for (q = 13; q < NumberOfElements; q++) + { + IP0 = pOutputArray[q] + ((p4 * m4) >> 9) - ((p6 * m6) >> 10); + (pOutputArray[q] ^ p4) >= 0 ? m4++ : m4--; + (pOutputArray[q] ^ p6) >= 0 ? m6-- : m6++; + p4 = (2 * IP0) - IP1; + p6 = IP0; + + pOutputArray[q] = IP0 + ((p5 * 31) >> 5); + p5 = pOutputArray[q]; + + IP1 = IP0; + } +} + +void CAntiPredictorHigh3700To3800::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // the frame to start prediction on + #define FIRST_ELEMENT 16 + + int x = 100; + int y = -25; + + // short frame handling + if (NumberOfElements < 20) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, FIRST_ELEMENT * 4); + + // variable declares and initializations + int bm[FIRST_ELEMENT]; memset(bm, 0, FIRST_ELEMENT * 4); + int m2 = 64, m3 = 115, m4 = 64, m5 = 740, m6 = 0; + int p4 = pInputArray[FIRST_ELEMENT - 1]; + int p3 = (pInputArray[FIRST_ELEMENT - 1] - pInputArray[FIRST_ELEMENT - 2]) << 1; + int p2 = pInputArray[FIRST_ELEMENT - 1] + ((pInputArray[FIRST_ELEMENT - 3] - pInputArray[FIRST_ELEMENT - 2]) << 3);// - pInputArray[3] + pInputArray[2]; + int *op = &pOutputArray[FIRST_ELEMENT]; + int *ip = &pInputArray[FIRST_ELEMENT]; + int IPP2 = ip[-2]; + int IPP1 = ip[-1]; + int p7 = 2 * ip[-1] - ip[-2]; + int opp = op[-1]; + int Original; + + // undo the initial prediction stuff + for (int q = 1; q < FIRST_ELEMENT; q++) { + pOutputArray[q] += pOutputArray[q - 1]; + } + + // pump the primary loop + for (;op < &pOutputArray[NumberOfElements]; op++, ip++) { + + Original = *ip - 1; + *ip = Original - (((ip[-1] * bm[0]) + (ip[-2] * bm[1]) + (ip[-3] * bm[2]) + (ip[-4] * bm[3]) + (ip[-5] * bm[4]) + (ip[-6] * bm[5]) + (ip[-7] * bm[6]) + (ip[-8] * bm[7]) + (ip[-9] * bm[8]) + (ip[-10] * bm[9]) + (ip[-11] * bm[10]) + (ip[-12] * bm[11]) + (ip[-13] * bm[12]) + (ip[-14] * bm[13]) + (ip[-15] * bm[14]) + (ip[-16] * bm[15])) >> 8); + + if (Original > 0) + { + bm[0] -= ip[-1] > 0 ? 1 : -1; + bm[1] += ((unsigned int(ip[-2]) >> 30) & 2) - 1; + bm[2] -= ip[-3] > 0 ? 1 : -1; + bm[3] += ((unsigned int(ip[-4]) >> 30) & 2) - 1; + bm[4] -= ip[-5] > 0 ? 1 : -1; + bm[5] += ((unsigned int(ip[-6]) >> 30) & 2) - 1; + bm[6] -= ip[-7] > 0 ? 1 : -1; + bm[7] += ((unsigned int(ip[-8]) >> 30) & 2) - 1; + bm[8] -= ip[-9] > 0 ? 1 : -1; + bm[9] += ((unsigned int(ip[-10]) >> 30) & 2) - 1; + bm[10] -= ip[-11] > 0 ? 1 : -1; + bm[11] += ((unsigned int(ip[-12]) >> 30) & 2) - 1; + bm[12] -= ip[-13] > 0 ? 1 : -1; + bm[13] += ((unsigned int(ip[-14]) >> 30) & 2) - 1; + bm[14] -= ip[-15] > 0 ? 1 : -1; + bm[15] += ((unsigned int(ip[-16]) >> 30) & 2) - 1; + } + else if (Original < 0) + { + bm[0] -= ip[-1] <= 0 ? 1 : -1; + bm[1] -= ((unsigned int(ip[-2]) >> 30) & 2) - 1; + bm[2] -= ip[-3] <= 0 ? 1 : -1; + bm[3] -= ((unsigned int(ip[-4]) >> 30) & 2) - 1; + bm[4] -= ip[-5] <= 0 ? 1 : -1; + bm[5] -= ((unsigned int(ip[-6]) >> 30) & 2) - 1; + bm[6] -= ip[-7] <= 0 ? 1 : -1; + bm[7] -= ((unsigned int(ip[-8]) >> 30) & 2) - 1; + bm[8] -= ip[-9] <= 0 ? 1 : -1; + bm[9] -= ((unsigned int(ip[-10]) >> 30) & 2) - 1; + bm[10] -= ip[-11] <= 0 ? 1 : -1; + bm[11] -= ((unsigned int(ip[-12]) >> 30) & 2) - 1; + bm[12] -= ip[-13] <= 0 ? 1 : -1; + bm[13] -= ((unsigned int(ip[-14]) >> 30) & 2) - 1; + bm[14] -= ip[-15] <= 0 ? 1 : -1; + bm[15] -= ((unsigned int(ip[-16]) >> 30) & 2) - 1; + } + + ///////////////////////////////////////////// + *op = *ip + (((p2 * m2) + (p3 * m3) + (p4 * m4)) >> 11); + + if (*ip > 0) + { + m2 -= p2 > 0 ? -1 : 1; + m3 -= p3 > 0 ? -4 : 4; + m4 -= p4 > 0 ? -4 : 4; + } + else if (*ip < 0) + { + m2 -= p2 > 0 ? 1 : -1; + m3 -= p3 > 0 ? 4 : -4; + m4 -= p4 > 0 ? 4 : -4; + } + + p4 = *op; + p2 = p4 + ((IPP2 - IPP1) << 3); + p3 = (p4 - IPP1) << 1; + + IPP2 = IPP1; + IPP1 = p4; + + ///////////////////////////////////////////// + *op += (((p7 * m5) - (opp * m6)) >> 10); + + (IPP1 ^ p7) >= 0 ? m5+=2 : m5-=2; + (IPP1 ^ opp) >= 0 ? m6-- : m6++; + + p7 = 2 * *op - opp; + opp = *op; + + ///////////////////////////////////////////// + *op += ((op[-1] * 31) >> 5); + } +} + +void CAntiPredictorHigh3800ToCurrent::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // the frame to start prediction on + #define FIRST_ELEMENT 16 + + // short frame handling + if (NumberOfElements < 20) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, FIRST_ELEMENT * 4); + + // variable declares and initializations + int bm[FIRST_ELEMENT]; memset(bm, 0, FIRST_ELEMENT * 4); + int m2 = 64, m3 = 115, m4 = 64, m5 = 740, m6 = 0; + int p4 = pInputArray[FIRST_ELEMENT - 1]; + int p3 = (pInputArray[FIRST_ELEMENT - 1] - pInputArray[FIRST_ELEMENT - 2]) << 1; + int p2 = pInputArray[FIRST_ELEMENT - 1] + ((pInputArray[FIRST_ELEMENT - 3] - pInputArray[FIRST_ELEMENT - 2]) << 3);// - pInputArray[3] + pInputArray[2]; + int *op = &pOutputArray[FIRST_ELEMENT]; + int *ip = &pInputArray[FIRST_ELEMENT]; + int IPP2 = ip[-2]; + int IPP1 = ip[-1]; + int p7 = 2 * ip[-1] - ip[-2]; + int opp = op[-1]; + + // undo the initial prediction stuff + for (int q = 1; q < FIRST_ELEMENT; q++) + { + pOutputArray[q] += pOutputArray[q - 1]; + } + + // pump the primary loop + for (;op < &pOutputArray[NumberOfElements]; op++, ip++) + { + + unsigned int *pip = (unsigned int *) &ip[-FIRST_ELEMENT]; + int *pbm = &bm[0]; + int nDotProduct = 0; + + if (*ip > 0) + { + EXPAND_16_TIMES(nDotProduct += *pip * *pbm; *pbm++ += ((*pip++ >> 30) & 2) - 1;) + } + else if (*ip < 0) + { + EXPAND_16_TIMES(nDotProduct += *pip * *pbm; *pbm++ -= ((*pip++ >> 30) & 2) - 1;) + } + else + { + EXPAND_16_TIMES(nDotProduct += *pip++ * *pbm++;) + } + + *ip -= (nDotProduct >> 9); + + ///////////////////////////////////////////// + *op = *ip + (((p2 * m2) + (p3 * m3) + (p4 * m4)) >> 11); + + if (*ip > 0) + { + m2 -= ((p2 >> 30) & 2) - 1; + m3 -= ((p3 >> 28) & 8) - 4; + m4 -= ((p4 >> 28) & 8) - 4; + + } + else if (*ip < 0) + { + m2 += ((p2 >> 30) & 2) - 1; + m3 += ((p3 >> 28) & 8) - 4; + m4 += ((p4 >> 28) & 8) - 4; + } + + + p2 = *op + ((IPP2 - p4) << 3); + p3 = (*op - p4) << 1; + IPP2 = p4; + p4 = *op; + + ///////////////////////////////////////////// + *op += (((p7 * m5) - (opp * m6)) >> 10); + + if (p4 > 0) + { + m5 -= ((p7 >> 29) & 4) - 2; + m6 += ((opp >> 30) & 2) - 1; + } + else if (p4 < 0) + { + m5 += ((p7 >> 29) & 4) - 2; + m6 -= ((opp >> 30) & 2) - 1; + } + + p7 = 2 * *op - opp; + opp = *op; + + ///////////////////////////////////////////// + *op += ((op[-1] * 31) >> 5); + } + + #undef FIRST_ELEMENT +} + +#endif // #ifdef ENABLE_COMPRESSION_MODE_HIGH + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/AntiPredictorNormal.cpp b/MAC_SDK/Source/MACLib/Old/AntiPredictorNormal.cpp new file mode 100644 index 0000000..9a8daea --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/AntiPredictorNormal.cpp @@ -0,0 +1,262 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "Anti-Predictor.h" +#ifdef ENABLE_COMPRESSION_MODE_NORMAL + +void CAntiPredictorNormal0000To3320::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // variable declares + int *ip, *op, *op1, *op2; + int p, pw; + int m; + + // short frame handling + if (NumberOfElements < 32) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + //////////////////////////////////////// + // order 3 + //////////////////////////////////////// + memcpy(pOutputArray, pInputArray, 32); + + // initialize values + m = 300; + op = &pOutputArray[8]; + op1 = &pOutputArray[7]; + op2 = &pOutputArray[6]; + + // make the first prediction + p = (pOutputArray[7] * 3) - (pOutputArray[6] * 3) + pOutputArray[5]; + pw = (p * m) >> 12; + + // loop through the array + for (ip = &pInputArray[8]; ip < &pInputArray[NumberOfElements]; ip++, op++, op1++, op2++) { + + // figure the output value + *op = *ip + pw; + + // adjust m + if (*ip > 0) + m += (p > 0) ? 4 : -4; + else if (*ip < 0) + m += (p > 0) ? -4 : 4; + + // make the next prediction + p = (*op * 3) - (*op1 * 3) + *op2; + pw = (p * m) >> 12; + } + + + /////////////////////////////////////// + // order 2 + /////////////////////////////////////// + memcpy(pInputArray, pOutputArray, 32); + m = 3000; + + op1 = &pInputArray[7]; + p = (*op1 * 2) - pInputArray[6]; + pw = (p * m) >> 12; + + for (op = &pInputArray[8], ip = &pOutputArray[8]; ip < &pOutputArray[NumberOfElements]; ip++, op++, op1++) + { + *op = *ip + pw; + + // adjust m + if (*ip > 0) + m += (p > 0) ? 12 : -12; + else if (*ip < 0) + m += (p > 0) ? -12 : 12; + + p = (*op * 2) - *op1; + pw = (p * m) >> 12; + + } + + /////////////////////////////////////// + // order 1 + /////////////////////////////////////// + pOutputArray[0] = pInputArray[0]; + pOutputArray[1] = pInputArray[1] + pOutputArray[0]; + pOutputArray[2] = pInputArray[2] + pOutputArray[1]; + pOutputArray[3] = pInputArray[3] + pOutputArray[2]; + pOutputArray[4] = pInputArray[4] + pOutputArray[3]; + pOutputArray[5] = pInputArray[5] + pOutputArray[4]; + pOutputArray[6] = pInputArray[6] + pOutputArray[5]; + pOutputArray[7] = pInputArray[7] + pOutputArray[6]; + + m = 3900; + + p = pOutputArray[7]; + pw = (p * m) >> 12; + + for (op = &pOutputArray[8], ip = &pInputArray[8]; ip < &pInputArray[NumberOfElements]; ip++, op++) { + *op = *ip + pw; + + // adjust m + if (*ip > 0) + m += (p > 0) ? 1 : -1; + else if (*ip < 0) + m += (p > 0) ? -1 : 1; + + p = *op; + pw = (p * m) >> 12; + } + +} + +void CAntiPredictorNormal3320To3800::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // variable declares + int q; + + // short frame handling + if (NumberOfElements < 8) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, 20); + + // initialize values + int m1 = 0; + int m2 = 64; + int m3 = 28; + int OP0; + int OP1 = pOutputArray[4]; + + int p3 = (3 * (pOutputArray[4] - pOutputArray[3])) + pOutputArray[2]; + int p2 = pInputArray[4] + ((pInputArray[2] - pInputArray[3]) << 3) - pInputArray[1] + pInputArray[0]; + int p1 = pOutputArray[4]; + + for (q = 5; q < NumberOfElements; q++) + { + OP0 = pInputArray[q] + ((p1 * m1) >> 8); + (pInputArray[q] ^ p1) > 0 ? m1++ : m1--; + p1 = OP0; + + pInputArray[q] = OP0 + ((p2 * m2) >> 11); + (OP0 ^ p2) > 0 ? m2++ : m2--; + p2 = pInputArray[q] + ((pInputArray[q - 2] - pInputArray[q - 1]) << 3) - pInputArray[q - 3] + pInputArray[q - 4]; + + pOutputArray[q] = pInputArray[q] + ((p3 * m3) >> 9); + (pInputArray[q] ^ p3) > 0 ? m3++ : m3--; + p3 = (3 * (pOutputArray[q] - pOutputArray[q - 1])) + pOutputArray[q - 2]; + } + + int m4 = 370; + int m5 = 3900; + + pOutputArray[1] = pInputArray[1] + pOutputArray[0]; + pOutputArray[2] = pInputArray[2] + pOutputArray[1]; + pOutputArray[3] = pInputArray[3] + pOutputArray[2]; + pOutputArray[4] = pInputArray[4] + pOutputArray[3]; + + int p4 = (2 * pInputArray[4]) - pInputArray[3]; + int p5 = pOutputArray[4]; + int IP0, IP1; + + IP1 = pInputArray[4]; + for (q = 5; q < NumberOfElements; q++) + { + IP0 = pOutputArray[q] + ((p4 * m4) >> 9); + (pOutputArray[q] ^ p4) > 0 ? m4++ : m4--; + p4 = (2 * IP0) - IP1; + + pOutputArray[q] = IP0 + ((p5 * m5) >> 12); + (IP0 ^ p5) > 0 ? m5++ : m5--; + p5 = pOutputArray[q]; + + IP1 = IP0; + } +} + +void CAntiPredictorNormal3800ToCurrent::AntiPredict(int *pInputArray, int *pOutputArray, int NumberOfElements) +{ + // the frame to start prediction on + #define FIRST_ELEMENT 4 + + // short frame handling + if (NumberOfElements < 8) + { + memcpy(pOutputArray, pInputArray, NumberOfElements * 4); + return; + } + + // make the first five samples identical in both arrays + memcpy(pOutputArray, pInputArray, FIRST_ELEMENT * 4); + + // variable declares and initializations + int m2 = 64, m3 = 115, m4 = 64, m5 = 740, m6 = 0; + int p4 = pInputArray[FIRST_ELEMENT - 1]; + int p3 = (pInputArray[FIRST_ELEMENT - 1] - pInputArray[FIRST_ELEMENT - 2]) << 1; + int p2 = pInputArray[FIRST_ELEMENT - 1] + ((pInputArray[FIRST_ELEMENT - 3] - pInputArray[FIRST_ELEMENT - 2]) << 3);// - pInputArray[3] + pInputArray[2]; + int *op = &pOutputArray[FIRST_ELEMENT]; + int *ip = &pInputArray[FIRST_ELEMENT]; + int IPP2 = ip[-2]; + int p7 = 2 * ip[-1] - ip[-2]; + int opp = op[-1]; + + // undo the initial prediction stuff + for (int q = 1; q < FIRST_ELEMENT; q++) { + pOutputArray[q] += pOutputArray[q - 1]; + } + + // pump the primary loop + for (; op < &pOutputArray[NumberOfElements]; op++, ip++) { + + register int o = *op, i = *ip; + + ///////////////////////////////////////////// + o = i + (((p2 * m2) + (p3 * m3) + (p4 * m4)) >> 11); + + if (i > 0) + { + m2 -= ((p2 >> 30) & 2) - 1; + m3 -= ((p3 >> 28) & 8) - 4; + m4 -= ((p4 >> 28) & 8) - 4; + + } + else if (i < 0) + { + m2 += ((p2 >> 30) & 2) - 1; + m3 += ((p3 >> 28) & 8) - 4; + m4 += ((p4 >> 28) & 8) - 4; + } + + + p2 = o + ((IPP2 - p4) << 3); + p3 = (o - p4) << 1; + IPP2 = p4; + p4 = o; + + ///////////////////////////////////////////// + o += (((p7 * m5) - (opp * m6)) >> 10); + + if (p4 > 0) + { + m5 -= ((p7 >> 29) & 4) - 2; + m6 += ((opp >> 30) & 2) - 1; + } + else if (p4 < 0) + { + m5 += ((p7 >> 29) & 4) - 2; + m6 -= ((opp >> 30) & 2) - 1; + } + + p7 = 2 * o - opp; + opp = o; + + ///////////////////////////////////////////// + *op = o + ((op[-1] * 31) >> 5); + } +} + +#endif // #ifdef ENABLE_COMPRESSION_MODE_NORMAL + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.cpp b/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.cpp new file mode 100644 index 0000000..ce99936 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.cpp @@ -0,0 +1,353 @@ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "../APEInfo.h" +#include "UnBitarrayOld.h" +#include "../BitArray.h" + +const uint32 K_SUM_MIN_BOUNDARY_OLD[32] = {0,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0,0,0}; +const uint32 K_SUM_MAX_BOUNDARY_OLD[32] = {128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0,0,0,0}; +const uint32 Powers_of_Two[32] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648}; +const uint32 Powers_of_Two_Reversed[32] = {2147483648,1073741824,536870912,268435456,134217728,67108864,33554432,16777216,8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}; +const uint32 Powers_of_Two_Minus_One[33] = {0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215,33554431,67108863,134217727,268435455,536870911,1073741823,2147483647,4294967295}; +const uint32 Powers_of_Two_Minus_One_Reversed[33] = {4294967295,2147483647,1073741823,536870911,268435455,134217727,67108863,33554431,16777215,8388607,4194303,2097151,1048575,524287,262143,131071,65535,32767,16383,8191,4095,2047,1023,511,255,127,63,31,15,7,3,1,0}; + +const uint32 K_SUM_MIN_BOUNDARY[32] = {0,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0}; +const uint32 K_SUM_MAX_BOUNDARY[32] = {32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0,0}; + +/*********************************************************************************** +Construction +***********************************************************************************/ +CUnBitArrayOld::CUnBitArrayOld(IAPEDecompress * pAPEDecompress, int nVersion) +{ + int nBitArrayBytes = 262144; + + // calculate the bytes + if (nVersion <= 3880) + { + int nMaxFrameBytes = (pAPEDecompress->GetInfo(APE_INFO_BLOCKS_PER_FRAME) * 50) / 8; + nBitArrayBytes = 65536; + while (nBitArrayBytes < nMaxFrameBytes) + { + nBitArrayBytes <<= 1; + } + + nBitArrayBytes = max(nBitArrayBytes, 262144); + } + else if (nVersion <= 3890) + { + nBitArrayBytes = 65536; + } + else + { + // error + } + + CreateHelper(GET_IO(pAPEDecompress), nBitArrayBytes, nVersion); + + // set the refill threshold + if (m_nVersion <= 3880) + m_nRefillBitThreshold = (m_nBits - (16384 * 8)); + else + m_nRefillBitThreshold = (m_nBits - 512); +} + +CUnBitArrayOld::~CUnBitArrayOld() +{ + SAFE_ARRAY_DELETE(m_pBitArray) +} + +//////////////////////////////////////////////////////////////////////////////////// +// Gets the number of m_nBits of data left in the m_nCurrentBitIndex array +//////////////////////////////////////////////////////////////////////////////////// +uint32 CUnBitArrayOld::GetBitsRemaining() +{ + return (m_nElements * 32 - m_nCurrentBitIndex); +} + +//////////////////////////////////////////////////////////////////////////////////// +// Gets a rice value from the array +//////////////////////////////////////////////////////////////////////////////////// +uint32 CUnBitArrayOld::DecodeValueRiceUnsigned(uint32 k) +{ + // variable declares + uint32 v; + + // plug through the string of 0's (the overflow) + uint32 BitInitial = m_nCurrentBitIndex; + while (!(m_pBitArray[m_nCurrentBitIndex >> 5] & Powers_of_Two_Reversed[m_nCurrentBitIndex++ & 31])) {} + + // if k = 0, your done + if (k == 0) + return (m_nCurrentBitIndex - BitInitial - 1); + + // put the overflow value into v + v = (m_nCurrentBitIndex - BitInitial - 1) << k; + + return v | DecodeValueXBits(k); +} + +//////////////////////////////////////////////////////////////////////////////////// +// Get the optimal k for a given value +//////////////////////////////////////////////////////////////////////////////////// +__inline uint32 CUnBitArrayOld::Get_K(uint32 x) +{ + if (x == 0) return 0; + + uint32 k = 0; + while (x >= Powers_of_Two[++k]) {} + return k; +} + +unsigned int CUnBitArrayOld::DecodeValue(DECODE_VALUE_METHOD DecodeMethod, int nParam1, int nParam2) +{ + switch (DecodeMethod) + { + case DECODE_VALUE_METHOD_UNSIGNED_INT: + return DecodeValueXBits(32); + case DECODE_VALUE_METHOD_UNSIGNED_RICE: + return DecodeValueRiceUnsigned(nParam1); + case DECODE_VALUE_METHOD_X_BITS: + return DecodeValueXBits(nParam1); + } + + return 0; +} + +//////////////////////////////////////////////////////////////////////////////////// +// Generates an array from the m_nCurrentBitIndexarray +//////////////////////////////////////////////////////////////////////////////////// +void CUnBitArrayOld::GenerateArrayOld(int* Output_Array, uint32 Number_of_Elements, int Minimum_nCurrentBitIndex_Array_Bytes) { + + //variable declarations + uint32 K_Sum; + uint32 q; + uint32 kmin, kmax; + uint32 k; + uint32 Max; + int *p1, *p2; + + // fill bit array if necessary + // could use seek information to determine what the max was... + uint32 Max_Bits_Needed = Number_of_Elements * 50; + + if (Minimum_nCurrentBitIndex_Array_Bytes > 0) + { + // this is actually probably double what is really needed + // we can only calculate the space needed for both arrays in multichannel + Max_Bits_Needed = ((Minimum_nCurrentBitIndex_Array_Bytes + 4) * 8); + } + + if (Max_Bits_Needed > GetBitsRemaining()) + FillBitArray(); + + // decode the first 5 elements (all k = 10) + Max = (Number_of_Elements < 5) ? Number_of_Elements : 5; + for (q = 0; q < Max; q++) + { + Output_Array[q] = DecodeValueRiceUnsigned(10); + } + + // quit if that was all + if (Number_of_Elements <= 5) + { + for (p2 = &Output_Array[0]; p2 < &Output_Array[Number_of_Elements]; p2++) + *p2 = (*p2 & 1) ? (*p2 >> 1) + 1 : -(*p2 >> 1); + return; + } + + // update k and K_Sum + K_Sum = Output_Array[0] + Output_Array[1] + Output_Array[2] + Output_Array[3] + Output_Array[4]; + k = Get_K(K_Sum / 10); + + // work through the rest of the elements before the primary loop + Max = (Number_of_Elements < 64) ? Number_of_Elements : 64; + for (q = 5; q < Max; q++) + { + Output_Array[q] = DecodeValueRiceUnsigned(k); + K_Sum += Output_Array[q]; + k = Get_K(K_Sum / (q + 1) / 2); + } + + // quit if that was all + if (Number_of_Elements <= 64) + { + for (p2 = &Output_Array[0]; p2 < &Output_Array[Number_of_Elements]; p2++) + *p2 = (*p2 & 1) ? (*p2 >> 1) + 1 : -(*p2 >> 1); + return; + } + + // set all of the variables up for the primary loop + uint32 v, Bit_Array_Index; + k = Get_K(K_Sum >> 7); + kmin = K_SUM_MIN_BOUNDARY_OLD[k]; + kmax = K_SUM_MAX_BOUNDARY_OLD[k]; + p1 = &Output_Array[64]; p2 = &Output_Array[0]; + + // the primary loop + for (p1 = &Output_Array[64], p2 = &Output_Array[0]; p1 < &Output_Array[Number_of_Elements]; p1++, p2++) + { + // plug through the string of 0's (the overflow) + uint32 Bit_Initial = m_nCurrentBitIndex; + while (!(m_pBitArray[m_nCurrentBitIndex >> 5] & Powers_of_Two_Reversed[m_nCurrentBitIndex++ & 31])) {} + + // if k = 0, your done + if (k == 0) + { + v = (m_nCurrentBitIndex - Bit_Initial - 1); + } + else + { + // put the overflow value into v + v = (m_nCurrentBitIndex - Bit_Initial - 1) << k; + + // store the bit information and incement the bit pointer by 'k' + Bit_Array_Index = m_nCurrentBitIndex >> 5; + unsigned int Bit_Index = m_nCurrentBitIndex & 31; + m_nCurrentBitIndex += k; + + // figure the extra bits on the left and the left value + int Left_Extra_Bits = (32 - k) - Bit_Index; + unsigned int Left_Value = m_pBitArray[Bit_Array_Index] & Powers_of_Two_Minus_One_Reversed[Bit_Index]; + + if (Left_Extra_Bits >= 0) + v |= (Left_Value >> Left_Extra_Bits); + else + v |= (Left_Value << -Left_Extra_Bits) | (m_pBitArray[Bit_Array_Index + 1] >> (32 + Left_Extra_Bits)); + } + + *p1 = v; + K_Sum += *p1 - *p2; + + // convert *p2 to unsigned + *p2 = (*p2 % 2) ? (*p2 >> 1) + 1 : -(*p2 >> 1); + + // adjust k if necessary + if ((K_Sum < kmin) || (K_Sum >= kmax)) + { + if (K_Sum < kmin) + while (K_Sum < K_SUM_MIN_BOUNDARY_OLD[--k]) {} + else + while (K_Sum >= K_SUM_MAX_BOUNDARY_OLD[++k]) {} + + kmax = K_SUM_MAX_BOUNDARY_OLD[k]; + kmin = K_SUM_MIN_BOUNDARY_OLD[k]; + } + } + + for (; p2 < &Output_Array[Number_of_Elements]; p2++) + *p2 = (*p2 & 1) ? (*p2 >> 1) + 1 : -(*p2 >> 1); +} + +void CUnBitArrayOld::GenerateArray(int *pOutputArray, int nElements, int nBytesRequired) +{ + if (m_nVersion < 3860) + { + GenerateArrayOld(pOutputArray, nElements, nBytesRequired); + } + else if (m_nVersion <= 3890) + { + GenerateArrayRice(pOutputArray, nElements, nBytesRequired); + } + else + { + // error + } +} + +void CUnBitArrayOld::GenerateArrayRice(int* Output_Array, uint32 Number_of_Elements, int Minimum_nCurrentBitIndex_Array_Bytes) +{ + ///////////////////////////////////////////////////////////////////////////// + // decode the bit array + ///////////////////////////////////////////////////////////////////////////// + + k = 10; + K_Sum = 1024 * 16; + + if (m_nVersion <= 3880) + { + // the primary loop + for (int *p1 = &Output_Array[0]; p1 < &Output_Array[Number_of_Elements]; p1++) + { + *p1 = DecodeValueNew(FALSE); + } + } + else + { + // the primary loop + for (int *p1 = &Output_Array[0]; p1 < &Output_Array[Number_of_Elements]; p1++) + { + *p1 = DecodeValueNew(TRUE); + } + } +} + +__inline int CUnBitArrayOld::DecodeValueNew(BOOL bCapOverflow) +{ + // make sure there is room for the data + // this is a little slower than ensuring a huge block to start with, but it's safer + if (m_nCurrentBitIndex > m_nRefillBitThreshold) + { + FillBitArray(); + } + + unsigned int v; + + // plug through the string of 0's (the overflow) + uint32 Bit_Initial = m_nCurrentBitIndex; + while (!(m_pBitArray[m_nCurrentBitIndex >> 5] & Powers_of_Two_Reversed[m_nCurrentBitIndex++ & 31])) {} + + int nOverflow = (m_nCurrentBitIndex - Bit_Initial - 1); + + if (bCapOverflow) + { + while (nOverflow >= 16) + { + k += 4; + nOverflow -= 16; + } + } + + // if k = 0, your done + if (k != 0) + { + // put the overflow value into v + v = nOverflow << k; + + // store the bit information and incement the bit pointer by 'k' + unsigned int Bit_Array_Index = m_nCurrentBitIndex >> 5; + unsigned int Bit_Index = m_nCurrentBitIndex & 31; + m_nCurrentBitIndex += k; + + // figure the extra bits on the left and the left value + int Left_Extra_Bits = (32 - k) - Bit_Index; + unsigned int Left_Value = m_pBitArray[Bit_Array_Index] & Powers_of_Two_Minus_One_Reversed[Bit_Index]; + + if (Left_Extra_Bits >= 0) + { + v |= (Left_Value >> Left_Extra_Bits); + } + else + { + v |= (Left_Value << -Left_Extra_Bits) | (m_pBitArray[Bit_Array_Index + 1] >> (32 + Left_Extra_Bits)); + } + } + else + { + v = nOverflow; + } + + // update K_Sum + K_Sum += v - ((K_Sum + 8) >> 4); + + // update k + if (K_Sum < K_SUM_MIN_BOUNDARY[k]) + k--; + else if (K_Sum >= K_SUM_MAX_BOUNDARY[k]) + k++; + + // convert to unsigned and save + return (v & 1) ? (v >> 1) + 1 : -(int(v >> 1)); +} + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.h b/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.h new file mode 100644 index 0000000..8a5beb5 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/UnBitArrayOld.h @@ -0,0 +1,46 @@ +#ifndef APE_UNBITARRAY_OLD_H +#define APE_UNBITARRAY_OLD_H + +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "../UnBitArrayBase.h" + +class IAPEDecompress; + +// decodes 0000 up to and including 3890 +class CUnBitArrayOld : public CUnBitArrayBase +{ +public: + + // construction/destruction + CUnBitArrayOld(IAPEDecompress *pAPEDecompress, int nVersion); + ~CUnBitArrayOld(); + + // functions + void GenerateArray(int *pOutputArray, int nElements, int nBytesRequired = -1); + unsigned int DecodeValue(DECODE_VALUE_METHOD DecodeMethod, int nParam1 = 0, int nParam2 = 0); + +private: + + void GenerateArrayOld(int* pOutputArray, uint32 NumberOfElements, int MinimumBitArrayBytes); + void GenerateArrayRice(int* pOutputArray, uint32 NumberOfElements, int MinimumBitArrayBytes); + + uint32 DecodeValueRiceUnsigned(uint32 k); + + // data + uint32 k; + uint32 K_Sum; + uint32 m_nRefillBitThreshold; + + // functions + __inline int DecodeValueNew(BOOL bCapOverflow); + uint32 GetBitsRemaining(); + __inline uint32 Get_K(uint32 x); +}; + +#endif + +#endif // #ifndef APE_UNBITARRAY_OLD_H + + diff --git a/MAC_SDK/Source/MACLib/Old/UnMAC.cpp b/MAC_SDK/Source/MACLib/Old/UnMAC.cpp new file mode 100644 index 0000000..43d3732 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/UnMAC.cpp @@ -0,0 +1,261 @@ +/***************************************************************************************** +UnMAC.cpp +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. + +CUnMAC - the main hub for decompression (manages all of the other components) + +Notes: + -none +*****************************************************************************************/ + +/***************************************************************************************** +Includes +*****************************************************************************************/ +#include "All.h" +#ifdef BACKWARDS_COMPATIBILITY + +#include "../APEInfo.h" +#include "UnMAC.h" +#include "GlobalFunctions.h" +#include "../UnBitArrayBase.h" +#include "Anti-Predictor.h" +#include "../Prepare.h" +#include "../UnBitArray.h" +#include "../NewPredictor.h" +#include "APEDecompressCore.h" + +/***************************************************************************************** +CUnMAC class construction +*****************************************************************************************/ +CUnMAC::CUnMAC() +{ + // initialize member variables + m_bInitialized = FALSE; + m_LastDecodedFrameIndex = -1; + m_pAPEDecompress = NULL; + + m_pAPEDecompressCore = NULL; + m_pPrepare = NULL; + + m_nBlocksProcessed = 0; + m_nCRC = 0; + +} + +/***************************************************************************************** +CUnMAC class destruction +*****************************************************************************************/ +CUnMAC::~CUnMAC() +{ + // uninitialize the decoder in case it isn't already + Uninitialize(); +} + +/***************************************************************************************** +Initialize +*****************************************************************************************/ +int CUnMAC::Initialize(IAPEDecompress *pAPEDecompress) +{ + // uninitialize if it is currently initialized + if (m_bInitialized) + Uninitialize(); + + if (pAPEDecompress == NULL) + { + Uninitialize(); + return ERROR_INITIALIZING_UNMAC; + } + + // set the member pointer to the IAPEDecompress class + m_pAPEDecompress = pAPEDecompress; + + // set the last decode frame to -1 so it forces a seek on start + m_LastDecodedFrameIndex = -1; + + m_pAPEDecompressCore = new CAPEDecompressCore(GET_IO(pAPEDecompress), pAPEDecompress); + m_pPrepare = new CPrepare; + + // set the initialized flag to TRUE + m_bInitialized = TRUE; + + m_pAPEDecompress->GetInfo(APE_INFO_WAVEFORMATEX, (int) &m_wfeInput); + + // return a successful value + return ERROR_SUCCESS; +} + +/***************************************************************************************** +Uninitialize +*****************************************************************************************/ +int CUnMAC::Uninitialize() +{ + if (m_bInitialized) + { + SAFE_DELETE(m_pAPEDecompressCore) + SAFE_DELETE(m_pPrepare) + + // clear the APE info pointer + m_pAPEDecompress = NULL; + + // set the last decoded frame again + m_LastDecodedFrameIndex = -1; + + // set the initialized flag to FALSE + m_bInitialized = FALSE; + } + + return ERROR_SUCCESS; +} + +/***************************************************************************************** +Decompress frame +*****************************************************************************************/ +int CUnMAC::DecompressFrame(unsigned char *pOutputData, int32 FrameIndex, int CPULoadBalancingFactor) +{ + return DecompressFrameOld(pOutputData, FrameIndex, CPULoadBalancingFactor); +} + +/***************************************************************************************** +Seek to the proper frame (if necessary) and do any alignment of the bit array +*****************************************************************************************/ +int CUnMAC::SeekToFrame(int FrameIndex) +{ + if (GET_FRAMES_START_ON_BYTES_BOUNDARIES(m_pAPEDecompress)) + { + if ((m_LastDecodedFrameIndex == -1) || ((FrameIndex - 1) != m_LastDecodedFrameIndex)) + { + int SeekRemainder = (m_pAPEDecompress->GetInfo(APE_INFO_SEEK_BYTE, FrameIndex) - m_pAPEDecompress->GetInfo(APE_INFO_SEEK_BYTE, 0)) % 4; + m_pAPEDecompressCore->GetUnBitArrray()->FillAndResetBitArray(m_pAPEDecompress->GetInfo(APE_INFO_SEEK_BYTE, FrameIndex) - SeekRemainder, SeekRemainder * 8); + } + else + { + m_pAPEDecompressCore->GetUnBitArrray()->AdvanceToByteBoundary(); + } + } + else + { + if ((m_LastDecodedFrameIndex == -1) || ((FrameIndex - 1) != m_LastDecodedFrameIndex)) + { + m_pAPEDecompressCore->GetUnBitArrray()->FillAndResetBitArray(m_pAPEDecompress->GetInfo(APE_INFO_SEEK_BYTE, FrameIndex), m_pAPEDecompress->GetInfo(APE_INFO_SEEK_BIT, FrameIndex)); + } + } + + return ERROR_SUCCESS; +} + +/***************************************************************************************** +Old code for frame decompression +*****************************************************************************************/ +int CUnMAC::DecompressFrameOld(unsigned char *pOutputData, int32 FrameIndex, int CPULoadBalancingFactor) +{ + // error check the parameters (too high of a frame index, etc.) + if (FrameIndex >= m_pAPEDecompress->GetInfo(APE_INFO_TOTAL_FRAMES)) { return ERROR_SUCCESS; } + + // get the number of samples in the frame + int nBlocks = 0; + nBlocks = ((FrameIndex + 1) >= m_pAPEDecompress->GetInfo(APE_INFO_TOTAL_FRAMES)) ? m_pAPEDecompress->GetInfo(APE_INFO_FINAL_FRAME_BLOCKS) : m_pAPEDecompress->GetInfo(APE_INFO_BLOCKS_PER_FRAME); + if (nBlocks == 0) + return -1; // nothing to do (file must be zero length) (have to return error) + + // take care of seeking and frame alignment + if (SeekToFrame(FrameIndex) != 0) { return -1; } + + // get the checksum + unsigned int nSpecialCodes = 0; + uint32 nStoredCRC = 0; + + if (GET_USES_CRC(m_pAPEDecompress) == FALSE) + { + nStoredCRC = m_pAPEDecompressCore->GetUnBitArrray()->DecodeValue(DECODE_VALUE_METHOD_UNSIGNED_RICE, 30); + if (nStoredCRC == 0) + { + nSpecialCodes = SPECIAL_FRAME_LEFT_SILENCE | SPECIAL_FRAME_RIGHT_SILENCE; + } + } + else + { + nStoredCRC = m_pAPEDecompressCore->GetUnBitArrray()->DecodeValue(DECODE_VALUE_METHOD_UNSIGNED_INT); + + // get any 'special' codes if the file uses them (for silence, FALSE stereo, etc.) + nSpecialCodes = 0; + if (GET_USES_SPECIAL_FRAMES(m_pAPEDecompress)) + { + if (nStoredCRC & 0x80000000) + { + nSpecialCodes = m_pAPEDecompressCore->GetUnBitArrray()->DecodeValue(DECODE_VALUE_METHOD_UNSIGNED_INT); + } + nStoredCRC &= 0x7FFFFFFF; + } + } + + // the CRC that will be figured during decompression + uint32 CRC = 0xFFFFFFFF; + + // decompress and convert from (x,y) -> (l,r) + // sort of int and ugly.... sorry + if (m_pAPEDecompress->GetInfo(APE_INFO_CHANNELS) == 2) + { + m_pAPEDecompressCore->GenerateDecodedArrays(nBlocks, nSpecialCodes, FrameIndex, CPULoadBalancingFactor); + + WAVEFORMATEX WaveFormatEx; m_pAPEDecompress->GetInfo(APE_INFO_WAVEFORMATEX, (int) &WaveFormatEx); + m_pPrepare->UnprepareOld(m_pAPEDecompressCore->GetDataX(), m_pAPEDecompressCore->GetDataY(), nBlocks, &WaveFormatEx, + pOutputData, (unsigned int *) &CRC, (int *) &nSpecialCodes, m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + } + else if (m_pAPEDecompress->GetInfo(APE_INFO_CHANNELS) == 1) + { + m_pAPEDecompressCore->GenerateDecodedArrays(nBlocks, nSpecialCodes, FrameIndex, CPULoadBalancingFactor); + + WAVEFORMATEX WaveFormatEx; m_pAPEDecompress->GetInfo(APE_INFO_WAVEFORMATEX, (int) &WaveFormatEx); + m_pPrepare->UnprepareOld(m_pAPEDecompressCore->GetDataX(), NULL, nBlocks, &WaveFormatEx, + pOutputData, (unsigned int *) &CRC, (int *) &nSpecialCodes, m_pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)); + } + + if (GET_USES_SPECIAL_FRAMES(m_pAPEDecompress)) + { + CRC >>= 1; + } + + // check the CRC + if (GET_USES_CRC(m_pAPEDecompress) == FALSE) + { + uint32 nChecksum = CalculateOldChecksum(m_pAPEDecompressCore->GetDataX(), m_pAPEDecompressCore->GetDataY(), m_pAPEDecompress->GetInfo(APE_INFO_CHANNELS), nBlocks); + if (nChecksum != nStoredCRC) + return -1; + } + else + { + if (CRC != nStoredCRC) + return -1; + } + + m_LastDecodedFrameIndex = FrameIndex; + return nBlocks; +} + + +/***************************************************************************************** +Figures the old checksum using the X,Y data +*****************************************************************************************/ +uint32 CUnMAC::CalculateOldChecksum(int *pDataX, int *pDataY, int nChannels, int nBlocks) +{ + uint32 nChecksum = 0; + + if (nChannels == 2) + { + for (int z = 0; z < nBlocks; z++) + { + int R = pDataX[z] - (pDataY[z] / 2); + int L = R + pDataY[z]; + nChecksum += (labs(R) + labs(L)); + } + } + else if (nChannels == 1) + { + for (int z = 0; z < nBlocks; z++) + nChecksum += labs(pDataX[z]); + } + + return nChecksum; +} + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Old/UnMAC.h b/MAC_SDK/Source/MACLib/Old/UnMAC.h new file mode 100644 index 0000000..20263eb --- /dev/null +++ b/MAC_SDK/Source/MACLib/Old/UnMAC.h @@ -0,0 +1,69 @@ +/***************************************************************************************** +UnMAC.h +Copyright (C) 2000-2001 by Matthew T. Ashland All Rights Reserved. + +Methods for decompressing or verifying APE files + +Notes: + -none +*****************************************************************************************/ + +#ifndef APE_UNMAC_H +#define APE_UNMAC_H + +#include "../BitArray.h" +#include "../UnBitArrayBase.h" + +class CAntiPredictor; +class CPrepare; +class CAPEDecompressCore; +class CPredictorBase; +class IPredictorDecompress; +class IAPEDecompress; + +/***************************************************************************************** +CUnMAC class... a class that allows decoding on a frame-by-frame basis +*****************************************************************************************/ +class CUnMAC +{ +public: + + // construction/destruction + CUnMAC(); + ~CUnMAC(); + + // functions + int Initialize(IAPEDecompress *pAPEDecompress); + int Uninitialize(); + int DecompressFrame(unsigned char *pOutputData, int32 FrameIndex, int CPULoadBalancingFactor = 0); + + int SeekToFrame(int FrameIndex); + +private: + + // data members + BOOL m_bInitialized; + int m_LastDecodedFrameIndex; + IAPEDecompress * m_pAPEDecompress; + CPrepare * m_pPrepare; + + CAPEDecompressCore * m_pAPEDecompressCore; + + // functions + void GenerateDecodedArrays(int nBlocks, int nSpecialCodes, int nFrameIndex, int nCPULoadBalancingFactor); + void GenerateDecodedArray(int *Input_Array, uint32 Number_of_Elements, int Frame_Index, CAntiPredictor *pAntiPredictor, int CPULoadBalancingFactor = 0); + + int CreateAntiPredictors(int nCompressionLevel, int nVersion); + + int DecompressFrameOld(unsigned char *pOutputData, int32 FrameIndex, int CPULoadBalancingFactor); + uint32 CalculateOldChecksum(int *pDataX, int *pDataY, int nChannels, int nBlocks); + +public: + + int m_nBlocksProcessed; + unsigned int m_nCRC; + unsigned int m_nStoredCRC; + WAVEFORMATEX m_wfeInput; +}; + +#endif // #ifndef APE_UNMAC_H diff --git a/MAC_SDK/Source/MACLib/Predictor.h b/MAC_SDK/Source/MACLib/Predictor.h new file mode 100644 index 0000000..9f6262e --- /dev/null +++ b/MAC_SDK/Source/MACLib/Predictor.h @@ -0,0 +1,30 @@ +#ifndef APE_PREDICTOR_H +#define APE_PREDICTOR_H + +/************************************************************************************************* +IPredictorCompress - the interface for compressing (predicting) data +*************************************************************************************************/ +class IPredictorCompress +{ +public: + IPredictorCompress(int nCompressionLevel) {} + virtual ~IPredictorCompress() {} + + virtual int CompressValue(int nA, int nB = 0) = 0; + virtual int Flush() = 0; +}; + +/************************************************************************************************* +IPredictorDecompress - the interface for decompressing (un-predicting) data +*************************************************************************************************/ +class IPredictorDecompress +{ +public: + IPredictorDecompress(int nCompressionLevel, int nVersion) {} + virtual ~IPredictorDecompress() {} + + virtual int DecompressValue(int nA, int nB = 0) = 0; + virtual int Flush() = 0; +}; + +#endif // #ifndef APE_PREDICTOR_H diff --git a/MAC_SDK/Source/MACLib/Prepare.cpp b/MAC_SDK/Source/MACLib/Prepare.cpp new file mode 100644 index 0000000..2e5a58c --- /dev/null +++ b/MAC_SDK/Source/MACLib/Prepare.cpp @@ -0,0 +1,510 @@ +#include "All.h" +#include "Prepare.h" + +const uint32 CRC32_TABLE[256] = {0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368, + 4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850, + 2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117}; + +int CPrepare::Prepare(const unsigned char * pRawData, int nBytes, const WAVEFORMATEX * pWaveFormatEx, int * pOutputX, int *pOutputY, unsigned int *pCRC, int *pSpecialCodes, int *pPeakLevel) +{ + // error check the parameters + if (pRawData == NULL || pWaveFormatEx == NULL) + return ERROR_BAD_PARAMETER; + + // initialize the pointers that got passed in + *pCRC = 0xFFFFFFFF; + *pSpecialCodes = 0; + + // variables + uint32 CRC = 0xFFFFFFFF; + const int nTotalBlocks = nBytes / pWaveFormatEx->nBlockAlign; + int R,L; + + // the prepare code + + if (pWaveFormatEx->wBitsPerSample == 8) + { + if (pWaveFormatEx->nChannels == 2) + { + for (int nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + R = (int) (*((unsigned char *) pRawData) - 128); + L = (int) (*((unsigned char *) (pRawData + 1)) - 128); + + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + // check the peak + if (labs(L) > *pPeakLevel) + *pPeakLevel = labs(L); + if (labs(R) > *pPeakLevel) + *pPeakLevel = labs(R); + + // convert to x,y + pOutputY[nBlockIndex] = L - R; + pOutputX[nBlockIndex] = R + (pOutputY[nBlockIndex] / 2); + } + } + else if (pWaveFormatEx->nChannels == 1) + { + for (int nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + R = (int) (*((unsigned char *) pRawData) - 128); + + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + // check the peak + if (labs(R) > *pPeakLevel) + *pPeakLevel = labs(R); + + // convert to x,y + pOutputX[nBlockIndex] = R; + } + } + } + else if (pWaveFormatEx->wBitsPerSample == 24) + { + if (pWaveFormatEx->nChannels == 2) + { + for (int nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + uint32 nTemp = 0; + + nTemp |= (*pRawData << 0); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 8); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 16); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + if (nTemp & 0x800000) + R = (int) (nTemp & 0x7FFFFF) - 0x800000; + else + R = (int) (nTemp & 0x7FFFFF); + + nTemp = 0; + + nTemp |= (*pRawData << 0); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 8); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 16); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + if (nTemp & 0x800000) + L = (int) (nTemp & 0x7FFFFF) - 0x800000; + else + L = (int) (nTemp & 0x7FFFFF); + + // check the peak + if (labs(L) > *pPeakLevel) + *pPeakLevel = labs(L); + if (labs(R) > *pPeakLevel) + *pPeakLevel = labs(R); + + // convert to x,y + pOutputY[nBlockIndex] = L - R; + pOutputX[nBlockIndex] = R + (pOutputY[nBlockIndex] / 2); + + } + } + else if (pWaveFormatEx->nChannels == 1) + { + for (int nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + uint32 nTemp = 0; + + nTemp |= (*pRawData << 0); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 8); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + nTemp |= (*pRawData << 16); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + if (nTemp & 0x800000) + R = (int) (nTemp & 0x7FFFFF) - 0x800000; + else + R = (int) (nTemp & 0x7FFFFF); + + // check the peak + if (labs(R) > *pPeakLevel) + *pPeakLevel = labs(R); + + // convert to x,y + pOutputX[nBlockIndex] = R; + } + } + } + else + { + if (pWaveFormatEx->nChannels == 2) + { + int LPeak = 0; + int RPeak = 0; + int nBlockIndex = 0; + for (nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + + R = (int) *((int16 *) pRawData); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + L = (int) *((int16 *) pRawData); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + // check the peak + if (labs(L) > LPeak) + LPeak = labs(L); + if (labs(R) > RPeak) + RPeak = labs(R); + + // convert to x,y + pOutputY[nBlockIndex] = L - R; + pOutputX[nBlockIndex] = R + (pOutputY[nBlockIndex] / 2); + } + + if (LPeak == 0) { *pSpecialCodes |= SPECIAL_FRAME_LEFT_SILENCE; } + if (RPeak == 0) { *pSpecialCodes |= SPECIAL_FRAME_RIGHT_SILENCE; } + if (max(LPeak, RPeak) > *pPeakLevel) + { + *pPeakLevel = max(LPeak, RPeak); + } + + // check for pseudo-stereo files + nBlockIndex = 0; + while (pOutputY[nBlockIndex++] == 0) + { + if (nBlockIndex == (nBytes / 4)) + { + *pSpecialCodes |= SPECIAL_FRAME_PSEUDO_STEREO; + break; + } + } + + } + else if (pWaveFormatEx->nChannels == 1) + { + int nPeak = 0; + for (int nBlockIndex = 0; nBlockIndex < nTotalBlocks; nBlockIndex++) + { + R = (int) *((int16 *) pRawData); + + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *pRawData++]; + + // check the peak + if (labs(R) > nPeak) + nPeak = labs(R); + + //convert to x,y + pOutputX[nBlockIndex] = R; + } + + if (nPeak > *pPeakLevel) + *pPeakLevel = nPeak; + if (nPeak == 0) { *pSpecialCodes |= SPECIAL_FRAME_MONO_SILENCE; } + } + } + + CRC = CRC ^ 0xFFFFFFFF; + + // add the special code + CRC >>= 1; + + if (*pSpecialCodes != 0) + { + CRC |= (1 << 31); + } + + *pCRC = CRC; + + return ERROR_SUCCESS; +} + +void CPrepare::Unprepare(int X, int Y, const WAVEFORMATEX * pWaveFormatEx, unsigned char * pOutput, unsigned int * pCRC) +{ + #define CALCULATE_CRC_BYTE *pCRC = (*pCRC >> 8) ^ CRC32_TABLE[(*pCRC & 0xFF) ^ *pOutput++]; + // decompress and convert from (x,y) -> (l,r) + // sort of long and ugly.... sorry + + if (pWaveFormatEx->nChannels == 2) + { + if (pWaveFormatEx->wBitsPerSample == 16) + { + // get the right and left values + int nR = X - (Y / 2); + int nL = nR + Y; + + // error check (for overflows) + if ((nR < -32768) || (nR > 32767) || (nL < -32768) || (nL > 32767)) + { + throw(-1); + } + + *(int16 *) pOutput = (int16) nR; + CALCULATE_CRC_BYTE + CALCULATE_CRC_BYTE + + *(int16 *) pOutput = (int16) nL; + CALCULATE_CRC_BYTE + CALCULATE_CRC_BYTE + } + else if (pWaveFormatEx->wBitsPerSample == 8) + { + unsigned char R = (X - (Y / 2) + 128); + *pOutput = R; + CALCULATE_CRC_BYTE + *pOutput = (unsigned char) (R + Y); + CALCULATE_CRC_BYTE + } + else if (pWaveFormatEx->wBitsPerSample == 24) + { + int32 RV, LV; + + RV = X - (Y / 2); + LV = RV + Y; + + uint32 nTemp = 0; + if (RV < 0) + nTemp = ((uint32) (RV + 0x800000)) | 0x800000; + else + nTemp = (uint32) RV; + + *pOutput = (unsigned char) ((nTemp >> 0) & 0xFF); + CALCULATE_CRC_BYTE + *pOutput = (unsigned char) ((nTemp >> 8) & 0xFF); + CALCULATE_CRC_BYTE + *pOutput = (unsigned char) ((nTemp >> 16) & 0xFF); + CALCULATE_CRC_BYTE + + nTemp = 0; + if (LV < 0) + nTemp = ((uint32) (LV + 0x800000)) | 0x800000; + else + nTemp = (uint32) LV; + + *pOutput = (unsigned char) ((nTemp >> 0) & 0xFF); + CALCULATE_CRC_BYTE + + *pOutput = (unsigned char) ((nTemp >> 8) & 0xFF); + CALCULATE_CRC_BYTE + + *pOutput = (unsigned char) ((nTemp >> 16) & 0xFF); + CALCULATE_CRC_BYTE + } + } + else if (pWaveFormatEx->nChannels == 1) + { + if (pWaveFormatEx->wBitsPerSample == 16) + { + int16 R = X; + + *(int16 *) pOutput = (int16) R; + CALCULATE_CRC_BYTE + CALCULATE_CRC_BYTE + } + else if (pWaveFormatEx->wBitsPerSample == 8) + { + unsigned char R = X + 128; + *pOutput = R; + CALCULATE_CRC_BYTE + } + else if (pWaveFormatEx->wBitsPerSample == 24) + { + int32 RV = X; + + uint32 nTemp = 0; + if (RV < 0) + nTemp = ((uint32) (RV + 0x800000)) | 0x800000; + else + nTemp = (uint32) RV; + + *pOutput = (unsigned char) ((nTemp >> 0) & 0xFF); + CALCULATE_CRC_BYTE + *pOutput = (unsigned char) ((nTemp >> 8) & 0xFF); + CALCULATE_CRC_BYTE + *pOutput = (unsigned char) ((nTemp >> 16) & 0xFF); + CALCULATE_CRC_BYTE + } + } +} + +#ifdef BACKWARDS_COMPATIBILITY + +int CPrepare::UnprepareOld(int *pInputX, int *pInputY, int nBlocks, const WAVEFORMATEX *pWaveFormatEx, unsigned char *pRawData, unsigned int *pCRC, int *pSpecialCodes, int nFileVersion) +{ + // the CRC that will be figured during decompression + uint32 CRC = 0xFFFFFFFF; + + // decompress and convert from (x,y) -> (l,r) + // sort of int and ugly.... sorry + if (pWaveFormatEx->nChannels == 2) + { + // convert the x,y data to raw data + if (pWaveFormatEx->wBitsPerSample == 16) + { + int16 R; + unsigned char *Buffer = &pRawData[0]; + int *pX = pInputX; + int *pY = pInputY; + + for (; pX < &pInputX[nBlocks]; pX++, pY++) + { + R = *pX - (*pY / 2); + + *(int16 *) Buffer = (int16) R; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *(int16 *) Buffer = (int16) R + *pY; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + } + } + else if (pWaveFormatEx->wBitsPerSample == 8) + { + unsigned char *R = (unsigned char *) &pRawData[0]; + unsigned char *L = (unsigned char *) &pRawData[1]; + + if (nFileVersion > 3830) + { + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++, L+=2, R+=2) + { + *R = (unsigned char) (pInputX[SampleIndex] - (pInputY[SampleIndex] / 2) + 128); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *R]; + *L = (unsigned char) (*R + pInputY[SampleIndex]); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *L]; + } + } + else + { + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++, L+=2, R+=2) + { + *R = (unsigned char) (pInputX[SampleIndex] - (pInputY[SampleIndex] / 2)); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *R]; + *L = (unsigned char) (*R + pInputY[SampleIndex]); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *L]; + + } + } + } + else if (pWaveFormatEx->wBitsPerSample == 24) + { + unsigned char *Buffer = (unsigned char *) &pRawData[0]; + int32 RV, LV; + + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++) + { + RV = pInputX[SampleIndex] - (pInputY[SampleIndex] / 2); + LV = RV + pInputY[SampleIndex]; + + uint32 nTemp = 0; + if (RV < 0) + nTemp = ((uint32) (RV + 0x800000)) | 0x800000; + else + nTemp = (uint32) RV; + + *Buffer = (unsigned char) ((nTemp >> 0) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 8) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 16) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + nTemp = 0; + if (LV < 0) + nTemp = ((uint32) (LV + 0x800000)) | 0x800000; + else + nTemp = (uint32) LV; + + *Buffer = (unsigned char) ((nTemp >> 0) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 8) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 16) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + } + } + } + else if (pWaveFormatEx->nChannels == 1) + { + // convert to raw data + if (pWaveFormatEx->wBitsPerSample == 8) + { + unsigned char *R = (unsigned char *) &pRawData[0]; + + if (nFileVersion > 3830) + { + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++, R++) + { + *R = pInputX[SampleIndex] + 128; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *R]; + } + } + else + { + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++, R++) + { + *R = (unsigned char) (pInputX[SampleIndex]); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *R]; + } + } + + } + else if (pWaveFormatEx->wBitsPerSample == 24) + { + + unsigned char *Buffer = (unsigned char *) &pRawData[0]; + int32 RV; + for (int SampleIndex = 0; SampleIndex> 0) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 8) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + + *Buffer = (unsigned char) ((nTemp >> 16) & 0xFF); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + } + } + else + { + unsigned char *Buffer = &pRawData[0]; + + for (int SampleIndex = 0; SampleIndex < nBlocks; SampleIndex++) + { + *(int16 *) Buffer = (int16) (pInputX[SampleIndex]); + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + CRC = (CRC >> 8) ^ CRC32_TABLE[(CRC & 0xFF) ^ *Buffer++]; + } + } + } + + CRC = CRC ^ 0xFFFFFFFF; + + *pCRC = CRC; + + return 0; +} + +#endif // #ifdef BACKWARDS_COMPATIBILITY diff --git a/MAC_SDK/Source/MACLib/Prepare.h b/MAC_SDK/Source/MACLib/Prepare.h new file mode 100644 index 0000000..eb5a844 --- /dev/null +++ b/MAC_SDK/Source/MACLib/Prepare.h @@ -0,0 +1,38 @@ +#ifndef APE_PREPARE_H +#define APE_PREPARE_H + +#define SPECIAL_FRAME_MONO_SILENCE 1 +#define SPECIAL_FRAME_LEFT_SILENCE 1 +#define SPECIAL_FRAME_RIGHT_SILENCE 2 +#define SPECIAL_FRAME_PSEUDO_STEREO 4 + +/***************************************************************************** +Manage the preparation stage of compression and decompression + +Tasks: + +1) convert data to 32-bit +2) convert L,R to X,Y +3) calculate the CRC +4) do simple analysis +5) check for the peak value +*****************************************************************************/ + +class IPredictorDecompress; + +class CPrepare +{ +public: + + int Prepare(const unsigned char * pRawData, int nBytes, const WAVEFORMATEX * pWaveFormatEx, int * pOutputX, int * pOutputY, unsigned int * pCRC, int * pSpecialCodes, int * pPeakLevel); + void Unprepare(int X, int Y, const WAVEFORMATEX * pWaveFormatEx, unsigned char * pOutput, unsigned int * pCRC); + + +#ifdef BACKWARDS_COMPATIBILITY + int UnprepareOld(int * pInputX, int *pInputY, int nBlocks, const WAVEFORMATEX * pWaveFormatEx, unsigned char * pRawData, unsigned int * pCRC, int * pSpecialCodes, int nFileVersion); +#endif + +}; + + +#endif // #ifndef APE_PREPARE_H diff --git a/MAC_SDK/Source/MACLib/ScaledFirstOrderFilter.h b/MAC_SDK/Source/MACLib/ScaledFirstOrderFilter.h new file mode 100644 index 0000000..f4222dd --- /dev/null +++ b/MAC_SDK/Source/MACLib/ScaledFirstOrderFilter.h @@ -0,0 +1,31 @@ +#ifndef APE_SCALEDFIRSTORDERFILTER_H +#define APE_SCALEDFIRSTORDERFILTER_H + +template class CScaledFirstOrderFilter +{ +public: + + __inline void Flush() + { + m_nLastValue = 0; + } + + __inline int Compress(const int nInput) + { + int nRetVal = nInput - ((m_nLastValue * MULTIPLY) >> SHIFT); + m_nLastValue = nInput; + return nRetVal; + } + + __inline int Decompress(const int nInput) + { + m_nLastValue = nInput + ((m_nLastValue * MULTIPLY) >> SHIFT); + return m_nLastValue; + } + +protected: + + int m_nLastValue; +}; + +#endif // #ifndef APE_SCALEDFIRSTORDERFILTER_H diff --git a/MAC_SDK/Source/MACLib/StartFilter.h b/MAC_SDK/Source/MACLib/StartFilter.h new file mode 100644 index 0000000..821c659 --- /dev/null +++ b/MAC_SDK/Source/MACLib/StartFilter.h @@ -0,0 +1,178 @@ +#ifndef APE_START_FILTER_H +#define APE_START_FILTER_H + +class CStartFilter +{ +public: + + CStartFilter() + { + + } + + ~CStartFilter() + { + + + } + + void Flush() + { + m_rbInputA.Flush(); + m_rbInputB.Flush(); + + memset(m_aryMA, 0, sizeof(m_aryMA)); + memset(m_aryMB, 0, sizeof(m_aryMB)); + + m_Stage1FilterA1.Flush(); + m_Stage1FilterA2.Flush(); + m_Stage1FilterA3.Flush(); + + m_Stage1FilterB1.Flush(); + m_Stage1FilterB2.Flush(); + m_Stage1FilterB3.Flush(); + } + + void Compress(int & nA, int & nB) + { +/* + nA = m_Stage1FilterA1.Compress(nA); + nA = m_Stage1FilterA2.Compress(nA); + nA = m_Stage1FilterA3.Compress(nA); + + nB = m_Stage1FilterB1.Compress(nB); + nB = m_Stage1FilterB2.Compress(nB); + nB = m_Stage1FilterB3.Compress(nB); + return; +//*/ + + nA = m_Stage1FilterA1.Compress(nA); + nA = m_Stage1FilterA2.Compress(nA); +// nA = m_Stage1FilterA3.Compress(nA); + + nB = m_Stage1FilterB1.Compress(nB); + nB = m_Stage1FilterB2.Compress(nB); + + //int nTemp = nA; nA = nB; nB = nTemp; +// nB = m_Stage1FilterB3.Compress(nB); + +// nA = nA - nB; +// nB = nB + (nA / 2); + + +// return; + + m_rbInputA[0] = nA; m_rbInputB[0] = nB; + + { + int nPrediction1 = m_rbInputA[-1]; + int nPrediction2 = m_rbInputA[-2]; + int nPrediction3 = m_rbInputA[-1] - m_rbInputA[-2]; + int nPrediction4 = m_rbInputB[-1]; + + int nTotalPrediction = (nPrediction1 * m_aryMA[0]) + (nPrediction2 * m_aryMA[1]) + + (nPrediction3 * m_aryMA[2]) + (nPrediction4 * m_aryMA[3]); + int nOutput = nA - (nTotalPrediction >> 13); + + if (nOutput > 0) + { + m_aryMA[0] -= 2*((nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0); + m_aryMA[1] -= (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryMA[2] -= (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryMA[3] -= 1*((nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0); + } + else if (nOutput < 0) + { + m_aryMA[0] += 2*((nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0); + m_aryMA[1] += (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryMA[2] += (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryMA[3] += 1*((nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0); + } + + nA = nOutput; + } + { + int nPrediction1 = m_rbInputB[-1]; + int nPrediction2 = m_rbInputB[-2]; + int nPrediction3 = 0;//m_rbInputB[-1] - m_rbInputB[-2]; + int nPrediction4 = m_rbInputA[0]; + + int nTotalPrediction = (nPrediction1 * m_aryMB[0]) + (nPrediction2 * m_aryMB[1]) + + (nPrediction3 * m_aryMB[2]) + (nPrediction4 * m_aryMB[3]); + int nOutput = nB - (nTotalPrediction >> 13); + + if (nOutput > 0) + { + m_aryMB[0] -= 2*((nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0); + m_aryMB[1] -= (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryMB[2] -= (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryMB[3] -= 1*((nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0); + } + else if (nOutput < 0) + { + m_aryMB[0] += 2*((nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0); + m_aryMB[1] += (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryMB[2] += (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryMB[3] += 1*((nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0); + } + + nB = nOutput; + } + + + m_rbInputA.IncrementSafe(); + m_rbInputB.IncrementSafe(); + + +/* +// nInput = m_Filter1.Compress(nInput); + + m_rbInput[0] = nInput; + + int nPrediction1 = m_rbInput[-1]; + int nPrediction2 = (2 * m_rbInput[-1]) - m_rbInput[-2]; + int nPrediction3 = m_rbInput[-1] - m_rbInput[-2]; + int nPrediction4 = m_nLastOutput; + + int nTotalPrediction = ((nPrediction1) * m_aryM[0]) + (nPrediction2 * m_aryM[1]) + + ((nPrediction3 >> 1) * m_aryM[2]) + (nPrediction4 * m_aryM[3]); + int nOutput = nInput - (nTotalPrediction >> 13); + + if (nOutput > 0) + { + m_aryM[0] -= (nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0; + m_aryM[1] -= (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryM[2] -= (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryM[3] -= (nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0; + } + else if (nOutput < 0) + { + m_aryM[0] += (nPrediction1) ? ((nPrediction1 >> 30) & 2) - 1 : 0; + m_aryM[1] += (nPrediction2) ? ((nPrediction2 >> 30) & 2) - 1 : 0; + m_aryM[2] += (nPrediction3) ? ((nPrediction3 >> 30) & 2) - 1 : 0; + m_aryM[3] += (nPrediction4) ? ((nPrediction4 >> 30) & 2) - 1 : 0; + } + + m_nLastOutput = nOutput; + m_rbInput.IncrementSafe(); + + return nOutput; + //*/ + } + +protected: + + CScaledFirstOrderFilter<31, 5> m_Stage1FilterA1; + CScaledFirstOrderFilter<24, 5> m_Stage1FilterA2; + CScaledFirstOrderFilter<7, 5> m_Stage1FilterA3; + + CScaledFirstOrderFilter<31, 5> m_Stage1FilterB1; + CScaledFirstOrderFilter<24, 5> m_Stage1FilterB2; + CScaledFirstOrderFilter<7, 5> m_Stage1FilterB3; + + CRollBufferFast m_rbInputA; + CRollBufferFast m_rbInputB; + int m_aryMA[8]; int m_aryMB[8]; +}; + +#endif // #ifndef APE_START_FILTER_H diff --git a/MAC_SDK/Source/MACLib/UnBitArray.cpp b/MAC_SDK/Source/MACLib/UnBitArray.cpp new file mode 100644 index 0000000..fca206e --- /dev/null +++ b/MAC_SDK/Source/MACLib/UnBitArray.cpp @@ -0,0 +1,293 @@ +#include "All.h" +#include "APEInfo.h" +#include "UnBitArray.h" +#include "BitArray.h" + +const uint32 POWERS_OF_TWO_MINUS_ONE_REVERSED[33] = {4294967295,2147483647,1073741823,536870911,268435455,134217727,67108863,33554431,16777215,8388607,4194303,2097151,1048575,524287,262143,131071,65535,32767,16383,8191,4095,2047,1023,511,255,127,63,31,15,7,3,1,0}; + +const uint32 K_SUM_MIN_BOUNDARY[32] = {0,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,0,0,0,0}; + +const uint32 RANGE_TOTAL_1[65] = {0,14824,28224,39348,47855,53994,58171,60926,62682,63786,64463,64878,65126,65276,65365,65419,65450,65469,65480,65487,65491,65493,65494,65495,65496,65497,65498,65499,65500,65501,65502,65503,65504,65505,65506,65507,65508,65509,65510,65511,65512,65513,65514,65515,65516,65517,65518,65519,65520,65521,65522,65523,65524,65525,65526,65527,65528,65529,65530,65531,65532,65533,65534,65535,65536}; +const uint32 RANGE_WIDTH_1[64] = {14824,13400,11124,8507,6139,4177,2755,1756,1104,677,415,248,150,89,54,31,19,11,7,4,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; + +const uint32 RANGE_TOTAL_2[65] = {0,19578,36160,48417,56323,60899,63265,64435,64971,65232,65351,65416,65447,65466,65476,65482,65485,65488,65490,65491,65492,65493,65494,65495,65496,65497,65498,65499,65500,65501,65502,65503,65504,65505,65506,65507,65508,65509,65510,65511,65512,65513,65514,65515,65516,65517,65518,65519,65520,65521,65522,65523,65524,65525,65526,65527,65528,65529,65530,65531,65532,65533,65534,65535,65536}; +const uint32 RANGE_WIDTH_2[64] = {19578,16582,12257,7906,4576,2366,1170,536,261,119,65,31,19,10,6,3,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; + +#define RANGE_OVERFLOW_TOTAL_WIDTH 65536 +#define RANGE_OVERFLOW_SHIFT 16 + +#define CODE_BITS 32 +#define TOP_VALUE ((unsigned int ) 1 << (CODE_BITS - 1)) +#define SHIFT_BITS (CODE_BITS - 9) +#define EXTRA_BITS ((CODE_BITS - 2) % 8 + 1) +#define BOTTOM_VALUE (TOP_VALUE >> 8) + +#define MODEL_ELEMENTS 64 + +/*********************************************************************************** +Construction +***********************************************************************************/ +CUnBitArray::CUnBitArray(CIO * pIO, int nVersion) +{ + CreateHelper(pIO, 16384, nVersion); + m_nFlushCounter = 0; + m_nFinalizeCounter = 0; +} + +CUnBitArray::~CUnBitArray() +{ + SAFE_ARRAY_DELETE(m_pBitArray) +} + +unsigned int CUnBitArray::DecodeValue(DECODE_VALUE_METHOD DecodeMethod, int nParam1, int nParam2) +{ + switch (DecodeMethod) + { + case DECODE_VALUE_METHOD_UNSIGNED_INT: + return DecodeValueXBits(32); + } + + return 0; +} + +void CUnBitArray::GenerateArray(int * pOutputArray, int nElements, int nBytesRequired) +{ + GenerateArrayRange(pOutputArray, nElements); +} + +__inline unsigned char CUnBitArray::GetC() +{ + unsigned char nValue = (unsigned char) (m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))); + m_nCurrentBitIndex += 8; + return nValue; +} + +__inline int CUnBitArray::RangeDecodeFast(int nShift) +{ + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.buffer << 8) | ((m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))) & 0xFF); + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) | ((m_RangeCoderInfo.buffer >> 1) & 0xFF); + m_RangeCoderInfo.range <<= 8; + } + + // decode + m_RangeCoderInfo.range = m_RangeCoderInfo.range >> nShift; + return m_RangeCoderInfo.low / m_RangeCoderInfo.range; +} + +__inline int CUnBitArray::RangeDecodeFastWithUpdate(int nShift) +{ + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.buffer << 8) | ((m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))) & 0xFF); + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) | ((m_RangeCoderInfo.buffer >> 1) & 0xFF); + m_RangeCoderInfo.range <<= 8; + } + + // decode + m_RangeCoderInfo.range = m_RangeCoderInfo.range >> nShift; + int nRetVal = m_RangeCoderInfo.low / m_RangeCoderInfo.range; + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * nRetVal; + return nRetVal; +} + +int CUnBitArray::DecodeValueRange(UNBIT_ARRAY_STATE & BitArrayState) +{ + // make sure there is room for the data + // this is a little slower than ensuring a huge block to start with, but it's safer + if (m_nCurrentBitIndex > m_nRefillBitThreshold) + { + FillBitArray(); + } + + int nValue = 0; + + if (m_nVersion >= 3990) + { + // figure the pivot value + int nPivotValue = max(BitArrayState.nKSum / 32, 1); + + // get the overflow + int nOverflow = 0; + { + // decode + int nRangeTotal = RangeDecodeFast(RANGE_OVERFLOW_SHIFT); + + // lookup the symbol (must be a faster way than this) + while (nRangeTotal >= RANGE_TOTAL_2[nOverflow + 1]) { nOverflow++; } + + // update + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * RANGE_TOTAL_2[nOverflow]; + m_RangeCoderInfo.range = m_RangeCoderInfo.range * RANGE_WIDTH_2[nOverflow]; + + // get the working k + if (nOverflow == (MODEL_ELEMENTS - 1)) + { + nOverflow = RangeDecodeFastWithUpdate(16); + nOverflow <<= 16; + nOverflow |= RangeDecodeFastWithUpdate(16); + } + } + + // get the value + int nBase = 0; + { + int nShift = 0; + if (nPivotValue >= (1 << 16)) + { + int nPivotValueBits = 0; + while ((nPivotValue >> nPivotValueBits) > 0) { nPivotValueBits++; } + int nSplitFactor = 1 << (nPivotValueBits - 16); + + int nPivotValueA = (nPivotValue / nSplitFactor) + 1; + int nPivotValueB = nSplitFactor; + + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.buffer << 8) | ((m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))) & 0xFF); + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) | ((m_RangeCoderInfo.buffer >> 1) & 0xFF); + m_RangeCoderInfo.range <<= 8; + } + m_RangeCoderInfo.range = m_RangeCoderInfo.range / nPivotValueA; + int nBaseA = m_RangeCoderInfo.low / m_RangeCoderInfo.range; + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * nBaseA; + + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.buffer << 8) | ((m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))) & 0xFF); + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) | ((m_RangeCoderInfo.buffer >> 1) & 0xFF); + m_RangeCoderInfo.range <<= 8; + } + m_RangeCoderInfo.range = m_RangeCoderInfo.range / nPivotValueB; + int nBaseB = m_RangeCoderInfo.low / m_RangeCoderInfo.range; + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * nBaseB; + + nBase = nBaseA * nSplitFactor + nBaseB; + } + else + { + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_RangeCoderInfo.buffer = (m_RangeCoderInfo.buffer << 8) | ((m_pBitArray[m_nCurrentBitIndex >> 5] >> (24 - (m_nCurrentBitIndex & 31))) & 0xFF); + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.low = (m_RangeCoderInfo.low << 8) | ((m_RangeCoderInfo.buffer >> 1) & 0xFF); + m_RangeCoderInfo.range <<= 8; + } + + // decode + m_RangeCoderInfo.range = m_RangeCoderInfo.range / nPivotValue; + int nBaseLower = m_RangeCoderInfo.low / m_RangeCoderInfo.range; + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * nBaseLower; + + nBase = nBaseLower; + } + } + + // build the value + nValue = nBase + (nOverflow * nPivotValue); + } + else + { + // decode + int nRangeTotal = RangeDecodeFast(RANGE_OVERFLOW_SHIFT); + + // lookup the symbol (must be a faster way than this) + int nOverflow = 0; + while (nRangeTotal >= RANGE_TOTAL_1[nOverflow + 1]) { nOverflow++; } + + // update + m_RangeCoderInfo.low -= m_RangeCoderInfo.range * RANGE_TOTAL_1[nOverflow]; + m_RangeCoderInfo.range = m_RangeCoderInfo.range * RANGE_WIDTH_1[nOverflow]; + + // get the working k + int nTempK; + if (nOverflow == (MODEL_ELEMENTS - 1)) + { + nTempK = RangeDecodeFastWithUpdate(5); + nOverflow = 0; + } + else + { + nTempK = (BitArrayState.k < 1) ? 0 : BitArrayState.k - 1; + } + + // figure the extra bits on the left and the left value + if (nTempK <= 16 || m_nVersion < 3910) + { + nValue = RangeDecodeFastWithUpdate(nTempK); + } + else + { + int nX1 = RangeDecodeFastWithUpdate(16); + int nX2 = RangeDecodeFastWithUpdate(nTempK - 16); + nValue = nX1 | (nX2 << 16); + } + + // build the value and output it + nValue += (nOverflow << nTempK); + } + + // update nKSum + BitArrayState.nKSum += ((nValue + 1) / 2) - ((BitArrayState.nKSum + 16) >> 5); + + // update k + if (BitArrayState.nKSum < K_SUM_MIN_BOUNDARY[BitArrayState.k]) + BitArrayState.k--; + else if (BitArrayState.nKSum >= K_SUM_MIN_BOUNDARY[BitArrayState.k + 1]) + BitArrayState.k++; + + // output the value (converted to signed) + return (nValue & 1) ? (nValue >> 1) + 1 : -(nValue >> 1); +} + +void CUnBitArray::FlushState(UNBIT_ARRAY_STATE & BitArrayState) +{ + BitArrayState.k = 10; + BitArrayState.nKSum = (1 << BitArrayState.k) * 16; +} + +void CUnBitArray::FlushBitArray() +{ + AdvanceToByteBoundary(); + m_nCurrentBitIndex += 8; // ignore the first byte... (slows compression too much to not output this dummy byte) + m_RangeCoderInfo.buffer = GetC(); + m_RangeCoderInfo.low = m_RangeCoderInfo.buffer >> (8 - EXTRA_BITS); + m_RangeCoderInfo.range = (unsigned int) 1 << EXTRA_BITS; + + m_nRefillBitThreshold = (m_nBits - 512); +} + +void CUnBitArray::Finalize() +{ + // normalize + while (m_RangeCoderInfo.range <= BOTTOM_VALUE) + { + m_nCurrentBitIndex += 8; + m_RangeCoderInfo.range <<= 8; + } + + // used to back-pedal the last two bytes out + // this should never have been a problem because we've outputted and normalized beforehand + // but stopped doing it as of 3.96 in case it accounted for rare decompression failures + if (m_nVersion <= 3950) + m_nCurrentBitIndex -= 16; +} + +void CUnBitArray::GenerateArrayRange(int * pOutputArray, int nElements) +{ + UNBIT_ARRAY_STATE BitArrayState; + FlushState(BitArrayState); + FlushBitArray(); + + for (int z = 0; z < nElements; z++) + { + pOutputArray[z] = DecodeValueRange(BitArrayState); + } + + Finalize(); +} diff --git a/MAC_SDK/Source/MACLib/UnBitArray.h b/MAC_SDK/Source/MACLib/UnBitArray.h new file mode 100644 index 0000000..28f2e7d --- /dev/null +++ b/MAC_SDK/Source/MACLib/UnBitArray.h @@ -0,0 +1,51 @@ +#ifndef APE_UNBITARRAY_H +#define APE_UNBITARRAY_H + +#include "UnBitArrayBase.h" + +class IAPEDecompress; + +struct RANGE_CODER_STRUCT_DECOMPRESS +{ + unsigned int low; // low end of interval + unsigned int range; // length of interval + unsigned int buffer; // buffer for input/output +}; + +class CUnBitArray : public CUnBitArrayBase +{ +public: + + // construction/destruction + CUnBitArray(CIO * pIO, int nVersion); + ~CUnBitArray(); + + unsigned int DecodeValue(DECODE_VALUE_METHOD DecodeMethod, int nParam1 = 0, int nParam2 = 0); + + void GenerateArray(int * pOutputArray, int nElements, int nBytesRequired = -1); + + int DecodeValueRange(UNBIT_ARRAY_STATE & BitArrayState); + + void FlushState(UNBIT_ARRAY_STATE & BitArrayState); + void FlushBitArray(); + void Finalize(); + +private: + + void GenerateArrayRange(int * pOutputArray, int nElements); + + // data + int m_nFlushCounter; + int m_nFinalizeCounter; + + RANGE_CODER_STRUCT_DECOMPRESS m_RangeCoderInfo; + + uint32 m_nRefillBitThreshold; + + // functions + inline int RangeDecodeFast(int nShift); + inline int RangeDecodeFastWithUpdate(int nShift); + inline unsigned char GetC(); +}; + +#endif // #ifndef APE_UNBITARRAY_H diff --git a/MAC_SDK/Source/MACLib/UnBitArrayBase.cpp b/MAC_SDK/Source/MACLib/UnBitArrayBase.cpp new file mode 100644 index 0000000..e819290 --- /dev/null +++ b/MAC_SDK/Source/MACLib/UnBitArrayBase.cpp @@ -0,0 +1,112 @@ +#include "All.h" +#include "UnBitArrayBase.h" +#include "APEInfo.h" +#include "UnBitArray.h" +#ifdef BACKWARDS_COMPATIBILITY + #include "Old/APEDecompressOld.h" + #include "Old/UnBitArrayOld.h" +#endif + +const uint32 POWERS_OF_TWO_MINUS_ONE[33] = {0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215,33554431,67108863,134217727,268435455,536870911,1073741823,2147483647,4294967295}; + +CUnBitArrayBase * CreateUnBitArray(IAPEDecompress * pAPEDecompress, int nVersion) +{ +#ifdef BACKWARDS_COMPATIBILITY + if (nVersion >= 3900) + return (CUnBitArrayBase * ) new CUnBitArray(GET_IO(pAPEDecompress), nVersion); + else + return (CUnBitArrayBase * ) new CUnBitArrayOld(pAPEDecompress, nVersion); +#else + return (CUnBitArrayBase * ) new CUnBitArray(GET_IO(pAPEDecompress), nVersion); +#endif +} + +void CUnBitArrayBase::AdvanceToByteBoundary() +{ + int nMod = m_nCurrentBitIndex % 8; + if (nMod != 0) { m_nCurrentBitIndex += 8 - nMod; } +} + +uint32 CUnBitArrayBase::DecodeValueXBits(uint32 nBits) +{ + // get more data if necessary + if ((m_nCurrentBitIndex + nBits) >= m_nBits) + FillBitArray(); + + // variable declares + uint32 nLeftBits = 32 - (m_nCurrentBitIndex & 31); + uint32 nBitArrayIndex = m_nCurrentBitIndex >> 5; + m_nCurrentBitIndex += nBits; + + // if their isn't an overflow to the right value, get the value and exit + if (nLeftBits >= nBits) + return (m_pBitArray[nBitArrayIndex] & (POWERS_OF_TWO_MINUS_ONE[nLeftBits])) >> (nLeftBits - nBits); + + // must get the "split" value from left and right + int nRightBits = nBits - nLeftBits; + + uint32 nLeftValue = ((m_pBitArray[nBitArrayIndex] & POWERS_OF_TWO_MINUS_ONE[nLeftBits]) << nRightBits); + uint32 nRightValue = (m_pBitArray[nBitArrayIndex + 1] >> (32 - nRightBits)); + return (nLeftValue | nRightValue); +} + +int CUnBitArrayBase::FillAndResetBitArray(int nFileLocation, int nNewBitIndex) +{ + // reset the bit index + m_nCurrentBitIndex = nNewBitIndex; + + // seek if necessary + if (nFileLocation != -1) + { + if (m_pIO->Seek(nFileLocation, FILE_BEGIN) != 0) + return ERROR_IO_READ; + } + + // read the new data into the bit array + unsigned int nBytesRead = 0; + if (m_pIO->Read(((unsigned char *) m_pBitArray), m_nBytes, &nBytesRead) != 0) + return ERROR_IO_READ; + + return 0; +} + +int CUnBitArrayBase::FillBitArray() +{ + // get the bit array index + uint32 nBitArrayIndex = m_nCurrentBitIndex >> 5; + + // move the remaining data to the front + memmove((void *) (m_pBitArray), (const void *) (m_pBitArray + nBitArrayIndex), m_nBytes - (nBitArrayIndex * 4)); + + // read the new data + int nBytesToRead = nBitArrayIndex * 4; + unsigned int nBytesRead = 0; + int nRetVal = m_pIO->Read((unsigned char *) (m_pBitArray + m_nElements - nBitArrayIndex), nBytesToRead, &nBytesRead); + + // adjust the m_Bit pointer + m_nCurrentBitIndex = m_nCurrentBitIndex & 31; + + // return + return (nRetVal == 0) ? 0 : ERROR_IO_READ; +} + +int CUnBitArrayBase::CreateHelper(CIO * pIO, int nBytes, int nVersion) +{ + // check the parameters + if ((pIO == NULL) || (nBytes <= 0)) { return ERROR_BAD_PARAMETER; } + + // save the size + m_nElements = nBytes / 4; + m_nBytes = m_nElements * 4; + m_nBits = m_nBytes * 8; + + // set the variables + m_pIO = pIO; + m_nVersion = nVersion; + m_nCurrentBitIndex = 0; + + // create the bitarray + m_pBitArray = new uint32 [m_nElements]; + + return (m_pBitArray != NULL) ? 0 : ERROR_INSUFFICIENT_MEMORY; +} diff --git a/MAC_SDK/Source/MACLib/UnBitArrayBase.h b/MAC_SDK/Source/MACLib/UnBitArrayBase.h new file mode 100644 index 0000000..eb81e15 --- /dev/null +++ b/MAC_SDK/Source/MACLib/UnBitArrayBase.h @@ -0,0 +1,59 @@ +#ifndef APE_UNBITARRAYBASE_H +#define APE_UNBITARRAYBASE_H + +class IAPEDecompress; +class CIO; + +struct UNBIT_ARRAY_STATE +{ + uint32 k; + uint32 nKSum; +}; + +enum DECODE_VALUE_METHOD +{ + DECODE_VALUE_METHOD_UNSIGNED_INT, + DECODE_VALUE_METHOD_UNSIGNED_RICE, + DECODE_VALUE_METHOD_X_BITS +}; + +class CUnBitArrayBase +{ +public: + + // virtual destructor + virtual ~CUnBitArrayBase() {} + + // functions + virtual int FillBitArray(); + virtual int FillAndResetBitArray(int nFileLocation = -1, int nNewBitIndex = 0); + + virtual void GenerateArray(int * pOutputArray, int nElements, int nBytesRequired = -1) {} + virtual unsigned int DecodeValue(DECODE_VALUE_METHOD DecodeMethod, int nParam1 = 0, int nParam2 = 0) { return 0; } + + virtual void AdvanceToByteBoundary(); + + virtual int DecodeValueRange(UNBIT_ARRAY_STATE & BitArrayState) { return 0; } + virtual void FlushState(UNBIT_ARRAY_STATE & BitArrayState) {} + virtual void FlushBitArray() {} + virtual void Finalize() {} + +protected: + + virtual int CreateHelper(CIO * pIO, int nBytes, int nVersion); + virtual uint32 DecodeValueXBits(uint32 nBits); + + uint32 m_nElements; + uint32 m_nBytes; + uint32 m_nBits; + + int m_nVersion; + CIO * m_pIO; + + uint32 m_nCurrentBitIndex; + uint32 * m_pBitArray; +}; + +CUnBitArrayBase * CreateUnBitArray(IAPEDecompress * pAPEDecompress, int nVersion); + +#endif // #ifndef APE_UNBITARRAYBASE_H diff --git a/MAC_SDK/Source/MACLib/WAVInputSource.cpp b/MAC_SDK/Source/MACLib/WAVInputSource.cpp new file mode 100644 index 0000000..c21ae83 --- /dev/null +++ b/MAC_SDK/Source/MACLib/WAVInputSource.cpp @@ -0,0 +1,279 @@ +#include "All.h" +#include "WAVInputSource.h" +#include IO_HEADER_FILE +#include "MACLib.h" +#include "GlobalFunctions.h" + +struct RIFF_HEADER +{ + char cRIFF[4]; // the characters 'RIFF' indicating that it's a RIFF file + unsigned long nBytes; // the number of bytes following this header +}; + +struct DATA_TYPE_ID_HEADER +{ + char cDataTypeID[4]; // should equal 'WAVE' for a WAV file +}; + +struct WAV_FORMAT_HEADER +{ + unsigned short nFormatTag; // the format of the WAV...should equal 1 for a PCM file + unsigned short nChannels; // the number of channels + unsigned long nSamplesPerSecond; // the number of samples per second + unsigned long nBytesPerSecond; // the bytes per second + unsigned short nBlockAlign; // block alignment + unsigned short nBitsPerSample; // the number of bits per sample +}; + +struct RIFF_CHUNK_HEADER +{ + char cChunkLabel[4]; // should equal "data" indicating the data chunk + unsigned long nChunkBytes; // the bytes of the chunk +}; + + +CInputSource * CreateInputSource(const wchar_t * pSourceName, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode) +{ + // error check the parameters + if ((pSourceName == NULL) || (wcslen(pSourceName) == 0)) + { + if (pErrorCode) *pErrorCode = ERROR_BAD_PARAMETER; + return NULL; + } + + // get the extension + const wchar_t * pExtension = &pSourceName[wcslen(pSourceName)]; + while ((pExtension > pSourceName) && (*pExtension != '.')) + pExtension--; + + // create the proper input source + if (wcsicmp(pExtension, L".wav") == 0) + { + if (pErrorCode) *pErrorCode = ERROR_SUCCESS; + return new CWAVInputSource(pSourceName, pwfeSource, pTotalBlocks, pHeaderBytes, pTerminatingBytes, pErrorCode); + } + else + { + if (pErrorCode) *pErrorCode = ERROR_INVALID_INPUT_FILE; + return NULL; + } +} + +CWAVInputSource::CWAVInputSource(CIO * pIO, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode) + : CInputSource(pIO, pwfeSource, pTotalBlocks, pHeaderBytes, pTerminatingBytes, pErrorCode) +{ + m_bIsValid = FALSE; + + if (pIO == NULL || pwfeSource == NULL) + { + if (pErrorCode) *pErrorCode = ERROR_BAD_PARAMETER; + return; + } + + m_spIO.Assign(pIO, FALSE, FALSE); + + int nRetVal = AnalyzeSource(); + if (nRetVal == ERROR_SUCCESS) + { + // fill in the parameters + if (pwfeSource) memcpy(pwfeSource, &m_wfeSource, sizeof(WAVEFORMATEX)); + if (pTotalBlocks) *pTotalBlocks = m_nDataBytes / m_wfeSource.nBlockAlign; + if (pHeaderBytes) *pHeaderBytes = m_nHeaderBytes; + if (pTerminatingBytes) *pTerminatingBytes = m_nTerminatingBytes; + + m_bIsValid = TRUE; + } + + if (pErrorCode) *pErrorCode = nRetVal; +} + +CWAVInputSource::CWAVInputSource(const wchar_t * pSourceName, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode) + : CInputSource(pSourceName, pwfeSource, pTotalBlocks, pHeaderBytes, pTerminatingBytes, pErrorCode) +{ + m_bIsValid = FALSE; + + if (pSourceName == NULL || pwfeSource == NULL) + { + if (pErrorCode) *pErrorCode = ERROR_BAD_PARAMETER; + return; + } + + m_spIO.Assign(new IO_CLASS_NAME); + if (m_spIO->Open(pSourceName) != ERROR_SUCCESS) + { + m_spIO.Delete(); + if (pErrorCode) *pErrorCode = ERROR_INVALID_INPUT_FILE; + return; + } + + int nRetVal = AnalyzeSource(); + if (nRetVal == ERROR_SUCCESS) + { + // fill in the parameters + if (pwfeSource) memcpy(pwfeSource, &m_wfeSource, sizeof(WAVEFORMATEX)); + if (pTotalBlocks) *pTotalBlocks = m_nDataBytes / m_wfeSource.nBlockAlign; + if (pHeaderBytes) *pHeaderBytes = m_nHeaderBytes; + if (pTerminatingBytes) *pTerminatingBytes = m_nTerminatingBytes; + + m_bIsValid = TRUE; + } + + if (pErrorCode) *pErrorCode = nRetVal; +} + +CWAVInputSource::~CWAVInputSource() +{ + + +} + +int CWAVInputSource::AnalyzeSource() +{ + // seek to the beginning (just in case) + m_spIO->Seek(0, FILE_BEGIN); + + // get the file size + m_nFileBytes = m_spIO->GetSize(); + + // get the RIFF header + RIFF_HEADER RIFFHeader; + RETURN_ON_ERROR(ReadSafe(m_spIO, &RIFFHeader, sizeof(RIFFHeader))) + + // make sure the RIFF header is valid + if (!(RIFFHeader.cRIFF[0] == 'R' && RIFFHeader.cRIFF[1] == 'I' && RIFFHeader.cRIFF[2] == 'F' && RIFFHeader.cRIFF[3] == 'F')) + return ERROR_INVALID_INPUT_FILE; + + // read the data type header + DATA_TYPE_ID_HEADER DataTypeIDHeader; + RETURN_ON_ERROR(ReadSafe(m_spIO, &DataTypeIDHeader, sizeof(DataTypeIDHeader))) + + // make sure it's the right data type + if (!(DataTypeIDHeader.cDataTypeID[0] == 'W' && DataTypeIDHeader.cDataTypeID[1] == 'A' && DataTypeIDHeader.cDataTypeID[2] == 'V' && DataTypeIDHeader.cDataTypeID[3] == 'E')) + return ERROR_INVALID_INPUT_FILE; + + // find the 'fmt ' chunk + RIFF_CHUNK_HEADER RIFFChunkHeader; + RETURN_ON_ERROR(ReadSafe(m_spIO, &RIFFChunkHeader, sizeof(RIFFChunkHeader))) + + while (!(RIFFChunkHeader.cChunkLabel[0] == 'f' && RIFFChunkHeader.cChunkLabel[1] == 'm' && RIFFChunkHeader.cChunkLabel[2] == 't' && RIFFChunkHeader.cChunkLabel[3] == ' ')) + { + // move the file pointer to the end of this chunk + m_spIO->Seek(RIFFChunkHeader.nChunkBytes, FILE_CURRENT); + + // check again for the data chunk + RETURN_ON_ERROR(ReadSafe(m_spIO, &RIFFChunkHeader, sizeof(RIFFChunkHeader))) + } + + // read the format info + WAV_FORMAT_HEADER WAVFormatHeader; + RETURN_ON_ERROR(ReadSafe(m_spIO, &WAVFormatHeader, sizeof(WAVFormatHeader))) + + // error check the header to see if we support it + if (WAVFormatHeader.nFormatTag != 1) + return ERROR_INVALID_INPUT_FILE; + + // copy the format information to the WAVEFORMATEX passed in + FillWaveFormatEx(&m_wfeSource, WAVFormatHeader.nSamplesPerSecond, WAVFormatHeader.nBitsPerSample, WAVFormatHeader.nChannels); + + // skip over any extra data in the header + int nWAVFormatHeaderExtra = RIFFChunkHeader.nChunkBytes - sizeof(WAVFormatHeader); + if (nWAVFormatHeaderExtra < 0) + return ERROR_INVALID_INPUT_FILE; + else + m_spIO->Seek(nWAVFormatHeaderExtra, FILE_CURRENT); + + // find the data chunk + RETURN_ON_ERROR(ReadSafe(m_spIO, &RIFFChunkHeader, sizeof(RIFFChunkHeader))) + + while (!(RIFFChunkHeader.cChunkLabel[0] == 'd' && RIFFChunkHeader.cChunkLabel[1] == 'a' && RIFFChunkHeader.cChunkLabel[2] == 't' && RIFFChunkHeader.cChunkLabel[3] == 'a')) + { + // move the file pointer to the end of this chunk + m_spIO->Seek(RIFFChunkHeader.nChunkBytes, FILE_CURRENT); + + // check again for the data chunk + RETURN_ON_ERROR(ReadSafe(m_spIO, &RIFFChunkHeader, sizeof(RIFFChunkHeader))) + } + + // we're at the data block + m_nHeaderBytes = m_spIO->GetPosition(); + m_nDataBytes = RIFFChunkHeader.nChunkBytes; + if (m_nDataBytes < 0) + m_nDataBytes = m_nFileBytes - m_nHeaderBytes; + + // make sure the data bytes is a whole number of blocks + if ((m_nDataBytes % m_wfeSource.nBlockAlign) != 0) + return ERROR_INVALID_INPUT_FILE; + + // calculate the terminating byts + m_nTerminatingBytes = m_nFileBytes - m_nDataBytes - m_nHeaderBytes; + + // we made it this far, everything must be cool + return ERROR_SUCCESS; +} + +int CWAVInputSource::GetData(unsigned char * pBuffer, int nBlocks, int * pBlocksRetrieved) +{ + if (!m_bIsValid) return ERROR_UNDEFINED; + + int nBytes = (m_wfeSource.nBlockAlign * nBlocks); + unsigned int nBytesRead = 0; + + if (m_spIO->Read(pBuffer, nBytes, &nBytesRead) != ERROR_SUCCESS) + return ERROR_IO_READ; + + if (pBlocksRetrieved) *pBlocksRetrieved = (nBytesRead / m_wfeSource.nBlockAlign); + + return ERROR_SUCCESS; +} + +int CWAVInputSource::GetHeaderData(unsigned char * pBuffer) +{ + if (!m_bIsValid) return ERROR_UNDEFINED; + + int nRetVal = ERROR_SUCCESS; + + if (m_nHeaderBytes > 0) + { + int nOriginalFileLocation = m_spIO->GetPosition(); + + m_spIO->Seek(0, FILE_BEGIN); + + unsigned int nBytesRead = 0; + int nReadRetVal = m_spIO->Read(pBuffer, m_nHeaderBytes, &nBytesRead); + + if ((nReadRetVal != ERROR_SUCCESS) || (m_nHeaderBytes != int(nBytesRead))) + { + nRetVal = ERROR_UNDEFINED; + } + + m_spIO->Seek(nOriginalFileLocation, FILE_BEGIN); + } + + return nRetVal; +} + +int CWAVInputSource::GetTerminatingData(unsigned char * pBuffer) +{ + if (!m_bIsValid) return ERROR_UNDEFINED; + + int nRetVal = ERROR_SUCCESS; + + if (m_nTerminatingBytes > 0) + { + int nOriginalFileLocation = m_spIO->GetPosition(); + + m_spIO->Seek(-m_nTerminatingBytes, FILE_END); + + unsigned int nBytesRead = 0; + int nReadRetVal = m_spIO->Read(pBuffer, m_nTerminatingBytes, &nBytesRead); + + if ((nReadRetVal != ERROR_SUCCESS) || (m_nTerminatingBytes != int(nBytesRead))) + { + nRetVal = ERROR_UNDEFINED; + } + + m_spIO->Seek(nOriginalFileLocation, FILE_BEGIN); + } + + return nRetVal; +} diff --git a/MAC_SDK/Source/MACLib/WAVInputSource.h b/MAC_SDK/Source/MACLib/WAVInputSource.h new file mode 100644 index 0000000..9d14813 --- /dev/null +++ b/MAC_SDK/Source/MACLib/WAVInputSource.h @@ -0,0 +1,64 @@ +#ifndef APE_WAVINPUTSOURCE_H +#define APE_WAVINPUTSOURCE_H + +#include "IO.h" + +/************************************************************************************* +CInputSource - base input format class (allows multiple format support) +*************************************************************************************/ +class CInputSource +{ +public: + + // construction / destruction + CInputSource(CIO * pIO, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode = NULL) { } + CInputSource(const wchar_t * pSourceName, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode = NULL) { } + virtual ~CInputSource() { } + + // get data + virtual int GetData(unsigned char * pBuffer, int nBlocks, int * pBlocksRetrieved) = 0; + + // get header / terminating data + virtual int GetHeaderData(unsigned char * pBuffer) = 0; + virtual int GetTerminatingData(unsigned char * pBuffer) = 0; +}; + +/************************************************************************************* +CWAVInputSource - wraps working with WAV files (could be extended to any format) +*************************************************************************************/ +class CWAVInputSource : public CInputSource +{ +public: + + // construction / destruction + CWAVInputSource(CIO * pIO, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode = NULL); + CWAVInputSource(const wchar_t * pSourceName, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode = NULL); + ~CWAVInputSource(); + + // get data + int GetData(unsigned char * pBuffer, int nBlocks, int * pBlocksRetrieved); + + // get header / terminating data + int GetHeaderData(unsigned char * pBuffer); + int GetTerminatingData(unsigned char * pBuffer); + +private: + + int AnalyzeSource(); + + CSmartPtr m_spIO; + + WAVEFORMATEX m_wfeSource; + int m_nHeaderBytes; + int m_nDataBytes; + int m_nTerminatingBytes; + int m_nFileBytes; + BOOL m_bIsValid; +}; + +/************************************************************************************* +Input souce creation +*************************************************************************************/ +CInputSource * CreateInputSource(const wchar_t * pSourceName, WAVEFORMATEX * pwfeSource, int * pTotalBlocks, int * pHeaderBytes, int * pTerminatingBytes, int * pErrorCode = NULL); + +#endif // #ifndef APE_WAVINPUTSOURCE_H diff --git a/MAC_SDK/Source/MACLib/md5.h b/MAC_SDK/Source/MACLib/md5.h new file mode 100644 index 0000000..0167ab3 --- /dev/null +++ b/MAC_SDK/Source/MACLib/md5.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. + * + * License to copy and use this software is granted provided that it is identified + * as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material + * mentioning or referencing this software or this function. + * + * License is also granted to make and use derivative works provided that such + * works are identified as "derived from the RSA Data Security, Inc. MD5 Message- + * Digest Algorithm" in all material mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either the + * merchantability of this software or the suitability of this software for any + * particular purpose. It is provided "as is" without express or implied warranty + * of any kind. These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef MD5SUM_MD5_H +#define MD5SUM_MD5_H + +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; + +/* + * Define the MD5 context structure + * Please DO NOT change the order or contents of the structure as various assembler files depend on it !! + */ + +typedef struct { + uint32_t state [ 4]; /* state (ABCD) */ + uint32_t count [ 2]; /* number of bits, modulo 2^64 (least sig word first) */ + uint8_t buffer [64]; /* input buffer for incomplete buffer data */ +} MD5_CTX; + +void MD5Init ( MD5_CTX* ctx ); +void MD5Update ( MD5_CTX* ctx, const uint8_t* buf, size_t len ); +void MD5Final ( uint8_t digest [16], MD5_CTX* ctx ); + +class CMD5Helper +{ +public: + + CMD5Helper(BOOL bInitialize = TRUE) + { + if (bInitialize) + Initialize(); + } + + BOOL Initialize() + { + memset(&m_MD5Context, 0, sizeof(m_MD5Context)); + MD5Init(&m_MD5Context); + m_nTotalBytes = 0; + return TRUE; + } + + inline void AddData(const void * pData, int nBytes) + { + MD5Update(&m_MD5Context, (const unsigned char *) pData, nBytes); + m_nTotalBytes += nBytes; + } + + BOOL GetResult(unsigned char cResult[16]) + { + memset(cResult, 0, 16); + MD5Final(cResult, &m_MD5Context); + return TRUE; + } + +protected: + + MD5_CTX m_MD5Context; + BOOL m_bStopped; + int m_nTotalBytes; +}; + + +#endif /* MD5SUM_MD5_H */ diff --git a/MAC_SDK/Source/Makefile b/MAC_SDK/Source/Makefile new file mode 100644 index 0000000..63adbe7 --- /dev/null +++ b/MAC_SDK/Source/Makefile @@ -0,0 +1,69 @@ +# +# Simple Makefile +# +# Frank Klemm +# + +TARGET = mac +INCLUDES = -IShared -IMACLib -IConsole +CPPOPT = -s -O3 -Wall -pedantic -D__GNUC_IA32__ +COMPILER = gcc + +SOURCEFILES = \ +Console/Console.cpp \ +MACLib/APECompress.cpp \ +MACLib/APECompressCore.cpp \ +MACLib/APECompressCreate.cpp \ +MACLib/APEDecompress.cpp \ +MACLib/APEInfo.cpp \ +MACLib/APELink.cpp \ +MACLib/APESimple.cpp \ +MACLib/APETag.cpp \ +MACLib/BitArray.cpp \ +MACLib/MACLib.cpp \ +MACLib/MACProgressHelper.cpp \ +MACLib/NNFilter.cpp \ +MACLib/NewPredictor.cpp \ +MACLib/Prepare.cpp \ +MACLib/UnBitArray.cpp \ +MACLib/UnBitArrayBase.cpp \ +MACLib/WAVInputSource.cpp \ +Shared/GlobalFunctions.cpp \ +Shared/StdLibFileIO.cpp \ +Shared/WinFileIO.cpp \ +MACLib/NNFilterAsm.o + + + +$(TARGET): $(SOURCEFILES) + $(COMPILER) -static $(CPPOPT) $(INCLUDES) -o $(TARGET)-static $(SOURCEFILES) + $(COMPILER) $(CPPOPT) $(INCLUDES) -o $(TARGET) $(SOURCEFILES) + +MACLib/NNFilterAsm.o : MACLib/NNFilterAsm.nas + nasm -f elf -o MACLib/NNFilterAsm.o MACLib/NNFilterAsm.nas -l MACLib/NNFilterAsm.lst + +APE_Source.tar.bz2: + @sh ./MakeSourceBall + +test: + @echo e4dd45d9b5ec4cc91f3bd2210a543df6 + @./$(TARGET) Adagio.ape - -d | md5sum + +speed: + @sync + @cat Adagio.ape > /dev/null + @sync + time ./mac Adagio.ape /dev/null -d + + +# Samual Barber: Adagio for Strings (10:10.84) +# +# C version 203.01 sec +# First ASM version 76.89 sec +# 76.85 sec +# 77.12 sec +# 76.23 sec +# 75.67 sec +# 76.26 sec +# 76.79 sec +# 76.70 sec diff --git a/MAC_SDK/Source/Readme.htm b/MAC_SDK/Source/Readme.htm new file mode 100644 index 0000000..5f8c51e --- /dev/null +++ b/MAC_SDK/Source/Readme.htm @@ -0,0 +1,67 @@ + + + + + + +Monkey + + + + +

Monkey's Audio Source Code +Readme
+
(last updated July 7, 2002)

+

Introduction

+

First off, just to be clear, you have to fully +agree with the included license agreement before using / viewing any of the +included materials.  The big points are that you can't steal code or try to +make money with it (without permission) and that you have to submit changes and +improvements back to the Monkey's Audio project.  With that out of the way, +I'm hoping that by releasing the source code, we'll be able to work together to +make Monkey's Audio better.  Please direct any suggestions or improvements +to the Monkey's Audio developer's forum or to me personally when appropriate. +(email @ monkeysaudio.com)  And thank you for taking the time to help.

+

Important Note

+

The Monkey's Audio format is not +"finalized".  In fact, the compression / decompression engines +are continually being improved.  This is what makes MAC fun to work on, and +it's what makes progress possible.  I realize that this can be a pain for +3rd party developers, but it's the only way to avoid stagnation.  So, you +can not hard code Monkey's Audio support and expect it to work with the newest +versions of MAC forever.  Either use a DLL or else accept that you'll have +to re-link to MACLib once in a while.

+

Things that it'd be great if you worked on

+

1. It would be nice to have makefiles for gcc +or any other compilers that people commonly use.

+

2. Pour through the code and look for bone-head +maneuvers.

+

3. Submit any necessary changes for +cross-platform compilation. 

+

4. XMMS, Lame DLL, PocketPC, etc. plugins / +implementations.

+

5. A console front-end that doesn't suck. (more +options, etc.)  Also, don't worry about maintaining compatibility with the +current parameter passing scheme -- just use whatever makes sense.

+

Tips for building MACLib outside of Windows

+

1. in "Shared/All.h" do this:

+
    +
  • #define BUILD_CROSS_PLATFORM
  • +
  • look through "Shared/All.h" and + "Shared/NoWindows.h" to make sure all the defines are acceptable
  • +
+

2. You need to use NASM to build the assembly +if you want it. (helps speed a lot)  Check out "MacLib/Assembly/..." +for more information.

+

Known non-Windows problems (help fixing them +would be great)

+

2. The macros PUMP_MESSAGE_LOOP, MESSAGEBOX, and a few others don't work.

+

 

+

- +All materials and programs copyrighted 2000-2002 by Matthew T. Ashland -

+

- +All rights reserved. -

+ + + + diff --git a/MAC_SDK/Source/Shared/APEInfoDialog.cpp b/MAC_SDK/Source/Shared/APEInfoDialog.cpp new file mode 100644 index 0000000..a4a99da --- /dev/null +++ b/MAC_SDK/Source/Shared/APEInfoDialog.cpp @@ -0,0 +1,308 @@ +#include "All.h" +#include "APEInfo.h" +#include "APEInfoDialog.h" +#include "ID3Genres.h" +#include "APECompress.h" +#include "CharacterHelper.h" + +/*************************************************************************************** +The dialog component ID's +***************************************************************************************/ +#define FILE_NAME_EDIT 1000 + +#define ENCODER_VERSION_STATIC 2000 +#define COMPRESSION_LEVEL_STATIC 2001 +#define FORMAT_FLAGS_STATIC 2002 +#define HAS_TAG_STATIC 2003 + +#define SAMPLE_RATE_STATIC 3000 +#define CHANNELS_STATIC 3001 +#define BITS_PER_SAMPLE_STATIC 3002 +#define PEAK_LEVEL_STATIC 3003 + +#define TRACK_LENGTH_STATIC 4000 +#define WAV_SIZE_STATIC 4001 +#define APE_SIZE_STATIC 4002 +#define COMPRESSION_RATIO_STATIC 4003 + +#define TITLE_EDIT 5000 +#define ARTIST_EDIT 5001 +#define ALBUM_EDIT 5002 +#define COMMENT_EDIT 5003 +#define YEAR_EDIT 5004 +#define GENRE_COMBOBOX 5005 +#define TRACK_EDIT 5006 + +#define SAVE_TAG_BUTTON 6000 +#define REMOVE_TAG_BUTTON 6001 +#define CANCEL_BUTTON 6002 + +/*************************************************************************************** +Global pointer to this instance +***************************************************************************************/ +CAPEInfoDialog * g_pAPEDecompressDialog = NULL; + +/*************************************************************************************** +Construction / destruction +***************************************************************************************/ +CAPEInfoDialog::CAPEInfoDialog() +{ + g_pAPEDecompressDialog = NULL; +} + +CAPEInfoDialog::~CAPEInfoDialog() +{ + +} + +/*************************************************************************************** +Display the file info dialog +***************************************************************************************/ +int CAPEInfoDialog::ShowAPEInfoDialog(const str_utf16 * pFilename, HINSTANCE hInstance, const str_utf16 * lpszTemplateName, HWND hWndParent) +{ + // only allow one instance at a time + if (g_pAPEDecompressDialog != NULL) { return -1; } + + // open the file + int nErrorCode = ERROR_SUCCESS; + m_pAPEDecompress = CreateIAPEDecompress(pFilename, &nErrorCode); + if (m_pAPEDecompress == NULL || nErrorCode != ERROR_SUCCESS) + return nErrorCode; + + g_pAPEDecompressDialog = this; + + DialogBoxParam(hInstance, lpszTemplateName, hWndParent, (DLGPROC) DialogProc, 0); + + // clean up + SAFE_DELETE(m_pAPEDecompress); + g_pAPEDecompressDialog = NULL; + + return 0; +} + +/*************************************************************************************** +Fill the genre combobox +***************************************************************************************/ +int CAPEInfoDialog::FillGenreComboBox(HWND hDlg, int nComboBoxID, char *pSelectedGenre) +{ + // declare the variables + int nRetVal; + HWND hGenreComboBox = GetDlgItem(hDlg, nComboBoxID); + + // reset the contents of the combobox + SendMessage(hGenreComboBox, CB_RESETCONTENT, 0, 0); + + // propagate the combobox (0 to 126 so "Undefined" isn't repeated) + for (int z = 0; z < GENRE_COUNT; z++) + { + //add the genre string + nRetVal = SendMessage(hGenreComboBox, CB_ADDSTRING, 0, (LPARAM) g_ID3Genre[z]); + if (nRetVal == CB_ERR) { return -1; } + } + + // add the 'Undefined' genre + nRetVal = SendMessage(hGenreComboBox, CB_ADDSTRING, 0, (LPARAM) "Undefined"); + if (nRetVal == CB_ERR) { return -1; } + + // set the genre id (if it's specified) + if (pSelectedGenre) + { + if (strlen(pSelectedGenre) > 0) + SendMessage(hGenreComboBox, CB_SELECTSTRING, -1, (LPARAM) pSelectedGenre); + } + + return 0; +} + +/*************************************************************************************** +The dialog procedure +***************************************************************************************/ +LRESULT CALLBACK CAPEInfoDialog::DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) +{ + // get the class + IAPEDecompress * pAPEDecompress = g_pAPEDecompressDialog->m_pAPEDecompress; + + int wmID, wmEvent; + + switch (message) + { + case WM_INITDIALOG: + { + // variable declares + TCHAR cTemp[1024] = { 0 }; + + // set info + wchar_t cFilename[MAX_PATH + 1] = {0}; + GET_IO(pAPEDecompress)->GetName(&cFilename[0]); + + SetDlgItemText(hDlg, FILE_NAME_EDIT, cFilename); + + switch (pAPEDecompress->GetInfo(APE_INFO_COMPRESSION_LEVEL)) + { + case COMPRESSION_LEVEL_FAST: _stprintf(cTemp, _T("Mode: Fast")); break; + case COMPRESSION_LEVEL_NORMAL: _stprintf(cTemp, _T("Mode: Normal")); break; + case COMPRESSION_LEVEL_HIGH: _stprintf(cTemp, _T("Mode: High")); break; + case COMPRESSION_LEVEL_EXTRA_HIGH: _stprintf(cTemp, _T("Mode: Extra High")); break; + case COMPRESSION_LEVEL_INSANE: _stprintf(cTemp, _T("Mode: Insane")); break; + default: _stprintf(cTemp, _T("Mode: Unknown")); break; + } + SetDlgItemText(hDlg, COMPRESSION_LEVEL_STATIC, cTemp); + + _stprintf(cTemp, _T("Version: %.2f"), float(pAPEDecompress->GetInfo(APE_INFO_FILE_VERSION)) / float(1000)); + SetDlgItemText(hDlg, ENCODER_VERSION_STATIC, cTemp); + + _stprintf(cTemp, _T("Format Flags: %d"), pAPEDecompress->GetInfo(APE_INFO_FORMAT_FLAGS)); + SetDlgItemText(hDlg, FORMAT_FLAGS_STATIC, cTemp); + + _stprintf(cTemp, _T("Sample Rate: %d"), pAPEDecompress->GetInfo(APE_INFO_SAMPLE_RATE)); + SetDlgItemText(hDlg, SAMPLE_RATE_STATIC, cTemp); + + _stprintf(cTemp, _T("Channels: %d"), pAPEDecompress->GetInfo(APE_INFO_CHANNELS)); + SetDlgItemText(hDlg, CHANNELS_STATIC, cTemp); + + _stprintf(cTemp, _T("Bits Per Sample: %d"), pAPEDecompress->GetInfo(APE_INFO_BITS_PER_SAMPLE)); + SetDlgItemText(hDlg, BITS_PER_SAMPLE_STATIC, cTemp); + + int nSeconds = pAPEDecompress->GetInfo(APE_INFO_LENGTH_MS) / 1000; int nMinutes = nSeconds / 60; nSeconds = nSeconds % 60; int nHours = nMinutes / 60; nMinutes = nMinutes % 60; + if (nHours > 0) _stprintf(cTemp, _T("Length: %d:%02d:%02d"), nHours, nMinutes, nSeconds); + else if (nMinutes > 0) _stprintf(cTemp, _T("Length: %d:%02d"), nMinutes, nSeconds); + else _stprintf(cTemp, _T("Length: 0:%02d"), nSeconds); + SetDlgItemText(hDlg, TRACK_LENGTH_STATIC, cTemp); + + int nPeakLevel = pAPEDecompress->GetInfo(APE_INFO_PEAK_LEVEL); + if (nPeakLevel >= 0) _stprintf(cTemp, _T("Peak Level: %d"), nPeakLevel); + else _stprintf(cTemp, _T("Peak Level: ?")); + SetDlgItemText(hDlg, PEAK_LEVEL_STATIC, cTemp); + + // the file size + _stprintf(cTemp, _T("APE: %.2f MB"), float(pAPEDecompress->GetInfo(APE_INFO_APE_TOTAL_BYTES)) / float(1048576)); + SetDlgItemText(hDlg, APE_SIZE_STATIC, cTemp); + + _stprintf(cTemp, _T("WAV: %.2f MB"), float(pAPEDecompress->GetInfo(APE_INFO_WAV_TOTAL_BYTES)) / float(1048576)); + SetDlgItemText(hDlg, WAV_SIZE_STATIC, cTemp); + + // the compression ratio + _stprintf(cTemp, _T("Compression: %.2f%%"), float(pAPEDecompress->GetInfo(APE_INFO_AVERAGE_BITRATE) * 100) / float(pAPEDecompress->GetInfo(APE_INFO_DECOMPRESSED_BITRATE))); + SetDlgItemText(hDlg, COMPRESSION_RATIO_STATIC, cTemp); + + // the has tag + BOOL bHasID3Tag = GET_TAG(pAPEDecompress)->GetHasID3Tag(); + BOOL bHasAPETag = GET_TAG(pAPEDecompress)->GetHasAPETag(); + + if (!bHasID3Tag && !bHasAPETag) + _stprintf(cTemp, _T("Tag: None")); + else if (bHasID3Tag && !bHasAPETag) + _stprintf(cTemp, _T("Tag: ID3v1.1")); + else if (!bHasID3Tag && bHasAPETag) + _stprintf(cTemp, _T("Tag: APE Tag")); + else + _stprintf(cTemp, _T("Tag: Corrupt")); + SetDlgItemText(hDlg, HAS_TAG_STATIC, cTemp); + + wchar_t cBuffer[256]; + int nBufferBytes = 256; + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_TITLE, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, TITLE_EDIT, cBuffer); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_ARTIST, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, ARTIST_EDIT, cBuffer); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_ALBUM, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, ALBUM_EDIT, cBuffer); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_COMMENT, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, COMMENT_EDIT, cBuffer); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_YEAR, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, YEAR_EDIT, cBuffer); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_TRACK, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, TRACK_EDIT, cBuffer); + + g_pAPEDecompressDialog->FillGenreComboBox(hDlg, GENRE_COMBOBOX, NULL); + + nBufferBytes = 256; + GET_TAG(pAPEDecompress)->GetFieldString(APE_TAG_FIELD_GENRE, cBuffer, &nBufferBytes); + SetDlgItemText(hDlg, GENRE_COMBOBOX, cBuffer); + + return TRUE; + break; + } + case WM_COMMAND: + wmID = LOWORD(wParam); + wmEvent = HIWORD(wParam); + + switch (wmID) + { + case IDCANCEL: + // traps the [esc] key + EndDialog(hDlg, 0); + return TRUE; + break; + case CANCEL_BUTTON: + EndDialog(hDlg, 0); + return TRUE; + break; + case REMOVE_TAG_BUTTON: + { + // make sure you really wanted to + int nRetVal = ::MessageBox(hDlg, _T("Are you sure you want to permanently remove the tag?"), _T("Are You Sure?"), MB_YESNO | MB_ICONQUESTION); + if (nRetVal == IDYES) + { + // remove the ID3 tag... + if (GET_TAG(pAPEDecompress)->Remove() != 0) + { + MessageBox(hDlg, _T("Error removing tag. (could the file be read-only?)"), _T("Error Removing Tag"), MB_OK | MB_ICONEXCLAMATION); + return TRUE; + } + else + { + EndDialog(hDlg, 0); + return TRUE; + } + } + break; + } + case SAVE_TAG_BUTTON: + + // make the id3 tag + TCHAR cBuffer[256]; int z; + + #define SAVE_FIELD(ID, Field) \ + for (z = 0; z < 256; z++) { cBuffer[z] = 0; } \ + GetDlgItemText(hDlg, ID, cBuffer, 256); \ + GET_TAG(pAPEDecompress)->SetFieldString(Field, cBuffer); + + SAVE_FIELD(TITLE_EDIT, APE_TAG_FIELD_TITLE) + SAVE_FIELD(ARTIST_EDIT, APE_TAG_FIELD_ARTIST) + SAVE_FIELD(ALBUM_EDIT, APE_TAG_FIELD_ALBUM) + SAVE_FIELD(COMMENT_EDIT, APE_TAG_FIELD_COMMENT) + SAVE_FIELD(TRACK_EDIT, APE_TAG_FIELD_TRACK) + SAVE_FIELD(YEAR_EDIT, APE_TAG_FIELD_YEAR) + SAVE_FIELD(GENRE_COMBOBOX, APE_TAG_FIELD_GENRE) + + if (GET_TAG(pAPEDecompress)->Save() != 0) + { + MessageBox(hDlg, _T("Error saving tag. (could the file be read-only?)"), _T("Error Saving Tag"), MB_OK | MB_ICONEXCLAMATION); + return TRUE; + } + + EndDialog(hDlg, 0); + break; + } + break; + case WM_CLOSE: + EndDialog(hDlg, 0); + return TRUE; + break; + } + + return FALSE; +} \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/APEInfoDialog.h b/MAC_SDK/Source/Shared/APEInfoDialog.h new file mode 100644 index 0000000..60a2495 --- /dev/null +++ b/MAC_SDK/Source/Shared/APEInfoDialog.h @@ -0,0 +1,22 @@ +#ifndef APE_APEINFODIALOG_H +#define APE_APEINFODIALOG_H + +BOOL CALLBACK FileInfoDialogProcedureA(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); + +class CAPEInfoDialog +{ +public: + + CAPEInfoDialog(); + ~CAPEInfoDialog(); + + int ShowAPEInfoDialog(const str_utf16 * pFilename, HINSTANCE hInstance, const str_utf16 * lpszTemplateName, HWND hWndParent); + +private: + + static LRESULT CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); + int FillGenreComboBox(HWND hDlg, int nComboBoxID, char * pSelectedGenre); + IAPEDecompress * m_pAPEDecompress; +}; + +#endif // #ifndef APE_APEINFODIALOG_H \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/All.h b/MAC_SDK/Source/Shared/All.h new file mode 100644 index 0000000..fc29b5f --- /dev/null +++ b/MAC_SDK/Source/Shared/All.h @@ -0,0 +1,237 @@ +#ifndef APE_ALL_H +#define APE_ALL_H + +/***************************************************************************************** +Cross platform building switch +*****************************************************************************************/ +//#define BUILD_CROSS_PLATFORM + +/***************************************************************************************** +Unicode +*****************************************************************************************/ +#ifdef _UNICODE + +#else + +#endif // #ifdef _UNICODE + + +/***************************************************************************************** +Global includes +*****************************************************************************************/ +#ifndef BUILD_CROSS_PLATFORM + #include +#endif + +#ifdef _WIN32 + #include + #include +#else + #include + #include + #include + #include + #include + #include "NoWindows.h" +#endif + +#include +#include +#include +#include +#include +#include "SmartPtr.h" + +/***************************************************************************************** +Global compiler settings (useful for porting) +*****************************************************************************************/ +#ifndef BUILD_CROSS_PLATFORM +#ifndef _WIN64 + #define ENABLE_ASSEMBLY +#endif +#endif + +#define BACKWARDS_COMPATIBILITY + +#define ENABLE_COMPRESSION_MODE_FAST +#define ENABLE_COMPRESSION_MODE_NORMAL +#define ENABLE_COMPRESSION_MODE_HIGH +#define ENABLE_COMPRESSION_MODE_EXTRA_HIGH + +#ifdef _WIN32 + typedef unsigned __int32 uint32; + typedef __int32 int32; + typedef unsigned __int16 uint16; + typedef __int16 int16; + typedef unsigned __int8 uint8; + typedef __int8 int8; + typedef char str_ansi; + typedef unsigned char str_utf8; + typedef wchar_t str_utf16; + + #define IO_USE_WIN_FILE_IO + #define IO_HEADER_FILE "WinFileIO.h" + #define IO_CLASS_NAME CWinFileIO + #define DLLEXPORT __declspec(dllexport) + #define SLEEP(MILLISECONDS) ::Sleep(MILLISECONDS) + #define MESSAGEBOX(PARENT, TEXT, CAPTION, TYPE) ::MessageBox(PARENT, TEXT, CAPTION, TYPE) + #define PUMP_MESSAGE_LOOP { MSG Msg; while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) != 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } + #define ODS OutputDebugString + #define TICK_COUNT_TYPE unsigned long + #define TICK_COUNT_READ(VARIABLE) VARIABLE = GetTickCount() + #define TICK_COUNT_FREQ 1000 +#else + #define IO_USE_STD_LIB_FILE_IO + #define IO_HEADER_FILE "StdLibFileIO.h" + #define IO_CLASS_NAME CStdLibFileIO + #define DLLEXPORT + #define SLEEP(MILLISECONDS) { struct timespec t; t.tv_sec = (MILLISECONDS) / 1000; t.tv_nsec = (MILLISECONDS) % 1000 * 1000000; nanosleep(&t, NULL); } + #define MESSAGEBOX(PARENT, TEXT, CAPTION, TYPE) + #define PUMP_MESSAGE_LOOP + #define ODS printf + #define TICK_COUNT_TYPE unsigned long long + #define TICK_COUNT_READ(VARIABLE) { struct timeval t; gettimeofday(&t, NULL); VARIABLE = t.tv_sec * 1000000LLU + t.tv_usec; } + #define TICK_COUNT_FREQ 1000000 +#endif + +/***************************************************************************************** +Global defines +*****************************************************************************************/ +#define MAC_VERSION_NUMBER 3990 +#define MAC_VERSION_STRING _T("3.99") +#define MAC_NAME _T("Monkey's Audio 3.99") +#define PLUGIN_NAME "Monkey's Audio Player v3.99" +#define MJ_PLUGIN_NAME _T("APE Plugin (v3.99)") +#define CONSOLE_NAME "--- Monkey's Audio Console Front End (v 3.99) (c) Matthew T. Ashland ---\n" +#define PLUGIN_ABOUT _T("Monkey's Audio Player v3.99\nCopyrighted (c) 2000-2004 by Matthew T. Ashland") +#define MAC_DLL_INTERFACE_VERSION_NUMBER 1000 + +/***************************************************************************************** +Byte order +*****************************************************************************************/ +#define __LITTLE_ENDIAN 1234 +#define __BIG_ENDIAN 4321 +#define __BYTE_ORDER __LITTLE_ENDIAN + +/***************************************************************************************** +Macros +*****************************************************************************************/ +#define MB(TEST) MESSAGEBOX(NULL, TEST, _T("Information"), MB_OK); +#define MBN(NUMBER) { TCHAR cNumber[16]; _stprintf(cNumber, _T("%d"), NUMBER); MESSAGEBOX(NULL, cNumber, _T("Information"), MB_OK); } + +#define SAFE_DELETE(POINTER) if (POINTER) { delete POINTER; POINTER = NULL; } +#define SAFE_ARRAY_DELETE(POINTER) if (POINTER) { delete [] POINTER; POINTER = NULL; } +#define SAFE_VOID_CLASS_DELETE(POINTER, Class) { Class *pClass = (Class *) POINTER; if (pClass) { delete pClass; POINTER = NULL; } } +#define SAFE_FILE_CLOSE(HANDLE) if (HANDLE != INVALID_HANDLE_VALUE) { CloseHandle(HANDLE); HANDLE = INVALID_HANDLE_VALUE; } + +#define ODN(NUMBER) { TCHAR cNumber[16]; _stprintf(cNumber, _T("%d\n"), int(NUMBER)); ODS(cNumber); } + +#define CATCH_ERRORS(CODE) try { CODE } catch(...) { } + +#define RETURN_ON_ERROR(FUNCTION) { int nRetVal = FUNCTION; if (nRetVal != 0) { return nRetVal; } } +#define RETURN_VALUE_ON_ERROR(FUNCTION, VALUE) { int nRetVal = FUNCTION; if (nRetVal != 0) { return VALUE; } } +#define RETURN_ON_EXCEPTION(CODE, VALUE) { try { CODE } catch(...) { return VALUE; } } + +#define THROW_ON_ERROR(CODE) { int nRetVal = CODE; if (nRetVal != 0) throw(nRetVal); } + +#define EXPAND_1_TIMES(CODE) CODE +#define EXPAND_2_TIMES(CODE) CODE CODE +#define EXPAND_3_TIMES(CODE) CODE CODE CODE +#define EXPAND_4_TIMES(CODE) CODE CODE CODE CODE +#define EXPAND_5_TIMES(CODE) CODE CODE CODE CODE CODE +#define EXPAND_6_TIMES(CODE) CODE CODE CODE CODE CODE CODE +#define EXPAND_7_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_8_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_9_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_12_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_14_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_15_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_16_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_30_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_31_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_32_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_64_TIMES(CODE) CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE CODE +#define EXPAND_N_TIMES(NUMBER, CODE) EXPAND_##NUMBER##_TIMES(CODE) + +#define UNROLL_4_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) +#define UNROLL_8_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) +#define UNROLL_15_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) +#define UNROLL_16_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) +#define UNROLL_64_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) +#define UNROLL_128_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) MACRO(64) MACRO(65) MACRO(66) MACRO(67) MACRO(68) MACRO(69) MACRO(70) MACRO(71) MACRO(72) MACRO(73) MACRO(74) MACRO(75) MACRO(76) MACRO(77) MACRO(78) MACRO(79) MACRO(80) MACRO(81) MACRO(82) MACRO(83) MACRO(84) MACRO(85) MACRO(86) MACRO(87) MACRO(88) MACRO(89) MACRO(90) MACRO(91) MACRO(92) MACRO(93) MACRO(94) MACRO(95) MACRO(96) MACRO(97) MACRO(98) MACRO(99) MACRO(100) MACRO(101) MACRO(102) MACRO(103) MACRO(104) MACRO(105) MACRO(106) MACRO(107) MACRO(108) MACRO(109) MACRO(110) MACRO(111) MACRO(112) MACRO(113) MACRO(114) MACRO(115) MACRO(116) MACRO(117) MACRO(118) MACRO(119) MACRO(120) MACRO(121) MACRO(122) MACRO(123) MACRO(124) MACRO(125) MACRO(126) MACRO(127) +#define UNROLL_256_TIMES(MACRO) MACRO(0) MACRO(1) MACRO(2) MACRO(3) MACRO(4) MACRO(5) MACRO(6) MACRO(7) MACRO(8) MACRO(9) MACRO(10) MACRO(11) MACRO(12) MACRO(13) MACRO(14) MACRO(15) MACRO(16) MACRO(17) MACRO(18) MACRO(19) MACRO(20) MACRO(21) MACRO(22) MACRO(23) MACRO(24) MACRO(25) MACRO(26) MACRO(27) MACRO(28) MACRO(29) MACRO(30) MACRO(31) MACRO(32) MACRO(33) MACRO(34) MACRO(35) MACRO(36) MACRO(37) MACRO(38) MACRO(39) MACRO(40) MACRO(41) MACRO(42) MACRO(43) MACRO(44) MACRO(45) MACRO(46) MACRO(47) MACRO(48) MACRO(49) MACRO(50) MACRO(51) MACRO(52) MACRO(53) MACRO(54) MACRO(55) MACRO(56) MACRO(57) MACRO(58) MACRO(59) MACRO(60) MACRO(61) MACRO(62) MACRO(63) MACRO(64) MACRO(65) MACRO(66) MACRO(67) MACRO(68) MACRO(69) MACRO(70) MACRO(71) MACRO(72) MACRO(73) MACRO(74) MACRO(75) MACRO(76) MACRO(77) MACRO(78) MACRO(79) MACRO(80) MACRO(81) MACRO(82) MACRO(83) MACRO(84) MACRO(85) MACRO(86) MACRO(87) MACRO(88) MACRO(89) MACRO(90) MACRO(91) MACRO(92) MACRO(93) MACRO(94) MACRO(95) MACRO(96) MACRO(97) MACRO(98) MACRO(99) MACRO(100) MACRO(101) MACRO(102) MACRO(103) MACRO(104) MACRO(105) MACRO(106) MACRO(107) MACRO(108) MACRO(109) MACRO(110) MACRO(111) MACRO(112) MACRO(113) MACRO(114) MACRO(115) MACRO(116) MACRO(117) MACRO(118) MACRO(119) MACRO(120) MACRO(121) MACRO(122) MACRO(123) MACRO(124) MACRO(125) MACRO(126) MACRO(127) \ + MACRO(128) MACRO(129) MACRO(130) MACRO(131) MACRO(132) MACRO(133) MACRO(134) MACRO(135) MACRO(136) MACRO(137) MACRO(138) MACRO(139) MACRO(140) MACRO(141) MACRO(142) MACRO(143) MACRO(144) MACRO(145) MACRO(146) MACRO(147) MACRO(148) MACRO(149) MACRO(150) MACRO(151) MACRO(152) MACRO(153) MACRO(154) MACRO(155) MACRO(156) MACRO(157) MACRO(158) MACRO(159) MACRO(160) MACRO(161) MACRO(162) MACRO(163) MACRO(164) MACRO(165) MACRO(166) MACRO(167) MACRO(168) MACRO(169) MACRO(170) MACRO(171) MACRO(172) MACRO(173) MACRO(174) MACRO(175) MACRO(176) MACRO(177) MACRO(178) MACRO(179) MACRO(180) MACRO(181) MACRO(182) MACRO(183) MACRO(184) MACRO(185) MACRO(186) MACRO(187) MACRO(188) MACRO(189) MACRO(190) MACRO(191) MACRO(192) MACRO(193) MACRO(194) MACRO(195) MACRO(196) MACRO(197) MACRO(198) MACRO(199) MACRO(200) MACRO(201) MACRO(202) MACRO(203) MACRO(204) MACRO(205) MACRO(206) MACRO(207) MACRO(208) MACRO(209) MACRO(210) MACRO(211) MACRO(212) MACRO(213) MACRO(214) MACRO(215) MACRO(216) MACRO(217) MACRO(218) MACRO(219) MACRO(220) MACRO(221) MACRO(222) MACRO(223) MACRO(224) MACRO(225) MACRO(226) MACRO(227) MACRO(228) MACRO(229) MACRO(230) MACRO(231) MACRO(232) MACRO(233) MACRO(234) MACRO(235) MACRO(236) MACRO(237) MACRO(238) MACRO(239) MACRO(240) MACRO(241) MACRO(242) MACRO(243) MACRO(244) MACRO(245) MACRO(246) MACRO(247) MACRO(248) MACRO(249) MACRO(250) MACRO(251) MACRO(252) MACRO(253) MACRO(254) MACRO(255) + +/***************************************************************************************** +Error Codes +*****************************************************************************************/ + +// success +#ifndef ERROR_SUCCESS +#define ERROR_SUCCESS 0 +#endif + +// file and i/o errors (1000's) +#define ERROR_IO_READ 1000 +#define ERROR_IO_WRITE 1001 +#define ERROR_INVALID_INPUT_FILE 1002 +#define ERROR_INVALID_OUTPUT_FILE 1003 +#define ERROR_INPUT_FILE_TOO_LARGE 1004 +#define ERROR_INPUT_FILE_UNSUPPORTED_BIT_DEPTH 1005 +#define ERROR_INPUT_FILE_UNSUPPORTED_SAMPLE_RATE 1006 +#define ERROR_INPUT_FILE_UNSUPPORTED_CHANNEL_COUNT 1007 +#define ERROR_INPUT_FILE_TOO_SMALL 1008 +#define ERROR_INVALID_CHECKSUM 1009 +#define ERROR_DECOMPRESSING_FRAME 1010 +#define ERROR_INITIALIZING_UNMAC 1011 +#define ERROR_INVALID_FUNCTION_PARAMETER 1012 +#define ERROR_UNSUPPORTED_FILE_TYPE 1013 +#define ERROR_UPSUPPORTED_FILE_VERSION 1014 + +// memory errors (2000's) +#define ERROR_INSUFFICIENT_MEMORY 2000 + +// dll errors (3000's) +#define ERROR_LOADINGAPE_DLL 3000 +#define ERROR_LOADINGAPE_INFO_DLL 3001 +#define ERROR_LOADING_UNMAC_DLL 3002 + +// general and misc errors +#define ERROR_USER_STOPPED_PROCESSING 4000 +#define ERROR_SKIPPED 4001 + +// programmer errors +#define ERROR_BAD_PARAMETER 5000 + +// IAPECompress errors +#define ERROR_APE_COMPRESS_TOO_MUCH_DATA 6000 + +// unknown error +#define ERROR_UNDEFINED -1 + +#define ERROR_EXPLANATION \ + { ERROR_IO_READ , "I/O read error" }, \ + { ERROR_IO_WRITE , "I/O write error" }, \ + { ERROR_INVALID_INPUT_FILE , "invalid input file" }, \ + { ERROR_INVALID_OUTPUT_FILE , "invalid output file" }, \ + { ERROR_INPUT_FILE_TOO_LARGE , "input file file too large" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_BIT_DEPTH , "input file unsupported bit depth" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_SAMPLE_RATE , "input file unsupported sample rate" }, \ + { ERROR_INPUT_FILE_UNSUPPORTED_CHANNEL_COUNT , "input file unsupported channel count" }, \ + { ERROR_INPUT_FILE_TOO_SMALL , "input file too small" }, \ + { ERROR_INVALID_CHECKSUM , "invalid checksum" }, \ + { ERROR_DECOMPRESSING_FRAME , "decompressing frame" }, \ + { ERROR_INITIALIZING_UNMAC , "initializing unmac" }, \ + { ERROR_INVALID_FUNCTION_PARAMETER , "invalid function parameter" }, \ + { ERROR_UNSUPPORTED_FILE_TYPE , "unsupported file type" }, \ + { ERROR_INSUFFICIENT_MEMORY , "insufficient memory" }, \ + { ERROR_LOADINGAPE_DLL , "loading MAC.dll" }, \ + { ERROR_LOADINGAPE_INFO_DLL , "loading MACinfo.dll" }, \ + { ERROR_LOADING_UNMAC_DLL , "loading UnMAC.dll" }, \ + { ERROR_USER_STOPPED_PROCESSING , "user stopped processing" }, \ + { ERROR_SKIPPED , "skipped" }, \ + { ERROR_BAD_PARAMETER , "bad parameter" }, \ + { ERROR_APE_COMPRESS_TOO_MUCH_DATA , "APE compress too much data" }, \ + { ERROR_UNDEFINED , "undefined" }, \ + +#endif // #ifndef APE_ALL_H \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/CharacterHelper.cpp b/MAC_SDK/Source/Shared/CharacterHelper.cpp new file mode 100644 index 0000000..fb4bbc6 --- /dev/null +++ b/MAC_SDK/Source/Shared/CharacterHelper.cpp @@ -0,0 +1,143 @@ +#include "All.h" +#include "CharacterHelper.h" + +str_ansi * GetANSIFromUTF8(const str_utf8 * pUTF8) +{ + str_utf16 * pUTF16 = GetUTF16FromUTF8(pUTF8); + str_ansi * pANSI = GetANSIFromUTF16(pUTF16); + delete [] pUTF16; + return pANSI; +} + +str_ansi * GetANSIFromUTF16(const str_utf16 * pUTF16) +{ + const int nCharacters = pUTF16 ? wcslen(pUTF16) : 0; + #ifdef _WIN32 + int nANSICharacters = (2 * nCharacters); + str_ansi * pANSI = new str_ansi [nANSICharacters + 1]; + memset(pANSI, 0, (nANSICharacters + 1) * sizeof(str_ansi)); + if (pUTF16) + WideCharToMultiByte(CP_ACP, 0, pUTF16, -1, pANSI, nANSICharacters, NULL, NULL); + #else + str_utf8 * pANSI = new str_utf8 [nCharacters + 1]; + for (int z = 0; z < nCharacters; z++) + pANSI[z] = (pUTF16[z] >= 256) ? '?' : (str_utf8) pUTF16[z]; + pANSI[nCharacters] = 0; + #endif + + return (str_ansi *) pANSI; +} + +str_utf16 * GetUTF16FromANSI(const str_ansi * pANSI) +{ + const int nCharacters = pANSI ? strlen(pANSI) : 0; + str_utf16 * pUTF16 = new str_utf16 [nCharacters + 1]; + + #ifdef _WIN32 + memset(pUTF16, 0, sizeof(str_utf16) * (nCharacters + 1)); + if (pANSI) + MultiByteToWideChar(CP_ACP, 0, pANSI, -1, pUTF16, nCharacters); + #else + for (int z = 0; z < nCharacters; z++) + pUTF16[z] = (str_utf16) ((str_utf8) pANSI[z]); + pUTF16[nCharacters] = 0; + #endif + + return pUTF16; +} + +str_utf16 * GetUTF16FromUTF8(const str_utf8 * pUTF8) +{ + // get the length + int nCharacters = 0; int nIndex = 0; + while (pUTF8[nIndex] != 0) + { + if ((pUTF8[nIndex] & 0x80) == 0) + nIndex += 1; + else if ((pUTF8[nIndex] & 0xE0) == 0xE0) + nIndex += 3; + else + nIndex += 2; + + nCharacters += 1; + } + + // make a UTF-16 string + str_utf16 * pUTF16 = new str_utf16 [nCharacters + 1]; + nIndex = 0; nCharacters = 0; + while (pUTF8[nIndex] != 0) + { + if ((pUTF8[nIndex] & 0x80) == 0) + { + pUTF16[nCharacters] = pUTF8[nIndex]; + nIndex += 1; + } + else if ((pUTF8[nIndex] & 0xE0) == 0xE0) + { + pUTF16[nCharacters] = ((pUTF8[nIndex] & 0x1F) << 12) | ((pUTF8[nIndex + 1] & 0x3F) << 6) | (pUTF8[nIndex + 2] & 0x3F); + nIndex += 3; + } + else + { + pUTF16[nCharacters] = ((pUTF8[nIndex] & 0x3F) << 6) | (pUTF8[nIndex + 1] & 0x3F); + nIndex += 2; + } + + nCharacters += 1; + } + pUTF16[nCharacters] = 0; + + return pUTF16; +} + +str_utf8 * GetUTF8FromANSI(const str_ansi * pANSI) +{ + str_utf16 * pUTF16 = GetUTF16FromANSI(pANSI); + str_utf8 * pUTF8 = GetUTF8FromUTF16(pUTF16); + delete [] pUTF16; + return pUTF8; +} + +str_utf8 * GetUTF8FromUTF16(const str_utf16 * pUTF16) +{ + // get the size(s) + int nCharacters = wcslen(pUTF16); + int nUTF8Bytes = 0; + for (int z = 0; z < nCharacters; z++) + { + if (pUTF16[z] < 0x0080) + nUTF8Bytes += 1; + else if (pUTF16[z] < 0x0800) + nUTF8Bytes += 2; + else + nUTF8Bytes += 3; + } + + // allocate a UTF-8 string + str_utf8 * pUTF8 = new str_utf8 [nUTF8Bytes + 1]; + + // create the UTF-8 string + int nUTF8Index = 0; + for (int z = 0; z < nCharacters; z++) + { + if (pUTF16[z] < 0x0080) + { + pUTF8[nUTF8Index++] = (str_utf8) pUTF16[z]; + } + else if (pUTF16[z] < 0x0800) + { + pUTF8[nUTF8Index++] = 0xC0 | (pUTF16[z] >> 6); + pUTF8[nUTF8Index++] = 0x80 | (pUTF16[z] & 0x3F); + } + else + { + pUTF8[nUTF8Index++] = 0xE0 | (pUTF16[z] >> 12); + pUTF8[nUTF8Index++] = 0x80 | ((pUTF16[z] >> 6) & 0x3F); + pUTF8[nUTF8Index++] = 0x80 | (pUTF16[z] & 0x3F); + } + } + pUTF8[nUTF8Index++] = 0; + + // return the UTF-8 string + return pUTF8; +} \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/CharacterHelper.h b/MAC_SDK/Source/Shared/CharacterHelper.h new file mode 100644 index 0000000..6f63a1e --- /dev/null +++ b/MAC_SDK/Source/Shared/CharacterHelper.h @@ -0,0 +1,15 @@ +/******************************************************************************************* +Character set conversion helpers +*******************************************************************************************/ + +#ifndef CHARACTER_HELPER_H +#define CHARACTER_HELPER_H + +str_ansi * GetANSIFromUTF8(const str_utf8 * pUTF8); +str_ansi * GetANSIFromUTF16(const str_utf16 * pUTF16); +str_utf16 * GetUTF16FromANSI(const str_ansi * pANSI); +str_utf16 * GetUTF16FromUTF8(const str_utf8 * pUTF8); +str_utf8 * GetUTF8FromANSI(const str_ansi * pANSI); +str_utf8 * GetUTF8FromUTF16(const str_utf16 * pUTF16); + +#endif // #ifndef CHARACTER_HELPER_H \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/CircleBuffer.cpp b/MAC_SDK/Source/Shared/CircleBuffer.cpp new file mode 100644 index 0000000..7ed9ec2 --- /dev/null +++ b/MAC_SDK/Source/Shared/CircleBuffer.cpp @@ -0,0 +1,89 @@ +#include "All.h" +#include "CircleBuffer.h" + +CCircleBuffer::CCircleBuffer() +{ + m_pBuffer = NULL; + m_nTotal = 0; + m_nHead = 0; + m_nTail = 0; + m_nEndCap = 0; + m_nMaxDirectWriteBytes = 0; +} + +CCircleBuffer::~CCircleBuffer() +{ + SAFE_ARRAY_DELETE(m_pBuffer) +} + +void CCircleBuffer::CreateBuffer(int nBytes, int nMaxDirectWriteBytes) +{ + SAFE_ARRAY_DELETE(m_pBuffer) + + m_nMaxDirectWriteBytes = nMaxDirectWriteBytes; + m_nTotal = nBytes + 1 + nMaxDirectWriteBytes; + m_pBuffer = new unsigned char [m_nTotal]; + m_nHead = 0; + m_nTail = 0; + m_nEndCap = m_nTotal; +} + +int CCircleBuffer::MaxAdd() +{ + int nMaxAdd = (m_nTail >= m_nHead) ? (m_nTotal - 1 - m_nMaxDirectWriteBytes) - (m_nTail - m_nHead) : m_nHead - m_nTail - 1; + return nMaxAdd; +} + +int CCircleBuffer::MaxGet() +{ + return (m_nTail >= m_nHead) ? m_nTail - m_nHead : (m_nEndCap - m_nHead) + m_nTail; +} + +int CCircleBuffer::Get(unsigned char * pBuffer, int nBytes) +{ + int nTotalGetBytes = 0; + + if (pBuffer != NULL && nBytes > 0) + { + int nHeadBytes = min(m_nEndCap - m_nHead, nBytes); + int nFrontBytes = nBytes - nHeadBytes; + + memcpy(&pBuffer[0], &m_pBuffer[m_nHead], nHeadBytes); + nTotalGetBytes = nHeadBytes; + + if (nFrontBytes > 0) + { + memcpy(&pBuffer[nHeadBytes], &m_pBuffer[0], nFrontBytes); + nTotalGetBytes += nFrontBytes; + } + + RemoveHead(nBytes); + } + + return nTotalGetBytes; +} + +void CCircleBuffer::Empty() +{ + m_nHead = 0; + m_nTail = 0; + m_nEndCap = m_nTotal; +} + +int CCircleBuffer::RemoveHead(int nBytes) +{ + nBytes = min(MaxGet(), nBytes); + m_nHead += nBytes; + if (m_nHead >= m_nEndCap) + m_nHead -= m_nEndCap; + return nBytes; +} + +int CCircleBuffer::RemoveTail(int nBytes) +{ + nBytes = min(MaxGet(), nBytes); + m_nTail -= nBytes; + if (m_nTail < 0) + m_nTail += m_nEndCap; + return nBytes; +} diff --git a/MAC_SDK/Source/Shared/CircleBuffer.h b/MAC_SDK/Source/Shared/CircleBuffer.h new file mode 100644 index 0000000..3d008dd --- /dev/null +++ b/MAC_SDK/Source/Shared/CircleBuffer.h @@ -0,0 +1,59 @@ +#ifndef APE_CIRCLEBUFFER_H +#define APE_CIRCLEBUFFER_H + +class CCircleBuffer +{ +public: + + // construction / destruction + CCircleBuffer(); + virtual ~CCircleBuffer(); + + // create the buffer + void CreateBuffer(int nBytes, int nMaxDirectWriteBytes); + + // query + int MaxAdd(); + int MaxGet(); + + // direct writing + inline unsigned char * CCircleBuffer::GetDirectWritePointer() + { + // return a pointer to the tail -- note that it will always be safe to write + // at least m_nMaxDirectWriteBytes since we use an end cap region + return &m_pBuffer[m_nTail]; + } + + inline void CCircleBuffer::UpdateAfterDirectWrite(int nBytes) + { + // update the tail + m_nTail += nBytes; + + // if the tail enters the "end cap" area, set the end cap and loop around + if (m_nTail >= (m_nTotal - m_nMaxDirectWriteBytes)) + { + m_nEndCap = m_nTail; + m_nTail = 0; + } + } + + // get data + int Get(unsigned char * pBuffer, int nBytes); + + // remove / empty + void Empty(); + int RemoveHead(int nBytes); + int RemoveTail(int nBytes); + +private: + + int m_nTotal; + int m_nMaxDirectWriteBytes; + int m_nEndCap; + int m_nHead; + int m_nTail; + unsigned char * m_pBuffer; +}; + + +#endif // #ifndef APE_CIRCLEBUFFER_H diff --git a/MAC_SDK/Source/Shared/GlobalFunctions.cpp b/MAC_SDK/Source/Shared/GlobalFunctions.cpp new file mode 100644 index 0000000..5f0b578 --- /dev/null +++ b/MAC_SDK/Source/Shared/GlobalFunctions.cpp @@ -0,0 +1,100 @@ +#include "All.h" +#include "GlobalFunctions.h" +#include "IO.h" + +/* +#ifndef __GNUC_IA32__ + +extern "C" BOOL GetMMXAvailable(void) +{ +#ifdef ENABLE_ASSEMBLY + + unsigned long nRegisterEDX; + + try + { + __asm mov eax, 1 + __asm CPUID + __asm mov nRegisterEDX, edx + } + catch(...) + { + return FALSE; + } + + if (nRegisterEDX & 0x800000) + RETURN_ON_EXCEPTION(__asm emms, FALSE) + else + return FALSE; + + return TRUE; + +#else + return FALSE; +#endif +} + +#endif // #ifndef __GNUC_IA32__ +*/ + +int ReadSafe(CIO * pIO, void * pBuffer, int nBytes) +{ + unsigned int nBytesRead = 0; + int nRetVal = pIO->Read(pBuffer, nBytes, &nBytesRead); + if (nRetVal == ERROR_SUCCESS) + { + if (nBytes != int(nBytesRead)) + nRetVal = ERROR_IO_READ; + } + + return nRetVal; +} + +int WriteSafe(CIO * pIO, void * pBuffer, int nBytes) +{ + unsigned int nBytesWritten = 0; + int nRetVal = pIO->Write(pBuffer, nBytes, &nBytesWritten); + if (nRetVal == ERROR_SUCCESS) + { + if (nBytes != int(nBytesWritten)) + nRetVal = ERROR_IO_WRITE; + } + + return nRetVal; +} + +BOOL FileExists(wchar_t * pFilename) +{ + if (0 == wcscmp(pFilename, L"-") || 0 == wcscmp(pFilename, L"/dev/stdin")) + return TRUE; + +#ifdef _WIN32 + + BOOL bFound = FALSE; + + WIN32_FIND_DATA WFD; + HANDLE hFind = FindFirstFile(pFilename, &WFD); + if (hFind != INVALID_HANDLE_VALUE) + { + bFound = TRUE; + CloseHandle(hFind); + } + + return bFound; + +#else + + CSmartPtr spANSI(GetANSIFromUTF16(pFilename), TRUE); + + struct stat b; + + if (stat(spANSI, &b) != 0) + return FALSE; + + if (!S_ISREG(b.st_mode)) + return FALSE; + + return TRUE; + +#endif +} \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/GlobalFunctions.h b/MAC_SDK/Source/Shared/GlobalFunctions.h new file mode 100644 index 0000000..0928cbb --- /dev/null +++ b/MAC_SDK/Source/Shared/GlobalFunctions.h @@ -0,0 +1,21 @@ +#ifndef APE_GLOBALFUNCTIONS_H +#define APE_GLOBALFUNCTIONS_H + +/************************************************************************************* +Definitions +*************************************************************************************/ +class CIO; + +/************************************************************************************* +Read / Write from an IO source and return failure if the number of bytes specified +isn't read or written +*************************************************************************************/ +int ReadSafe(CIO * pIO, void * pBuffer, int nBytes); +int WriteSafe(CIO * pIO, void * pBuffer, int nBytes); + +/************************************************************************************* +Checks for the existence of a file +*************************************************************************************/ +BOOL FileExists(wchar_t * pFilename); + +#endif // #ifndef APE_GLOBALFUNCTIONS_H diff --git a/MAC_SDK/Source/Shared/ID3Genres.h b/MAC_SDK/Source/Shared/ID3Genres.h new file mode 100644 index 0000000..aa168ee --- /dev/null +++ b/MAC_SDK/Source/Shared/ID3Genres.h @@ -0,0 +1,27 @@ +#ifndef APE_ID3GENRES_H +#define APE_ID3GENRES_H + +#define GENRE_UNDEFINED 255 +#define GENRE_COUNT 148 + +const LPCWSTR g_ID3Genre[GENRE_COUNT] = +{ + L"Blues", L"Classic Rock", L"Country", L"Dance", L"Disco", L"Funk", L"Grunge", L"Hip-Hop", + L"Jazz", L"Metal", L"New Age", L"Oldies", L"Other", L"Pop", L"R&B", L"Rap", L"Reggae", L"Rock", L"Techno", + L"Industrial", L"Alternative", L"Ska", L"Death Metal", L"Pranks", L"Soundtrack", L"Euro-Techno", L"Ambient", + L"Trip-Hop", L"Vocal", L"Jazz+Funk", L"Fusion", L"Trance", L"Classical", L"Instrumental", L"Acid", L"House", L"Game", + L"Sound Clip", L"Gospel", L"Noise", L"AlternRock", L"Bass", L"Soul", L"Punk", L"Space", L"Meditative", L"Instrumental Pop", + L"Instrumental Rock", L"Ethnic", L"Gothic", L"Darkwave", L"Techno-Industrial", L"Electronic", L"Pop-Folk", L"Eurodance", + L"Dream", L"Southern Rock", L"Comedy", L"Cult", L"Gangsta", L"Top 40", L"Christian Rap", L"Pop/Funk", L"Jungle", + L"Native American", L"Cabaret", L"New Wave", L"Psychadelic", L"Rave", L"Showtunes", L"Trailer", L"Lo-Fi", L"Tribal", + L"Acid Punk", L"Acid Jazz", L"Polka", L"Retro", L"Musical", L"Rock & Roll", L"Hard Rock", L"Folk", L"Folk-Rock", L"National Folk", + L"Swing", L"Fast Fusion", L"Bebop", L"Latin", L"Revival", L"Celtic", L"Bluegrass", L"Avantgarde", L"Gothic Rock", L"Progressive Rock", + L"Psychedelic Rock", L"Symphonic Rock", L"Slow Rock", L"Big Band", L"Chorus", L"Easy Listening", L"Acoustic", L"Humour", + L"Speech", L"Chanson", L"Opera", L"Chamber Music", L"Sonata", L"Symphony", L"Booty Bass", L"Primus", L"Porn Groove", + L"Satire", L"Slow Jam", L"Club", L"Tango", L"Samba", L"Folklore", L"Ballad", L"Power Ballad", L"Rhythmic Soul", L"Freestyle", + L"Duet", L"Punk Rock", L"Drum Solo", L"Acapella", L"Euro-House", L"Dance Hall", L"Goa", L"Drum & Bass", L"Club House", L"Hardcore", + L"Terror", L"Indie", L"BritPop", L"Black Punk", L"Polsk Punk", L"Beat", L"Christian Gangsta", L"Heavy Metal", L"Black Metal", + L"Crossover", L"Contemporary C", L"Christian Rock", L"Merengue", L"Salsa", L"Thrash Metal", L"Anime", L"JPop", L"SynthPop" +}; + +#endif // #ifndef APE_ID3GENRES_H diff --git a/MAC_SDK/Source/Shared/IO.h b/MAC_SDK/Source/Shared/IO.h new file mode 100644 index 0000000..63b4d7f --- /dev/null +++ b/MAC_SDK/Source/Shared/IO.h @@ -0,0 +1,49 @@ +#ifndef APE_IO_H +#define APE_IO_H + +#ifndef FILE_BEGIN + #define FILE_BEGIN 0 +#endif + +#ifndef FILE_CURRENT + #define FILE_CURRENT 1 +#endif + +#ifndef FILE_END + #define FILE_END 2 +#endif + +class CIO +{ + +public: + + //construction / destruction + CIO() { } + virtual ~CIO() { }; + + // open / close + virtual int Open(const wchar_t * pName) = 0; + virtual int Close() = 0; + + // read / write + virtual int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead) = 0; + virtual int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten) = 0; + + // seek + virtual int Seek(int nDistance, unsigned int nMoveMode) = 0; + + // creation / destruction + virtual int Create(const wchar_t * pName) = 0; + virtual int Delete() = 0; + + // other functions + virtual int SetEOF() = 0; + + // attributes + virtual int GetPosition() = 0; + virtual int GetSize() = 0; + virtual int GetName(wchar_t * pBuffer) = 0; +}; + +#endif // #ifndef APE_IO_H diff --git a/MAC_SDK/Source/Shared/NoWindows.h b/MAC_SDK/Source/Shared/NoWindows.h new file mode 100644 index 0000000..e6519d7 --- /dev/null +++ b/MAC_SDK/Source/Shared/NoWindows.h @@ -0,0 +1,68 @@ +#ifndef _WIN32 + +#ifndef APE_NOWINDOWS_H +#define APE_NOWINDOWS_H + +#define FALSE 0 +#define TRUE 1 + +#define NEAR +#define FAR + +typedef unsigned int uint32; +typedef int int32; +typedef unsigned short uint16; +typedef short int16; +typedef unsigned char uint8; +typedef char int8; +typedef char str_ansi; +typedef unsigned char str_utf8; +typedef wchar_t str_utf16; + +typedef unsigned long DWORD; +typedef int BOOL; +typedef unsigned char BYTE; +typedef unsigned short WORD; +typedef float FLOAT; +typedef void * HANDLE; +typedef unsigned int UINT; +typedef unsigned int WPARAM; +typedef long LPARAM; +typedef const char * LPCSTR; +typedef char * LPSTR; +typedef long LRESULT; + +#define ZeroMemory(POINTER, BYTES) memset(POINTER, 0, BYTES); +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#define min(a,b) (((a) < (b)) ? (a) : (b)) + +#define __stdcall +#define CALLBACK + +#define _stricmp strcasecmp +#define _strnicmp strncasecmp + +#define _FPOSOFF(fp) ((long)(fp).__pos) +#define MAX_PATH 260 + +#ifndef _WAVEFORMATEX_ +#define _WAVEFORMATEX_ + +typedef struct tWAVEFORMATEX +{ + WORD wFormatTag; /* format type */ + WORD nChannels; /* number of channels (i.e. mono, stereo...) */ + DWORD nSamplesPerSec; /* sample rate */ + DWORD nAvgBytesPerSec; /* for buffer estimation */ + WORD nBlockAlign; /* block size of data */ + WORD wBitsPerSample; /* number of bits per sample of mono data */ + WORD cbSize; /* the count in bytes of the size of */ + /* extra information (after cbSize) */ +} WAVEFORMATEX, *PWAVEFORMATEX, NEAR *NPWAVEFORMATEX, FAR *LPWAVEFORMATEX; +typedef const WAVEFORMATEX FAR *LPCWAVEFORMATEX; + +#endif // #ifndef _WAVEFORMATEX_ + +#endif // #ifndef APE_NOWINDOWS_H + +#endif // #ifndef _WIN32 diff --git a/MAC_SDK/Source/Shared/RollBuffer.h b/MAC_SDK/Source/Shared/RollBuffer.h new file mode 100644 index 0000000..0c5b8e0 --- /dev/null +++ b/MAC_SDK/Source/Shared/RollBuffer.h @@ -0,0 +1,120 @@ +#ifndef APE_ROLLBUFFER_H +#define APE_ROLLBUFFER_H + +template class CRollBuffer +{ +public: + + CRollBuffer() + { + m_pData = NULL; + m_pCurrent = NULL; + } + + ~CRollBuffer() + { + SAFE_ARRAY_DELETE(m_pData); + } + + int Create(int nWindowElements, int nHistoryElements) + { + SAFE_ARRAY_DELETE(m_pData) + m_nWindowElements = nWindowElements; + m_nHistoryElements = nHistoryElements; + + m_pData = new TYPE[m_nWindowElements + m_nHistoryElements]; + if (m_pData == NULL) + return ERROR_INSUFFICIENT_MEMORY; + + Flush(); + return 0; + } + + void Flush() + { + ZeroMemory(m_pData, (m_nHistoryElements + 1) * sizeof(TYPE)); + m_pCurrent = &m_pData[m_nHistoryElements]; + } + + void Roll() + { + memcpy(&m_pData[0], &m_pCurrent[-m_nHistoryElements], m_nHistoryElements * sizeof(TYPE)); + m_pCurrent = &m_pData[m_nHistoryElements]; + } + + __inline void IncrementSafe() + { + m_pCurrent++; + if (m_pCurrent == &m_pData[m_nWindowElements + m_nHistoryElements]) + Roll(); + } + + __inline void IncrementFast() + { + m_pCurrent++; + } + + __inline TYPE & operator[](const int nIndex) const + { + return m_pCurrent[nIndex]; + } + +protected: + + TYPE * m_pData; + TYPE * m_pCurrent; + int m_nHistoryElements; + int m_nWindowElements; +}; + +template class CRollBufferFast +{ +public: + + CRollBufferFast() + { + m_pData = new TYPE[WINDOW_ELEMENTS + HISTORY_ELEMENTS]; + Flush(); + } + + ~CRollBufferFast() + { + SAFE_ARRAY_DELETE(m_pData); + } + + void Flush() + { + ZeroMemory(m_pData, (HISTORY_ELEMENTS + 1) * sizeof(TYPE)); + m_pCurrent = &m_pData[HISTORY_ELEMENTS]; + } + + void Roll() + { + memcpy(&m_pData[0], &m_pCurrent[-HISTORY_ELEMENTS], HISTORY_ELEMENTS * sizeof(TYPE)); + m_pCurrent = &m_pData[HISTORY_ELEMENTS]; + } + + __inline void IncrementSafe() + { + m_pCurrent++; + if (m_pCurrent == &m_pData[WINDOW_ELEMENTS + HISTORY_ELEMENTS]) + Roll(); + } + + __inline void IncrementFast() + { + m_pCurrent++; + } + + __inline TYPE & operator[](const int nIndex) const + { + return m_pCurrent[nIndex]; + } + +protected: + + TYPE * m_pData; + TYPE * m_pCurrent; +}; + +#endif // #ifndef APE_ROLLBUFFER_H diff --git a/MAC_SDK/Source/Shared/SmartPtr.h b/MAC_SDK/Source/Shared/SmartPtr.h new file mode 100644 index 0000000..c9bb9be --- /dev/null +++ b/MAC_SDK/Source/Shared/SmartPtr.h @@ -0,0 +1,89 @@ +#ifndef APE_SMARTPTR_H +#define APE_SMARTPTR_H + +// disable the operator -> on UDT warning +#ifdef _MSC_VER + #pragma warning(push) + #pragma warning(disable : 4284) +#endif + +/************************************************************************************************* +CSmartPtr - a simple smart pointer class that can automatically initialize and free memory + note: (doesn't do garbage collection / reference counting because of the many pitfalls) +*************************************************************************************************/ +template class CSmartPtr +{ +public: + TYPE * m_pObject; + BOOL m_bArray; + BOOL m_bDelete; + + CSmartPtr() + { + m_bDelete = TRUE; + m_pObject = NULL; + } + CSmartPtr(TYPE * a_pObject, BOOL a_bArray = FALSE, BOOL a_bDelete = TRUE) + { + m_bDelete = TRUE; + m_pObject = NULL; + Assign(a_pObject, a_bArray, a_bDelete); + } + + ~CSmartPtr() + { + Delete(); + } + + void Assign(TYPE * a_pObject, BOOL a_bArray = FALSE, BOOL a_bDelete = TRUE) + { + Delete(); + + m_bDelete = a_bDelete; + m_bArray = a_bArray; + m_pObject = a_pObject; + } + + void Delete() + { + if (m_bDelete && m_pObject) + { + if (m_bArray) + delete [] m_pObject; + else + delete m_pObject; + + m_pObject = NULL; + } + } + + void SetDelete(const BOOL a_bDelete) + { + m_bDelete = a_bDelete; + } + + __inline TYPE * GetPtr() const + { + return m_pObject; + } + + __inline operator TYPE * () const + { + return m_pObject; + } + + __inline TYPE * operator ->() const + { + return m_pObject; + } + + // declare assignment, but don't implement (compiler error if we try to use) + // that way we can't carelessly mix smart pointers and regular pointers + __inline void * operator =(void *) const; +}; + +#ifdef _MSC_VER + #pragma warning(pop) +#endif _MSC_VER + +#endif // #ifndef APE_SMARTPTR_H diff --git a/MAC_SDK/Source/Shared/StdLibFileIO.cpp b/MAC_SDK/Source/Shared/StdLibFileIO.cpp new file mode 100644 index 0000000..5f59069 --- /dev/null +++ b/MAC_SDK/Source/Shared/StdLibFileIO.cpp @@ -0,0 +1,239 @@ +#include "All.h" + +#ifdef IO_USE_STD_LIB_FILE_IO + +#include "StdLibFileIO.h" + +/////////////////////////////////////////////////////// + +// low level I/O, where are prototypes and constants? +#if defined _WIN32 || defined __TURBOC__ || defined __ZTC__ || defined _MSC_VER +# include +# include +# include +# include +# include +#elif defined __unix__ || defined __linux__ +# include +# include +# include +# include +# include +# include +#else +# include +# include +# include +# include +#endif + + +#ifndef O_BINARY +# ifdef _O_BINARY +# define O_BINARY _O_BINARY +# else +# define O_BINARY 0 +# endif +#endif + +//// Binary/Low-Level-IO /////////////////////////////////////////// +// +// All file I/O is basicly handled via an ANSI file pointer (type: FILE*) in +// FILEIO-Mode 1 and via a POSIX file descriptor (type: int) in +// FILEIO-Mode 2 and 3. +// +// Some operation are only available via the POSIX interface (fcntl, setmode, +// ...) so we need a function to get the file descriptor from a file pointer. +// In FILEIO-Mode 2 and 3 this is a dummy function because we always working +// with this file descriptors. +// + +#if defined __BORLANDC__ || defined _WIN32 +# define FILENO(__fp) _fileno ((__fp)) +#elif defined __CYGWIN__ || defined __TURBOC__ || defined __unix__ || defined __EMX__ || defined _MSC_VER +# define FILENO(__fp) fileno ((__fp)) +#else +# define FILENO(__fp) fileno ((__fp)) +#endif + + +// +// If we have access to a file via file name, we can open the file with an +// additional "b" or a O_BINARY within the (f)open function to get a +// transparent untranslated data stream which is necessary for audio bitstream +// data and also for PCM data. If we are working with +// stdin/stdout/FILENO_STDIN/FILENO_STDOUT we can't open the file with this +// attributes, because the files are already open. So we need a non +// standardized sequence to switch to this mode (not necessary for Unix). +// Mostly the sequency is the same for incoming and outgoing streams, but only +// mostly so we need one for IN and one for OUT. +// Macros are called with the file pointer and you get back the untransalted file +// pointer which can be equal or different from the original. +// + +#if defined __EMX__ +# define SETBINARY_IN(__fp) (_fsetmode ( (__fp), "b" ), (__fp)) +# define SETBINARY_OUT(__fp) (_fsetmode ( (__fp), "b" ), (__fp)) +#elif defined __TURBOC__ || defined __BORLANDC__ +# define SETBINARY_IN(__fp) (setmode ( FILENO ((__fp)), O_BINARY ), (__fp)) +# define SETBINARY_OUT(__fp) (setmode ( FILENO ((__fp)), O_BINARY ), (__fp)) +#elif defined __CYGWIN__ +# define SETBINARY_IN(__fp) (setmode ( FILENO ((__fp)), _O_BINARY ), (__fp)) +# define SETBINARY_OUT(__fp) (setmode ( FILENO ((__fp)), _O_BINARY ), (__fp)) +#elif defined _WIN32 +# define SETBINARY_IN(__fp) (_setmode ( FILENO ((__fp)), _O_BINARY ), (__fp)) +# define SETBINARY_OUT(__fp) (_setmode ( FILENO ((__fp)), _O_BINARY ), (__fp)) +#elif defined _MSC_VER +# define SETBINARY_IN(__fp) (setmode ( FILENO ((__fp)), O_BINARY ), (__fp)) +# define SETBINARY_OUT(__fp) (setmode ( FILENO ((__fp)), O_BINARY ), (__fp)) +#elif defined __unix__ +# define SETBINARY_IN(__fp) (__fp) +# define SETBINARY_OUT(__fp) (__fp) +#elif 0 +# define SETBINARY_IN(__fp) (freopen ( NULL, "rb", (__fp) ), (__fp)) +# define SETBINARY_OUT(__fp) (freopen ( NULL, "wb", (__fp) ), (__fp)) +#else +# define SETBINARY_IN(__fp) (__fp) +# define SETBINARY_OUT(__fp) (__fp) +#endif + + +/////////////////////////////////////////////////////// + +CStdLibFileIO::CStdLibFileIO() +{ + memset(m_cFileName, 0, MAX_PATH); + m_bReadOnly = FALSE; + m_pFile = NULL; +} + +CStdLibFileIO::~CStdLibFileIO() +{ + Close(); +} + +int CStdLibFileIO::GetHandle() +{ + return FILENO(m_pFile); +} + +int CStdLibFileIO::Open(LPCTSTR pName) +{ + Close(); + + m_bReadOnly = FALSE; + + if (0 == strcmp(pName, "-") || 0 == strcmp(pName, "/dev/stdin")) + { + m_pFile = SETBINARY_IN(stdin); + m_bReadOnly = TRUE; // ReadOnly + } + else if (0 == strcmp (pName, "/dev/stdout")) + { + m_pFile = SETBINARY_OUT(stdout); + m_bReadOnly = FALSE; // WriteOnly + } + else + { + m_pFile = fopen(pName, "rb"); + m_bReadOnly = FALSE; // Read/Write + } + + if (!m_pFile) + return -1; + + strcpy(m_cFileName, pName); + + return 0; +} + +int CStdLibFileIO::Close() +{ + int nRetVal = -1; + + if (m_pFile != NULL) + { + nRetVal = fclose(m_pFile); + m_pFile = NULL; + } + + return nRetVal; +} + +int CStdLibFileIO::Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead) +{ + *pBytesRead = fread(pBuffer, 1, nBytesToRead, m_pFile); + return ferror(m_pFile) ? ERROR_IO_READ : 0; +} + +int CStdLibFileIO::Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten) +{ + *pBytesWritten = fwrite(pBuffer, 1, nBytesToWrite, m_pFile); + + return (ferror(m_pFile) || (*pBytesWritten != nBytesToWrite)) ? ERROR_IO_WRITE : 0; +} + +int CStdLibFileIO::Seek(int nDistance, unsigned int nMoveMode) +{ + return fseek(m_pFile, nDistance, nMoveMode); +} + +int CStdLibFileIO::SetEOF() +{ + return ftruncate(GetHandle(), GetPosition()); +} + +int CStdLibFileIO::GetPosition() +{ + fpos_t fPosition; + + memset(&fPosition, 0, sizeof(fPosition)); + fgetpos(m_pFile, &fPosition); + return _FPOSOFF(fPosition); +} + +int CStdLibFileIO::GetSize() +{ + int nCurrentPosition = GetPosition(); + Seek(0, FILE_END); + int nLength = GetPosition(); + Seek(nCurrentPosition, FILE_BEGIN); + return nLength; +} + +int CStdLibFileIO::GetName(char * pBuffer) +{ + strcpy(pBuffer, m_cFileName); + return 0; +} + +int CStdLibFileIO::Create(const wchar_t * pName) +{ + Close(); + + if (0 == strcmp (pName, "-") || 0 == strcmp (pName, "/dev/stdout")) + { + m_pFile = SETBINARY_OUT(stdout); + m_bReadOnly = FALSE; // WriteOnly + } + else + { + m_pFile = fopen (pName, "wb"); // Read/Write + m_bReadOnly = FALSE; + } + + if (!m_pFile) + return -1; + + strcpy (m_cFileName, pName); + + return 0; +} + +int CStdLibFileIO::Delete() +{ + Close(); + return unlink (m_cFileName); // 0 success, -1 error +} + +#endif // #ifdef IO_USE_STD_LIB_FILE_IO diff --git a/MAC_SDK/Source/Shared/StdLibFileIO.h b/MAC_SDK/Source/Shared/StdLibFileIO.h new file mode 100644 index 0000000..cf4b2b6 --- /dev/null +++ b/MAC_SDK/Source/Shared/StdLibFileIO.h @@ -0,0 +1,50 @@ +#ifdef IO_USE_STD_LIB_FILE_IO + +#ifndef APE_STDLIBFILEIO_H +#define APE_STDLIBFILEIO_H + +#include "IO.h" + +class CStdLibFileIO : public CIO +{ +public: + + // construction / destruction + CStdLibFileIO(); + ~CStdLibFileIO(); + + // open / close + int Open(LPCTSTR pName); + int Close(); + + // read / write + int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead); + int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten); + + // seek + int Seek(int nDistance, unsigned int nMoveMode); + + // other functions + int SetEOF(); + + // creation / destruction + int Create(const char * pName); + int Delete(); + + // attributes + int GetPosition(); + int GetSize(); + int GetName(char * pBuffer); + int GetHandle(); + +private: + + char m_cFileName[MAX_PATH]; + BOOL m_bReadOnly; + FILE * m_pFile; +}; + +#endif // #ifndef APE_STDLIBFILEIO_H + +#endif // #ifdef IO_USE_STD_LIB_FILE_IO + diff --git a/MAC_SDK/Source/Shared/StdString.h b/MAC_SDK/Source/Shared/StdString.h new file mode 100644 index 0000000..a1709f5 --- /dev/null +++ b/MAC_SDK/Source/Shared/StdString.h @@ -0,0 +1,3015 @@ +// ============================================================================= +// FILE: StdString.h +// AUTHOR: Joe O'Leary (with outside help noted in comments) +// REMARKS: +// This header file declares the CStdStr template. This template derives +// the Standard C++ Library basic_string<> template and add to it the +// the following conveniences: +// - The full MFC CString set of functions (including implicit cast) +// - writing to/reading from COM IStream interfaces +// - Functional objects for use in STL algorithms +// +// From this template, we intstantiate two classes: CStdStringA and +// CStdStringW. The name "CStdString" is just a #define of one of these, +// based upone the _UNICODE macro setting +// +// This header also declares our own version of the MFC/ATL UNICODE-MBCS +// conversion macros. Our version looks exactly like the Microsoft's to +// facilitate portability. +// +// NOTE: +// If you you use this in an MFC or ATL build, you should include either +// afx.h or atlbase.h first, as appropriate. +// +// PEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS: +// +// Several people have helped me iron out problems and othewise improve +// this class. OK, this is a long list but in my own defense, this code +// has undergone two major rewrites. Many of the improvements became +// necessary after I rewrote the code as a template. Others helped me +// improve the CString facade. +// +// Anyway, these people are (in chronological order): +// +// - Pete the Plumber (???) +// - Julian Selman +// - Chris (of Melbsys) +// - Dave Plummer +// - John C Sipos +// - Chris Sells +// - Nigel Nunn +// - Fan Xia +// - Matthew Williams +// - Carl Engman +// - Mark Zeren +// - Craig Watson +// - Rich Zuris +// - Karim Ratib +// - Chris Conti +// - Baptiste Lepilleur +// - Greg Pickles +// - Jim Cline +// - Jeff Kohn +// - Todd Heckel +// - Ullrich Pollhne +// - Joe Vitaterna +// - Joe Woodbury +// - Aaron (no last name) +// - Joldakowski (???) +// - Scott Hathaway +// - Eric Nitzche +// - Pablo Presedo +// +// REVISION HISTORY +// 2001-APR-27 - StreamLoad was calculating the number of BYTES in one +// case, not characters. Thanks to Pablo Presedo for this. +// +// 2001-FEB-23 - Replace() had a bug which caused infinite loops if the +// source string was empty. Fixed thanks to Eric Nitzsche. +// +// 2001-FEB-23 - Scott Hathaway was a huge help in providing me with the +// ability to build CStdString on Sun Unix systems. He +// sent me detailed build reports about what works and what +// does not. If CStdString compiles on your Unix box, you +// can thank Scott for it. +// +// 2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do +// range check as CString's does. Now fixed -- thanks! +// +// 2000-NOV-07 - Aaron pointed out that I was calling static member +// functions of char_traits via a temporary. This was not +// technically wrong, but it was unnecessary and caused +// problems for poor old buggy VC5. Thanks Aaron! +// +// 2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match +// what the CString::Find code really ends up doing. I was +// trying to match the docs. Now I match the CString code +// - Joe also caught me truncating strings for GetBuffer() calls +// when the supplied length was less than the current length. +// +// 2000-MAY-25 - Better support for STLPORT's Standard library distribution +// - Got rid of the NSP macro - it interfered with Koenig lookup +// - Thanks to Joe Woodbury for catching a TrimLeft() bug that +// I introduced in January. Empty strings were not getting +// trimmed +// +// 2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind +// is supposed to be a const function. +// +// 2000-MAR-07 - Thanks to Ullrich Pollhne for catching a range bug in one +// of the overloads of assign. +// +// 2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior! +// Thanks to Todd Heckel for helping out with this. +// +// 2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the +// Trim() function more efficient. +// - Thanks to Jeff Kohn for prompting me to find and fix a typo +// in one of the addition operators that takes _bstr_t. +// - Got rid of the .CPP file - you only need StdString.h now! +// +// 1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem +// with my implementation of CStdString::FormatV in which +// resulting string might not be properly NULL terminated. +// +// 1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment +// bug that MS has not fixed. CStdString did nothing to fix +// it either but it does now! The bug was: create a string +// longer than 31 characters, get a pointer to it (via c_str()) +// and then assign that pointer to the original string object. +// The resulting string would be empty. Not with CStdString! +// +// 1999-OCT-06 - BufferSet was erasing the string even when it was merely +// supposed to shrink it. Fixed. Thanks to Chris Conti. +// - Some of the Q172398 fixes were not checking for assignment- +// to-self. Fixed. Thanks to Baptiste Lepilleur. +// +// 1999-AUG-20 - Improved Load() function to be more efficient by using +// SizeOfResource(). Thanks to Rich Zuris for this. +// - Corrected resource ID constructor, again thanks to Rich. +// - Fixed a bug that occurred with UNICODE characters above +// the first 255 ANSI ones. Thanks to Craig Watson. +// - Added missing overloads of TrimLeft() and TrimRight(). +// Thanks to Karim Ratib for pointing them out +// +// 1999-JUL-21 - Made all calls to GetBuf() with no args check length first. +// +// 1999-JUL-10 - Improved MFC/ATL independence of conversion macros +// - Added SS_NO_REFCOUNT macro to allow you to disable any +// reference-counting your basic_string<> impl. may do. +// - Improved ReleaseBuffer() to be as forgiving as CString. +// Thanks for Fan Xia for helping me find this and to +// Matthew Williams for pointing it out directly. +// +// 1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in +// ToLower/ToUpper. They should call GetBuf() instead of +// data() in order to ensure the changed string buffer is not +// reference-counted (in those implementations that refcount). +// +// 1999-JUL-01 - Added a true CString facade. Now you can use CStdString as +// a drop-in replacement for CString. If you find this useful, +// you can thank Chris Sells for finally convincing me to give +// in and implement it. +// - Changed operators << and >> (for MFC CArchive) to serialize +// EXACTLY as CString's do. So now you can send a CString out +// to a CArchive and later read it in as a CStdString. I have +// no idea why you would want to do this but you can. +// +// 1999-JUN-21 - Changed the CStdString class into the CStdStr template. +// - Fixed FormatV() to correctly decrement the loop counter. +// This was harmless bug but a bug nevertheless. Thanks to +// Chris (of Melbsys) for pointing it out +// - Changed Format() to try a normal stack-based array before +// using to _alloca(). +// - Updated the text conversion macros to properly use code +// pages and to fit in better in MFC/ATL builds. In other +// words, I copied Microsoft's conversion stuff again. +// - Added equivalents of CString::GetBuffer, GetBufferSetLength +// - new sscpy() replacement of CStdString::CopyString() +// - a Trim() function that combines TrimRight() and TrimLeft(). +// +// 1999-MAR-13 - Corrected the "NotSpace" functional object to use _istpace() +// instead of _isspace() Thanks to Dave Plummer for this. +// +// 1999-FEB-26 - Removed errant line (left over from testing) that #defined +// _MFC_VER. Thanks to John C Sipos for noticing this. +// +// 1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that +// caused infinite recursion and stack overflow +// - Added member functions to simplify the process of +// persisting CStdStrings to/from DCOM IStream interfaces +// - Added functional objects (e.g. StdStringLessNoCase) that +// allow CStdStrings to be used as keys STL map objects with +// case-insensitive comparison +// - Added array indexing operators (i.e. operator[]). I +// originally assumed that these were unnecessary and would be +// inherited from basic_string. However, without them, Visual +// C++ complains about ambiguous overloads when you try to use +// them. Thanks to Julian Selman to pointing this out. +// +// 1998-FEB-?? - Added overloads of assign() function to completely account +// for Q172398 bug. Thanks to "Pete the Plumber" for this +// +// 1998-FEB-?? - Initial submission +// +// COPYRIGHT: +// 1999 Joseph M. O'Leary. This code is free. Use it anywhere you want. +// Rewrite it, restructure it, whatever. Please don't blame me if it makes +// your $30 billion dollar satellite explode in orbit. If you redistribute +// it in any form, I'd appreciate it if you would leave this notice here. +// +// If you find any bugs, please let me know: +// +// jmoleary@earthlink.net +// http://home.earthlink.net/~jmoleary +// ============================================================================= + +// Avoid multiple inclusion the VC++ way, +// Turn off browser references +// Turn off unavoidable compiler warnings + +#if defined(_MSC_VER) && (_MSC_VER > 1100) + #pragma once + #pragma component(browser, off, references, "CStdString") + #pragma warning (disable : 4290) // C++ Exception Specification ignored + #pragma warning (disable : 4127) // Conditional expression is constant + #pragma warning (disable : 4097) // typedef name used as synonym for class name +#endif + +#ifndef STDSTRING_H +#define STDSTRING_H + +// MACRO: SS_NO_REFCOUNT: +// turns off reference counting at the assignment level +// I define this by default. comment it out if you don't want it. + +#define SS_NO_REFCOUNT + +// In non-Visual C++ and/or non-Win32 builds, we can't use some cool stuff. + +#if !defined(_MSC_VER) || !defined(_WIN32) + #define SS_ANSI +#endif + +// Avoid legacy code screw up: if _UNICODE is defined, UNICODE must be as well + +#if defined (_UNICODE) && !defined (UNICODE) + #define UNICODE +#endif +#if defined (UNICODE) && !defined (_UNICODE) + #define _UNICODE +#endif + +// ----------------------------------------------------------------------------- +// MIN and MAX. The Standard C++ template versions go by so many names (at +// at least in the MS implementation) that you never know what's available +// ----------------------------------------------------------------------------- +template +inline const Type& SSMIN(const Type& arg1, const Type& arg2) +{ + return arg2 < arg1 ? arg2 : arg1; +} +template +inline const Type& SSMAX(const Type& arg1, const Type& arg2) +{ + return arg2 > arg1 ? arg2 : arg1; +} + +// If they have not #included W32Base.h (part of my W32 utility library) then +// we need to define some stuff. Otherwise, this is all defined there. + +#if !defined(W32BASE_H) + + // If they want us to use only standard C++ stuff (no Win32 stuff) + + #ifdef SS_ANSI + + // On non-Win32 platforms, there is no TCHAR.H so define what we need + + #ifndef _WIN32 + + typedef const char* PCSTR; + typedef char* PSTR; + typedef const wchar_t* PCWSTR; + typedef wchar_t* PWSTR; + #ifdef UNICODE + typedef wchar_t TCHAR; + #else + typedef char TCHAR; + #endif + typedef wchar_t OLECHAR; + + #else + + #include + #include + #ifndef STRICT + #define STRICT + #endif + + #endif // #ifndef _WIN32 + + + // Make sure ASSERT and verify are defined in an ANSI fashion + + #ifndef ASSERT + #include + #define ASSERT(f) assert((f)) + #endif + #ifndef VERIFY + #ifdef _DEBUG + #define VERIFY(x) ASSERT((x)) + #else + #define VERIFY(x) x + #endif + #endif + + #else // #ifdef SS_ANSI + + #include + #include + #ifndef STRICT + #define STRICT + #endif + + // Make sure ASSERT and verify are defined + + #ifndef ASSERT + #include + #define ASSERT(f) _ASSERTE((f)) + #endif + #ifndef VERIFY + #ifdef _DEBUG + #define VERIFY(x) ASSERT((x)) + #else + #define VERIFY(x) x + #endif + #endif + + #endif // #ifdef SS_ANSI + + #ifndef UNUSED + #define UNUSED(x) x + #endif + +#endif // #ifndef W32BASE_H + +// Standard headers needed + +#include // basic_string +#include // for_each, etc. +#include // for StdStringLessNoCase, et al +#include // for various facets + +// If this is a recent enough version of VC include comdef.h, so we can write +// member functions to deal with COM types & compiler support classes e.g. _bstr_t + +#if defined (_MSC_VER) && (_MSC_VER >= 1100) + #include + #define SS_INC_COMDEF // signal that we #included MS comdef.h file + #define STDSTRING_INC_COMDEF + #define SS_NOTHROW __declspec(nothrow) +#else + #define SS_NOTHROW +#endif + +#ifndef TRACE + #define TRACE_DEFINED_HERE + #define TRACE +#endif + +// Microsoft defines PCSTR, PCWSTR, etc, but no PCTSTR. I hate to use the +// versions with the "L" in front of them because that's a leftover from Win 16 +// days, even though it evaluates to the same thing. Therefore, Define a PCSTR +// as an LPCTSTR. + +#if !defined(PCTSTR) && !defined(PCTSTR_DEFINED) + typedef const TCHAR* PCTSTR; + #define PCTSTR_DEFINED +#endif + +#if !defined(PCOLESTR) && !defined(PCOLESTR_DEFINED) + typedef const OLECHAR* PCOLESTR; + #define PCOLESTR_DEFINED +#endif + +#if !defined(POLESTR) && !defined(POLESTR_DEFINED) + typedef OLECHAR* POLESTR; + #define POLESTR_DEFINED +#endif + +#if !defined(PCUSTR) && !defined(PCUSTR_DEFINED) + typedef const unsigned char* PCUSTR; + typedef unsigned char* PUSTR; + #define PCUSTR_DEFINED +#endif + +// SS_USE_FACET macro and why we need it: +// +// Since I'm a good little Standard C++ programmer, I use locales. Thus, I +// need to make use of the use_facet<> template function here. Unfortunately, +// this need is complicated by the fact the MS' implementation of the Standard +// C++ Library has a non-standard version of use_facet that takes more +// arguments than the standard dictates. Since I'm trying to write CStdString +// to work with any version of the Standard library, this presents a problem. +// +// The upshot of this is that I can't do 'use_facet' directly. The MS' docs +// tell me that I have to use a macro, _USE() instead. Since _USE obviously +// won't be available in other implementations, this means that I have to write +// my OWN macro -- SS_USE_FACET -- that evaluates either to _USE or to the +// standard, use_facet. +// +// If you are having trouble with the SS_USE_FACET macro, in your implementation +// of the Standard C++ Library, you can define your own version of SS_USE_FACET. +#ifndef schMSG + #define schSTR(x) #x + #define schSTR2(x) schSTR(x) + #define schMSG(desc) message(__FILE__ "(" schSTR2(__LINE__) "):" #desc) +#endif + +#ifndef SS_USE_FACET + // STLPort #defines a macro (__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) for + // all MSVC builds, erroneously in my opinion. It causes problems for + // my SS_ANSI builds. In my code, I always comment out that line. You'll + // find it in \stlport\config\stl_msvc.h + #if defined(__SGI_STL_PORT) && (__SGI_STL_PORT >= 0x400 ) + #if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) && defined(_MSC_VER) + #ifdef SS_ANSI + #pragma schMSG(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS defined!!) + #endif + #endif + #define SS_USE_FACET(loc, fac) std::use_facet(loc) + #elif defined(_MSC_VER ) + #define SS_USE_FACET(loc, fac) _USE(loc, fac) + + // ...and + #elif defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) + #define SS_USE_FACET(loc, fac) std::use_facet(loc, (fac*)0) + #else + #define SS_USE_FACET(loc, fac) std::use_facet(loc) + #endif +#endif + +// ============================================================================= +// UNICODE/MBCS conversion macros. Made to work just like the MFC/ATL ones. +// ============================================================================= + +// First define the conversion helper functions. We define these regardless of +// any preprocessor macro settings since their names won't collide. + +#ifdef SS_ANSI // Are we doing things the standard, non-Win32 way?... + + typedef std::codecvt SSCodeCvt; + + // Not sure if we need all these headers. I believe ANSI says we do. + + #include + #include + #include + #ifndef va_start + #include + #endif + + // StdCodeCvt - made to look like Win32 functions WideCharToMultiByte annd + // MultiByteToWideChar but uses locales in SS_ANSI builds + inline PWSTR StdCodeCvt(PWSTR pW, PCSTR pA, int nChars, + const std::locale& loc=std::locale()) + { + ASSERT(0 != pA); + ASSERT(0 != pW); + pW[0] = '\0'; + PCSTR pBadA = 0; + PWSTR pBadW = 0; + SSCodeCvt::result res = SSCodeCvt::ok; + const SSCodeCvt& conv = SS_USE_FACET(loc, SSCodeCvt); + SSCodeCvt::state_type st= { 0 }; + res = conv.in(st, + pA, pA + nChars, pBadA, + pW, pW + nChars, pBadW); + ASSERT(SSCodeCvt::ok == res); + return pW; + } + inline PWSTR StdCodeCvt(PWSTR pW, PCUSTR pA, int nChars, + const std::locale& loc=std::locale()) + { + return StdCodeCvt(pW, (PCSTR)pA, nChars, loc); + } + + inline PSTR StdCodeCvt(PSTR pA, PCWSTR pW, int nChars, + const std::locale& loc=std::locale()) + { + ASSERT(0 != pA); + ASSERT(0 != pW); + pA[0] = '\0'; + PSTR pBadA = 0; + PCWSTR pBadW = 0; + SSCodeCvt::result res = SSCodeCvt::ok; + const SSCodeCvt& conv = SS_USE_FACET(loc, SSCodeCvt); + SSCodeCvt::state_type st= { 0 }; + res = conv.out(st, + pW, pW + nChars, pBadW, + pA, pA + nChars, pBadA); + ASSERT(SSCodeCvt::ok == res); + return pA; + } + inline PUSTR StdCodeCvt(PUSTR pA, PCWSTR pW, int nChars, + const std::locale& loc=std::locale()) + { + return (PUSTR)StdCodeCvt((PSTR)pA, pW, nChars, loc); + } + +#else // ...or are we doing things assuming win32 and Visual C++? + + #include // needed for _alloca + + inline PWSTR StdCodeCvt(PWSTR pW, PCSTR pA, int nChars, UINT acp=CP_ACP) + { + ASSERT(0 != pA); + ASSERT(0 != pW); + pW[0] = '\0'; + MultiByteToWideChar(acp, 0, pA, -1, pW, nChars); + return pW; + } + inline PWSTR StdCodeCvt(PWSTR pW, PCUSTR pA, int nChars, UINT acp=CP_ACP) + { + return StdCodeCvt(pW, (PCSTR)pA, nChars, acp); + } + + inline PSTR StdCodeCvt(PSTR pA, PCWSTR pW, int nChars, UINT acp=CP_ACP) + { + ASSERT(0 != pA); + ASSERT(0 != pW); + pA[0] = '\0'; + WideCharToMultiByte(acp, 0, pW, -1, pA, nChars, 0, 0); + return pA; + } + inline PUSTR StdCodeCvt(PUSTR pA, PCWSTR pW, int nChars, UINT acp=CP_ACP) + { + return (PUSTR)StdCodeCvt((PSTR)pA, pW, nChars, acp); + } + + // Define our conversion macros to look exactly like Microsoft's to + // facilitate using this stuff both with and without MFC/ATL + + #ifdef _CONVERSION_USES_THREAD_LOCALE + #ifndef _DEBUG + #define SSCVT int _cvt; _cvt; UINT _acp=GetACP(); \ + _acp; PCWSTR _pw; _pw; PCSTR _pa; _pa + #else + #define SSCVT int _cvt = 0; _cvt; UINT _acp=GetACP();\ + _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa + #endif + #else + #ifndef _DEBUG + #define SSCVT int _cvt; _cvt; UINT _acp=CP_ACP; _acp;\ + PCWSTR _pw; _pw; PCSTR _pa; _pa + #else + #define SSCVT int _cvt = 0; _cvt; UINT _acp=CP_ACP; \ + _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa + #endif + #endif + + #ifdef _CONVERSION_USES_THREAD_LOCALE + #define SSA2W(pa) (\ + ((_pa = pa) == 0) ? 0 : (\ + _cvt = (strlen(_pa)+1),\ + StdCodeCvt((PWSTR) _alloca(_cvt*2), _pa, _cvt, _acp))) + #define SSW2A(pw) (\ + ((_pw = pw) == 0) ? 0 : (\ + _cvt = (wcslen(_pw)+1)*2,\ + StdW2AHelper((LPSTR) _alloca(_cvt), _pw, _cvt, _acp))) + #else + #define SSA2W(pa) (\ + ((_pa = pa) == 0) ? 0 : (\ + _cvt = (strlen(_pa)+1),\ + StdCodeCvt((PWSTR) _alloca(_cvt*2), _pa, _cvt))) + #define SSW2A(pw) (\ + ((_pw = pw) == 0) ? 0 : (\ + _cvt = (wcslen(_pw)+1)*2,\ + StdCodeCvt((LPSTR) _alloca(_cvt), _pw, _cvt))) + #endif + + #define SSA2CW(pa) ((PCWSTR)SSA2W((pa))) + #define SSW2CA(pw) ((PCSTR)SSW2A((pw))) + + #ifdef UNICODE + #define SST2A SSW2A + #define SSA2T SSA2W + #define SST2CA SSW2CA + #define SSA2CT SSA2CW + inline PWSTR SST2W(PTSTR p) { return p; } + inline PTSTR SSW2T(PWSTR p) { return p; } + inline PCWSTR SST2CW(PCTSTR p) { return p; } + inline PCTSTR SSW2CT(PCWSTR p) { return p; } + #else + #define SST2W SSA2W + #define SSW2T SSW2A + #define SST2CW SSA2CW + #define SSW2CT SSW2CA + inline PSTR SST2A(PTSTR p) { return p; } + inline PTSTR SSA2T(PSTR p) { return p; } + inline PCSTR SST2CA(PCTSTR p) { return p; } + inline PCTSTR SSA2CT(PCSTR p) { return p; } + #endif // #ifdef UNICODE + + #if defined(UNICODE) + // in these cases the default (TCHAR) is the same as OLECHAR + inline PCOLESTR SST2COLE(PCTSTR p) { return p; } + inline PCTSTR SSOLE2CT(PCOLESTR p) { return p; } + inline POLESTR SST2OLE(PTSTR p) { return p; } + inline PTSTR SSOLE2T(POLESTR p) { return p; } + #elif defined(OLE2ANSI) + // in these cases the default (TCHAR) is the same as OLECHAR + inline PCOLESTR SST2COLE(PCTSTR p) { return p; } + inline PCTSTR SSOLE2CT(PCOLESTR p) { return p; } + inline POLESTR SST2OLE(PTSTR p) { return p; } + inline PTSTR SSOLE2T(POLESTR p) { return p; } + #else + //CharNextW doesn't work on Win95 so we use this + #define SST2COLE(pa) SSA2CW((pa)) + #define SST2OLE(pa) SSA2W((pa)) + #define SSOLE2CT(po) SSW2CA((po)) + #define SSOLE2T(po) SSW2A((po)) + #endif + + #ifdef OLE2ANSI + #define SSW2OLE SSW2A + #define SSOLE2W SSA2W + #define SSW2COLE SSW2CA + #define SSOLE2CW SSA2CW + inline POLESTR SSA2OLE(PSTR p) { return p; } + inline PSTR SSOLE2A(POLESTR p) { return p; } + inline PCOLESTR SSA2COLE(PCSTR p) { return p; } + inline PCSTR SSOLE2CA(PCOLESTR p){ return p; } + #else + #define SSA2OLE SSA2W + #define SSOLE2A SSW2A + #define SSA2COLE SSA2CW + #define SSOLE2CA SSW2CA + inline POLESTR SSW2OLE(PWSTR p) { return p; } + inline PWSTR SSOLE2W(POLESTR p) { return p; } + inline PCOLESTR SSW2COLE(PCWSTR p) { return p; } + inline PCWSTR SSOLE2CW(PCOLESTR p){ return p; } + #endif + + // Above we've defined macros that look like MS' but all have + // an 'SS' prefix. Now we need the real macros. We'll either + // get them from the macros above or from MFC/ATL. If + // SS_NO_CONVERSION is #defined, we'll forgo them + + #ifndef SS_NO_CONVERSION + + #if defined (USES_CONVERSION) + + #define _NO_STDCONVERSION // just to be consistent + + #else + + #ifdef _MFC_VER + + #include + #define _NO_STDCONVERSION // just to be consistent + + #else + + #define USES_CONVERSION SSCVT + #define A2CW SSA2CW + #define W2CA SSW2CA + #define T2A SST2A + #define A2T SSA2T + #define T2W SST2W + #define W2T SSW2T + #define T2CA SST2CA + #define A2CT SSA2CT + #define T2CW SST2CW + #define W2CT SSW2CT + #define ocslen sslen + #define ocscpy sscpy + #define T2COLE SST2COLE + #define OLE2CT SSOLE2CT + #define T2OLE SST2COLE + #define OLE2T SSOLE2CT + #define A2OLE SSA2OLE + #define OLE2A SSOLE2A + #define W2OLE SSW2OLE + #define OLE2W SSOLE2W + #define A2COLE SSA2COLE + #define OLE2CA SSOLE2CA + #define W2COLE SSW2COLE + #define OLE2CW SSOLE2CW + + #endif // #ifdef _MFC_VER + #endif // #ifndef USES_CONVERSION + #endif // #ifndef SS_NO_CONVERSION + + // Define ostring - generic name for std::basic_string + + #if !defined(ostring) && !defined(OSTRING_DEFINED) + typedef std::basic_string ostring; + #define OSTRING_DEFINED + #endif + +#endif // #ifndef SS_ANSI + +// StdCodeCvt when there's no conversion to be done +inline PSTR StdCodeCvt(PSTR pDst, PCSTR pSrc, int nChars) +{ + pDst[0] = '\0'; + std::char_traits::copy(pDst, pSrc, nChars); + if ( nChars > 0 ) + pDst[nChars] = '\0'; + + return pDst; +} +inline PSTR StdCodeCvt(PSTR pDst, PCUSTR pSrc, int nChars) +{ + return StdCodeCvt(pDst, (PCSTR)pSrc, nChars); +} +inline PUSTR StdCodeCvt(PUSTR pDst, PCSTR pSrc, int nChars) +{ + return (PUSTR)StdCodeCvt((PSTR)pDst, pSrc, nChars); +} + +inline PWSTR StdCodeCvt(PWSTR pDst, PCWSTR pSrc, int nChars) +{ + pDst[0] = '\0'; + std::char_traits::copy(pDst, pSrc, nChars); + if ( nChars > 0 ) + pDst[nChars] = '\0'; + + return pDst; +} + + +// Define tstring -- generic name for std::basic_string + +#if !defined(tstring) && !defined(TSTRING_DEFINED) + typedef std::basic_string tstring; + #define TSTRING_DEFINED +#endif + +// a very shorthand way of applying the fix for KB problem Q172398 +// (basic_string assignment bug) + +#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) + #define Q172398(x) (x).erase() +#else + #define Q172398(x) +#endif + +// ============================================================================= +// INLINE FUNCTIONS ON WHICH CSTDSTRING RELIES +// +// Usually for generic text mapping, we rely on preprocessor macro definitions +// to map to string functions. However the CStdStr<> template cannot use +// macro-based generic text mappings because its character types do not get +// resolved until template processing which comes AFTER macro processing. In +// other words, UNICODE is of little help to us in the CStdStr template +// +// Therefore, to keep the CStdStr declaration simple, we have these inline +// functions. The template calls them often. Since they are inline (and NOT +// exported when this is built as a DLL), they will probably be resolved away +// to nothing. +// +// Without these functions, the CStdStr<> template would probably have to broken +// out into two, almost identical classes. Either that or it would be a huge, +// convoluted mess, with tons of "if" statements all over the place checking the +// size of template parameter CT. +// +// In several cases, you will see two versions of each function. One version is +// the more portable, standard way of doing things, while the other is the +// non-standard, but often significantly faster Visual C++ way. +// ============================================================================= + +// If they defined SS_NO_REFCOUNT, then we must convert all assignments + +#ifdef SS_NO_REFCOUNT + #define SSREF(x) (x).c_str() +#else + #define SSREF(x) (x) +#endif + +// ----------------------------------------------------------------------------- +// sslen: strlen/wcslen wrappers +// ----------------------------------------------------------------------------- +template inline int sslen(const CT* pT) +{ + return 0 == pT ? 0 : std::char_traits::length(pT); +} +inline SS_NOTHROW int sslen(const std::string& s) +{ + return s.length(); +} +inline SS_NOTHROW int sslen(const std::wstring& s) +{ + return s.length(); +} + + +// ----------------------------------------------------------------------------- +// ssasn: assignment functions -- assign "sSrc" to "sDst" +// ----------------------------------------------------------------------------- +typedef std::string::size_type SS_SIZETYPE; // just for shorthand, really +typedef std::string::pointer SS_PTRTYPE; +typedef std::wstring::size_type SW_SIZETYPE; +typedef std::wstring::pointer SW_PTRTYPE; + +inline void ssasn(std::string& sDst, const std::string& sSrc) +{ + if ( sDst.c_str() != sSrc.c_str() ) + { + sDst.erase(); + sDst.assign(SSREF(sSrc)); + } +} +inline void ssasn(std::string& sDst, PCSTR pA) +{ + // Watch out for NULLs, as always. + + if ( 0 == pA ) + { + sDst.erase(); + } + + // If pA actually points to part of sDst, we must NOT erase(), but + // rather take a substring + + else if ( pA >= sDst.c_str() && pA <= sDst.c_str() + sDst.size() ) + { + sDst =sDst.substr(static_cast(pA-sDst.c_str())); + } + + // Otherwise (most cases) apply the assignment bug fix, if applicable + // and do the assignment + + else + { + Q172398(sDst); + sDst.assign(pA); + } +} +inline void ssasn(std::string& sDst, const std::wstring& sSrc) +{ +#ifdef SS_ANSI + int nLen = sSrc.size(); + sDst.resize(0); + sDst.resize(nLen); + StdCodeCvt(const_cast(sDst.data()), sSrc.c_str(), nLen); +#else + SSCVT; + sDst.assign(SSW2CA(sSrc.c_str())); +#endif +} +inline void ssasn(std::string& sDst, PCWSTR pW) +{ +#ifdef SS_ANSI + int nLen = sslen(pW); + sDst.resize(0); + sDst.resize(nLen); + StdCodeCvt(const_cast(sDst.data()), pW, nLen); +#else + SSCVT; + sDst.assign(pW ? SSW2CA(pW) : ""); +#endif +} +inline void ssasn(std::string& sDst, const int nNull) +{ + UNUSED(nNull); + ASSERT(nNull==0); + sDst.assign(""); +} +inline void ssasn(std::wstring& sDst, const std::wstring& sSrc) +{ + if ( sDst.c_str() != sSrc.c_str() ) + { + sDst.erase(); + sDst.assign(SSREF(sSrc)); + } +} +inline void ssasn(std::wstring& sDst, PCWSTR pW) +{ + // Watch out for NULLs, as always. + + if ( 0 == pW ) + { + sDst.erase(); + } + + // If pW actually points to part of sDst, we must NOT erase(), but + // rather take a substring + + else if ( pW >= sDst.c_str() && pW <= sDst.c_str() + sDst.size() ) + { + sDst = sDst.substr(static_cast(pW-sDst.c_str())); + } + + // Otherwise (most cases) apply the assignment bug fix, if applicable + // and do the assignment + + else + { + Q172398(sDst); + sDst.assign(pW); + } +} +#undef StrSizeType +inline void ssasn(std::wstring& sDst, const std::string& sSrc) +{ +#ifdef SS_ANSI + int nLen = sSrc.size(); + sDst.resize(0); + sDst.resize(nLen); + StdCodeCvt(const_cast(sDst.data()), sSrc.c_str(), nLen); +#else + SSCVT; + sDst.assign(SSA2CW(sSrc.c_str())); +#endif +} +inline void ssasn(std::wstring& sDst, PCSTR pA) +{ +#ifdef SS_ANSI + int nLen = sslen(pA); + sDst.resize(0); + sDst.resize(nLen); + StdCodeCvt(const_cast(sDst.data()), pA, nLen); +#else + SSCVT; + sDst.assign(pA ? SSA2CW(pA) : L""); +#endif +} +inline void ssasn(std::wstring& sDst, const int nNull) +{ + UNUSED(nNull); + ASSERT(nNull==0); + sDst.assign(L""); +} + + +// ----------------------------------------------------------------------------- +// ssadd: string object concatenation -- add second argument to first +// ----------------------------------------------------------------------------- +inline void ssadd(std::string& sDst, const std::wstring& sSrc) +{ +#ifdef SS_ANSI + int nLen = sSrc.size(); + sDst.resize(sDst.size() + nLen); + StdCodeCvt(const_cast(sDst.data()+nLen), sSrc.c_str(), nLen); +#else + SSCVT; + sDst.append(SSW2CA(sSrc.c_str())); +#endif +} +inline void ssadd(std::string& sDst, const std::string& sSrc) +{ + sDst.append(sSrc.c_str()); +} +inline void ssadd(std::string& sDst, PCWSTR pW) +{ +#ifdef SS_ANSI + int nLen = sslen(pW); + sDst.resize(sDst.size() + nLen); + StdCodeCvt(const_cast(sDst.data()+nLen), pW, nLen); +#else + SSCVT; + if ( 0 != pW ) + sDst.append(SSW2CA(pW)); +#endif +} +inline void ssadd(std::string& sDst, PCSTR pA) +{ + if ( pA ) + sDst.append(pA); +} +inline void ssadd(std::wstring& sDst, const std::wstring& sSrc) +{ + sDst.append(sSrc.c_str()); +} +inline void ssadd(std::wstring& sDst, const std::string& sSrc) +{ +#ifdef SS_ANSI + int nLen = sSrc.size(); + sDst.resize(sDst.size() + nLen); + StdCodeCvt(const_cast(sDst.data()+nLen), sSrc.c_str(), nLen); +#else + SSCVT; + sDst.append(SSA2CW(sSrc.c_str())); +#endif +} +inline void ssadd(std::wstring& sDst, PCSTR pA) +{ +#ifdef SS_ANSI + int nLen = sslen(pA); + sDst.resize(sDst.size() + nLen); + StdCodeCvt(const_cast(sDst.data()+nLen), pA, nLen); +#else + SSCVT; + if ( 0 != pA ) + sDst.append(SSA2CW(pA)); +#endif +} +inline void ssadd(std::wstring& sDst, PCWSTR pW) +{ + if ( pW ) + sDst.append(pW); +} + + +// ----------------------------------------------------------------------------- +// ssicmp: comparison (case insensitive ) +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI + template + inline int ssicmp(const CT* pA1, const CT* pA2) + { + std::locale loc; + const std::ctype& ct = SS_USE_FACET(loc, std::ctype); + CT f; + CT l; + + do + { + f = ct.tolower(*(pA1++)); + l = ct.tolower(*(pA2++)); + } while ( (f) && (f == l) ); + + return (int)(f - l); + } +#else + #ifdef _MBCS + inline long sscmp(PCSTR pA1, PCSTR pA2) + { + return _mbscmp((PCUSTR)pA1, (PCUSTR)pA2); + } + inline long ssicmp(PCSTR pA1, PCSTR pA2) + { + return _mbsicmp((PCUSTR)pA1, (PCUSTR)pA2); + } + #else + inline long sscmp(PCSTR pA1, PCSTR pA2) + { + return strcmp(pA1, pA2); + } + inline long ssicmp(PCSTR pA1, PCSTR pA2) + { + return _stricmp(pA1, pA2); + } + #endif + inline long sscmp(PCWSTR pW1, PCWSTR pW2) + { + return wcscmp(pW1, pW2); + } + inline long ssicmp(PCWSTR pW1, PCWSTR pW2) + { + return _wcsicmp(pW1, pW2); + } +#endif + +// ----------------------------------------------------------------------------- +// ssupr/sslwr: Uppercase/Lowercase conversion functions +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI + template + inline void sslwr(CT* pT, size_t nLen) + { + SS_USE_FACET(std::locale(), std::ctype).tolower(pT, pT+nLen); + } + template + inline void ssupr(CT* pT, size_t nLen) + { + SS_USE_FACET(std::locale(), std::ctype).toupper(pT, pT+nLen); + } +#else // #else we must be on Win32 + #ifdef _MBCS + inline void ssupr(PSTR pA, size_t /*nLen*/) + { + _mbsupr((PUSTR)pA); + } + inline void sslwr(PSTR pA, size_t /*nLen*/) + { + _mbslwr((PUSTR)pA); + } + #else + inline void ssupr(PSTR pA, size_t /*nLen*/) + { + _strupr(pA); + } + inline void sslwr(PSTR pA, size_t /*nLen*/) + { + _strlwr(pA); + } + #endif + inline void ssupr(PWSTR pW, size_t /*nLen*/) + { + _wcsupr(pW); + } + inline void sslwr(PWSTR pW, size_t /*nLen*/) + { + _wcslwr(pW); + } +#endif // #ifdef SS_ANSI + +// ----------------------------------------------------------------------------- +// vsprintf/vswprintf or _vsnprintf/_vsnwprintf equivalents. In standard +// builds we can't use _vsnprintf/_vsnwsprintf because they're MS extensions. +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI + inline int ssvsprintf(PSTR pA, size_t /*nCount*/, PCSTR pFmtA, va_list vl) + { + return vsprintf(pA, pFmtA, vl); + } + inline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) + { + // JMO: It is beginning to seem like Microsoft Visual C++ is the only + // CRT distribution whose version of vswprintf takes THREE arguments. + // All others seem to take FOUR arguments. Therefore instead of + // checking for every possible distro here, I'll assume that unless + // I am running with Microsoft's CRT, then vswprintf takes four + // arguments. If you get a compilation error here, then you can just + // change this code to call the three-argument version. +// #if !defined(__MWERKS__) && !defined(__SUNPRO_CC_COMPAT) && !defined(__SUNPRO_CC) + #ifndef _MSC_VER + return vswprintf(pW, nCount, pFmtW, vl); + #else + nCount; + return vswprintf(pW, pFmtW, vl); + #endif + } +#else + inline int ssnprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl) + { + return _vsnprintf(pA, nCount, pFmtA, vl); + } + inline int ssnprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) + { + return _vsnwprintf(pW, nCount, pFmtW, vl); + } +#endif + + +// ----------------------------------------------------------------------------- +// ssload: Type safe, overloaded ::LoadString wrappers +// There is no equivalent of these in non-Win32-specific builds. However, I'm +// thinking that with the message facet, there might eventually be one +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI +#else + inline int ssload(HMODULE hInst, UINT uId, PSTR pBuf, int nMax) + { + return ::LoadStringA(hInst, uId, pBuf, nMax); + } + inline int ssload(HMODULE hInst, UINT uId, PWSTR pBuf, int nMax) + { + return ::LoadStringW(hInst, uId, pBuf, nMax); + } +#endif + + +// ----------------------------------------------------------------------------- +// sscoll/ssicoll: Collation wrappers +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI + template + inline int sscoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2) + { + const std::collate& coll = + SS_USE_FACET(std::locale(), std::collate); + return coll.compare(sz1, sz1+nLen1, sz2, sz2+nLen2); + } + template + inline int ssicoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2) + { + const std::locale loc; + const std::collate& coll = SS_USE_FACET(loc, std::collate); + + // Some implementations seem to have trouble using the collate<> + // facet typedefs so we'll just default to basic_string and hope + // that's what the collate facet uses (which it generally should) + +// std::collate::string_type s1(sz1); +// std::collate::string_type s2(sz2); + std::basic_string s1(sz1); + std::basic_string s2(sz2); + + sslwr(const_cast(s1.c_str()), nLen1); + sslwr(const_cast(s2.c_str()), nLen2); + return coll.compare(s1.c_str(), s1.c_str()+nLen1, + s2.c_str(), s2.c_str()+nLen2); + } +#else + #ifdef _MBCS + inline int sscoll(PCSTR sz1, int /*nLen1*/, PCSTR sz2, int /*nLen2*/) + { + return _mbscoll((PCUSTR)sz1, (PCUSTR)sz2); + } + inline int ssicoll(PCSTR sz1, int /*nLen1*/, PCSTR sz2, int /*nLen2*/) + { + return _mbsicoll((PCUSTR)sz1, (PCUSTR)sz2); + } + #else + inline int sscoll(PCSTR sz1, int /*nLen1*/, PCSTR sz2, int /*nLen2*/) + { + return strcoll(sz1, sz2); + } + inline int ssicoll(PCSTR sz1, int /*nLen1*/, PCSTR sz2, int /*nLen2*/) + { + return _stricoll(sz1, sz2); + } + #endif + inline int sscoll(PCWSTR sz1, int /*nLen1*/, PCWSTR sz2, int /*nLen2*/) + { + return wcscoll(sz1, sz2); + } + inline int ssicoll(PCWSTR sz1, int /*nLen1*/, PCWSTR sz2, int /*nLen2*/) + { + return _wcsicoll(sz1, sz2); + } +#endif + + +// ----------------------------------------------------------------------------- +// ssfmtmsg: FormatMessage equivalents. Needed because I added a CString facade +// Again -- no equivalent of these on non-Win32 builds but their might one day +// be one if the message facet gets implemented +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI +#else + inline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId, + DWORD dwLangId, PSTR pBuf, DWORD nSize, + va_list* vlArgs) + { + return FormatMessageA(dwFlags, pSrc, dwMsgId, dwLangId, + pBuf, nSize,vlArgs); + } + inline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId, + DWORD dwLangId, PWSTR pBuf, DWORD nSize, + va_list* vlArgs) + { + return FormatMessageW(dwFlags, pSrc, dwMsgId, dwLangId, + pBuf, nSize,vlArgs); + } +#endif + + + +// FUNCTION: sscpy. Copies up to 'nMax' characters from pSrc to pDst. +// ----------------------------------------------------------------------------- +// FUNCTION: sscpy +// inline int sscpy(PSTR pDst, PCSTR pSrc, int nMax=-1); +// inline int sscpy(PUSTR pDst, PCSTR pSrc, int nMax=-1) +// inline int sscpy(PSTR pDst, PCWSTR pSrc, int nMax=-1); +// inline int sscpy(PWSTR pDst, PCWSTR pSrc, int nMax=-1); +// inline int sscpy(PWSTR pDst, PCSTR pSrc, int nMax=-1); +// +// DESCRIPTION: +// This function is very much (but not exactly) like strcpy. These +// overloads simplify copying one C-style string into another by allowing +// the caller to specify two different types of strings if necessary. +// +// The strings must NOT overlap +// +// "Character" is expressed in terms of the destination string, not +// the source. If no 'nMax' argument is supplied, then the number of +// characters copied will be sslen(pSrc). A NULL terminator will +// also be added so pDst must actually be big enough to hold nMax+1 +// characters. The return value is the number of characters copied, +// not including the NULL terminator. +// +// PARAMETERS: +// pSrc - the string to be copied FROM. May be a char based string, an +// MBCS string (in Win32 builds) or a wide string (wchar_t). +// pSrc - the string to be copied TO. Also may be either MBCS or wide +// nMax - the maximum number of characters to be copied into szDest. Note +// that this is expressed in whatever a "character" means to pDst. +// If pDst is a wchar_t type string than this will be the maximum +// number of wchar_ts that my be copied. The pDst string must be +// large enough to hold least nMaxChars+1 characters. +// If the caller supplies no argument for nMax this is a signal to +// the routine to copy all the characters in pSrc, regardless of +// how long it is. +// +// RETURN VALUE: none +// ----------------------------------------------------------------------------- +template +inline int sscpycvt(CT1* pDst, const CT2* pSrc, int nChars) +{ + StdCodeCvt(pDst, pSrc, nChars); + pDst[SSMAX(nChars, 0)] = '\0'; + return nChars; +} + +template +inline int sscpy(CT1* pDst, const CT2* pSrc, int nMax, int nLen) +{ + return sscpycvt(pDst, pSrc, SSMIN(nMax, nLen)); +} +template +inline int sscpy(CT1* pDst, const CT2* pSrc, int nMax) +{ + return sscpycvt(pDst, pSrc, SSMIN(nMax, sslen(pSrc))); +} +template +inline int sscpy(CT1* pDst, const CT2* pSrc) +{ + return sscpycvt(pDst, pSrc, sslen(pSrc)); +} +template +inline int sscpy(CT1* pDst, const std::basic_string& sSrc, int nMax) +{ + return sscpycvt(pDst, sSrc.c_str(), SSMIN(nMax, (int)sSrc.length())); +} +template +inline int sscpy(CT1* pDst, const std::basic_string& sSrc) +{ + return sscpycvt(pDst, sSrc.c_str(), (int)sSrc.length()); +} + +#ifdef SS_INC_COMDEF + template + inline int sscpy(CT1* pDst, const _bstr_t& bs, int nMax) + { + return sscpycvt(pDst, static_cast(bs), SSMIN(nMax, (int)bs.length())); + } + template + inline int sscpy(CT1* pDst, const _bstr_t& bs) + { + return sscpy(pDst, bs, bs.length()); + } +#endif + + +// ----------------------------------------------------------------------------- +// Functional objects for changing case. They also let you pass locales +// ----------------------------------------------------------------------------- + +#ifdef SS_ANSI + template + struct SSToUpper : public std::binary_function + { + inline CT operator()(const CT& t, const std::locale& loc) const + { + return std::toupper(t, loc); + } + }; + template + struct SSToLower : public std::binary_function + { + inline CT operator()(const CT& t, const std::locale& loc) const + { + return std::tolower(t, loc); + } + }; +#endif + +// This struct is used for TrimRight() and TrimLeft() function implementations. +//template +//struct NotSpace : public std::unary_function +//{ +// const std::locale& loc; +// inline NotSpace(const std::locale& locArg) : loc(locArg) {} +// inline bool operator() (CT t) { return !std::isspace(t, loc); } +//}; +template +struct NotSpace : public std::unary_function +{ + const std::locale& loc; + NotSpace(const std::locale& locArg) : loc(locArg) {} + + // DINKUMWARE BUG: + // Note -- using std::isspace in a COM DLL gives us access violations + // because it causes the dynamic addition of a function to be called + // when the library shuts down. Unfortunately the list is maintained + // in DLL memory but the function is in static memory. So the COM DLL + // goes away along with the function that was supposed to be called, + // and then later when the DLL CRT shuts down it unloads the list and + // tries to call the long-gone function. + // This is DinkumWare's implementation problem. Until then, we will + // use good old isspace and iswspace from the CRT unless they + // specify SS_ANSI +#ifdef SS_ANSI + bool operator() (CT t) const { return !std::isspace(t, loc); } +#else + bool ssisp(char c) const { return FALSE != ::isspace((int) c); } + bool ssisp(wchar_t c) const { return FALSE != ::iswspace((wint_t) c); } + bool operator()(CT t) const { return !ssisp(t); } +#endif +}; + + + + +// Now we can define the template (finally!) +// ============================================================================= +// TEMPLATE: CStdStr +// template class CStdStr : public std::basic_string +// +// REMARKS: +// This template derives from basic_string and adds some MFC CString- +// like functionality +// +// Basically, this is my attempt to make Standard C++ library strings as +// easy to use as the MFC CString class. +// +// Note that although this is a template, it makes the assumption that the +// template argument (CT, the character type) is either char or wchar_t. +// ============================================================================= + +//#define CStdStr _SS // avoid compiler warning 4786 + + +template +class CStdStr : public std::basic_string +{ + // Typedefs for shorter names. Using these names also appears to help + // us avoid some ambiguities that otherwise arise on some platforms + + typedef typename std::basic_string MYBASE; // my base class + typedef CStdStr MYTYPE; // myself + typedef typename MYBASE::const_pointer PCMYSTR; // PCSTR or PCWSTR + typedef typename MYBASE::pointer PMYSTR; // PSTR or PWSTR + typedef typename MYBASE::iterator MYITER; // my iterator type + typedef typename MYBASE::const_iterator MYCITER; // you get the idea... + typedef typename MYBASE::reverse_iterator MYRITER; + typedef typename MYBASE::size_type MYSIZE; + typedef typename MYBASE::value_type MYVAL; + typedef typename MYBASE::allocator_type MYALLOC; + +public: + + // shorthand conversion from PCTSTR to string resource ID + #define _TRES(pctstr) (LOWORD((DWORD)(pctstr))) + + // CStdStr inline constructors + CStdStr() + { + } + + CStdStr(const MYTYPE& str) : MYBASE(SSREF(str)) + { + } + + CStdStr(const std::string& str) + { + ssasn(*this, SSREF(str)); + } + + CStdStr(const std::wstring& str) + { + ssasn(*this, SSREF(str)); + } + + CStdStr(PCMYSTR pT, MYSIZE n) : MYBASE(pT, n) + { + } + + CStdStr(PCSTR pA) + { + #ifdef SS_ANSI + *this = pA; + #else + if ( 0 != HIWORD(pA) ) + *this = pA; + else if ( 0 != pA && !Load(_TRES(pA)) ) + TRACE(_T("Can't load string %u\n"), _TRES(pA)); + #endif + } + + CStdStr(PCWSTR pW) + { + #ifdef SS_ANSI + *this = pW; + #else + if ( 0 != HIWORD(pW) ) + *this = pW; + else if ( 0 != pW && !Load(_TRES(pW)) ) + TRACE(_T("Can't load string %u\n"), _TRES(pW)); + #endif + } + + CStdStr(MYCITER first, MYCITER last) + : MYBASE(first, last) + { + } + + CStdStr(MYSIZE nSize, MYVAL ch, const MYALLOC& al=MYALLOC()) + : MYBASE(nSize, ch, al) + { + } + + #ifdef SS_INC_COMDEF + CStdStr(const _bstr_t& bstr) + { + if ( bstr.length() > 0 ) + append(static_cast(bstr), bstr.length()); + } + #endif + + // CStdStr inline assignment operators -- the ssasn function now takes care + // of fixing the MSVC assignment bug (see knowledge base article Q172398). + MYTYPE& operator=(const MYTYPE& str) + { + ssasn(*this, str); + return *this; + } + + MYTYPE& operator=(const std::string& str) + { + ssasn(*this, str); + return *this; + } + + MYTYPE& operator=(const std::wstring& str) + { + ssasn(*this, str); + return *this; + } + + MYTYPE& operator=(PCSTR pA) + { + ssasn(*this, pA); + return *this; + } + + MYTYPE& operator=(PCWSTR pW) + { + ssasn(*this, pW); + return *this; + } + + MYTYPE& operator=(CT t) + { + Q172398(*this); + MYBASE::assign(1, t); + return *this; + } + + #ifdef SS_INC_COMDEF + MYTYPE& operator=(const _bstr_t& bstr) + { + if ( bstr.length() > 0 ) + return assign(static_cast(bstr), bstr.length()); + else + { + erase(); + return *this; + } + } + #endif + + + // Overloads also needed to fix the MSVC assignment bug (KB: Q172398) + // *** Thanks to Pete The Plumber for catching this one *** + // They also are compiled if you have explicitly turned off refcounting + #if ( defined(_MSC_VER) && ( _MSC_VER < 1200 ) ) || defined(SS_NO_REFCOUNT) + + MYTYPE& assign(const MYTYPE& str) + { + ssasn(*this, str); + return *this; + } + + MYTYPE& assign(const MYTYPE& str, MYSIZE nStart, MYSIZE nChars) + { + // This overload of basic_string::assign is supposed to assign up to + // or the NULL terminator, whichever comes first. Since we + // are about to call a less forgiving overload (in which + // must be a valid length), we must adjust the length here to a safe + // value. Thanks to Ullrich Pollhne for catching this bug + + nChars = SSMIN(nChars, str.length() - nStart); + + // Watch out for assignment to self + + if ( this == &str ) + { + MYTYPE strTemp(str.c_str()+nStart, nChars); + assign(strTemp); + } + else + { + Q172398(*this); + MYBASE::assign(str.c_str()+nStart, nChars); + } + return *this; + } + + MYTYPE& assign(const MYBASE& str) + { + ssasn(*this, str); + return *this; + } + + MYTYPE& assign(const MYBASE& str, MYSIZE nStart, MYSIZE nChars) + { + // This overload of basic_string::assign is supposed to assign up to + // or the NULL terminator, whichever comes first. Since we + // are about to call a less forgiving overload (in which + // must be a valid length), we must adjust the length here to a safe + // value. Thanks to Ullrich Pollhne for catching this bug + + nChars = SSMIN(nChars, str.length() - nStart); + + // Watch out for assignment to self + + if ( this == &str ) // watch out for assignment to self + { + MYTYPE strTemp(str.c_str() + nStart, nChars); + assign(strTemp); + } + else + { + Q172398(*this); + MYBASE::assign(str.c_str()+nStart, nChars); + } + return *this; + } + + MYTYPE& assign(const CT* pC, MYSIZE nChars) + { + // Q172398 only fix -- erase before assigning, but not if we're + // assigning from our own buffer + + #if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) + if ( !empty() && ( pC < data() || pC > data() + capacity() ) ) + erase(); + #endif + Q172398(*this); + MYBASE::assign(pC, nChars); + return *this; + } + + MYTYPE& assign(MYSIZE nChars, MYVAL val) + { + Q172398(*this); + MYBASE::assign(nChars, val); + return *this; + } + + MYTYPE& assign(const CT* pT) + { + return assign(pT, CStdStr::traits_type::length(pT)); + } + + MYTYPE& assign(MYCITER iterFirst, MYCITER iterLast) + { + #if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) + // Q172398 fix. don't call erase() if we're assigning from ourself + if ( iterFirst < begin() || iterFirst > begin() + size() ) + erase() + #endif + replace(begin(), end(), iterFirst, iterLast); + return *this; + } + #endif + + + // ------------------------------------------------------------------------- + // CStdStr inline concatenation. + // ------------------------------------------------------------------------- + MYTYPE& operator+=(const MYTYPE& str) + { + ssadd(*this, str); + return *this; + } + + MYTYPE& operator+=(const std::string& str) + { + ssadd(*this, str); + return *this; + } + + MYTYPE& operator+=(const std::wstring& str) + { + ssadd(*this, str); + return *this; + } + + MYTYPE& operator+=(PCSTR pA) + { + ssadd(*this, pA); + return *this; + } + + MYTYPE& operator+=(PCWSTR pW) + { + ssadd(*this, pW); + return *this; + } + + MYTYPE& operator+=(CT t) + { + append(1, t); + return *this; + } + #ifdef SS_INC_COMDEF // if we have _bstr_t, define a += for it too. + MYTYPE& operator+=(const _bstr_t& bstr) + { + return operator+=(static_cast(bstr)); + } + #endif + + + // addition operators -- global friend functions. + + friend MYTYPE operator+(const MYTYPE& str1, const MYTYPE& str2); + friend MYTYPE operator+(const MYTYPE& str, CT t); + friend MYTYPE operator+(const MYTYPE& str, PCSTR sz); + friend MYTYPE operator+(const MYTYPE& str, PCWSTR sz); + friend MYTYPE operator+(PCSTR pA, const MYTYPE& str); + friend MYTYPE operator+(PCWSTR pW, const MYTYPE& str); +#ifdef SS_INC_COMDEF + friend MYTYPE operator+(const _bstr_t& bstr, const MYTYPE& str); + friend MYTYPE operator+(const MYTYPE& str, const _bstr_t& bstr); +#endif + + // ------------------------------------------------------------------------- + // Case changing functions + // ------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + MYTYPE& ToUpper() + { + // Strictly speaking, this would be about the most portable way + + // std::transform(begin(), + // end(), + // begin(), + // std::bind2nd(SSToUpper(), std::locale())); + + // But practically speaking, this works faster + + if ( !empty() ) + ssupr(GetBuf(), size()); + + return *this; + } + + + + MYTYPE& ToLower() + { + // Strictly speaking, this would be about the most portable way + + // std::transform(begin(), + // end(), + // begin(), + // std::bind2nd(SSToLower(), std::locale())); + + // But practically speaking, this works faster + + if ( !empty() ) + sslwr(GetBuf(), size()); + + return *this; + } + + + + MYTYPE& Normalize() + { + return Trim().ToLower(); + } + + + // ------------------------------------------------------------------------- + // CStdStr -- Direct access to character buffer. In the MS' implementation, + // the at() function that we use here also calls _Freeze() providing us some + // protection from multithreading problems associated with ref-counting. + // ------------------------------------------------------------------------- + CT* GetBuf(int nMinLen=-1) + { + if ( static_cast(size()) < nMinLen ) + resize(static_cast(nMinLen)); + + return empty() ? const_cast(data()) : &(at(0)); + } + + CT* SetBuf(int nLen) + { + nLen = ( nLen > 0 ? nLen : 0 ); + if ( capacity() < 1 && nLen == 0 ) + resize(1); + + resize(static_cast(nLen)); + return const_cast(data()); + } + void RelBuf(int nNewLen=-1) + { + resize(static_cast(nNewLen > -1 ? nNewLen : sslen(c_str()))); + } + + void BufferRel() { RelBuf(); } // backwards compatability + CT* Buffer() { return GetBuf(); } // backwards compatability + CT* BufferSet(int nLen) { return SetBuf(nLen);}// backwards compatability + + bool Equals(const CT* pT, bool bUseCase=false) const + { // get copy, THEN compare (thread safe) + return bUseCase ? compare(pT) == 0 : ssicmp(MYTYPE(*this), pT) == 0; + } + + // ------------------------------------------------------------------------- + // FUNCTION: CStdStr::Load + // REMARKS: + // Loads string from resource specified by nID + // + // PARAMETERS: + // nID - resource Identifier. Purely a Win32 thing in this case + // + // RETURN VALUE: + // true if successful, false otherwise + // ------------------------------------------------------------------------- +#ifndef SS_ANSI + bool Load(UINT nId, HMODULE hModule=NULL) + { + bool bLoaded = false; // set to true of we succeed. + + #ifdef _MFC_VER // When in Rome... + + CString strRes; + bLoaded = FALSE != strRes.LoadString(nId); + if ( bLoaded ) + *this = strRes; + + #else + + // Get the resource name and module handle + + if ( NULL == hModule ) + hModule = GetResourceHandle(); + + PCTSTR szName = MAKEINTRESOURCE((nId>>4)+1); // lifted + DWORD dwSize = 0; + + // No sense continuing if we can't find the resource + + HRSRC hrsrc = ::FindResource(hModule, szName, RT_STRING); + + if ( NULL == hrsrc ) + TRACE(_T("Cannot find resource %d: 0x%X"), nId, ::GetLastError()); + else if ( 0 == (dwSize = ::SizeofResource(hModule, hrsrc) / sizeof(CT))) + TRACE(_T("Cant get size of resource %d 0x%X\n"),nId,GetLastError()); + else + { + bLoaded = 0 != ssload(hModule, nId, GetBuf(dwSize), dwSize); + ReleaseBuffer(); + } + + #endif + + if ( !bLoaded ) + TRACE(_T("String not loaded 0x%X\n"), ::GetLastError()); + + return bLoaded; + } +#endif + + // ------------------------------------------------------------------------- + // FUNCTION: CStdStr::Format + // void _cdecl Formst(CStdStringA& PCSTR szFormat, ...) + // void _cdecl Format(PCSTR szFormat); + // + // DESCRIPTION: + // This function does sprintf/wsprintf style formatting on CStdStringA + // objects. It looks a lot like MFC's CString::Format. Some people + // might even call this identical. Fortunately, these people are now + // dead. + // + // PARAMETERS: + // nId - ID of string resource holding the format string + // szFormat - a PCSTR holding the format specifiers + // argList - a va_list holding the arguments for the format specifiers. + // + // RETURN VALUE: None. + // ------------------------------------------------------------------------- + // formatting (using wsprintf style formatting) + #ifndef SS_ANSI + void Format(UINT nId, ...) + { + va_list argList; + va_start(argList, nId); + va_start(argList, nId); + + MYTYPE strFmt; + if ( strFmt.Load(nId) ) + FormatV(strFmt, argList); + + va_end(argList); + } + #endif + void Format(const CT* szFmt, ...) + { + va_list argList; + va_start(argList, szFmt); + FormatV(szFmt, argList); + va_end(argList); + } + void AppendFormat(const CT* szFmt, ...) + { + va_list argList; + va_start(argList, szFmt); + AppendFormatV(szFmt, argList); + va_end(argList); + } + + #define MAX_FMT_TRIES 5 // #of times we try + #define FMT_BLOCK_SIZE 2048 // # of bytes to increment per try + #define BUFSIZE_1ST 256 + #define BUFSIZE_2ND 512 + #define STD_BUF_SIZE 1024 + + // an efficient way to add formatted characters to the string. You may only + // add up to STD_BUF_SIZE characters at a time, though + void AppendFormatV(const CT* szFmt, va_list argList) + { + CT szBuf[STD_BUF_SIZE]; + #ifdef SS_ANSI + int nLen = ssvsprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList); + #else + int nLen = ssnprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList); + #endif + if ( 0 < nLen ) + append(szBuf, nLen); + } + + // ------------------------------------------------------------------------- + // FUNCTION: FormatV + // void FormatV(PCSTR szFormat, va_list, argList); + // + // DESCRIPTION: + // This function formats the string with sprintf style format-specs. + // It makes a general guess at required buffer size and then tries + // successively larger buffers until it finds one big enough or a + // threshold (MAX_FMT_TRIES) is exceeded. + // + // PARAMETERS: + // szFormat - a PCSTR holding the format of the output + // argList - a Microsoft specific va_list for variable argument lists + // + // RETURN VALUE: + // ------------------------------------------------------------------------- + + void FormatV(const CT* szFormat, va_list argList) + { + #ifdef SS_ANSI + + int nLen = sslen(szFormat) + STD_BUF_SIZE; + ssvsprintf(GetBuffer(nLen), nLen-1, szFormat, argList); + ReleaseBuffer(); + + #else + + CT* pBuf = NULL; + int nChars = 1; + int nUsed = 0; + size_type nActual = 0; + int nTry = 0; + + do + { + // Grow more than linearly (e.g. 512, 1536, 3072, etc) + + nChars += ((nTry+1) * FMT_BLOCK_SIZE); + pBuf = reinterpret_cast(_alloca(sizeof(CT)*nChars)); + nUsed = ssnprintf(pBuf, nChars-1, szFormat, argList); + + // Ensure proper NULL termination. + + nActual = nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1); + pBuf[nActual+1]= '\0'; + + + } while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES ); + + // assign whatever we managed to format + + assign(pBuf, nActual); + + #endif + } + + + // ------------------------------------------------------------------------- + // CString Facade Functions: + // + // The following methods are intended to allow you to use this class as a + // drop-in replacement for CString. + // ------------------------------------------------------------------------- + #ifndef SS_ANSI + BSTR AllocSysString() const + { + ostring os; + ssasn(os, *this); + return ::SysAllocString(os.c_str()); + } + #endif + + int Collate(PCMYSTR szThat) const + { + return sscoll(c_str(), length(), szThat, sslen(szThat)); + } + + int CollateNoCase(PCMYSTR szThat) const + { + return ssicoll(c_str(), length(), szThat, sslen(szThat)); + } + + int Compare(PCMYSTR szThat) const + { + return MYBASE::compare(szThat); + } + + int CompareNoCase(PCMYSTR szThat) const + { + return ssicmp(c_str(), szThat); + } + + int Delete(int nIdx, int nCount=1) + { + if ( nIdx < GetLength() ) + erase(static_cast(nIdx), static_cast(nCount)); + + return GetLength(); + } + + void Empty() + { + erase(); + } + + int Find(CT ch) const + { + MYSIZE nIdx = find_first_of(ch); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + int Find(PCMYSTR szSub) const + { + MYSIZE nIdx = find(szSub); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + int Find(CT ch, int nStart) const + { + // CString::Find docs say add 1 to nStart when it's not zero + // CString::Find code doesn't do that however. We'll stick + // with what the code does + + MYSIZE nIdx = find_first_of(ch, static_cast(nStart)); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + int Find(PCMYSTR szSub, int nStart) const + { + // CString::Find docs say add 1 to nStart when it's not zero + // CString::Find code doesn't do that however. We'll stick + // with what the code does + + MYSIZE nIdx = find(szSub, static_cast(nStart)); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + int FindOneOf(PCMYSTR szCharSet) const + { + MYSIZE nIdx = find_first_of(szCharSet); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + +#ifndef SS_ANSI + void FormatMessage(PCMYSTR szFormat, ...) throw(std::exception) + { + va_list argList; + va_start(argList, szFormat); + PMYSTR szTemp; + if ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER, + szFormat, 0, 0, + reinterpret_cast(&szTemp), 0, &argList) == 0 || + szTemp == 0 ) + { + throw std::runtime_error("out of memory"); + } + *this = szTemp; + LocalFree(szTemp); + va_end(argList); + } + + void FormatMessage(UINT nFormatId, ...) throw(std::exception) + { + MYTYPE sFormat; + VERIFY(sFormat.LoadString(nFormatId) != 0); + va_list argList; + va_start(argList, nFormatId); + PMYSTR szTemp; + if ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER, + sFormat, 0, 0, + reinterpret_cast(&szTemp), 0, &argList) == 0 || + szTemp == 0) + { + throw std::runtime_error("out of memory"); + } + *this = szTemp; + LocalFree(szTemp); + va_end(argList); + } +#endif + + + // ------------------------------------------------------------------------- + // GetXXXX -- Direct access to character buffer + // ------------------------------------------------------------------------- + CT GetAt(int nIdx) const + { + return at(static_cast(nIdx)); + } + + CT* GetBuffer(int nMinLen=-1) + { + return GetBuf(nMinLen); + } + + CT* GetBufferSetLength(int nLen) + { + return BufferSet(nLen); + } + + // GetLength() -- MFC docs say this is the # of BYTES but + // in truth it is the number of CHARACTERs (chars or wchar_ts) + int GetLength() const + { + return static_cast(length()); + } + + + int Insert(int nIdx, CT ch) + { + if ( static_cast(nIdx) > size() -1 ) + append(1, ch); + else + insert(static_cast(nIdx), 1, ch); + + return GetLength(); + } + int Insert(int nIdx, PCMYSTR sz) + { + if ( nIdx >= size() ) + append(sz, sslen(sz)); + else + insert(static_cast(nIdx), sz); + + return GetLength(); + } + + bool IsEmpty() const + { + return empty(); + } + + MYTYPE Left(int nCount) const + { + return substr(0, static_cast(nCount)); + } + + #ifndef SS_ANSI + bool LoadString(UINT nId) + { + return this->Load(nId); + } + #endif + + void MakeLower() + { + ToLower(); + } + + void MakeReverse() + { + std::reverse(begin(), end()); + } + + void MakeUpper() + { + ToUpper(); + } + + MYTYPE Mid(int nFirst ) const + { + return substr(static_cast(nFirst)); + } + + MYTYPE Mid(int nFirst, int nCount) const + { + return substr(static_cast(nFirst), static_cast(nCount)); + } + + void ReleaseBuffer(int nNewLen=-1) + { + RelBuf(nNewLen); + } + + int Remove(CT ch) + { + MYSIZE nIdx = 0; + int nRemoved = 0; + while ( (nIdx=find_first_of(ch)) != MYBASE::npos ) + { + erase(nIdx, 1); + nRemoved++; + } + return nRemoved; + } + + int Replace(CT chOld, CT chNew) + { + int nReplaced = 0; + for ( MYITER iter=begin(); iter != end(); iter++ ) + { + if ( *iter == chOld ) + { + *iter = chNew; + nReplaced++; + } + } + return nReplaced; + } + + int Replace(PCMYSTR szOld, PCMYSTR szNew) + { + int nReplaced = 0; + MYSIZE nIdx = 0; + MYSIZE nOldLen = sslen(szOld); + if ( 0 == nOldLen ) + return 0; + + static const CT ch = CT(0); + MYSIZE nNewLen = sslen(szNew); + PCMYSTR szRealNew = szNew == 0 ? &ch : szNew; + + while ( (nIdx=find(szOld, nIdx)) != MYBASE::npos ) + { + replace(begin()+nIdx, begin()+nIdx+nOldLen, szRealNew); + nReplaced++; + nIdx += nNewLen; + } + return nReplaced; + } + + int ReverseFind(CT ch) const + { + MYSIZE nIdx = find_last_of(ch); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + // ReverseFind overload that's not in CString but might be useful + int ReverseFind(PCMYSTR szFind, MYSIZE pos=MYBASE::npos) const + { + MYSIZE nIdx = rfind(0 == szFind ? MYTYPE() : szFind, pos); + return static_cast(MYBASE::npos == nIdx ? -1 : nIdx); + } + + MYTYPE Right(int nCount) const + { + nCount = SSMIN(nCount, static_cast(size())); + return substr(size()-static_cast(nCount)); + } + + void SetAt(int nIndex, CT ch) + { + ASSERT(size() > static_cast(nIndex)); + at(static_cast(nIndex)) = ch; + } + + #ifndef SS_ANSI + BSTR SetSysString(BSTR* pbstr) const + { + ostring os; + ssasn(os, *this); + if ( !::SysReAllocStringLen(pbstr, os.c_str(), os.length()) ) + throw std::runtime_error("out of memory"); + + ASSERT(*pbstr != 0); + return *pbstr; + } + #endif + + MYTYPE SpanExcluding(PCMYSTR szCharSet) const + { + return Left(find_first_of(szCharSet)); + } + + MYTYPE SpanIncluding(PCMYSTR szCharSet) const + { + return Left(find_first_not_of(szCharSet)); + } + + #if !defined(UNICODE) && !defined(SS_ANSI) + + // CString's OemToAnsi and AnsiToOem functions are available only in + // Unicode builds. However since we're a template we also need a + // runtime check of CT and a reinterpret_cast to account for the fact + // that CStdStringW gets instantiated even in non-Unicode builds. + + void AnsiToOem() + { + if ( sizeof(CT) == sizeof(char) && !empty() ) + { + ::CharToOem(reinterpret_cast(c_str()), + reinterpret_cast(GetBuf())); + } + else + { + ASSERT(false); + } + } + + void OemToAnsi() + { + if ( sizeof(CT) == sizeof(char) && !empty() ) + { + ::OemToChar(reinterpret_cast(c_str()), + reinterpret_cast(GetBuf())); + } + else + { + ASSERT(false); + } + } + + #endif + + + // ------------------------------------------------------------------------- + // Trim and its variants + // ------------------------------------------------------------------------- + MYTYPE& Trim() + { + return TrimLeft().TrimRight(); + } + + MYTYPE& TrimLeft() + { + erase(begin(), std::find_if(begin(),end(),NotSpace(std::locale()))); + return *this; + } + + MYTYPE& TrimLeft(CT tTrim) + { + erase(0, find_first_not_of(tTrim)); + return *this; + } + + MYTYPE& TrimLeft(PCMYSTR szTrimChars) + { + erase(0, find_first_not_of(szTrimChars)); + return *this; + } + + MYTYPE& TrimRight() + { + std::locale loc; + MYRITER it = std::find_if(rbegin(), rend(), NotSpace(loc)); + if ( rend() != it ) + erase(rend() - it); + + erase(it != rend() ? find_last_of(*it) + 1 : 0); + return *this; + } + + MYTYPE& TrimRight(CT tTrim) + { + MYSIZE nIdx = find_last_not_of(tTrim); + erase(MYBASE::npos == nIdx ? 0 : ++nIdx); + return *this; + } + + MYTYPE& TrimRight(PCMYSTR szTrimChars) + { + MYSIZE nIdx = find_last_not_of(szTrimChars); + erase(MYBASE::npos == nIdx ? 0 : ++nIdx); + return *this; + } + + void FreeExtra() + { + MYTYPE mt; + swap(mt); + if ( !mt.empty() ) + assign(mt.c_str(), mt.size()); + } + + // I have intentionally not implemented the following CString + // functions. You cannot make them work without taking advantage + // of implementation specific behavior. However if you absolutely + // MUST have them, uncomment out these lines for "sort-of-like" + // their behavior. You're on your own. + +// CT* LockBuffer() { return GetBuf(); }// won't really lock +// void UnlockBuffer(); { } // why have UnlockBuffer w/o LockBuffer? + + // Array-indexing operators. Required because we defined an implicit cast + // to operator const CT* (Thanks to Julian Selman for pointing this out) + CT& operator[](int nIdx) + { + return MYBASE::operator[](static_cast(nIdx)); + } + + const CT& operator[](int nIdx) const + { + return MYBASE::operator[](static_cast(nIdx)); + } + + CT& operator[](unsigned int nIdx) + { + return MYBASE::operator[](static_cast(nIdx)); + } + + const CT& operator[](unsigned int nIdx) const + { + return MYBASE::operator[](static_cast(nIdx)); + } + + operator const CT*() const + { + return c_str(); + } + + // IStream related functions. Useful in IPersistStream implementations + +#ifdef SS_INC_COMDEF + + // struct SSSHDR - useful for non Std C++ persistence schemes. + typedef struct SSSHDR + { + BYTE byCtrl; + ULONG nChars; + } SSSHDR; // as in "Standard String Stream Header" + + #define SSSO_UNICODE 0x01 // the string is a wide string + #define SSSO_COMPRESS 0x02 // the string is compressed + + // ------------------------------------------------------------------------- + // FUNCTION: StreamSize + // REMARKS: + // Returns how many bytes it will take to StreamSave() this CStdString + // object to an IStream. + // ------------------------------------------------------------------------- + ULONG StreamSize() const + { + // Control header plus string + ASSERT(size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR)); + return (size() * sizeof(CT)) + sizeof(SSSHDR); + } + + // ------------------------------------------------------------------------- + // FUNCTION: StreamSave + // REMARKS: + // Saves this CStdString object to a COM IStream. + // ------------------------------------------------------------------------- + HRESULT StreamSave(IStream* pStream) const + { + ASSERT(size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR)); + HRESULT hr = E_FAIL; + ASSERT(pStream != 0); + SSSHDR hdr; + hdr.byCtrl = sizeof(CT) == 2 ? SSSO_UNICODE : 0; + hdr.nChars = size(); + + + if ( FAILED(hr=pStream->Write(&hdr, sizeof(SSSHDR), 0)) ) + TRACE(_T("StreamSave: Cannot write control header, ERR=0x%X\n"),hr); + else if ( empty() ) + ; // nothing to write + else if ( FAILED(hr=pStream->Write(c_str(), size()*sizeof(CT), 0)) ) + TRACE(_T("StreamSave: Cannot write string to stream 0x%X\n"), hr); + + return hr; + } + + + // ------------------------------------------------------------------------- + // FUNCTION: StreamLoad + // REMARKS: + // This method loads the object from an IStream. + // ------------------------------------------------------------------------- + HRESULT StreamLoad(IStream* pStream) + { + ASSERT(pStream != 0); + SSSHDR hdr; + HRESULT hr = E_FAIL; + + if ( FAILED(hr=pStream->Read(&hdr, sizeof(SSSHDR), 0)) ) + { + TRACE(_T("StreamLoad: Cant read control header, ERR=0x%X\n"), hr); + } + else if ( hdr.nChars > 0 ) + { + ULONG nRead = 0; + PMYSTR pMyBuf = BufferSet(hdr.nChars); + + // If our character size matches the character size of the string + // we're trying to read, then we can read it directly into our + // buffer. Otherwise, we have to read into an intermediate buffer + // and convert. + + if ( (hdr.byCtrl & SSSO_UNICODE) != 0 ) + { + ULONG nBytes = hdr.nChars * sizeof(wchar_t); + if ( sizeof(CT) == sizeof(wchar_t) ) + { + if ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) ) + TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); + } + else + { + PWSTR pBufW = reinterpret_cast(_alloca((nBytes)+1)); + if ( FAILED(hr=pStream->Read(pBufW, nBytes, &nRead)) ) + TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); + else + sscpy(pMyBuf, pBufW, hdr.nChars); + } + } + else + { + ULONG nBytes = hdr.nChars * sizeof(char); + if ( sizeof(CT) == sizeof(char) ) + { + if ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) ) + TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); + } + else + { + PSTR pBufA = reinterpret_cast(_alloca(nBytes)); + if ( FAILED(hr=pStream->Read(pBufA, hdr.nChars, &nRead)) ) + TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); + else + sscpy(pMyBuf, pBufA, hdr.nChars); + } + } + } + else + { + this->erase(); + } + return hr; + } +#endif // #ifdef SS_INC_COMDEF + +#ifndef SS_ANSI + + // SetResourceHandle/GetResourceHandle. In MFC builds, these map directly + // to AfxSetResourceHandle and AfxGetResourceHandle. In non-MFC builds they + // point to a single static HINST so that those who call the member + // functions that take resource IDs can provide an alternate HINST of a DLL + // to search. This is not exactly the list of HMODULES that MFC provides + // but it's better than nothing. + + #ifdef _MFC_VER + static void SetResourceHandle(HMODULE hNew) + { + AfxSetResourceHandle(hNew); + } + static HMODULE GetResourceHandle() + { + return AfxGetResourceHandle(); + } + #else + static void SetResourceHandle(HMODULE hNew) + { + SSResourceHandle() = hNew; + } + static HMODULE GetResourceHandle() + { + return SSResourceHandle(); + } + #endif + +#endif +}; + + + +// ----------------------------------------------------------------------------- +// CStdStr friend addition functions defined as inline +// ----------------------------------------------------------------------------- +template +inline +CStdStr operator+(const CStdStr& str1, const CStdStr& str2) +{ + CStdStr strRet(SSREF(str1)); + strRet.append(str2); + return strRet; +} + +template +inline +CStdStr operator+(const CStdStr& str, CT t) +{ + // this particular overload is needed for disabling reference counting + // though it's only an issue from line 1 to line 2 + + CStdStr strRet(SSREF(str)); // 1 + strRet.append(1, t); // 2 + return strRet; +} + +template +inline +CStdStr operator+(const CStdStr& str, PCSTR pA) +{ + return CStdStr(str) + CStdStr(pA); +} + +template +inline +CStdStr operator+(PCSTR pA, const CStdStr& str) +{ + CStdStr strRet(pA); + strRet.append(str); + return strRet; +} + +template +inline +CStdStr operator+(const CStdStr& str, PCWSTR pW) +{ + return CStdStr(SSREF(str)) + CStdStr(pW); +} + +template +inline +CStdStr operator+(PCWSTR pW, const CStdStr& str) +{ + CStdStr strRet(pW); + strRet.append(str); + return strRet; +} + +#ifdef SS_INC_COMDEF + template + inline + CStdStr operator+(const _bstr_t& bstr, const CStdStr& str) + { + return static_cast(bstr) + str; + } + + template + inline + CStdStr operator+(const CStdStr& str, const _bstr_t& bstr) + { + return str + static_cast(bstr); + } +#endif + + + + +// ----------------------------------------------------------------------------- +// These versions of operator+ provided by Scott Hathaway in order to allow +// CStdString to build on Sun Unix systems. +// ----------------------------------------------------------------------------- + +#if defined(__SUNPRO_CC_COMPAT) || defined(__SUNPRO_CC) + +// Made non-template versions due to "undefined" errors on Sun Forte compiler +// when linking with friend template functions +inline +CStdStr operator+(const CStdStr& str1, + const CStdStr& str2) +{ + CStdStr strRet(SSREF(str1)); + strRet.append(str2); + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, wchar_t t) +{ + // this particular overload is needed for disabling reference counting + // though it's only an issue from line 1 to line 2 + + CStdStr strRet(SSREF(str)); // 1 + strRet.append(1, t); // 2 + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, PCWSTR pW) +{ + return CStdStr(str) + CStdStr(pW); +} + +inline +CStdStr operator+(PCWSTR pA, const CStdStr& str) +{ + CStdStr strRet(pA); + strRet.append(str); + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, PCSTR pW) +{ + return CStdStr(SSREF(str)) + CStdStr(pW); +} + +inline +CStdStr operator+(PCSTR pW, const CStdStr& str) +{ + CStdStr strRet(pW); + strRet.append(str); + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str1, const CStdStr& str2) +{ + CStdStr strRet(SSREF(str1)); + strRet.append(str2); + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, char t) +{ + // this particular overload is needed for disabling reference counting + // though it's only an issue from line 1 to line 2 + + CStdStr strRet(SSREF(str)); // 1 + strRet.append(1, t); // 2 + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, PCSTR pA) +{ + return CStdStr(str) + CStdStr(pA); +} + +inline +CStdStr operator+(PCSTR pA, const CStdStr& str) +{ + CStdStr strRet(pA); + strRet.append(str); + return strRet; +} + +inline +CStdStr operator+(const CStdStr& str, PCWSTR pW) +{ + return CStdStr(SSREF(str)) + CStdStr(pW); +} + +inline +CStdStr operator+(PCWSTR pW, const CStdStr& str) +{ + CStdStr strRet(pW); + strRet.append(str); + return strRet; +} + + +#endif // defined(__SUNPRO_CC_COMPAT) || defined(__SUNPRO_CC) + + +// ============================================================================= +// END OF CStdStr INLINE FUNCTION DEFINITIONS +// ============================================================================= + +// Now typedef our class names based upon this humongous template + +typedef CStdStr CStdStringA; // a better std::string +typedef CStdStr CStdStringW; // a better std::wstring +typedef CStdStr CStdStringO; // almost always CStdStringW + +#ifndef SS_ANSI + // SSResourceHandle: our MFC-like resource handle + inline HMODULE& SSResourceHandle() + { + static HMODULE hModuleSS = GetModuleHandle(0); + return hModuleSS; + } +#endif + + +// In MFC builds, define some global serialization operators +// Special operators that allow us to serialize CStdStrings to CArchives. +// Note that we use an intermediate CString object in order to ensure that +// we use the exact same format. + +#ifdef _MFC_VER + inline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringA& strA) + { + CString strTemp = strA; + return ar << strTemp; + } + inline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringW& strW) + { + CString strTemp = strW; + return ar << strTemp; + } + + inline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringA& strA) + { + CString strTemp; + ar >> strTemp; + strA = strTemp; + return ar; + } + inline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringW& strW) + { + CString strTemp; + ar >> strTemp; + strW = strTemp; + return ar; + } +#endif // #ifdef _MFC_VER -- (i.e. is this MFC?) + + + +// ----------------------------------------------------------------------------- +// HOW TO EXPORT CSTDSTRING FROM A DLL +// +// If you want to export CStdStringA and CStdStringW from a DLL, then all you +// need to +// 1. make sure that all components link to the same DLL version +// of the CRT (not the static one). +// 2. Uncomment the 3 lines of code below +// 3. #define 2 macros per the instructions in MS KnowledgeBase +// article Q168958. The macros are: +// +// MACRO DEFINTION WHEN EXPORTING DEFINITION WHEN IMPORTING +// ----- ------------------------ ------------------------- +// SSDLLEXP (nothing, just #define it) extern +// SSDLLSPEC __declspec(dllexport) __declspec(dllimport) +// +// Note that these macros must be available to ALL clients who want to +// link to the DLL and use the class. If they +// ----------------------------------------------------------------------------- +//#pragma warning(disable:4231) // non-standard extension ("extern template") +// SSDLLEXP template class SSDLLSPEC CStdStr; +// SSDLLEXP template class SSDLLSPEC CStdStr; + + +// ----------------------------------------------------------------------------- +// GLOBAL FUNCTION: WUFormat +// CStdStringA WUFormat(UINT nId, ...); +// CStdStringA WUFormat(PCSTR szFormat, ...); +// +// REMARKS: +// This function allows the caller for format and return a CStdStringA +// object with a single line of code. +// ----------------------------------------------------------------------------- +#ifdef SS_ANSI +#else + inline CStdStringA WUFormatA(UINT nId, ...) + { + va_list argList; + va_start(argList, nId); + + CStdStringA strFmt; + CStdStringA strOut; + if ( strFmt.Load(nId) ) + strOut.FormatV(strFmt, argList); + + va_end(argList); + return strOut; + } + inline CStdStringA WUFormatA(PCSTR szFormat, ...) + { + va_list argList; + va_start(argList, szFormat); + CStdStringA strOut; + strOut.FormatV(szFormat, argList); + va_end(argList); + return strOut; + } + + inline CStdStringW WUFormatW(UINT nId, ...) + { + va_list argList; + va_start(argList, nId); + + CStdStringW strFmt; + CStdStringW strOut; + if ( strFmt.Load(nId) ) + strOut.FormatV(strFmt, argList); + + va_end(argList); + return strOut; + } + inline CStdStringW WUFormatW(PCWSTR szwFormat, ...) + { + va_list argList; + va_start(argList, szwFormat); + CStdStringW strOut; + strOut.FormatV(szwFormat, argList); + va_end(argList); + return strOut; + } +#endif // #ifdef SS_ANSI + +#ifdef SS_ANSI +#else + // ------------------------------------------------------------------------- + // FUNCTION: WUSysMessage + // CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID); + // CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID); + // + // DESCRIPTION: + // This function simplifies the process of obtaining a string equivalent + // of a system error code returned from GetLastError(). You simply + // supply the value returned by GetLastError() to this function and the + // corresponding system string is returned in the form of a CStdStringA. + // + // PARAMETERS: + // dwError - a DWORD value representing the error code to be translated + // dwLangId - the language id to use. defaults to english. + // + // RETURN VALUE: + // a CStdStringA equivalent of the error code. Currently, this function + // only returns either English of the system default language strings. + // ------------------------------------------------------------------------- + #define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT) + inline CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID) + { + CHAR szBuf[512]; + + if ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, + dwLangId, szBuf, 511, NULL) ) + return WUFormatA("%s (0x%X)", szBuf, dwError); + else + return WUFormatA("Unknown error (0x%X)", dwError); + } + inline CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID) + { + WCHAR szBuf[512]; + + if ( 0 != ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, + dwLangId, szBuf, 511, NULL) ) + return WUFormatW(L"%s (0x%X)", szBuf, dwError); + else + return WUFormatW(L"Unknown error (0x%X)", dwError); + } +#endif + +// Define TCHAR based friendly names for some of these functions + +#ifdef UNICODE + #define CStdString CStdStringW + #define WUSysMessage WUSysMessageW + #define WUFormat WUFormatW +#else + #define CStdString CStdStringA + #define WUSysMessage WUSysMessageA + #define WUFormat WUFormatA +#endif + +// ...and some shorter names for the space-efficient + +#define WUSysMsg WUSysMessage +#define WUSysMsgA WUSysMessageA +#define WUSysMsgW WUSysMessageW +#define WUFmtA WUFormatA +#define WUFmtW WUFormatW +#define WUFmt WUFormat +#define WULastErrMsg() WUSysMessage(::GetLastError()) +#define WULastErrMsgA() WUSysMessageA(::GetLastError()) +#define WULastErrMsgW() WUSysMessageW(::GetLastError()) + + +// ----------------------------------------------------------------------------- +// FUNCTIONAL COMPARATORS: +// REMARKS: +// These structs are derived from the std::binary_function template. They +// give us functional classes (which may be used in Standard C++ Library +// collections and algorithms) that perform case-insensitive comparisons of +// CStdString objects. This is useful for maps in which the key may be the +// proper string but in the wrong case. +// ----------------------------------------------------------------------------- +#define StdStringLessNoCaseW SSLNCW // avoid VC compiler warning 4786 +#define StdStringEqualsNoCaseW SSENCW +#define StdStringLessNoCaseA SSLNCA +#define StdStringEqualsNoCaseA SSENCA + +#ifdef UNICODE + #define StdStringLessNoCase SSLNCW + #define StdStringEqualsNoCase SSENCW +#else + #define StdStringLessNoCase SSLNCA + #define StdStringEqualsNoCase SSENCA +#endif + +struct StdStringLessNoCaseW + : std::binary_function +{ + inline + bool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const + { return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; } +}; +struct StdStringEqualsNoCaseW + : std::binary_function +{ + inline + bool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const + { return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; } +}; +struct StdStringLessNoCaseA + : std::binary_function +{ + inline + bool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const + { return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; } +}; +struct StdStringEqualsNoCaseA + : std::binary_function +{ + inline + bool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const + { return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; } +}; + +// If we had to define our own version of TRACE above, get rid of it now + +#ifdef TRACE_DEFINED_HERE + #undef TRACE + #undef TRACE_DEFINED_HERE +#endif + + +#endif // #ifndef STDSTRING_H \ No newline at end of file diff --git a/MAC_SDK/Source/Shared/Unicows.cpp b/MAC_SDK/Source/Shared/Unicows.cpp new file mode 100644 index 0000000..e7131f1 --- /dev/null +++ b/MAC_SDK/Source/Shared/Unicows.cpp @@ -0,0 +1,18 @@ +#include + +HMODULE LoadUnicowsProc(void) +{ + HMODULE hModule = LoadLibraryA("unicows.dll"); + if (hModule == NULL) + { + MessageBoxA(NULL, "The Microsoft Layer for Unicode failed to initialize. Please re-install.", "Unicode Failure", MB_OK | MB_ICONERROR); + _exit(-1); + } + + return hModule; +} + +extern "C" +{ + extern FARPROC _PfnLoadUnicows = (FARPROC) &LoadUnicowsProc; +} diff --git a/MAC_SDK/Source/Shared/WAVInfoDialog.cpp b/MAC_SDK/Source/Shared/WAVInfoDialog.cpp new file mode 100644 index 0000000..30c3540 --- /dev/null +++ b/MAC_SDK/Source/Shared/WAVInfoDialog.cpp @@ -0,0 +1,156 @@ +#include +#include "All.h" + +#include "WAVInfoDialog.h" +#include "WAVInputSource.h" +#include "CharacterHelper.h" + +/*************************************************************************************** +The dialog component ID's +***************************************************************************************/ +#define FILE_NAME_STATIC 1000 + +#define FILE_SIZE_STATIC 2000 +#define TRACK_LENGTH_STATIC 2001 +#define AUDIO_BYTES_STATIC 2002 +#define HEADER_BYTES_STATIC 2003 +#define TERMINATING_BYTES_STATIC 2004 + +#define SAMPLE_RATE_STATIC 3000 +#define CHANNELS_STATIC 3001 +#define BITS_PER_SAMPLE_STATIC 3002 + +#define OK_BUTTON 4000 + +/*************************************************************************************** +Global pointer to this instance +***************************************************************************************/ +CWAVInfoDialog * g_pWAVInfoDialog; + + +/*************************************************************************************** +Construction / destruction +***************************************************************************************/ +CWAVInfoDialog::CWAVInfoDialog() +{ + g_pWAVInfoDialog = NULL; +} + +CWAVInfoDialog::~CWAVInfoDialog() +{ + +} + +/*************************************************************************************** +Display the file info dialog +***************************************************************************************/ +long CWAVInfoDialog::ShowWAVInfoDialog(const str_utf16 * pFilename, HINSTANCE hInstance, const str_utf16 * lpTemplateName, HWND hWndParent) +{ + //only allow one instance at a time + if (g_pWAVInfoDialog != NULL) + { + return -1; + } + + _tcscpy(m_cFileName, pFilename); + g_pWAVInfoDialog = this; + + DialogBoxParam(hInstance, lpTemplateName, hWndParent, (DLGPROC) DialogProc, 0); + + g_pWAVInfoDialog = NULL; + return 0; +} + +/*************************************************************************************** +Initialize the dialog +***************************************************************************************/ +long CWAVInfoDialog::InitDialog(HWND hDlg) +{ + // analyze the WAV + WAVEFORMATEX wfeWAV; + int nTotalBlocks = 0; + int nHeaderBytes = 0; + int nTerminatingBytes = 0; + int nErrorCode = 0; + + CWAVInputSource WAVInfo(m_cFileName, &wfeWAV, &nTotalBlocks, &nHeaderBytes, &nTerminatingBytes, &nErrorCode); + if (nErrorCode != 0) + return nErrorCode; + + int nAudioBytes = nTotalBlocks * wfeWAV.nBlockAlign; + + // set info + TCHAR cTemp[1024] = { 0 }; + + SetDlgItemText(hDlg, FILE_NAME_STATIC, m_cFileName); + + _stprintf(cTemp, _T("Sample Rate: %d"), wfeWAV.nSamplesPerSec); + SetDlgItemText(hDlg, SAMPLE_RATE_STATIC, cTemp); + + _stprintf(cTemp, _T("Channels: %d"), wfeWAV.nChannels); + SetDlgItemText(hDlg, CHANNELS_STATIC, cTemp); + + _stprintf(cTemp, _T("Bits Per Sample: %d"), int(wfeWAV.wBitsPerSample)); + SetDlgItemText(hDlg, BITS_PER_SAMPLE_STATIC, cTemp); + + int nSeconds = nAudioBytes / wfeWAV.nAvgBytesPerSec; int nMinutes = nSeconds / 60; nSeconds = nSeconds % 60; int nHours = nMinutes / 60; nMinutes = nMinutes % 60; + if (nHours > 0) _stprintf(cTemp, _T("Length: %d:%02d:%02d"), nHours, nMinutes, nSeconds); + else if (nMinutes > 0) _stprintf(cTemp, _T("Length: %d:%02d"), nMinutes, nSeconds); + else _stprintf(cTemp, _T("Length: 0:%02d"), nSeconds); + SetDlgItemText(hDlg, TRACK_LENGTH_STATIC, cTemp); + + _stprintf(cTemp, _T("Audio Bytes: %d"), nAudioBytes); + SetDlgItemText(hDlg, AUDIO_BYTES_STATIC, cTemp); + + _stprintf(cTemp, _T("Header Bytes: %d"), nHeaderBytes); + SetDlgItemText(hDlg, HEADER_BYTES_STATIC, cTemp); + + _stprintf(cTemp, _T("Terminating Bytes: %d"), nTerminatingBytes); + SetDlgItemText(hDlg, TERMINATING_BYTES_STATIC, cTemp); + + _stprintf(cTemp, _T("File Size: %.2f MB"), float(nAudioBytes + nHeaderBytes + nTerminatingBytes) / float(1024 * 1024)); + SetDlgItemText(hDlg, FILE_SIZE_STATIC, cTemp); + + return 0; +} + +/*************************************************************************************** +The dialog procedure +***************************************************************************************/ +LRESULT CALLBACK CWAVInfoDialog::DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) +{ + int wmID, wmEvent; + long RetVal; + + switch (message) + { + case WM_INITDIALOG: + //fill in the info on initialization + RetVal = g_pWAVInfoDialog->InitDialog(hDlg); + return TRUE; + break; + case WM_COMMAND: + wmID = LOWORD(wParam); + wmEvent = HIWORD(wParam); + switch (wmID) + { + case IDCANCEL: //traps the [esc] key + EndDialog(hDlg, 0); + return TRUE; + break; + case OK_BUTTON: + EndDialog(hDlg, 0); + return TRUE; + break; + } + break; + case WM_CLOSE: + EndDialog(hDlg, 0); + return TRUE; + break; + } + + return FALSE; +} + + diff --git a/MAC_SDK/Source/Shared/WAVInfoDialog.h b/MAC_SDK/Source/Shared/WAVInfoDialog.h new file mode 100644 index 0000000..31fe1c5 --- /dev/null +++ b/MAC_SDK/Source/Shared/WAVInfoDialog.h @@ -0,0 +1,22 @@ +#ifndef APE_WAVINFODIALOG_H +#define APE_WAVINFODIALOG_H + +BOOL CALLBACK FileInfoDialogProcedureA(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); + +class CWAVInfoDialog +{ +public: + + CWAVInfoDialog(); + ~CWAVInfoDialog(); + + long ShowWAVInfoDialog(const str_utf16 * pFilename, HINSTANCE hInstance, const str_utf16 * lpTemplateName, HWND hWndParent); + +private: + + static LRESULT CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); + long InitDialog(HWND hDlg); + TCHAR m_cFileName[MAX_PATH]; +}; + +#endif // #ifndef APE_WAVINFODIALOG_H diff --git a/MAC_SDK/Source/Shared/WinFileIO.cpp b/MAC_SDK/Source/Shared/WinFileIO.cpp new file mode 100644 index 0000000..44e2e4a --- /dev/null +++ b/MAC_SDK/Source/Shared/WinFileIO.cpp @@ -0,0 +1,162 @@ +#include "All.h" + +#ifdef IO_USE_WIN_FILE_IO + +#include "WinFileIO.h" +#include +#include "CharacterHelper.h" + +CWinFileIO::CWinFileIO() +{ + m_hFile = INVALID_HANDLE_VALUE; + memset(m_cFileName, 0, MAX_PATH); + m_bReadOnly = FALSE; +} + +CWinFileIO::~CWinFileIO() +{ + Close(); +} + +int CWinFileIO::Open(const wchar_t * pName) +{ + Close(); + + #ifdef _UNICODE + CSmartPtr spName((wchar_t *) pName, TRUE, FALSE); + #else + CSmartPtr spName(GetANSIFromUTF16(pName), TRUE); + #endif + + m_hFile = ::CreateFile(spName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (m_hFile == INVALID_HANDLE_VALUE) + { + m_hFile = ::CreateFile(spName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (m_hFile == INVALID_HANDLE_VALUE) + { + return -1; + } + else + { + m_bReadOnly = TRUE; + } + } + else + { + m_bReadOnly = FALSE; + } + + wcscpy(m_cFileName, pName); + + return 0; +} + +int CWinFileIO::Close() +{ + SAFE_FILE_CLOSE(m_hFile); + + return 0; +} + +int CWinFileIO::Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead) +{ + unsigned int nTotalBytesRead = 0; + int nBytesLeft = nBytesToRead; + BOOL bRetVal = TRUE; + unsigned char * pucBuffer = (unsigned char *) pBuffer; + + *pBytesRead = 1; + while ((nBytesLeft > 0) && (*pBytesRead > 0) && bRetVal) + { + bRetVal = ::ReadFile(m_hFile, &pucBuffer[nBytesToRead - nBytesLeft], nBytesLeft, (unsigned long *) pBytesRead, NULL); + if (bRetVal == TRUE) + { + nBytesLeft -= *pBytesRead; + nTotalBytesRead += *pBytesRead; + } + } + + *pBytesRead = nTotalBytesRead; + + return (bRetVal == FALSE) ? ERROR_IO_READ : 0; +} + +int CWinFileIO::Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten) +{ + BOOL bRetVal = WriteFile(m_hFile, pBuffer, nBytesToWrite, (unsigned long *) pBytesWritten, NULL); + + if ((bRetVal == 0) || (*pBytesWritten != nBytesToWrite)) + return ERROR_IO_WRITE; + else + return 0; +} + +int CWinFileIO::Seek(int nDistance, unsigned int nMoveMode) +{ + SetFilePointer(m_hFile, nDistance, NULL, nMoveMode); + return 0; +} + +int CWinFileIO::SetEOF() +{ + BOOL bRetVal = SetEndOfFile(m_hFile); + if (bRetVal == FALSE) + { + return -1; + } + else + { + return 0; + } +} + +int CWinFileIO::GetPosition() +{ + return SetFilePointer(m_hFile, 0, NULL, FILE_CURRENT); +} + +int CWinFileIO::GetSize() +{ + return GetFileSize(m_hFile, NULL); +} + +int CWinFileIO::GetName(wchar_t * pBuffer) +{ + wcscpy(pBuffer, m_cFileName); + return 0; +} + +int CWinFileIO::Create(const wchar_t * pName) +{ + Close(); + + #ifdef _UNICODE + CSmartPtr spName((wchar_t *) pName, TRUE, FALSE); + #else + CSmartPtr spName(GetANSIFromUTF16(pName), TRUE); + #endif + + m_hFile = CreateFile(spName, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (m_hFile == INVALID_HANDLE_VALUE) { return -1; } + + m_bReadOnly = FALSE; + + wcscpy(m_cFileName, pName); + + return 0; +} + +int CWinFileIO::Delete() +{ + Close(); + + #ifdef _UNICODE + CSmartPtr spName(m_cFileName, TRUE, FALSE); + #else + CSmartPtr spName(GetANSIFromUTF16(m_cFileName), TRUE); + #endif + + return DeleteFile(spName) ? 0 : -1; +} + +#endif // #ifdef IO_USE_WIN_FILE_IO diff --git a/MAC_SDK/Source/Shared/WinFileIO.h b/MAC_SDK/Source/Shared/WinFileIO.h new file mode 100644 index 0000000..cbe5811 --- /dev/null +++ b/MAC_SDK/Source/Shared/WinFileIO.h @@ -0,0 +1,49 @@ +#ifdef IO_USE_WIN_FILE_IO + +#ifndef _winfileio_h_ +#define _winfileio_h_ + +#include "IO.h" + +class CWinFileIO : public CIO +{ +public: + + // construction / destruction + CWinFileIO(); + ~CWinFileIO(); + + // open / close + int Open(const wchar_t * pName); + int Close(); + + // read / write + int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead); + int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten); + + // seek + int Seek(int nDistance, unsigned int nMoveMode); + + // other functions + int SetEOF(); + + // creation / destruction + int Create(const wchar_t * pName); + int Delete(); + + // attributes + int GetPosition(); + int GetSize(); + int GetName(wchar_t * pBuffer); + +private: + + HANDLE m_hFile; + wchar_t m_cFileName[MAX_PATH]; + BOOL m_bReadOnly; +}; + + +#endif //_winfileio_h_ + +#endif //IO_USE_WIN_FILE_IO \ No newline at end of file diff --git a/WavPackDotNet/AssemblyInfo.cpp b/WavPackDotNet/AssemblyInfo.cpp new file mode 100644 index 0000000..8559184 --- /dev/null +++ b/WavPackDotNet/AssemblyInfo.cpp @@ -0,0 +1,39 @@ + +using namespace System; +using namespace System::Reflection; +using namespace System::Runtime::CompilerServices; +using namespace System::Runtime::InteropServices; +using namespace System::Security::Permissions; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly:AssemblyTitleAttribute("WavPackDotNet")]; +[assembly:AssemblyDescriptionAttribute("")]; +[assembly:AssemblyConfigurationAttribute("")]; +[assembly:AssemblyCompanyAttribute("")]; +[assembly:AssemblyProductAttribute("")]; +[assembly:AssemblyCopyrightAttribute("Copyright 2006-2007 Moitah")]; +[assembly:AssemblyTrademarkAttribute("")]; +[assembly:AssemblyCultureAttribute("")]; + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the value or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly:AssemblyVersionAttribute("1.2.0.0")]; + +[assembly:ComVisible(false)]; + +[assembly:CLSCompliantAttribute(true)]; + +[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/WavPackDotNet/WavPack/libwavpack.lib b/WavPackDotNet/WavPack/libwavpack.lib new file mode 100644 index 0000000..66ed3a9 Binary files /dev/null and b/WavPackDotNet/WavPack/libwavpack.lib differ diff --git a/WavPackDotNet/WavPack/wavpack.h b/WavPackDotNet/WavPack/wavpack.h new file mode 100644 index 0000000..8ba9d91 --- /dev/null +++ b/WavPackDotNet/WavPack/wavpack.h @@ -0,0 +1,300 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wavpack.h + +#ifndef WAVPACK_H +#define WAVPACK_H + +// This header file contains all the definitions required to use the +// functions in "wputils.c" to read and write WavPack files and streams. + +#include + +#if defined(_WIN32) && !defined(__MINGW32__) +#include +typedef unsigned __int64 uint64_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int8 uint8_t; +typedef __int64 int64_t; +typedef __int32 int32_t; +typedef __int16 int16_t; +typedef __int8 int8_t; +typedef float float32_t; +#else +#include +#endif + +typedef unsigned char uchar; + +#if !defined(__GNUC__) || defined(WIN32) +typedef unsigned short ushort; +typedef unsigned int uint; +#endif + +// RIFF / wav header formats (these occur at the beginning of both wav files +// and pre-4.0 WavPack files that are not in the "raw" mode). Generally, an +// application using the library to read or write WavPack files will not be +// concerned with any of these. + +typedef struct { + char ckID [4]; + uint32_t ckSize; + char formType [4]; +} RiffChunkHeader; + +typedef struct { + char ckID [4]; + uint32_t ckSize; +} ChunkHeader; + +#define ChunkHeaderFormat "4L" + +typedef struct { + ushort FormatTag, NumChannels; + uint32_t SampleRate, BytesPerSecond; + ushort BlockAlign, BitsPerSample; + ushort cbSize, ValidBitsPerSample; + int32_t ChannelMask; + ushort SubFormat; + char GUID [14]; +} WaveHeader; + +#define WaveHeaderFormat "SSLLSSSSLS" + +// This is the ONLY structure that occurs in WavPack files (as of version +// 4.0), and is the preamble to every block in both the .wv and .wvc +// files (in little-endian format). Normally, this structure has no use +// to an application using the library to read or write WavPack files, +// but if an application needs to manually parse WavPack files then this +// would be used (with appropriate endian correction). + +typedef struct { + char ckID [4]; + uint32_t ckSize; + short version; + uchar track_no, index_no; + uint32_t total_samples, block_index, block_samples, flags, crc; +} WavpackHeader; + +#define WavpackHeaderFormat "4LS2LLLLL" + +// or-values for WavpackHeader.flags +#define BYTES_STORED 3 // 1-4 bytes/sample +#define MONO_FLAG 4 // not stereo +#define HYBRID_FLAG 8 // hybrid mode +#define JOINT_STEREO 0x10 // joint stereo +#define CROSS_DECORR 0x20 // no-delay cross decorrelation +#define HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define FLOAT_DATA 0x80 // ieee 32-bit floating point data + +#define INT32_DATA 0x100 // special extended int handling +#define HYBRID_BITRATE 0x200 // bitrate noise (hybrid mode only) +#define HYBRID_BALANCE 0x400 // balance noise (hybrid stereo mode only) + +#define INITIAL_BLOCK 0x800 // initial block of multichannel segment +#define FINAL_BLOCK 0x1000 // final block of multichannel segment + +#define SHIFT_LSB 13 +#define SHIFT_MASK (0x1fL << SHIFT_LSB) + +#define MAG_LSB 18 +#define MAG_MASK (0x1fL << MAG_LSB) + +#define SRATE_LSB 23 +#define SRATE_MASK (0xfL << SRATE_LSB) + +#define FALSE_STEREO 0x40000000 // block is stereo, but data is mono + +#define IGNORED_FLAGS 0x18000000 // reserved, but ignore if encountered +#define NEW_SHAPING 0x20000000 // use IIR filter for negative shaping +#define UNKNOWN_FLAGS 0x80000000 // also reserved, but refuse decode if + // encountered + +#define MONO_DATA (MONO_FLAG | FALSE_STEREO) + +#define MIN_STREAM_VERS 0x402 // lowest stream version we'll decode +#define MAX_STREAM_VERS 0x410 // highest stream version we'll decode or encode +#define CUR_STREAM_VERS 0x405 // stream version we are writing now + +// These are the mask bit definitions for the metadata chunk id byte (see format.txt) + +#define ID_UNIQUE 0x3f +#define ID_OPTIONAL_DATA 0x20 +#define ID_ODD_SIZE 0x40 +#define ID_LARGE 0x80 + +#define ID_DUMMY 0x0 +#define ID_ENCODER_INFO 0x1 +#define ID_DECORR_TERMS 0x2 +#define ID_DECORR_WEIGHTS 0x3 +#define ID_DECORR_SAMPLES 0x4 +#define ID_ENTROPY_VARS 0x5 +#define ID_HYBRID_PROFILE 0x6 +#define ID_SHAPING_WEIGHTS 0x7 +#define ID_FLOAT_INFO 0x8 +#define ID_INT32_INFO 0x9 +#define ID_WV_BITSTREAM 0xa +#define ID_WVC_BITSTREAM 0xb +#define ID_WVX_BITSTREAM 0xc +#define ID_CHANNEL_INFO 0xd + +#define ID_RIFF_HEADER (ID_OPTIONAL_DATA | 0x1) +#define ID_RIFF_TRAILER (ID_OPTIONAL_DATA | 0x2) +#define ID_REPLAY_GAIN (ID_OPTIONAL_DATA | 0x3) // never used (APEv2) +#define ID_CUESHEET (ID_OPTIONAL_DATA | 0x4) // never used (APEv2) +#define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) +#define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) +#define ID_SAMPLE_RATE (ID_OPTIONAL_DATA | 0x7) + +///////////////////////// WavPack Configuration /////////////////////////////// + +// This external structure is used during encode to provide configuration to +// the encoding engine and during decoding to provide fle information back to +// the higher level functions. Not all fields are used in both modes. + +typedef struct { + float bitrate, shaping_weight; + int bits_per_sample, bytes_per_sample; + int qmode, flags, xmode, num_channels, float_norm_exp; + int32_t block_samples, extra_flags, sample_rate, channel_mask; + uchar md5_checksum [16], md5_read; + int num_tag_strings; + char **tag_strings; +} WavpackConfig; + +#define CONFIG_HYBRID_FLAG 8 // hybrid mode +#define CONFIG_JOINT_STEREO 0x10 // joint stereo +#define CONFIG_HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define CONFIG_FAST_FLAG 0x200 // fast mode +#define CONFIG_HIGH_FLAG 0x800 // high quality mode +#define CONFIG_VERY_HIGH_FLAG 0x1000 // very high +#define CONFIG_BITRATE_KBPS 0x2000 // bitrate is kbps, not bits / sample +#define CONFIG_SHAPE_OVERRIDE 0x8000 // shaping mode specified +#define CONFIG_JOINT_OVERRIDE 0x10000 // joint-stereo mode specified +#define CONFIG_CREATE_EXE 0x40000 // create executable +#define CONFIG_CREATE_WVC 0x80000 // create correction file +#define CONFIG_OPTIMIZE_WVC 0x100000 // maximize bybrid compression +#define CONFIG_CALC_NOISE 0x800000 // calc noise in hybrid mode +#define CONFIG_EXTRA_MODE 0x2000000 // extra processing mode +#define CONFIG_SKIP_WVX 0x4000000 // no wvx stream w/ floats & big ints +#define CONFIG_MD5_CHECKSUM 0x8000000 // store MD5 signature +#define CONFIG_OPTIMIZE_MONO 0x80000000 // optimize for mono streams posing as stereo + +////////////// Callbacks used for reading & writing WavPack streams ////////// + +typedef struct { + int32_t (*read_bytes)(void *id, void *data, int32_t bcount); + uint32_t (*get_pos)(void *id); + int (*set_pos_abs)(void *id, uint32_t pos); + int (*set_pos_rel)(void *id, int32_t delta, int mode); + int (*push_back_byte)(void *id, int c); + uint32_t (*get_length)(void *id); + int (*can_seek)(void *id); + + // this callback is for writing edited tags only + int32_t (*write_bytes)(void *id, void *data, int32_t bcount); +} WavpackStreamReader; + +typedef int (*WavpackBlockOutput)(void *id, void *data, int32_t bcount); + +//////////////////////////// function prototypes ///////////////////////////// + +// Note: See wputils.c sourcecode for descriptions for using these functions. + +typedef void WavpackContext; + +#ifdef __cplusplus +extern "C" { +#endif + +WavpackContext *WavpackOpenFileInputEx (WavpackStreamReader *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset); +WavpackContext *WavpackOpenFileInput (const wchar_t *infilename, char *error, int flags, int norm_offset); + +#define OPEN_WVC 0x1 // open/read "correction" file +#define OPEN_TAGS 0x2 // read ID3v1 / APEv2 tags (seekable file) +#define OPEN_WRAPPER 0x4 // make audio wrapper available (i.e. RIFF) +#define OPEN_2CH_MAX 0x8 // open multichannel as stereo (no downmix) +#define OPEN_NORMALIZE 0x10 // normalize floating point data to +/- 1.0 +#define OPEN_STREAMING 0x20 // "streaming" mode blindly unpacks blocks + // w/o regard to header file position info +#define OPEN_EDIT_TAGS 0x40 // allow editing of tags + +int WavpackGetMode (WavpackContext *wpc); + +#define MODE_WVC 0x1 +#define MODE_LOSSLESS 0x2 +#define MODE_HYBRID 0x4 +#define MODE_FLOAT 0x8 +#define MODE_VALID_TAG 0x10 +#define MODE_HIGH 0x20 +#define MODE_FAST 0x40 +#define MODE_EXTRA 0x80 +#define MODE_APETAG 0x100 +#define MODE_SFX 0x200 +#define MODE_VERY_HIGH 0x400 +#define MODE_MD5 0x800 + +char *WavpackGetErrorMessage (WavpackContext *wpc); +int WavpackGetVersion (WavpackContext *wpc); +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples); +uint32_t WavpackGetNumSamples (WavpackContext *wpc); +uint32_t WavpackGetSampleIndex (WavpackContext *wpc); +int WavpackGetNumErrors (WavpackContext *wpc); +int WavpackLossyBlocks (WavpackContext *wpc); +int WavpackSeekSample (WavpackContext *wpc, uint32_t sample); +WavpackContext *WavpackCloseFile (WavpackContext *wpc); +uint32_t WavpackGetSampleRate (WavpackContext *wpc); +int WavpackGetBitsPerSample (WavpackContext *wpc); +int WavpackGetBytesPerSample (WavpackContext *wpc); +int WavpackGetNumChannels (WavpackContext *wpc); +int WavpackGetChannelMask (WavpackContext *wpc); +int WavpackGetReducedChannels (WavpackContext *wpc); +int WavpackGetFloatNormExp (WavpackContext *wpc); +int WavpackGetMD5Sum (WavpackContext *wpc, uchar data [16]); +uint32_t WavpackGetWrapperBytes (WavpackContext *wpc); +uchar *WavpackGetWrapperData (WavpackContext *wpc); +void WavpackFreeWrapper (WavpackContext *wpc); +void WavpackSeekTrailingWrapper (WavpackContext *wpc); +double WavpackGetProgress (WavpackContext *wpc); +uint32_t WavpackGetFileSize (WavpackContext *wpc); +double WavpackGetRatio (WavpackContext *wpc); +double WavpackGetAverageBitrate (WavpackContext *wpc, int count_wvc); +double WavpackGetInstantBitrate (WavpackContext *wpc); +int WavpackGetNumTagItems (WavpackContext *wpc); +int WavpackGetTagItem (WavpackContext *wpc, const char *item, char *value, int size); +int WavpackGetTagItemIndexed (WavpackContext *wpc, int index, char *item, int size); +int WavpackAppendTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize); +int WavpackDeleteTagItem (WavpackContext *wpc, const char *item); +int WavpackWriteTag (WavpackContext *wpc); + +WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id); +int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples); +int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount); +int WavpackStoreMD5Sum (WavpackContext *wpc, uchar data [16]); +int WavpackPackInit (WavpackContext *wpc); +int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count); +int WavpackFlushSamples (WavpackContext *wpc); +void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block); +void *WavpackGetWrapperLocation (void *first_block, uint32_t *size); +double WavpackGetEncodedNoise (WavpackContext *wpc, double *peak); + +void WavpackFloatNormalize (int32_t *values, int32_t num_values, int delta_exp); + +void WavpackLittleEndianToNative (void *data, char *format); +void WavpackNativeToLittleEndian (void *data, char *format); + +uint32_t WavpackGetLibraryVersion (); +const char *WavpackGetLibraryVersionString (); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/WavPackDotNet/WavPackDotNet.cpp b/WavPackDotNet/WavPackDotNet.cpp new file mode 100644 index 0000000..e5f781d --- /dev/null +++ b/WavPackDotNet/WavPackDotNet.cpp @@ -0,0 +1,314 @@ +// **************************************************************************** +// +// Copyright (c) 2006-2007 Moitah (moitah@yahoo.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of the author nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. +// +// **************************************************************************** + +using namespace System; +using namespace System::Runtime::InteropServices; +using namespace System::Collections::Specialized; + +#include +#include +#include "WavPack\wavpack.h" +#include +typedef char str_ansi; +typedef wchar_t str_utf16; +#define BOOL int +#define TRUE 1 +#define FALSE 0 +#include "..\MAC_SDK\Shared\SmartPtr.h" +#include "..\MAC_SDK\Shared\APETag.h" + +namespace WavPackDotNet { + int write_block(void *id, void *data, int32_t length); + + public ref class WavPackReader { + public: + WavPackReader(String^ path) { + IntPtr pathChars; + char errorMessage[256]; + + _path = NULL; + + pathChars = Marshal::StringToHGlobalUni(path); + size_t pathLen = wcslen ((const wchar_t*)pathChars.ToPointer())+1; + _path = new wchar_t[pathLen]; + memcpy ((void*) _path, (const wchar_t*)pathChars.ToPointer(), pathLen*sizeof(wchar_t)); + Marshal::FreeHGlobal(pathChars); + + _wpc = WavpackOpenFileInput(_path, errorMessage, OPEN_WVC, 0); + if (_wpc == NULL) { + throw gcnew Exception("Unable to initialize the decoder."); + } + + _bitsPerSample = WavpackGetBitsPerSample(_wpc); + _channelCount = WavpackGetNumChannels(_wpc); + _sampleRate = WavpackGetSampleRate(_wpc); + _sampleCount = WavpackGetNumSamples(_wpc); + _sampleOffset = 0; + } + + ~WavPackReader() + { + if (_path) delete [] _path; + } + + property Int32 BitsPerSample { + Int32 get() { + return _bitsPerSample; + } + } + + property Int32 ChannelCount { + Int32 get() { + return _channelCount; + } + } + + property Int32 SampleRate { + Int32 get() { + return _sampleRate; + } + } + + property Int32 Length { + Int32 get() { + return _sampleCount; + } + } + + property Int32 Position { + Int32 get() { + return _sampleOffset; + } + void set(Int32 offset) { + _sampleOffset = offset; + if (!WavpackSeekSample(_wpc, offset)) { + throw gcnew Exception("Unable to seek."); + } + } + } + + property Int32 Remaining { + Int32 get() { + return _sampleCount - _sampleOffset; + } + } + + property NameValueCollection^ Tags { + NameValueCollection^ get () { + if (!_tags) GetTags (); + return _tags; + } + void set (NameValueCollection ^tags) { + _tags = tags; + } + } + + void Close() { + _wpc = WavpackCloseFile(_wpc); + } + + void Read(array^ sampleBuffer, Int32 sampleCount) { + pin_ptr pSampleBuffer = &sampleBuffer[0, 0]; + int samplesRead; + + samplesRead = WavpackUnpackSamples(_wpc, pSampleBuffer, sampleCount); + _sampleOffset += samplesRead; + + if (samplesRead != sampleCount) { + throw gcnew Exception("Decoder returned a different number of samples than requested."); + } + } + + private: + WavpackContext *_wpc; + NameValueCollection^ _tags; + Int32 _sampleCount, _sampleOffset; + Int32 _bitsPerSample, _channelCount, _sampleRate; + const wchar_t * _path; + + void GetTags (void) + { + _tags = gcnew NameValueCollection(); + CAPETag apeTag (_path, TRUE); + for (int i = 0; ; i++) + { + CAPETagField * field = apeTag.GetTagField (i); + if (!field) + break; + if (field->GetIsUTF8Text()) + { + int valueSize = field->GetFieldValueSize(); + while (valueSize && field->GetFieldValue()[valueSize-1]=='\0') + valueSize --; + const wchar_t * fieldName = field->GetFieldName (); + if (!_wcsicmp (fieldName, L"YEAR")) + fieldName = L"DATE"; + if (!_wcsicmp (fieldName, L"TRACK")) + fieldName = L"TRACKNUMBER"; + _tags->Add (gcnew String (fieldName), + gcnew String (field->GetFieldValue(), 0, valueSize, System::Text::Encoding::UTF8)); + } + } + } + }; + + public ref class WavPackWriter { + public: + WavPackWriter(String^ path, Int32 bitsPerSample, Int32 channelCount, Int32 sampleRate) { + IntPtr pathChars; + + if ((channelCount != 1) && (channelCount != 2)) { + throw gcnew Exception("Only stereo and mono audio formats are allowed."); + } + + _compressionMode = 1; + _extraMode = 0; + + _bitsPerSample = bitsPerSample; + _channelCount = channelCount; + _sampleRate = sampleRate; + + pathChars = Marshal::StringToHGlobalUni(path); + _hFile = _wfopen((const wchar_t*)pathChars.ToPointer(), L"w+b"); + Marshal::FreeHGlobal(pathChars); + if (!_hFile) { + throw gcnew Exception("Unable to open file."); + } + } + + void Close() { + WavpackFlushSamples(_wpc); + _wpc = WavpackCloseFile(_wpc); + fclose(_hFile); + + if ((_finalSampleCount != 0) && (_samplesWritten != _finalSampleCount)) { + throw gcnew Exception("Samples written differs from the expected sample count."); + } + } + + property Int32 FinalSampleCount { + Int32 get() { + return _finalSampleCount; + } + void set(Int32 value) { + if (value < 0) { + throw gcnew Exception("Invalid final sample count."); + } + if (_initialized) { + throw gcnew Exception("Final sample count cannot be changed after encoding begins."); + } + _finalSampleCount = value; + } + } + + property Int32 CompressionMode { + Int32 get() { + return _compressionMode; + } + void set(Int32 value) { + if ((value < 0) || (value > 3)) { + throw gcnew Exception("Invalid compression mode."); + } + _compressionMode = value; + } + } + + property Int32 ExtraMode { + Int32 get() { + return _extraMode; + } + void set(Int32 value) { + if ((value < 0) || (value > 6)) { + throw gcnew Exception("Invalid extra mode."); + } + _extraMode = value; + } + } + + void Write(array^ sampleBuffer, Int32 sampleCount) { + if (!_initialized) Initialize(); + + pin_ptr pSampleBuffer = &sampleBuffer[0, 0]; + + if (!WavpackPackSamples(_wpc, (int32_t*)pSampleBuffer, sampleCount)) { + throw gcnew Exception("An error occurred while encoding."); + } + + _samplesWritten += sampleCount; + } + + private: + FILE *_hFile; + bool _initialized; + WavpackContext *_wpc; + Int32 _finalSampleCount, _samplesWritten; + Int32 _bitsPerSample, _channelCount, _sampleRate; + Int32 _compressionMode, _extraMode; + + void Initialize() { + WavpackConfig config; + + _wpc = WavpackOpenFileOutput(write_block, _hFile, NULL); + if (!_wpc) { + throw gcnew Exception("Unable to create the encoder."); + } + + memset(&config, 0, sizeof(WavpackConfig)); + config.bits_per_sample = _bitsPerSample; + config.bytes_per_sample = (_bitsPerSample + 7) / 8; + config.num_channels = _channelCount; + config.channel_mask = 5 - _channelCount; + config.sample_rate = _sampleRate; + if (_compressionMode == 0) config.flags |= CONFIG_FAST_FLAG; + if (_compressionMode == 2) config.flags |= CONFIG_HIGH_FLAG; + if (_compressionMode == 3) config.flags |= CONFIG_HIGH_FLAG | CONFIG_VERY_HIGH_FLAG; + if (_extraMode != 0) { + config.flags |= CONFIG_EXTRA_MODE; + config.xmode = _extraMode; + } + + if (!WavpackSetConfiguration(_wpc, &config, (_finalSampleCount == 0) ? -1 : _finalSampleCount)) { + throw gcnew Exception("Invalid configuration setting."); + } + + if (!WavpackPackInit(_wpc)) { + throw gcnew Exception("Unable to initialize the encoder."); + } + + _initialized = true; + } + }; + +#pragma unmanaged + int write_block(void *id, void *data, int32_t length) { + return (fwrite(data, 1, length, (FILE*)id) == length); + } +} \ No newline at end of file diff --git a/WavPackDotNet/WavPackDotNet.sln b/WavPackDotNet/WavPackDotNet.sln new file mode 100644 index 0000000..773fcde --- /dev/null +++ b/WavPackDotNet/WavPackDotNet.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WavPackDotNet", "WavPackDotNet.vcproj", "{CC2E74B6-534A-43D8-9F16-AC03FE955000}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|Win32.ActiveCfg = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Debug|Win32.Build.0 = Debug|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|Win32.ActiveCfg = Release|Win32 + {CC2E74B6-534A-43D8-9F16-AC03FE955000}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WavPackDotNet/WavPackDotNet.vcproj b/WavPackDotNet/WavPackDotNet.vcproj new file mode 100644 index 0000000..c92c5ea --- /dev/null +++ b/WavPackDotNet/WavPackDotNet.vcproj @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WavPackDotNet/app.ico b/WavPackDotNet/app.ico new file mode 100644 index 0000000..3a5525f Binary files /dev/null and b/WavPackDotNet/app.ico differ diff --git a/WavPackDotNet/app.rc b/WavPackDotNet/app.rc new file mode 100644 index 0000000..8c1d640 --- /dev/null +++ b/WavPackDotNet/app.rc @@ -0,0 +1,63 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon placed first or with lowest ID value becomes application icon + +LANGUAGE 9, 1 +#pragma code_page(1252) +1 ICON "app.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" + "\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/WavPackDotNet/resource.h b/WavPackDotNet/resource.h new file mode 100644 index 0000000..1f2251c --- /dev/null +++ b/WavPackDotNet/resource.h @@ -0,0 +1,3 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by app.rc diff --git a/flac/AUTHORS b/flac/AUTHORS new file mode 100644 index 0000000..d179a79 --- /dev/null +++ b/flac/AUTHORS @@ -0,0 +1,41 @@ +/* FLAC - Free Lossless Audio Codec + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This file is part the FLAC project. FLAC is comprised of several + * components distributed under difference licenses. The codec libraries + * are distributed under Xiph.Org's BSD-like license (see the file + * COPYING.Xiph in this distribution). All other programs, libraries, and + * plugins are distributed under the GPL (see COPYING.GPL). The documentation + * is distributed under the Gnu FDL (see COPYING.FDL). Each file in the + * FLAC distribution contains at the top the terms under which it may be + * distributed. + * + * Since this particular file is relevant to all components of FLAC, + * it may be distributed under the Xiph.Org license, which is the least + * restrictive of those mentioned above. See the file COPYING.Xiph in this + * distribution. + */ + + +FLAC (http://flac.sourceforge.net/) is an Open Source lossless audio +codec developed by Josh Coalson . + +Other major contributors and their contributions: +"Andrey Astafiev" +* Russian translation of the HTML documentation + +"Miroslav Lichvar" +* IA-32 assembly versions of several libFLAC routines + +"Brady Patterson" +* AIFF file support, PPC assembly versions of libFLAC routines + +"Daisuke Shimamura" +* i18n support in the XMMS plugin + +"X-Fixer" +* Configuration system, tag editing, and file info in the Winamp2 plugin + +"Matt Zimmerman" +* Libtool/autoconf/automake make system, flac man page + diff --git a/flac/COPYING.FDL b/flac/COPYING.FDL new file mode 100644 index 0000000..ba72821 --- /dev/null +++ b/flac/COPYING.FDL @@ -0,0 +1,397 @@ + GNU Free Documentation License + Version 1.2, November 2002 + + + Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + +0. PREAMBLE + +The purpose of this License is to make a manual, textbook, or other +functional and useful document "free" in the sense of freedom: to +assure everyone the effective freedom to copy and redistribute it, +with or without modifying it, either commercially or noncommercially. +Secondarily, this License preserves for the author and publisher a way +to get credit for their work, while not being considered responsible +for modifications made by others. + +This License is a kind of "copyleft", which means that derivative +works of the document must themselves be free in the same sense. It +complements the GNU General Public License, which is a copyleft +license designed for free software. + +We have designed this License in order to use it for manuals for free +software, because free software needs free documentation: a free +program should come with manuals providing the same freedoms that the +software does. But this License is not limited to software manuals; +it can be used for any textual work, regardless of subject matter or +whether it is published as a printed book. We recommend this License +principally for works whose purpose is instruction or reference. + + +1. APPLICABILITY AND DEFINITIONS + +This License applies to any manual or other work, in any medium, that +contains a notice placed by the copyright holder saying it can be +distributed under the terms of this License. Such a notice grants a +world-wide, royalty-free license, unlimited in duration, to use that +work under the conditions stated herein. The "Document", below, +refers to any such manual or work. Any member of the public is a +licensee, and is addressed as "you". You accept the license if you +copy, modify or distribute the work in a way requiring permission +under copyright law. + +A "Modified Version" of the Document means any work containing the +Document or a portion of it, either copied verbatim, or with +modifications and/or translated into another language. + +A "Secondary Section" is a named appendix or a front-matter section of +the Document that deals exclusively with the relationship of the +publishers or authors of the Document to the Document's overall subject +(or to related matters) and contains nothing that could fall directly +within that overall subject. (Thus, if the Document is in part a +textbook of mathematics, a Secondary Section may not explain any +mathematics.) The relationship could be a matter of historical +connection with the subject or with related matters, or of legal, +commercial, philosophical, ethical or political position regarding +them. + +The "Invariant Sections" are certain Secondary Sections whose titles +are designated, as being those of Invariant Sections, in the notice +that says that the Document is released under this License. If a +section does not fit the above definition of Secondary then it is not +allowed to be designated as Invariant. The Document may contain zero +Invariant Sections. If the Document does not identify any Invariant +Sections then there are none. + +The "Cover Texts" are certain short passages of text that are listed, +as Front-Cover Texts or Back-Cover Texts, in the notice that says that +the Document is released under this License. A Front-Cover Text may +be at most 5 words, and a Back-Cover Text may be at most 25 words. + +A "Transparent" copy of the Document means a machine-readable copy, +represented in a format whose specification is available to the +general public, that is suitable for revising the document +straightforwardly with generic text editors or (for images composed of +pixels) generic paint programs or (for drawings) some widely available +drawing editor, and that is suitable for input to text formatters or +for automatic translation to a variety of formats suitable for input +to text formatters. A copy made in an otherwise Transparent file +format whose markup, or absence of markup, has been arranged to thwart +or discourage subsequent modification by readers is not Transparent. +An image format is not Transparent if used for any substantial amount +of text. A copy that is not "Transparent" is called "Opaque". + +Examples of suitable formats for Transparent copies include plain +ASCII without markup, Texinfo input format, LaTeX input format, SGML +or XML using a publicly available DTD, and standard-conforming simple +HTML, PostScript or PDF designed for human modification. Examples of +transparent image formats include PNG, XCF and JPG. Opaque formats +include proprietary formats that can be read and edited only by +proprietary word processors, SGML or XML for which the DTD and/or +processing tools are not generally available, and the +machine-generated HTML, PostScript or PDF produced by some word +processors for output purposes only. + +The "Title Page" means, for a printed book, the title page itself, +plus such following pages as are needed to hold, legibly, the material +this License requires to appear in the title page. For works in +formats which do not have any title page as such, "Title Page" means +the text near the most prominent appearance of the work's title, +preceding the beginning of the body of the text. + +A section "Entitled XYZ" means a named subunit of the Document whose +title either is precisely XYZ or contains XYZ in parentheses following +text that translates XYZ in another language. (Here XYZ stands for a +specific section name mentioned below, such as "Acknowledgements", +"Dedications", "Endorsements", or "History".) To "Preserve the Title" +of such a section when you modify the Document means that it remains a +section "Entitled XYZ" according to this definition. + +The Document may include Warranty Disclaimers next to the notice which +states that this License applies to the Document. These Warranty +Disclaimers are considered to be included by reference in this +License, but only as regards disclaiming warranties: any other +implication that these Warranty Disclaimers may have is void and has +no effect on the meaning of this License. + + +2. VERBATIM COPYING + +You may copy and distribute the Document in any medium, either +commercially or noncommercially, provided that this License, the +copyright notices, and the license notice saying this License applies +to the Document are reproduced in all copies, and that you add no other +conditions whatsoever to those of this License. You may not use +technical measures to obstruct or control the reading or further +copying of the copies you make or distribute. However, you may accept +compensation in exchange for copies. If you distribute a large enough +number of copies you must also follow the conditions in section 3. + +You may also lend copies, under the same conditions stated above, and +you may publicly display copies. + + +3. COPYING IN QUANTITY + +If you publish printed copies (or copies in media that commonly have +printed covers) of the Document, numbering more than 100, and the +Document's license notice requires Cover Texts, you must enclose the +copies in covers that carry, clearly and legibly, all these Cover +Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on +the back cover. Both covers must also clearly and legibly identify +you as the publisher of these copies. The front cover must present +the full title with all words of the title equally prominent and +visible. You may add other material on the covers in addition. +Copying with changes limited to the covers, as long as they preserve +the title of the Document and satisfy these conditions, can be treated +as verbatim copying in other respects. + +If the required texts for either cover are too voluminous to fit +legibly, you should put the first ones listed (as many as fit +reasonably) on the actual cover, and continue the rest onto adjacent +pages. + +If you publish or distribute Opaque copies of the Document numbering +more than 100, you must either include a machine-readable Transparent +copy along with each Opaque copy, or state in or with each Opaque copy +a computer-network location from which the general network-using +public has access to download using public-standard network protocols +a complete Transparent copy of the Document, free of added material. +If you use the latter option, you must take reasonably prudent steps, +when you begin distribution of Opaque copies in quantity, to ensure +that this Transparent copy will remain thus accessible at the stated +location until at least one year after the last time you distribute an +Opaque copy (directly or through your agents or retailers) of that +edition to the public. + +It is requested, but not required, that you contact the authors of the +Document well before redistributing any large number of copies, to give +them a chance to provide you with an updated version of the Document. + + +4. MODIFICATIONS + +You may copy and distribute a Modified Version of the Document under +the conditions of sections 2 and 3 above, provided that you release +the Modified Version under precisely this License, with the Modified +Version filling the role of the Document, thus licensing distribution +and modification of the Modified Version to whoever possesses a copy +of it. In addition, you must do these things in the Modified Version: + +A. Use in the Title Page (and on the covers, if any) a title distinct + from that of the Document, and from those of previous versions + (which should, if there were any, be listed in the History section + of the Document). You may use the same title as a previous version + if the original publisher of that version gives permission. +B. List on the Title Page, as authors, one or more persons or entities + responsible for authorship of the modifications in the Modified + Version, together with at least five of the principal authors of the + Document (all of its principal authors, if it has fewer than five), + unless they release you from this requirement. +C. State on the Title page the name of the publisher of the + Modified Version, as the publisher. +D. Preserve all the copyright notices of the Document. +E. Add an appropriate copyright notice for your modifications + adjacent to the other copyright notices. +F. Include, immediately after the copyright notices, a license notice + giving the public permission to use the Modified Version under the + terms of this License, in the form shown in the Addendum below. +G. Preserve in that license notice the full lists of Invariant Sections + and required Cover Texts given in the Document's license notice. +H. Include an unaltered copy of this License. +I. Preserve the section Entitled "History", Preserve its Title, and add + to it an item stating at least the title, year, new authors, and + publisher of the Modified Version as given on the Title Page. If + there is no section Entitled "History" in the Document, create one + stating the title, year, authors, and publisher of the Document as + given on its Title Page, then add an item describing the Modified + Version as stated in the previous sentence. +J. Preserve the network location, if any, given in the Document for + public access to a Transparent copy of the Document, and likewise + the network locations given in the Document for previous versions + it was based on. These may be placed in the "History" section. + You may omit a network location for a work that was published at + least four years before the Document itself, or if the original + publisher of the version it refers to gives permission. +K. For any section Entitled "Acknowledgements" or "Dedications", + Preserve the Title of the section, and preserve in the section all + the substance and tone of each of the contributor acknowledgements + and/or dedications given therein. +L. Preserve all the Invariant Sections of the Document, + unaltered in their text and in their titles. Section numbers + or the equivalent are not considered part of the section titles. +M. Delete any section Entitled "Endorsements". Such a section + may not be included in the Modified Version. +N. Do not retitle any existing section to be Entitled "Endorsements" + or to conflict in title with any Invariant Section. +O. Preserve any Warranty Disclaimers. + +If the Modified Version includes new front-matter sections or +appendices that qualify as Secondary Sections and contain no material +copied from the Document, you may at your option designate some or all +of these sections as invariant. To do this, add their titles to the +list of Invariant Sections in the Modified Version's license notice. +These titles must be distinct from any other section titles. + +You may add a section Entitled "Endorsements", provided it contains +nothing but endorsements of your Modified Version by various +parties--for example, statements of peer review or that the text has +been approved by an organization as the authoritative definition of a +standard. + +You may add a passage of up to five words as a Front-Cover Text, and a +passage of up to 25 words as a Back-Cover Text, to the end of the list +of Cover Texts in the Modified Version. Only one passage of +Front-Cover Text and one of Back-Cover Text may be added by (or +through arrangements made by) any one entity. If the Document already +includes a cover text for the same cover, previously added by you or +by arrangement made by the same entity you are acting on behalf of, +you may not add another; but you may replace the old one, on explicit +permission from the previous publisher that added the old one. + +The author(s) and publisher(s) of the Document do not by this License +give permission to use their names for publicity for or to assert or +imply endorsement of any Modified Version. + + +5. COMBINING DOCUMENTS + +You may combine the Document with other documents released under this +License, under the terms defined in section 4 above for modified +versions, provided that you include in the combination all of the +Invariant Sections of all of the original documents, unmodified, and +list them all as Invariant Sections of your combined work in its +license notice, and that you preserve all their Warranty Disclaimers. + +The combined work need only contain one copy of this License, and +multiple identical Invariant Sections may be replaced with a single +copy. If there are multiple Invariant Sections with the same name but +different contents, make the title of each such section unique by +adding at the end of it, in parentheses, the name of the original +author or publisher of that section if known, or else a unique number. +Make the same adjustment to the section titles in the list of +Invariant Sections in the license notice of the combined work. + +In the combination, you must combine any sections Entitled "History" +in the various original documents, forming one section Entitled +"History"; likewise combine any sections Entitled "Acknowledgements", +and any sections Entitled "Dedications". You must delete all sections +Entitled "Endorsements". + + +6. COLLECTIONS OF DOCUMENTS + +You may make a collection consisting of the Document and other documents +released under this License, and replace the individual copies of this +License in the various documents with a single copy that is included in +the collection, provided that you follow the rules of this License for +verbatim copying of each of the documents in all other respects. + +You may extract a single document from such a collection, and distribute +it individually under this License, provided you insert a copy of this +License into the extracted document, and follow this License in all +other respects regarding verbatim copying of that document. + + +7. AGGREGATION WITH INDEPENDENT WORKS + +A compilation of the Document or its derivatives with other separate +and independent documents or works, in or on a volume of a storage or +distribution medium, is called an "aggregate" if the copyright +resulting from the compilation is not used to limit the legal rights +of the compilation's users beyond what the individual works permit. +When the Document is included in an aggregate, this License does not +apply to the other works in the aggregate which are not themselves +derivative works of the Document. + +If the Cover Text requirement of section 3 is applicable to these +copies of the Document, then if the Document is less than one half of +the entire aggregate, the Document's Cover Texts may be placed on +covers that bracket the Document within the aggregate, or the +electronic equivalent of covers if the Document is in electronic form. +Otherwise they must appear on printed covers that bracket the whole +aggregate. + + +8. TRANSLATION + +Translation is considered a kind of modification, so you may +distribute translations of the Document under the terms of section 4. +Replacing Invariant Sections with translations requires special +permission from their copyright holders, but you may include +translations of some or all Invariant Sections in addition to the +original versions of these Invariant Sections. You may include a +translation of this License, and all the license notices in the +Document, and any Warranty Disclaimers, provided that you also include +the original English version of this License and the original versions +of those notices and disclaimers. In case of a disagreement between +the translation and the original version of this License or a notice +or disclaimer, the original version will prevail. + +If a section in the Document is Entitled "Acknowledgements", +"Dedications", or "History", the requirement (section 4) to Preserve +its Title (section 1) will typically require changing the actual +title. + + +9. TERMINATION + +You may not copy, modify, sublicense, or distribute the Document except +as expressly provided for under this License. Any other attempt to +copy, modify, sublicense or distribute the Document is void, and will +automatically terminate your rights under this License. However, +parties who have received copies, or rights, from you under this +License will not have their licenses terminated so long as such +parties remain in full compliance. + + +10. FUTURE REVISIONS OF THIS LICENSE + +The Free Software Foundation may publish new, revised versions +of the GNU Free Documentation License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. See +http://www.gnu.org/copyleft/. + +Each version of the License is given a distinguishing version number. +If the Document specifies that a particular numbered version of this +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that specified version or +of any later version that has been published (not as a draft) by the +Free Software Foundation. If the Document does not specify a version +number of this License, you may choose any version ever published (not +as a draft) by the Free Software Foundation. + + +ADDENDUM: How to use this License for your documents + +To use this License in a document you have written, include a copy of +the License in the document and put the following copyright and +license notices just after the title page: + + Copyright (c) YEAR YOUR NAME. + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.2 + or any later version published by the Free Software Foundation; + with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. + A copy of the license is included in the section entitled "GNU + Free Documentation License". + +If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, +replace the "with...Texts." line with this: + + with the Invariant Sections being LIST THEIR TITLES, with the + Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. + +If you have Invariant Sections without Cover Texts, or some other +combination of the three, merge those two alternatives to suit the +situation. + +If your document contains nontrivial examples of program code, we +recommend releasing these examples in parallel under your choice of +free software license, such as the GNU General Public License, +to permit their use in free software. diff --git a/flac/COPYING.GPL b/flac/COPYING.GPL new file mode 100644 index 0000000..90df1ce --- /dev/null +++ b/flac/COPYING.GPL @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/flac/COPYING.LGPL b/flac/COPYING.LGPL new file mode 100644 index 0000000..5faba9d --- /dev/null +++ b/flac/COPYING.LGPL @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/flac/COPYING.Xiph b/flac/COPYING.Xiph new file mode 100644 index 0000000..fdcf02e --- /dev/null +++ b/flac/COPYING.Xiph @@ -0,0 +1,28 @@ +Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- 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. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``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 FOUNDATION OR +CONTRIBUTORS 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. diff --git a/flac/FLAC.dsw b/flac/FLAC.dsw new file mode 100644 index 0000000..909a72b --- /dev/null +++ b/flac/FLAC.dsw @@ -0,0 +1,683 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "all"=.\all.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name all_dynamic + End Project Dependency + Begin Project Dependency + Project_Dep_Name all_static + End Project Dependency +}}} + +############################################################################### + +Project: "all_dynamic"=.\all_dynamic.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name examples + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac + End Project Dependency + Begin Project Dependency + Project_Dep_Name iffscan + End Project Dependency + Begin Project Dependency + Project_Dep_Name metaflac + End Project Dependency + Begin Project Dependency + Project_Dep_Name in_flac + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac_mac + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac_ren + End Project Dependency + Begin Project Dependency + Project_Dep_Name flacdiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name flactimer + End Project Dependency + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_analysis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_synthesis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name getopt_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_dynamic + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC++_dynamic + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libs_common_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name plugin_common_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name utf8_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_cuesheet + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_picture + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libFLAC + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libFLAC++ + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_seeking + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_streams + End Project Dependency +}}} + +############################################################################### + +Project: "all_static"=.\all_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name examples + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac + End Project Dependency + Begin Project Dependency + Project_Dep_Name iffscan + End Project Dependency + Begin Project Dependency + Project_Dep_Name metaflac + End Project Dependency + Begin Project Dependency + Project_Dep_Name in_flac + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac_mac + End Project Dependency + Begin Project Dependency + Project_Dep_Name flac_ren + End Project Dependency + Begin Project Dependency + Project_Dep_Name flacdiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name flactimer + End Project Dependency + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_analysis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_synthesis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name getopt_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libs_common_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name plugin_common_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name utf8_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_cuesheet + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_picture + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libFLAC + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libFLAC++ + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_seeking + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_streams + End Project Dependency +}}} + +############################################################################### + +Project: "examples"=.\examples\examples.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name example_c_decode_file + End Project Dependency + Begin Project Dependency + Project_Dep_Name example_c_encode_file + End Project Dependency + Begin Project Dependency + Project_Dep_Name example_cpp_decode_file + End Project Dependency + Begin Project Dependency + Project_Dep_Name example_cpp_encode_file + End Project Dependency +}}} + +############################################################################### + +Project: "example_c_decode_file"=.\examples\c\decode\file\example_c_decode_file.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "example_c_encode_file"=.\examples\c\encode\file\example_c_encode_file.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "example_cpp_decode_file"=.\examples\cpp\decode\file\example_cpp_decode_file.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "example_cpp_encode_file"=.\examples\cpp\encode\file\example_cpp_encode_file.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "flac"=.\src\flac\flac.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_analysis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_synthesis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name getopt_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name utf8_static + End Project Dependency +}}} + +############################################################################### + +Project: "iffscan"=.\src\flac\iffscan.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "flac_mac"=.\src\monkeys_audio_utilities\flac_mac\flac_mac.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "flac_ren"=.\src\monkeys_audio_utilities\flac_ren\flac_ren.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "replaygain_analysis_static"=.\src\share\replaygain_analysis\replaygain_analysis_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "replaygain_synthesis_static"=.\src\share\replaygain_synthesis\replaygain_synthesis_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "getopt_static"=.\src\share\getopt\getopt_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "grabbag_static"=.\src\share\grabbag\grabbag_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name replaygain_analysis_static + End Project Dependency +}}} + +############################################################################### + +Project: "in_flac"=.\src\plugin_winamp2\in_flac.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name plugin_common_static + End Project Dependency +}}} + +############################################################################### + +Project: "libFLAC_dynamic"=.\src\libFLAC\libFLAC_dynamic.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "libFLAC_static"=.\src\libFLAC\libFLAC_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "libFLAC++_dynamic"=".\src\libFLAC++\libFLAC++_dynamic.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_dynamic + End Project Dependency +}}} + +############################################################################### + +Project: "libFLAC++_static"=".\src\libFLAC++\libFLAC++_static.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "metaflac"=.\src\metaflac\metaflac.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name replaygain_analysis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name getopt_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name utf8_static + End Project Dependency +}}} + +############################################################################### + +Project: "plugin_common_static"=.\src\plugin_common\plugin_common_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name replaygain_synthesis_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_cuesheet"=.\src\test_grabbag\cuesheet\test_cuesheet.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_picture"=.\src\test_grabbag\picture\test_picture.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name grabbag_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_libs_common"=.\src\test_libs_common\test_libs_common_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_libFLAC"=.\src\test_libFLAC\test_libFLAC.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libs_common_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_libFLAC++"=".\src\test_libFLAC++\test_libFLAC++.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency + Begin Project Dependency + Project_Dep_Name test_libs_common_static + End Project Dependency +}}} + +############################################################################### + +Project: "test_seeking"=.\src\test_seeking\test_seeking.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "test_streams"=.\src\test_streams\test_streams.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "utf8_static"=.\src\share\utf8\utf8_static.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "flacdiff"=".\src\utils\flacdiff\flacdiff.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libFLAC++_static + End Project Dependency +}}} + +############################################################################### + +Project: "flactimer"=".\src\utils\flactimer\flactimer.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/flac/FLAC.sln b/flac/FLAC.sln new file mode 100644 index 0000000..adb21e6 --- /dev/null +++ b/flac/FLAC.sln @@ -0,0 +1,383 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_c_decode_file", "examples\c\decode\file\example_c_decode_file.vcproj", "{4CEFBD00-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_c_encode_file", "examples\c\encode\file\example_c_encode_file.vcproj", "{4CEFBD01-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_cpp_decode_file", "examples\cpp\decode\file\example_cpp_decode_file.vcproj", "{4CEFBE00-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + {4CEFBC86-C215-11DB-8314-0800200C9A66} = {4CEFBC86-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_cpp_encode_file", "examples\cpp\encode\file\example_cpp_encode_file.vcproj", "{4CEFBE01-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + {4CEFBC86-C215-11DB-8314-0800200C9A66} = {4CEFBC86-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flac", "src\flac\flac.vcproj", "{4CEFBC7D-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + {4CEFBC89-C215-11DB-8314-0800200C9A66} = {4CEFBC89-C215-11DB-8314-0800200C9A66} + {4CEFBC92-C215-11DB-8314-0800200C9A66} = {4CEFBC92-C215-11DB-8314-0800200C9A66} + {4CEFBC80-C215-11DB-8314-0800200C9A66} = {4CEFBC80-C215-11DB-8314-0800200C9A66} + {4CEFBC8A-C215-11DB-8314-0800200C9A66} = {4CEFBC8A-C215-11DB-8314-0800200C9A66} + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iffscan", "src\flac\iffscan.vcproj", "{4CEFBC94-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flac_mac", "src\monkeys_audio_utilities\flac_mac\flac_mac.vcproj", "{4CEFBC7E-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flac_ren", "src\monkeys_audio_utilities\flac_ren\flac_ren.vcproj", "{4CEFBC7F-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flacdiff", "src\utils\flacdiff\flacdiff.vcproj", "{4CEFBC93-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC86-C215-11DB-8314-0800200C9A66} = {4CEFBC86-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flactimer", "src\utils\flactimer\flactimer.vcproj", "{4CEFBC95-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "getopt_static", "src\share\getopt\getopt_static.vcproj", "{4CEFBC80-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grabbag_static", "src\share\grabbag\grabbag_static.vcproj", "{4CEFBC81-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + {4CEFBC89-C215-11DB-8314-0800200C9A66} = {4CEFBC89-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "in_flac", "src\plugin_winamp2\in_flac.vcproj", "{4CEFBC82-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + {4CEFBC8A-C215-11DB-8314-0800200C9A66} = {4CEFBC8A-C215-11DB-8314-0800200C9A66} + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + {4CEFBC88-C215-11DB-8314-0800200C9A66} = {4CEFBC88-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libFLAC_dynamic", "src\libFLAC\libFLAC_dynamic.vcproj", "{4CEFBC83-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libFLAC_static", "src\libFLAC\libFLAC_static.vcproj", "{4CEFBC84-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libFLAC++_dynamic", "src\libFLAC++\libFLAC++_dynamic.vcproj", "{4CEFBC85-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC83-C215-11DB-8314-0800200C9A66} = {4CEFBC83-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libFLAC++_static", "src\libFLAC++\libFLAC++_static.vcproj", "{4CEFBC86-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "metaflac", "src\metaflac\metaflac.vcproj", "{4CEFBC87-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + {4CEFBC80-C215-11DB-8314-0800200C9A66} = {4CEFBC80-C215-11DB-8314-0800200C9A66} + {4CEFBC92-C215-11DB-8314-0800200C9A66} = {4CEFBC92-C215-11DB-8314-0800200C9A66} + {4CEFBC89-C215-11DB-8314-0800200C9A66} = {4CEFBC89-C215-11DB-8314-0800200C9A66} + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "plugin_common_static", "src\plugin_common\plugin_common_static.vcproj", "{4CEFBC88-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "replaygain_analysis_static", "src\share\replaygain_analysis\replaygain_analysis_static.vcproj", "{4CEFBC89-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "replaygain_synthesis_static", "src\share\replaygain_synthesis\replaygain_synthesis_static.vcproj", "{4CEFBC8A-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_cuesheet", "src\test_grabbag\cuesheet\test_cuesheet.vcproj", "{4CEFBC8B-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_libFLAC", "src\test_libFLAC\test_libFLAC.vcproj", "{4CEFBC8C-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC8E-C215-11DB-8314-0800200C9A66} = {4CEFBC8E-C215-11DB-8314-0800200C9A66} + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_libFLAC++", "src\test_libFLAC++\test_libFLAC++.vcproj", "{4CEFBC8D-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC86-C215-11DB-8314-0800200C9A66} = {4CEFBC86-C215-11DB-8314-0800200C9A66} + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + {4CEFBC8E-C215-11DB-8314-0800200C9A66} = {4CEFBC8E-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_libs_common_static", "src\test_libs_common\test_libs_common_static.vcproj", "{4CEFBC8E-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_picture", "src\test_grabbag\picture\test_picture.vcproj", "{4CEFBC8F-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC81-C215-11DB-8314-0800200C9A66} = {4CEFBC81-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_seeking", "src\test_seeking\test_seeking.vcproj", "{4CEFBC90-C215-11DB-8314-0800200C9A66}" + ProjectSection(ProjectDependencies) = postProject + {4CEFBC84-C215-11DB-8314-0800200C9A66} = {4CEFBC84-C215-11DB-8314-0800200C9A66} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_streams", "src\test_streams\test_streams.vcproj", "{4CEFBC91-C215-11DB-8314-0800200C9A66}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "utf8_static", "src\share\utf8\utf8_static.vcproj", "{4CEFBC92-C215-11DB-8314-0800200C9A66}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBD00-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBD01-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBE00-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBE01-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC7D-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC94-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC7E-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC7F-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC93-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC95-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC80-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC81-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC82-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC83-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC84-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC85-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC86-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC87-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC88-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC89-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8A-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8B-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8C-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8D-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8E-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC8F-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC90-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC91-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Debug|Win32.Build.0 = Debug|Win32 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Debug|x64.ActiveCfg = Debug|x64 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Debug|x64.Build.0 = Debug|x64 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Release|Win32.ActiveCfg = Release|Win32 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Release|Win32.Build.0 = Release|Win32 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Release|x64.ActiveCfg = Release|x64 + {4CEFBC92-C215-11DB-8314-0800200C9A66}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/flac/Makefile.am b/flac/Makefile.am new file mode 100644 index 0000000..d2a9f7d --- /dev/null +++ b/flac/Makefile.am @@ -0,0 +1,52 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# automake provides the following useful targets: +# +# all: build all programs and libraries using the current +# configuration (set by configure) +# +# check: build and run all self-tests +# +# clean: remove everything except what's required to build everything +# +# distclean: remove everything except what goes in the distribution +# + +AUTOMAKE_OPTIONS = foreign 1.7 + +SUBDIRS = doc include m4 man src examples test build obj + +DISTCLEANFILES = libtool-disable-static + +EXTRA_DIST = \ + COPYING.FDL \ + COPYING.GPL \ + COPYING.LGPL \ + COPYING.Xiph \ + FLAC.dsw \ + FLAC.sln \ + Makefile.lite \ + all.dsp \ + all_dynamic.dsp \ + all_static.dsp \ + autogen.sh \ + config.rpath \ + depcomp \ + ltmain.sh \ + strip_non_asm_libtool_args.sh diff --git a/flac/Makefile.lite b/flac/Makefile.lite new file mode 100644 index 0000000..dbd21c7 --- /dev/null +++ b/flac/Makefile.lite @@ -0,0 +1,106 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# GNU Makefile +# +# Useful targets +# +# all : build all libraries and programs in the default configuration (currently 'release') +# debug : build all libraries and programs in debug mode +# valgrind: build all libraries and programs in debug mode, dynamically linked and ready for valgrind +# release : build all libraries and programs in release mode +# test : run the unit and stream tests +# clean : remove all non-distro files +# + +topdir = . + +.PHONY: all doc src examples libFLAC libFLAC++ share plugin_common plugin_xmms flac metaflac test_grabbag test_libFLAC test_libFLAC++ test_seeking test_streams +all: doc src examples + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +debug : CONFIG = debug +valgrind: CONFIG = valgrind +release : CONFIG = release + +debug : all +valgrind: all +release : all + +doc: + (cd $@ && $(MAKE) -f Makefile.lite) + +src: + (cd $@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +examples: src + (cd $@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +libFLAC: + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +libFLAC++: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +share: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +flac: libFLAC share + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +metaflac: libFLAC share + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +plugin_common: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +plugin_xmms: libFLAC plugin_common + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test_seeking: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test_streams: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test_grabbag: share + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test_libFLAC: libFLAC + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test_libFLAC++: libFLAC libFLAC++ + (cd src/$@ && $(MAKE) -f Makefile.lite $(CONFIG)) + +test: debug + (cd test && $(MAKE) -f Makefile.lite debug) + +testv: valgrind + (cd test && $(MAKE) -f Makefile.lite valgrind) + +testr: release + (cd test && $(MAKE) -f Makefile.lite release) + +clean: + -(cd doc && $(MAKE) -f Makefile.lite clean) + -(cd src && $(MAKE) -f Makefile.lite clean) + -(cd examples && $(MAKE) -f Makefile.lite clean) + -(cd test && $(MAKE) -f Makefile.lite clean) diff --git a/flac/README b/flac/README new file mode 100644 index 0000000..c0e74cc --- /dev/null +++ b/flac/README @@ -0,0 +1,254 @@ +/* FLAC - Free Lossless Audio Codec + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This file is part the FLAC project. FLAC is comprised of several + * components distributed under difference licenses. The codec libraries + * are distributed under Xiph.Org's BSD-like license (see the file + * COPYING.Xiph in this distribution). All other programs, libraries, and + * plugins are distributed under the LGPL or GPL (see COPYING.LGPL and + * COPYING.GPL). The documentation is distributed under the Gnu FDL (see + * COPYING.FDL). Each file in the FLAC distribution contains at the top the + * terms under which it may be distributed. + * + * Since this particular file is relevant to all components of FLAC, + * it may be distributed under the Xiph.Org license, which is the least + * restrictive of those mentioned above. See the file COPYING.Xiph in this + * distribution. + */ + + +FLAC (http://flac.sourceforge.net/) is an Open Source lossless audio +codec developed by Josh Coalson. + +FLAC is comprised of + * `libFLAC', a library which implements reference encoders and + decoders for native FLAC and Ogg FLAC, and a metadata interface + * `libFLAC++', a C++ object wrapper library around libFLAC + * `flac', a command-line program for encoding and decoding files + * `metaflac', a command-line program for viewing and editing FLAC + metadata + * player plugins for XMMS and Winamp + * user and API documentation + +The libraries (libFLAC, libFLAC++) are +licensed under Xiph.org's BSD-like license (see COPYING.Xiph). All other +programs and plugins are licensed under the GNU General Public License +(see COPYING.GPL). The documentation is licensed under the GNU Free +Documentation License (see COPYING.FDL). + + +=============================================================================== +FLAC - 1.2.1 - Contents +=============================================================================== + +- Introduction +- Prerequisites +- Note to embedded developers +- Building in a GNU environment +- Building with Makefile.lite +- Building with MSVC +- Building on Mac OS X + + +=============================================================================== +Introduction +=============================================================================== + +This is the source release for the FLAC project. See + + doc/html/index.html + +for full documentation. + +A brief description of the directory tree: + + doc/ the HTML documentation + include/ public include files for libFLAC and libFLAC++ + man/ the man page for `flac' + src/ the source code and private headers + test/ the test scripts + + +=============================================================================== +Prerequisites +=============================================================================== + +To build FLAC with support for Ogg FLAC you must have built and installed +libogg according to the specific instructions below. You must have +libogg 1.1.2 or greater, or there will be seeking problems with Ogg FLAC. + +If you are building on x86 and want the assembly optimizations, you will +need to have NASM >= 0.98.30 installed according to the specific instructions +below. + + +=============================================================================== +Note to embedded developers +=============================================================================== + +libFLAC has grown larger over time as more functionality has been +included, but much of it may be unnecessary for a particular embedded +implementation. Unused parts may be pruned by some simple editing of +configure.in and src/libFLAC/Makefile.am; the following dependency +graph shows which modules may be pruned without breaking things +further down: + +metadata.h + stream_decoder.h + format.h + +stream_encoder.h + stream_decoder.h + format.h + +stream_decoder.h + format.h + +In other words, for pure decoding applications, both the stream encoder +and metadata editing interfaces can be safely removed. + +There is a section dedicated to embedded use in the libFLAC API +HTML documentation (see doc/html/api/index.html). + +Also, there are several places in the libFLAC code with comments marked +with "OPT:" where a #define can be changed to enable code that might be +faster on a specific platform. Experimenting with these can yield faster +binaries. + + +=============================================================================== +Building in a GNU environment +=============================================================================== + +FLAC uses autoconf and libtool for configuring and building. +Better documentation for these will be forthcoming, but in +general, this should work: + +./configure && make && make check && make install + +The 'make check' step is optional; omit it to skip all the tests, +which can take several hours and use around 70-80 megs of disk space. +Even though it will stop with an explicit message on any failure, it +does print out a lot of stuff so you might want to capture the output +to a file if you're having a problem. Also, don't run 'make check' +as root because it confuses some of the tests. + +NOTE: Despite our best efforts it's entirely possible to have +problems when using older versions of autoconf, automake, or +libtool. If you have the latest versions and still can't get it +to work, see the next section on Makefile.lite. + +There are a few FLAC-specific arguments you can give to +`configure': + +--enable-debug : Builds everything with debug symbols and some +extra (and more verbose) error checking. + +--disable-asm-optimizations : Disables the compilation of the +assembly routines. Many routines have assembly versions for +speed and `configure' is pretty good about knowing what is +supported, but you can use this option to build only from the +C sources. May be necessary for building on OS X (Intel) + +--enable-sse : If you are building for an x86 CPU that supports +SSE instructions, you can enable some of the faster routines +if your operating system also supports SSE instructions. flac +can tell if the CPU supports the instructions but currently has +no way to test if the OS does, so if it does, you must pass +this argument to configure to use the SSE routines. If flac +crashes when built with this option you will have to go back and +configure without --enable-sse. Note that +--disable-asm-optimizations implies --disable-sse. + +--enable-local-xmms-plugin : Installs the FLAC XMMS plugin in +$HOME/.xmms/Plugins, instead of the global XMMS plugin area +(usually /usr/lib/xmms/Input). + +--with-ogg= +--with-xmms-prefix= +--with-libiconv-prefix= +Use these if you have these packages but configure can't find them. + +If you want to build completely from scratch (i.e. starting with just +configure.in and Makefile.am) you should be able to just run 'autogen.sh' +but make sure and read the comments in that file first. + + +=============================================================================== +Building with Makefile.lite +=============================================================================== + +There is a more lightweight build system for do-it-yourself-ers. +It is also useful if configure isn't working, which may be the +case since lately we've had some problems with different versions +of automake and libtool. The Makefile.lite system should work +on GNU systems with few or no adjustments. + +From the top level just 'make -f Makefile.lite'. You can +specify zero or one optional target from 'release', 'debug', +'test', or 'clean'. The default is 'release'. There is no +'install' target but everything you need will end up in the +obj/ directory. + +If you are not on an x86 system or you don't have nasm, you +may have to change the DEFINES in src/libFLAC/Makefile.lite. If +you don't have nasm, remove -DFLAC__HAS_NASM. If your target is +not an x86, change -DFLAC__CPU_IA32 to -DFLAC__CPU_UNKNOWN. + + +=============================================================================== +Building with MSVC +=============================================================================== + +There are .dsp projects and a master FLAC.dsw workspace to build all +the libraries and executables with MSVC6. There are also .vcproj +projects and a master FLAC.sln solution to build all the libraries and +executables with VC++ 2005. + +Prerequisite: you must have the Ogg libraries installed as described +later. + +Prerequisite: you must have nasm installed, and nasmw.exe must be in +your PATH, or the path to nasmw.exe must be added to the list of +directories for executable files in the MSVC global options. + +MSVC6: +To build everything, run Developer Studio, do File|Open Workspace, +and open FLAC.dsw. Select "Build | Set active configuration..." +from the menu, then in the dialog, select "All - Win32 Release" (or +Debug if you prefer). Click "Ok" then hit F7 to build. + +VC++ 2005: +To build everything, run Visual Studio, do File|Open and open FLAC.sln. +From the dropdown in the toolbar, select "Release" instead of "Debug", +then hit F7 to build. + +Either way, this will build all libraries both statically (e.g. +obj\release\lib\libFLAC_static.lib) and as DLLs (e.g. +obj\release\lib\libFLAC.dll), and it will build all binaries, statically +linked (e.g. obj\release\bin\flac.exe). + +Everything will end up in the "obj" directory. DLLs and .exe files +are all that are needed and can be copied to an installation area and +added to the PATH. The plugins have to be copied to their appropriate +place in the player area. For Winamp2 this is \Plugins. + +By default the code is configured with Ogg support. Before building FLAC +you will need to get the Ogg source distribution +(see http://xiph.org/ogg/vorbis/download/), build ogg_static.lib (load and +build win32\ogg_static.dsp), copy ogg_static.lib into FLAC's +'obj\release\lib' directory, and copy the entire include\ogg tree into +FLAC's 'include' directory (so that there is an 'ogg' directory in FLAC's +'include' directory with the files ogg.h, os_types.h and config_types.h). + +If you want to build without Ogg support, instead edit all .dsp or +.vcproj files and remove any occurrences of "/D FLAC__HAS_OGG". + + +=============================================================================== +Building on Mac OS X +=============================================================================== + +If you have Fink or a recent version of OS X with the proper autotooles, +the GNU flow above should work. The Project Builder project has been +deprecated but we are working on replacing it with an Xcode equivalent. diff --git a/flac/all.dsp b/flac/all.dsp new file mode 100644 index 0000000..c85ef84 --- /dev/null +++ b/flac/all.dsp @@ -0,0 +1,67 @@ +# Microsoft Developer Studio Project File - Name="all" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Generic Project" 0x010a + +CFG=all - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "all.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "all.mak" CFG="all - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "all - Win32 Release" (based on "Win32 (x86) Generic Project") +!MESSAGE "all - Win32 Debug" (based on "Win32 (x86) Generic Project") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "all" +# PROP Scc_LocalPath "." +MTL=midl.exe + +!IF "$(CFG)" == "all - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "obj\release" +# PROP Intermediate_Dir "obj\release" +# PROP Target_Dir "" + +!ELSEIF "$(CFG)" == "all - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "obj\debug" +# PROP Intermediate_Dir "obj\debug" +# PROP Target_Dir "" + +!ENDIF + +# Begin Target + +# Name "all - Win32 Release" +# Name "all - Win32 Debug" +# Begin Source File + +SOURCE=.\README +# End Source File +# End Target +# End Project diff --git a/flac/all_dynamic.dsp b/flac/all_dynamic.dsp new file mode 100644 index 0000000..8f93cae --- /dev/null +++ b/flac/all_dynamic.dsp @@ -0,0 +1,67 @@ +# Microsoft Developer Studio Project File - Name="all_dynamic" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Generic Project" 0x010a + +CFG=all_dynamic - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "all_dynamic.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "all_dynamic.mak" CFG="all_dynamic - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "all_dynamic - Win32 Release" (based on "Win32 (x86) Generic Project") +!MESSAGE "all_dynamic - Win32 Debug" (based on "Win32 (x86) Generic Project") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "all" +# PROP Scc_LocalPath "." +MTL=midl.exe + +!IF "$(CFG)" == "all_dynamic - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "obj\release" +# PROP Intermediate_Dir "obj\release" +# PROP Target_Dir "" + +!ELSEIF "$(CFG)" == "all_dynamic - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "obj\debug" +# PROP Intermediate_Dir "obj\debug" +# PROP Target_Dir "" + +!ENDIF + +# Begin Target + +# Name "all_dynamic - Win32 Release" +# Name "all_dynamic - Win32 Debug" +# Begin Source File + +SOURCE=.\README +# End Source File +# End Target +# End Project diff --git a/flac/all_static.dsp b/flac/all_static.dsp new file mode 100644 index 0000000..c96f3c0 --- /dev/null +++ b/flac/all_static.dsp @@ -0,0 +1,67 @@ +# Microsoft Developer Studio Project File - Name="all_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Generic Project" 0x010a + +CFG=all_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "all_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "all_static.mak" CFG="all_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "all_static - Win32 Release" (based on "Win32 (x86) Generic Project") +!MESSAGE "all_static - Win32 Debug" (based on "Win32 (x86) Generic Project") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "all" +# PROP Scc_LocalPath "." +MTL=midl.exe + +!IF "$(CFG)" == "all_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "obj\release" +# PROP Intermediate_Dir "obj\release" +# PROP Target_Dir "" + +!ELSEIF "$(CFG)" == "all_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "obj\debug" +# PROP Intermediate_Dir "obj\debug" +# PROP Target_Dir "" + +!ENDIF + +# Begin Target + +# Name "all_static - Win32 Release" +# Name "all_static - Win32 Debug" +# Begin Source File + +SOURCE=.\README +# End Source File +# End Target +# End Project diff --git a/flac/autogen.sh b/flac/autogen.sh new file mode 100644 index 0000000..ab0532e --- /dev/null +++ b/flac/autogen.sh @@ -0,0 +1,162 @@ +#!/bin/sh +# Run this to set up the build system: configure, makefiles, etc. +# (based on the version in enlightenment's cvs) + +# Some notes: +# +# You may need to specify -I /SOME_PATH/share/aclocal in ACLOCAL_FLAGS +# if any packages FLAC relies on (autotools, libogg, libiconv) are +# installed in non-standard places. +# +# If you don't have XMMS installed at all, you should comment out +# AM_PATH_XMMS in configure.in. +# +# FLAC uses iconv but not gettext. iconv requires config.rpath which +# is supplied by gettext, which is copied in by gettextize. But we +# can't run gettextize since we do not fulfill all it's requirements +# (because we don't use it). So you may have to: +# +# cp /usr/share/gettext/config.rpath . +# +# before running autogen.sh +# +# If you are running on OS X and get errors related to the AM_ICONV +# and/or AM_LANGINFO_CODESET macros, replace those 2 lines in +# configure.in with +# +# AC_DEFINE([HAVE_ICONV], [], [Whether we have libiconv available]) LIBICONV="-liconv" +# AC_SUBST(LIBICONV) +# +# See also http://lists.xiph.org/pipermail/flac-dev/2007-September/002384.html +# +# Also watchout, if you replace ltmain.sh, there is a bug in some +# versions of libtool (or maybe autoconf) on some platforms where the +# configure-generated libtool does not have $SED defined. See also: +# +# http://lists.gnu.org/archive/html/libtool/2003-11/msg00131.html + +package="flac" + +olddir=`pwd` +srcdir=`dirname $0` +test -z "$srcdir" && srcdir=. + +cd "$srcdir" +DIE=0 + +ACLOCAL_FLAGS="-I m4 $ACLOCAL_FLAGS" + +echo "checking for autoconf... " +(autoconf --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "You must have autoconf installed to compile $package." + echo "Download the appropriate package for your distribution," + echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" + DIE=1 +} + +VERSIONGREP="sed -e s/.*[^0-9\.]\([0-9][0-9]*\.[0-9][0-9]*\).*/\1/" +VERSIONMKMAJ="sed -e s/\([0-9][0-9]*\)[^0-9].*/\\1/" +VERSIONMKMIN="sed -e s/.*[0-9][0-9]*\.//" + +# do we need automake? +if test -r Makefile.am; then + AM_OPTIONS=`fgrep AUTOMAKE_OPTIONS Makefile.am` + AM_NEEDED=`echo $AM_OPTIONS | $VERSIONGREP` + if test x"$AM_NEEDED" = "x$AM_OPTIONS"; then + AM_NEEDED="" + fi + if test -z $AM_NEEDED; then + echo -n "checking for automake... " + AUTOMAKE=automake + ACLOCAL=aclocal + if ($AUTOMAKE --version < /dev/null > /dev/null 2>&1); then + echo "yes" + else + echo "no" + AUTOMAKE= + fi + else + echo -n "checking for automake $AM_NEEDED or later... " + majneeded=`echo $AM_NEEDED | $VERSIONMKMAJ` + minneeded=`echo $AM_NEEDED | $VERSIONMKMIN` + for am in automake-$AM_NEEDED automake$AM_NEEDED \ + automake automake-1.7 automake-1.8 automake-1.9 automake-1.10; do + ($am --version < /dev/null > /dev/null 2>&1) || continue + ver=`$am --version < /dev/null | head -n 1 | $VERSIONGREP` + maj=`echo $ver | $VERSIONMKMAJ` + min=`echo $ver | $VERSIONMKMIN` + if test $maj -eq $majneeded -a $min -ge $minneeded; then + AUTOMAKE=$am + echo $AUTOMAKE + break + fi + done + test -z $AUTOMAKE && echo "no" + echo -n "checking for aclocal $AM_NEEDED or later... " + for ac in aclocal-$AM_NEEDED aclocal$AM_NEEDED \ + aclocal aclocal-1.7 aclocal-1.8 aclocal-1.9 aclocal-1.10; do + ($ac --version < /dev/null > /dev/null 2>&1) || continue + ver=`$ac --version < /dev/null | head -n 1 | $VERSIONGREP` + maj=`echo $ver | $VERSIONMKMAJ` + min=`echo $ver | $VERSIONMKMIN` + if test $maj -eq $majneeded -a $min -ge $minneeded; then + ACLOCAL=$ac + echo $ACLOCAL + break + fi + done + test -z $ACLOCAL && echo "no" + fi + test -z $AUTOMAKE || test -z $ACLOCAL && { + echo + echo "You must have automake installed to compile $package." + echo "Download the appropriate package for your distribution," + echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" + exit 1 + } +fi + +echo -n "checking for libtool... " +for LIBTOOLIZE in libtoolize glibtoolize nope; do + ($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 && break +done +if test x$LIBTOOLIZE = xnope; then + echo "nope." + LIBTOOLIZE=libtoolize +else + echo $LIBTOOLIZE +fi +($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "You must have libtool installed to compile $package." + echo "Download the appropriate package for your system," + echo "or get the source from one of the GNU ftp sites" + echo "listed in http://www.gnu.org/order/ftp.html" + DIE=1 +} + +if test "$DIE" -eq 1; then + exit 1 +fi + +if test -z "$*"; then + echo "I am going to run ./configure with no arguments - if you wish " + echo "to pass any to it, please specify them on the $0 command line." +fi + +echo "Generating configuration files for $package, please wait...." + +echo " $ACLOCAL $ACLOCAL_FLAGS" +$ACLOCAL $ACLOCAL_FLAGS || exit 1 +echo " $LIBTOOLIZE --automake" +$LIBTOOLIZE --automake || exit 1 +echo " autoheader" +autoheader || exit 1 +echo " $AUTOMAKE --add-missing $AUTOMAKE_FLAGS" +$AUTOMAKE --add-missing $AUTOMAKE_FLAGS || exit 1 +echo " autoconf" +autoconf || exit 1 + +cd $olddir +$srcdir/configure --enable-maintainer-mode "$@" && echo diff --git a/flac/build/Makefile.am b/flac/build/Makefile.am new file mode 100644 index 0000000..ca310c2 --- /dev/null +++ b/flac/build/Makefile.am @@ -0,0 +1,22 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + compile.mk \ + config.mk \ + exe.mk \ + lib.mk diff --git a/flac/build/compile.mk b/flac/build/compile.mk new file mode 100644 index 0000000..2888a3a --- /dev/null +++ b/flac/build/compile.mk @@ -0,0 +1,63 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# GNU makefile fragment for building a library +# + +%.debug.o %.release.o : %.c + $(CC) $(CFLAGS) -c $< -o $@ +%.debug.o %.release.o : %.cc + $(CCC) $(CFLAGS) -c $< -o $@ +%.debug.o %.release.o : %.cpp + $(CCC) $(CFLAGS) -c $< -o $@ +%.debug.pic.o %.release.pic.o : %.c + $(CC) $(CFLAGS) -fPIC -DPIC -c $< -o $@ +%.debug.pic.o %.release.pic.o : %.cc + $(CCC) $(CFLAGS) -fPIC -DPIC -c $< -o $@ +%.debug.pic.o %.release.pic.o : %.cpp + $(CCC) $(CFLAGS) -fPIC -DPIC -c $< -o $@ +%.debug.i %.release.i : %.c + $(CC) $(CFLAGS) -E $< -o $@ +%.debug.i %.release.i : %.cc + $(CCC) $(CFLAGS) -E $< -o $@ +%.debug.i %.release.i : %.cpp + $(CCC) $(CFLAGS) -E $< -o $@ + +%.debug.o %.release.o : %.s +ifeq ($(OS),Darwin) + #$(CC) -c -arch ppc -Wall -force_cpusubtype_ALL $< -o $@ + $(AS) -arch ppc -force_cpusubtype_ALL $< -o $@ +else + $(AS) $< -o $@ +endif +%.debug.pic.o %.release.pic.o : %.s +ifeq ($(OS),Darwin) + #$(CC) -c -arch ppc -Wall -force_cpusubtype_ALL $< -o $@ + $(AS) -arch ppc -force_cpusubtype_ALL $< -o $@ +else + $(AS) $< -o $@ +endif + +%.debug.o : %.nasm + $(NASM) -f elf -d OBJ_FORMAT_elf -i ia32/ -g $< -o $@ +%.release.o : %.nasm + $(NASM) -f elf -d OBJ_FORMAT_elf -i ia32/ $< -o $@ +%.debug.pic.o : %.nasm + $(NASM) -f elf -d OBJ_FORMAT_elf -i ia32/ -g $< -o $@ +%.release.pic.o : %.nasm + $(NASM) -f elf -d OBJ_FORMAT_elf -i ia32/ $< -o $@ diff --git a/flac/build/config.mk b/flac/build/config.mk new file mode 100644 index 0000000..0ea6c04 --- /dev/null +++ b/flac/build/config.mk @@ -0,0 +1,57 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# debug/release selection +# + +DEFAULT_BUILD = release + +# returns i386, x86_64, powerpc, etc. +PROC := $(shell uname -p) +# returns Linux, Darwin, FreeBSD, etc. +OS := $(shell uname -s) + +debug : BUILD = debug +valgrind : BUILD = debug +release : BUILD = release + +# override LINKAGE on OS X until we figure out how to get 'cc -static' to work +ifeq ($(OS),Darwin) +LINKAGE = +else +debug : LINKAGE = -static +valgrind : LINKAGE = -dynamic +release : LINKAGE = -static +endif + +all default: $(DEFAULT_BUILD) + +# +# GNU makefile fragment for emulating stuff normally done by configure +# + +VERSION=\"1.2.1\" + +ifeq ($(OS),Darwin) +CONFIG_CFLAGS=-DHAVE_INTTYPES_H -DHAVE_ICONV -DHAVE_LANGINFO_CODESET -DFLAC__HAS_OGG -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DFLAC__SYS_DARWIN -DWORDS_BIGENDIAN +else +CONFIG_CFLAGS=-DHAVE_INTTYPES_H -DHAVE_ICONV -DHAVE_LANGINFO_CODESET -DHAVE_SOCKLEN_T -DFLAC__HAS_OGG -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 +endif + +OGG_INCLUDE_DIR=$(HOME)/local/include +OGG_LIB_DIR=$(HOME)/local/lib diff --git a/flac/build/exe.mk b/flac/build/exe.mk new file mode 100644 index 0000000..5bb4d76 --- /dev/null +++ b/flac/build/exe.mk @@ -0,0 +1,85 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# GNU makefile fragment for building an executable +# + +include $(topdir)/build/config.mk + +ifeq ($(OS),Darwin) +CC = cc +CCC = c++ +else +CC = gcc +CCC = g++ +endif +NASM = nasm +LINK = $(CC) $(LINKAGE) +OBJPATH = $(topdir)/obj +BINPATH = $(OBJPATH)/$(BUILD)/bin +LIBPATH = $(OBJPATH)/$(BUILD)/lib +DEBUG_BINPATH = $(OBJPATH)/debug/bin +DEBUG_LIBPATH = $(OBJPATH)/debug/lib +RELEASE_BINPATH = $(OBJPATH)/release/bin +RELEASE_LIBPATH = $(OBJPATH)/release/lib +PROGRAM = $(BINPATH)/$(PROGRAM_NAME) +DEBUG_PROGRAM = $(DEBUG_BINPATH)/$(PROGRAM_NAME) +RELEASE_PROGRAM = $(RELEASE_BINPATH)/$(PROGRAM_NAME) + +debug : CFLAGS = -g -O0 -DDEBUG $(CONFIG_CFLAGS) $(DEBUG_CFLAGS) -W -Wall -Wmissing-prototypes -Wstrict-prototypes -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) +valgrind: CFLAGS = -g -O0 -DDEBUG $(CONFIG_CFLAGS) $(DEBUG_CFLAGS) -DFLAC__VALGRIND_TESTING -W -Wall -Wmissing-prototypes -Wstrict-prototypes -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) +release : CFLAGS = -O3 -fomit-frame-pointer -funroll-loops -finline-functions -DNDEBUG $(CONFIG_CFLAGS) $(RELEASE_CFLAGS) -W -Wall -Wmissing-prototypes -Wstrict-prototypes -Winline -DFLaC__INLINE=__inline__ -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) + +LFLAGS = -L$(LIBPATH) + +DEBUG_OBJS = $(SRCS_C:%.c=%.debug.o) $(SRCS_CC:%.cc=%.debug.o) $(SRCS_CPP:%.cpp=%.debug.o) $(SRCS_NASM:%.nasm=%.debug.o) $(SRCS_S:%.s=%.debug.o) +RELEASE_OBJS = $(SRCS_C:%.c=%.release.o) $(SRCS_CC:%.cc=%.release.o) $(SRCS_CPP:%.cpp=%.release.o) $(SRCS_NASM:%.nasm=%.release.o) $(SRCS_S:%.s=%.release.o) +ifeq ($(PROC),x86_64) +DEBUG_PIC_OBJS = $(SRCS_C:%.c=%.debug.pic.o) $(SRCS_CC:%.cc=%.debug.pic.o) $(SRCS_CPP:%.cpp=%.debug.pic.o) $(SRCS_NASM:%.nasm=%.debug.pic.o) $(SRCS_S:%.s=%.debug.pic.o) +RELEASE_PIC_OBJS = $(SRCS_C:%.c=%.release.pic.o) $(SRCS_CC:%.cc=%.release.pic.o) $(SRCS_CPP:%.cpp=%.release.pic.o) $(SRCS_NASM:%.nasm=%.release.pic.o) $(SRCS_S:%.s=%.release.pic.o) +endif + +debug : $(DEBUG_PROGRAM) +valgrind: $(DEBUG_PROGRAM) +release : $(RELEASE_PROGRAM) + +# by default on OS X we link with static libs as much as possible + +$(DEBUG_PROGRAM) : $(DEBUG_OBJS) $(DEBUG_PIC_OBJS) +ifeq ($(OS),Darwin) + $(LINK) -o $@ $(DEBUG_OBJS) $(EXPLICIT_LIBS) +else + $(LINK) -o $@ $(DEBUG_OBJS) $(LFLAGS) $(LIBS) +endif + +$(RELEASE_PROGRAM) : $(RELEASE_OBJS) $(RELEASE_PIC_OBJS) +ifeq ($(OS),Darwin) + $(LINK) -o $@ $(RELEASE_OBJS) $(EXPLICIT_LIBS) +else + $(LINK) -o $@ $(RELEASE_OBJS) $(LFLAGS) $(LIBS) +endif + +include $(topdir)/build/compile.mk + +.PHONY : clean +clean : + -rm -f $(DEBUG_OBJS) $(RELEASE_OBJS) $(DEBUG_PIC_OBJS) $(RELEASE_PIC_OBJS) $(OBJPATH)/*/bin/$(PROGRAM_NAME) + +.PHONY : depend +depend: + makedepend -fMakefile.lite -- $(CFLAGS) $(INCLUDES) -- *.c *.cc *.cpp diff --git a/flac/build/lib.mk b/flac/build/lib.mk new file mode 100644 index 0000000..6e52528 --- /dev/null +++ b/flac/build/lib.mk @@ -0,0 +1,112 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# GNU makefile fragment for building a library +# + +include $(topdir)/build/config.mk + +ifeq ($(OS),Darwin) +CC = cc +CCC = c++ +else +CC = gcc +CCC = g++ +endif +AS = as +NASM = nasm +LINK = ar cru +OBJPATH = $(topdir)/obj +LIBPATH = $(OBJPATH)/$(BUILD)/lib +DEBUG_LIBPATH = $(OBJPATH)/debug/lib +RELEASE_LIBPATH = $(OBJPATH)/release/lib +ifeq ($(OS),Darwin) +STATIC_LIB_SUFFIX = a +DYNAMIC_LIB_SUFFIX = dylib +else +STATIC_LIB_SUFFIX = a +DYNAMIC_LIB_SUFFIX = so +endif +STATIC_LIB_NAME = $(LIB_NAME).$(STATIC_LIB_SUFFIX) +DYNAMIC_LIB_NAME = $(LIB_NAME).$(DYNAMIC_LIB_SUFFIX) +STATIC_LIB = $(LIBPATH)/$(STATIC_LIB_NAME) +DYNAMIC_LIB = $(LIBPATH)/$(DYNAMIC_LIB_NAME) +DEBUG_STATIC_LIB = $(DEBUG_LIBPATH)/$(STATIC_LIB_NAME) +DEBUG_DYNAMIC_LIB = $(DEBUG_LIBPATH)/$(DYNAMIC_LIB_NAME) +RELEASE_STATIC_LIB = $(RELEASE_LIBPATH)/$(STATIC_LIB_NAME) +RELEASE_DYNAMIC_LIB = $(RELEASE_LIBPATH)/$(DYNAMIC_LIB_NAME) +ifeq ($(OS),Darwin) +LINKD = $(CC) -dynamiclib -flat_namespace -undefined suppress -install_name $(DYNAMIC_LIB) +else +LINKD = $(CC) -shared +endif + +debug : CFLAGS = -g -O0 -DDEBUG $(CONFIG_CFLAGS) $(DEBUG_CFLAGS) -W -Wall -Wmissing-prototypes -Wstrict-prototypes -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) +valgrind: CFLAGS = -g -O0 -DDEBUG $(CONFIG_CFLAGS) $(DEBUG_CFLAGS) -DFLAC__VALGRIND_TESTING -W -Wall -Wmissing-prototypes -Wstrict-prototypes -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) +release : CFLAGS = -O3 -fomit-frame-pointer -funroll-loops -finline-functions -DNDEBUG $(CONFIG_CFLAGS) $(RELEASE_CFLAGS) -W -Wall -Wmissing-prototypes -Wstrict-prototypes -Winline -DFLaC__INLINE=__inline__ -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES) + +LFLAGS = -L$(LIBPATH) + +DEBUG_OBJS = $(SRCS_C:%.c=%.debug.o) $(SRCS_CC:%.cc=%.debug.o) $(SRCS_CPP:%.cpp=%.debug.o) $(SRCS_NASM:%.nasm=%.debug.o) $(SRCS_S:%.s=%.debug.o) +RELEASE_OBJS = $(SRCS_C:%.c=%.release.o) $(SRCS_CC:%.cc=%.release.o) $(SRCS_CPP:%.cpp=%.release.o) $(SRCS_NASM:%.nasm=%.release.o) $(SRCS_S:%.s=%.release.o) +ifeq ($(PROC),x86_64) +DEBUG_PIC_OBJS = $(SRCS_C:%.c=%.debug.pic.o) $(SRCS_CC:%.cc=%.debug.pic.o) $(SRCS_CPP:%.cpp=%.debug.pic.o) $(SRCS_NASM:%.nasm=%.debug.pic.o) $(SRCS_S:%.s=%.debug.pic.o) +RELEASE_PIC_OBJS = $(SRCS_C:%.c=%.release.pic.o) $(SRCS_CC:%.cc=%.release.pic.o) $(SRCS_CPP:%.cpp=%.release.pic.o) $(SRCS_NASM:%.nasm=%.release.pic.o) $(SRCS_S:%.s=%.release.pic.o) +endif + +debug : $(DEBUG_STATIC_LIB) $(DEBUG_DYNAMIC_LIB) +valgrind: $(DEBUG_STATIC_LIB) $(DEBUG_DYNAMIC_LIB) +release : $(RELEASE_STATIC_LIB) $(RELEASE_DYNAMIC_LIB) + +$(DEBUG_STATIC_LIB): $(DEBUG_OBJS) + $(LINK) $@ $(DEBUG_OBJS) && ranlib $@ + +$(RELEASE_STATIC_LIB): $(RELEASE_OBJS) + $(LINK) $@ $(RELEASE_OBJS) && ranlib $@ + +$(DEBUG_DYNAMIC_LIB) : $(DEBUG_OBJS) $(DEBUG_PIC_OBJS) +ifeq ($(OS),Darwin) + echo Not building dynamic lib, command is: $(LINKD) -o $@ $(DEBUG_OBJS) $(LFLAGS) $(LIBS) -lc +else +ifeq ($(PROC),x86_64) + $(LINKD) -o $@ $(DEBUG_PIC_OBJS) $(LFLAGS) $(LIBS) +else + $(LINKD) -o $@ $(DEBUG_OBJS) $(LFLAGS) $(LIBS) +endif +endif + +$(RELEASE_DYNAMIC_LIB) : $(RELEASE_OBJS) $(RELEASE_PIC_OBJS) +ifeq ($(OS),Darwin) + echo Not building dynamic lib, command is: $(LINKD) -o $@ $(RELEASE_OBJS) $(LFLAGS) $(LIBS) -lc +else +ifeq ($(PROC),x86_64) + $(LINKD) -o $@ $(RELEASE_PIC_OBJS) $(LFLAGS) $(LIBS) +else + $(LINKD) -o $@ $(RELEASE_OBJS) $(LFLAGS) $(LIBS) +endif +endif + +include $(topdir)/build/compile.mk + +.PHONY : clean +clean : + -rm -f $(DEBUG_OBJS) $(RELEASE_OBJS) $(DEBUG_PIC_OBJS) $(RELEASE_PIC_OBJS) $(OBJPATH)/*/lib/$(STATIC_LIB_NAME) $(OBJPATH)/*/lib/$(DYNAMIC_LIB_NAME) + +.PHONY : depend +depend: + makedepend -fMakefile.lite -- $(CFLAGS) $(INCLUDES) -- *.c *.cc *.cpp diff --git a/flac/configure.in b/flac/configure.in new file mode 100644 index 0000000..468881d --- /dev/null +++ b/flac/configure.in @@ -0,0 +1,390 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# NOTE that for many of the AM_CONDITIONALs we use the prefix FLaC__ +# instead of FLAC__ since autoconf triggers off 'AC_' in strings + +AC_INIT(src/flac/main.c) +AM_INIT_AUTOMAKE(flac, 1.2.1) + +# Don't automagically regenerate autoconf/automake generated files unless +# explicitly requested. Eases autobuilding -mdz +AM_MAINTAINER_MODE + +# We need two libtools, one that builds both shared and static, and +# one that builds only static. This is because the resulting libtool +# does not allow us to choose which to build at runtime. +AM_PROG_LIBTOOL +sed -e 's/^build_old_libs=yes/build_old_libs=no/' libtool > libtool-disable-static +chmod +x libtool-disable-static + +AC_SUBST(ACLOCAL_AMFLAGS, "-I m4") + +AM_PROG_AS +AC_PROG_CXX +AC_PROG_MAKE_SET + +AC_SYS_LARGEFILE +AC_FUNC_FSEEKO + +AC_CHECK_SIZEOF(void*,0) + +#@@@ new name is AC_CONFIG_HEADERS +AM_CONFIG_HEADER(config.h) + +AC_C_BIGENDIAN + +AC_CHECK_TYPES(socklen_t, [], []) + +dnl check for getopt in standard library +dnl AC_CHECK_FUNCS(getopt_long , , [LIBOBJS="$LIBOBJS getopt.o getopt1.o"] ) +AC_CHECK_FUNCS(getopt_long, [], []) + +case "$host_cpu" in + i*86) + cpu_ia32=true + AC_DEFINE(FLAC__CPU_IA32) + AH_TEMPLATE(FLAC__CPU_IA32, [define if building for ia32/i386]) + ;; + powerpc) + cpu_ppc=true + AC_DEFINE(FLAC__CPU_PPC) + AH_TEMPLATE(FLAC__CPU_PPC, [define if building for PowerPC]) + ;; + sparc) + cpu_sparc=true + AC_DEFINE(FLAC__CPU_SPARC) + AH_TEMPLATE(FLAC__CPU_SPARC, [define if building for SPARC]) + ;; +esac +AM_CONDITIONAL(FLaC__CPU_IA32, test "x$cpu_ia32" = xtrue) +AM_CONDITIONAL(FLaC__CPU_PPC, test "x$cpu_ppc" = xtrue) +AM_CONDITIONAL(FLaC__CPU_SPARC, test "x$cpu_sparc" = xtrue) + +case "$host" in + i386-*-openbsd3.[[0-3]]) OBJ_FORMAT=aoutb ;; + *-*-cygwin|*mingw*) OBJ_FORMAT=win32 ;; + *-*-darwin*) OBJ_FORMAT=macho ;; + *) OBJ_FORMAT=elf ;; +esac +AC_SUBST(OBJ_FORMAT) + +# only needed because of ntohl() usage, can get rid of after that's gone: +case "$host" in + *-*-cygwin|*mingw*) MINGW_WINSOCK_LIBS=-lwsock32 ;; + *) MINGW_WINSOCK_LIBS= ;; +esac +AC_SUBST(MINGW_WINSOCK_LIBS) + +case "$host" in + *-pc-linux-gnu) + sys_linux=true + AC_DEFINE(FLAC__SYS_LINUX) + AH_TEMPLATE(FLAC__SYS_LINUX, [define if building for Linux]) + ;; + *-*-darwin*) + sys_darwin=true + AC_DEFINE(FLAC__SYS_DARWIN) + AH_TEMPLATE(FLAC__SYS_DARWIN, [define if building for Darwin / MacOS X]) + ;; +esac +AM_CONDITIONAL(FLaC__SYS_DARWIN, test "x$sys_darwin" = xtrue) +AM_CONDITIONAL(FLaC__SYS_LINUX, test "x$sys_linux" = xtrue) + +if test "x$cpu_ia32" = xtrue ; then +AC_DEFINE(FLAC__ALIGN_MALLOC_DATA) +AH_TEMPLATE(FLAC__ALIGN_MALLOC_DATA, [define to align allocated memory on 32-byte boundaries]) +fi + +AC_ARG_ENABLE(asm-optimizations, AC_HELP_STRING([--disable-asm-optimizations], [Don't use any assembly optimization routines]), asm_opt=no, asm_opt=yes) +AM_CONDITIONAL(FLaC__NO_ASM, test "x$asm_opt" = xno) +if test "x$asm_opt" = xno ; then +AC_DEFINE(FLAC__NO_ASM) +AH_TEMPLATE(FLAC__NO_ASM, [define to disable use of assembly code]) +fi + +AC_ARG_ENABLE(debug, +AC_HELP_STRING([--enable-debug], [Turn on debugging]), +[case "${enableval}" in + yes) debug=true ;; + no) debug=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-debug) ;; +esac],[debug=false]) +AM_CONDITIONAL(DEBUG, test "x$debug" = xtrue) + +AC_ARG_ENABLE(sse, +AC_HELP_STRING([--enable-sse], [Enable SSE support by asserting that the OS supports SSE instructions]), +[case "${enableval}" in + yes) sse_os=true ;; + no) sse_os=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-sse) ;; +esac],[sse_os=false]) +AM_CONDITIONAL(FLaC__SSE_OS, test "x$sse_os" = xtrue) +if test "x$sse_os" = xtrue ; then +AC_DEFINE(FLAC__SSE_OS) +AH_TEMPLATE(FLAC__SSE_OS, [define if your operating system supports SSE instructions]) +fi + +AC_ARG_ENABLE(3dnow, +AC_HELP_STRING([--disable-3dnow], [Disable 3DNOW! optimizations]), +[case "${enableval}" in + yes) use_3dnow=true ;; + no) use_3dnow=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-3dnow) ;; +esac],[use_3dnow=true]) +AM_CONDITIONAL(FLaC__USE_3DNOW, test "x$use_3dnow" = xtrue) +if test "x$use_3dnow" = xtrue ; then +AC_DEFINE(FLAC__USE_3DNOW) +AH_TEMPLATE(FLAC__USE_3DNOW, [define to enable use of 3Dnow! instructions]) +fi + +AC_ARG_ENABLE(altivec, +AC_HELP_STRING([--disable-altivec], [Disable Altivec optimizations]), +[case "${enableval}" in + yes) use_altivec=true ;; + no) use_altivec=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-altivec) ;; +esac],[use_altivec=true]) +AM_CONDITIONAL(FLaC__USE_ALTIVEC, test "x$use_altivec" = xtrue) +if test "x$use_altivec" = xtrue ; then +AC_DEFINE(FLAC__USE_ALTIVEC) +AH_TEMPLATE(FLAC__USE_ALTIVEC, [define to enable use of Altivec instructions]) +fi + +AC_ARG_ENABLE(thorough-tests, +AC_HELP_STRING([--disable-thorough-tests], [Disable thorough (long) testing, do only basic tests]), +[case "${enableval}" in + yes) thorough_tests=true ;; + no) thorough_tests=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-thorough-tests) ;; +esac],[thorough_tests=true]) +AC_ARG_ENABLE(exhaustive-tests, +AC_HELP_STRING([--enable-exhaustive-tests], [Enable exhaustive testing (VERY long)]), +[case "${enableval}" in + yes) exhaustive_tests=true ;; + no) exhaustive_tests=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-exhaustive-tests) ;; +esac],[exhaustive_tests=false]) +if test "x$thorough_tests" = xfalse ; then +FLAC__TEST_LEVEL=0 +elif test "x$exhaustive_tests" = xfalse ; then +FLAC__TEST_LEVEL=1 +else +FLAC__TEST_LEVEL=2 +fi +AC_SUBST(FLAC__TEST_LEVEL) + +AC_ARG_ENABLE(valgrind-testing, +AC_HELP_STRING([--enable-valgrind-testing], [Run all tests inside Valgrind]), +[case "${enableval}" in + yes) FLAC__TEST_WITH_VALGRIND=yes ;; + no) FLAC__TEST_WITH_VALGRIND=no ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-valgrind-testing) ;; +esac],[FLAC__TEST_WITH_VALGRIND=no]) +AC_SUBST(FLAC__TEST_WITH_VALGRIND) + +AC_ARG_ENABLE(doxygen-docs, +AC_HELP_STRING([--disable-doxygen-docs], [Disable API documentation building via Doxygen]), +[case "${enableval}" in + yes) enable_doxygen_docs=true ;; + no) enable_doxygen_docs=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-doxygen-docs) ;; +esac],[enable_doxygen_docs=true]) +if test "x$enable_doxygen_docs" != xfalse ; then + AC_CHECK_PROGS(DOXYGEN, doxygen) +fi +AM_CONDITIONAL(FLaC__HAS_DOXYGEN, test -n "$DOXYGEN") + +AC_ARG_ENABLE(local-xmms-plugin, +AC_HELP_STRING([--enable-local-xmms-plugin], [Install XMMS plugin to ~/.xmms/Plugins instead of system location]), +[case "${enableval}" in + yes) install_xmms_plugin_locally=true ;; + no) install_xmms_plugin_locally=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-local-xmms-plugin) ;; +esac],[install_xmms_plugin_locally=false]) +AM_CONDITIONAL(FLaC__INSTALL_XMMS_PLUGIN_LOCALLY, test "x$install_xmms_plugin_locally" = xtrue) + +AC_ARG_ENABLE(xmms-plugin, +AC_HELP_STRING([--disable-xmms-plugin], [Do not build XMMS plugin]), +[case "${enableval}" in + yes) enable_xmms_plugin=true ;; + no) enable_xmms_plugin=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-xmms-plugin) ;; +esac],[enable_xmms_plugin=true]) +if test "x$enable_xmms_plugin" != xfalse ; then + AM_PATH_XMMS(0.9.5.1, , AC_MSG_WARN([*** XMMS >= 0.9.5.1 not installed - XMMS support will not be built])) +fi +AM_CONDITIONAL(FLaC__HAS_XMMS, test -n "$XMMS_INPUT_PLUGIN_DIR") + +dnl build FLAC++ or not +AC_ARG_ENABLE([cpplibs], +AC_HELP_STRING([--disable-cpplibs], [Do not build libFLAC++]), +[case "${enableval}" in + yes) disable_cpplibs=false ;; + no) disable_cpplibs=true ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-cpplibs) ;; +esac], [disable_cpplibs=false]) +AM_CONDITIONAL(FLaC__WITH_CPPLIBS, [test "x$disable_cpplibs" != xtrue]) + +dnl check for ogg library +AC_ARG_ENABLE([ogg], + AC_HELP_STRING([--disable-ogg], [Disable ogg support (default: test for libogg)]), + [ want_ogg=$enableval ], [ want_ogg=yes ] ) + +if test "x$want_ogg" != "xno"; then + XIPH_PATH_OGG(have_ogg=yes, AC_MSG_WARN([*** Ogg development enviroment not installed - Ogg support will not be built])) +fi + +AM_CONDITIONAL(FLaC__HAS_OGG, [test "x$have_ogg" = xyes]) +if test "x$have_ogg" = xyes ; then +AC_DEFINE(FLAC__HAS_OGG) +AH_TEMPLATE(FLAC__HAS_OGG, [define if you have the ogg library]) +fi + +dnl check for i18n(internationalization); these are from libiconv/gettext +AM_ICONV +AM_LANGINFO_CODESET + +AC_CHECK_PROGS(DOCBOOK_TO_MAN, docbook-to-man docbook2man) +AM_CONDITIONAL(FLaC__HAS_DOCBOOK_TO_MAN, test -n "$DOCBOOK_TO_MAN") +if test -n "$DOCBOOK_TO_MAN" ; then +AC_DEFINE(FLAC__HAS_DOCBOOK_TO_MAN) +AH_TEMPLATE(FLAC__HAS_DOCBOOK_TO_MAN, [define if you have docbook-to-man or docbook2man]) +fi + +# only matters for x86 +AC_CHECK_PROGS(NASM, nasm) +AM_CONDITIONAL(FLaC__HAS_NASM, test -n "$NASM") +if test -n "$NASM" ; then +AC_DEFINE(FLAC__HAS_NASM) +AH_TEMPLATE(FLAC__HAS_NASM, [define if you are compiling for x86 and have the NASM assembler]) +fi + +# only matters for PowerPC +AC_CHECK_PROGS(AS, as, as) +AC_CHECK_PROGS(GAS, gas, gas) + +# try -v (apple as) and --version (gas) at the same time +test "$AS" = "as" && as --version -v < /dev/null 2>&1 | grep Apple >/dev/null || AS=gas + +AM_CONDITIONAL(FLaC__HAS_AS, test "$AS" = "as") +AM_CONDITIONAL(FLaC__HAS_GAS, test "$AS" = "gas") +if test "$AS" = "as" ; then +AC_DEFINE(FLAC__HAS_AS) +AH_TEMPLATE(FLAC__HAS_AS, [define if you are compiling for PowerPC and have the 'as' assembler]) +fi +if test "$AS" = "gas" ; then +# funniest. macro. ever. +AC_DEFINE(FLAC__HAS_GAS) +AH_TEMPLATE(FLAC__HAS_GAS, [define if you are compiling for PowerPC and have the 'gas' assembler]) +fi + +CPPFLAGS='-I$(top_builddir) -I$(srcdir)/include -I$(top_srcdir)/include'" $CPPFLAGS" +if test "x$debug" = xtrue; then + CPPFLAGS="-DDEBUG $CPPFLAGS" + CFLAGS="-g $CFLAGS" +else + CPPFLAGS="-DNDEBUG $CPPFLAGS" + if test "x$GCC" = xyes; then + CPPFLAGS="-DFLaC__INLINE=__inline__ $CPPFLAGS" + CFLAGS="-O3 -funroll-loops -finline-functions -Wall -W -Winline $CFLAGS" + fi +fi + +#@@@ +AM_CONDITIONAL(FLaC__HAS_AS__TEMPORARILY_DISABLED, test "yes" = "no") +AM_CONDITIONAL(FLaC__HAS_GAS__TEMPORARILY_DISABLED, test "yes" = "no") + +AC_CONFIG_FILES([ \ + Makefile \ + src/Makefile \ + src/libFLAC/Makefile \ + src/libFLAC/flac.pc \ + src/libFLAC/ia32/Makefile \ + src/libFLAC/ppc/Makefile \ + src/libFLAC/ppc/as/Makefile \ + src/libFLAC/ppc/gas/Makefile \ + src/libFLAC/include/Makefile \ + src/libFLAC/include/private/Makefile \ + src/libFLAC/include/protected/Makefile \ + src/libFLAC++/Makefile \ + src/libFLAC++/flac++.pc \ + src/flac/Makefile \ + src/metaflac/Makefile \ + src/monkeys_audio_utilities/Makefile \ + src/monkeys_audio_utilities/flac_mac/Makefile \ + src/monkeys_audio_utilities/flac_ren/Makefile \ + src/plugin_common/Makefile \ + src/plugin_winamp2/Makefile \ + src/plugin_winamp2/include/Makefile \ + src/plugin_winamp2/include/winamp2/Makefile \ + src/plugin_xmms/Makefile \ + src/share/Makefile \ + src/share/getopt/Makefile \ + src/share/grabbag/Makefile \ + src/share/replaygain_analysis/Makefile \ + src/share/replaygain_synthesis/Makefile \ + src/share/replaygain_synthesis/include/Makefile \ + src/share/replaygain_synthesis/include/private/Makefile \ + src/share/utf8/Makefile \ + src/test_grabbag/Makefile \ + src/test_grabbag/cuesheet/Makefile \ + src/test_grabbag/picture/Makefile \ + src/test_libs_common/Makefile \ + src/test_libFLAC/Makefile \ + src/test_libFLAC++/Makefile \ + src/test_seeking/Makefile \ + src/test_streams/Makefile \ + examples/Makefile \ + examples/c/Makefile \ + examples/c/decode/Makefile \ + examples/c/decode/file/Makefile \ + examples/c/encode/Makefile \ + examples/c/encode/file/Makefile \ + examples/cpp/Makefile \ + examples/cpp/decode/Makefile \ + examples/cpp/decode/file/Makefile \ + examples/cpp/encode/Makefile \ + examples/cpp/encode/file/Makefile \ + include/Makefile \ + include/FLAC/Makefile \ + include/FLAC++/Makefile \ + include/share/Makefile \ + include/share/grabbag/Makefile \ + include/test_libs_common/Makefile \ + doc/Makefile \ + doc/html/Makefile \ + doc/html/images/Makefile \ + doc/html/images/hw/Makefile \ + doc/html/ru/Makefile \ + m4/Makefile \ + man/Makefile \ + test/Makefile \ + test/cuesheets/Makefile \ + test/flac-to-flac-metadata-test-files/Makefile \ + test/metaflac-test-files/Makefile \ + test/pictures/Makefile \ + build/Makefile \ + obj/Makefile \ + obj/debug/Makefile \ + obj/debug/bin/Makefile \ + obj/debug/lib/Makefile \ + obj/release/Makefile \ + obj/release/bin/Makefile \ + obj/release/lib/Makefile \ +]) +AC_OUTPUT diff --git a/flac/doc/Doxyfile b/flac/doc/Doxyfile new file mode 100644 index 0000000..33db277 --- /dev/null +++ b/flac/doc/Doxyfile @@ -0,0 +1,1220 @@ +# Doxyfile 1.4.2 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = FLAC + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = 1.2.1 + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = doxytmp + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, +# Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, +# Japanese-en (Japanese with English messages), Korean, Korean-en, Norwegian, +# Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, +# Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = NO + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = YES + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = YES + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = .. + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = YES + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = "assert=\par Assertions:\n" \ + "default=\par Default Value:\n" + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources +# only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = YES + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. + +SHOW_DIRECTORIES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the progam writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = ../include/FLAC \ + ../include/FLAC++ + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = doxygen.footer.html + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_PREDEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = FLAC__NO_DLL + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = FLAC_API FLACPP_API + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = FLAC.tag + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/flac/doc/Makefile.am b/flac/doc/Makefile.am new file mode 100644 index 0000000..87edd3e --- /dev/null +++ b/flac/doc/Makefile.am @@ -0,0 +1,43 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = . html + +if FLaC__HAS_DOXYGEN +FLAC.tag: Doxyfile + doxygen Doxyfile + rm -rf html/api + mv doxytmp/html html/api + rm -rf doxytmp +else +FLAC.tag: + echo "*** Warning: Doxygen not found; documentation will not be built." + touch $@ + mkdir -p html/api +endif + +docdir = $(datadir)/doc/$(PACKAGE)-$(VERSION) + +doc_DATA = \ + FLAC.tag + +EXTRA_DIST = Doxyfile Makefile.lite doxygen.footer.html doxygen.header.html $(doc_DATA) + +maintainer-clean-local: + rm -rf FLAC.tag html/api doxytmp diff --git a/flac/doc/Makefile.lite b/flac/doc/Makefile.lite new file mode 100644 index 0000000..b7062e6 --- /dev/null +++ b/flac/doc/Makefile.lite @@ -0,0 +1,28 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +topdir = .. + +FLAC.tag: Doxyfile + rm -rf doxytmp + doxygen Doxyfile + rm -rf html/api + mv doxytmp/html html/api + rm -rf doxytmp + +clean: + rm -rf FLAC.tag html/api doxytmp diff --git a/flac/doc/doxygen.footer.html b/flac/doc/doxygen.footer.html new file mode 100644 index 0000000..75df18f --- /dev/null +++ b/flac/doc/doxygen.footer.html @@ -0,0 +1,23 @@ + +
+ + + + + + + + + diff --git a/flac/doc/doxygen.header.html b/flac/doc/doxygen.header.html new file mode 100644 index 0000000..83593ce --- /dev/null +++ b/flac/doc/doxygen.header.html @@ -0,0 +1,6 @@ + + + + + + diff --git a/flac/doc/html/Makefile.am b/flac/doc/html/Makefile.am new file mode 100644 index 0000000..9cdd2c8 --- /dev/null +++ b/flac/doc/html/Makefile.am @@ -0,0 +1,80 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = ru images + +docdir = $(datadir)/doc/$(PACKAGE)-$(VERSION)/html + +doc_DATA = \ + changelog.html \ + comparison.html \ + comparison__chopin_prelude_24.html \ + comparison__dream_theater_600.html \ + comparison__eddie_warner_titus.html \ + comparison__fanfare_de_l_eventail_de_jeanne.html \ + comparison__gloria_estefan_conga.html \ + comparison__hand_in_my_pocket.html \ + comparison__l_sub_raga_sivapriya.html \ + comparison__laetatus_sum.html \ + comparison__mummified_in_barbed_wire.html \ + comparison__prokofiev_pcon3_3.html \ + comparison__ravel_sq4_4.html \ + comparison__scarlatti_k42.html \ + comparison__tool_forty_six_and_2.html \ + comparison__white_room.html \ + comparison_all_cpudectime.html \ + comparison_all_cpuenctime.html \ + comparison_all_procdectime.html \ + comparison_all_procenctime.html \ + comparison_all_ratio.html \ + developers.html \ + documentation.html \ + documentation_bugs.html \ + documentation_example_code.html \ + documentation_format_overview.html \ + documentation_tasks.html \ + documentation_tools.html \ + documentation_tools_flac.html \ + documentation_tools_metaflac.html \ + documentation_tools_plugins.html \ + download.html \ + faq.html \ + favicon.ico \ + features.html \ + flac.css \ + format.html \ + id.html \ + index.html \ + itunes.html \ + license.html \ + links.html \ + news.html \ + ogg_mapping.html + +EXTRA_DIST = $(doc_DATA) api + +# The install targets don't copy whole directories so we have to +# handle 'api/' specially: +install-data-local: + $(mkinstalldirs) $(DESTDIR)$(docdir)/api + (cd api && $(INSTALL_DATA) * $(DESTDIR)$(docdir)/api) +uninstall-local: + rm -rf $(DESTDIR)$(docdir)/api +maintainer-clean-local: + rm -rf api diff --git a/flac/doc/html/changelog.html b/flac/doc/html/changelog.html new file mode 100644 index 0000000..3332692 --- /dev/null +++ b/flac/doc/html/changelog.html @@ -0,0 +1,918 @@ + + + + + + + + + + + + + + + + FLAC - changelog + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ changelog +
+
+
+ This is an informal changelog, a summary of changes in each release. (See also known bugs.) Particulary important for developers is the precise description of changes to the library interfaces. See also the porting guide for specific instructions on porting to newer versions of FLAC.
+ +
+ + + + FLAC 1.2.1 (17-Sep-2007) + +
+ +
    +
  • + General: +
      +
    • With the new --keep-foreign-metadata in flac, non-audio RIFF and AIFF chunks can be stored in FLAC files and recreated when decoding. This allows, among other, things support for archiving BWF files and other WAVE files from editing tools that preserves all the metadata.
    • +
    +
  • +
  • + FLAC format: +
      +
    • Specified 2 new APPLICATION metadata blocks for storing WAVE and AIFF chunks (for use with --keep-foreign-metadata in flac).
    • +
    • The lead-out track number for non-CDDA cuesheets now must be 255.
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • This is not a format change, but changed default extension for Ogg FLAC from .ogg to .oga, according to new Xiph specification (SF #1762492).
    • +
    +
  • +
  • + flac: +
      +
    • Added a new option --no-utf8-convert which works like it does in metaflac (SF #973740).
    • +
    • Added a new option --keep-foreign-metadata which can save/restore RIFF and AIFF chunks to/from FLAC files (SF #363478).
    • +
    • Changed default extension for Ogg FLAC from .ogg to .oga, according to new Xiph specification (SF #1762492).
    • +
    • Fixed bug where using --replay-gain without any padding option caused only a small PADDING block to be created (SF #1760790).
    • +
    • Fixed bug where encoding from stdin on Windows could fail if WAVE/AIFF contained unknown chunks (SF #1776803).
    • +
    • Fixed bug where importing non-CDDA cuesheets would cause an invalid lead-out track number (SF #1764105).
    • +
    +
  • +
  • + metaflac: +
      +
    • Changed default extension for Ogg FLAC from .ogg to .oga, according to new Xiph specification (SF #1762492).
    • +
    • Fixed bug where importing non-CDDA cuesheets would cause an invalid lead-out track number (SF #1764105).
    • +
    +
  • +
  • + plugins: +
      +
    • (none)
    • +
    +
  • +
  • + build system: + +
  • +
  • + documentation: +
      +
    • Added new tutorial section for flac.
    • +
    • Added example code section for using libFLAC/libFLAC++.
    • +
    +
  • +
  • + libraries: +
      +
    • libFLAC: Fixed very rare seek bug (SF #1684049).
    • +
    • libFLAC: Fixed seek bug with Ogg FLAC and small streams (SF #1792172).
    • +
    • libFLAC: 64-bit fixes (SF #1790872).
    • +
    +
  • +
  • + Interface changes: +
      +
    • + libFLAC: +
        +
      • Added FLAC__metadata_simple_iterator_is_last()
      • +
      • Added FLAC__metadata_simple_iterator_get_block_offset()
      • +
      • Added FLAC__metadata_simple_iterator_get_block_length()
      • +
      • Added FLAC__metadata_simple_iterator_get_application_id()
      • +
      +
    • +
    • + libFLAC++: +
        +
      • Added FLAC::Metadata::SimpleIterator::is_last()
      • +
      • Added FLAC::Metadata::SimpleIterator::get_block_offset()
      • +
      • Added FLAC::Metadata::SimpleIterator::get_block_length()
      • +
      • Added FLAC::Metadata::SimpleIterator::get_application_id()
      • +
      +
    • +
    +
  • +
+ +
+ + FLAC 1.2.0 (23-Jul-2007) + +
+ +
    +
  • + General: +
      +
    • Small encoding speedups for all modes.
    • +
    +
  • +
  • + FLAC format: +
      +
    • One of the reserved bits in the FLAC frame header has been assigned for future use; make sure to refer to the porting guide if you parse FLAC streams manually.
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + flac: +
      +
    • Added runtime detection of SSE OS support for most operating systems.
    • +
    • Added a new undocumented option --ignore-chunk-sizes for ignoring the size of the 'data' chunk (WAVE) or 'SSND' chunk (AIFF). Can be used to encode files with bogus data sizes (e.g. with WAV files piped from foobar2000 to flac.exe as an external encoder). Use with caution: all subsequent data is treated as audio, so the data/SSND chunk must be the last or the following data/tags will be treated as audio and encoded.
    • +
    +
  • +
  • + metaflac: +
      +
    • (none)
    • +
    +
  • +
  • + plugins: +
      +
    • (none)
    • +
    +
  • +
  • + build system: +
      +
    • Added solution and project files for building with VC++ 2005.
    • +
    +
  • +
  • + libraries: +
      +
    • Added runtime detection of SSE OS support for most operating systems.
    • +
    • Fixed bug where invalid seek tables could cause some seeks to fail.
    • +
    +
  • +
  • + Interface changes (see also the porting guide for specific instructions on porting to FLAC 1.2.0): +
      +
    • + libFLAC: +
        +
      • Added FLAC__format_sample_rate_is_subset()
      • +
      +
    • +
    • + libFLAC++: +
        +
      • Added FLAC::Decoder::Stream::get_decode_position()
      • +
      +
    • +
    +
  • +
+ +
+ + FLAC 1.1.4 (13-Feb-2007) + +
+ +
    +
  • + General: +
      +
    • Improved compression with no change to format or decrease in speed.
    • +
    • Encoding and decoding speedups for all modes. Encoding at -8 is twice as fast.
    • +
    +
  • +
  • + FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + flac: +
      +
    • Improved compression with no change to format or decrease in speed.
    • +
    • Encoding and decoding speedups for all modes. Encoding at -8 is twice as fast.
    • +
    • Added a new option -w,--warnings-as-errors for treating all warnings as errors.
    • +
    • Allow --picture option to take only a filename, and have all other attributes extracted from the file itself.
    • +
    • Fixed a bug that caused suboptimal default compression settings in some locales (SF #1608883).
    • +
    • Fixed a bug where FLAC-to-FLAC transcoding of a corrupted FLAC file would truncate the transcoded file at the first error (SF #1615019).
    • +
    • Fixed a bug where using -F with FLAC-to-FLAC transcoding of a corrupted FLAC would have no effect (SF #1615391).
    • +
    • Fixed a bug where new PICTURE metadata blocks specified with --picture would not be transferred during FLAC-to-FLAC transcoding (SF #1627993).
    • +
    +
  • +
  • + metaflac: +
      +
    • Allow --import-picture-from option to take only a filename, and have all other attributes extracted from the file itself.
    • +
    +
  • +
  • + plugins: +
      +
    • Fixed a bug in the XMMS plugin where Ctrl-3 (file info) would cause a crash if the file did not exist (SF #1634941).
    • +
    +
  • +
  • + build system: +
      +
    • Fixed a makefile linkage bug with libogg (SF #1611414).
    • +
    • Added pkg-config files for libFLAC and libFLAC++ (SF #1647881).
    • +
    • Added --disable-ogg option for building without Ogg support even if libogg is installed (SF #1196996).
    • +
    +
  • +
  • + libraries: +
      +
    • Completely rewritten bitbuffer which uses native machine word size instead of bytes for dramatic speed improvements. The speedup should be most dramatic on CPUs with slower byte manipulation capability and big-endian machines.
    • +
    • Much faster Rice partition size estimation which greatly speeds encoding in higher modes.
    • +
    • Increased compression for all modes.
    • +
    • Reduced memory requirements for encoder and decoder.
    • +
    • Fixed a bug with default apodization settings that were erroneous in some locales (SF #1608883).
    • +
    +
  • +
  • + Interface changes: +
      +
    • + libFLAC: +
        +
      • (behavior only) FLAC__stream_encoder_set_metadata() now makes a copy of the "metadata" array of pointers (but still not copies of the objects themselves) so the client does not need to maintain its copy of the array after the call.
      • +
      +
    • +
    • + libFLAC++: +
        +
      • (none)
      • +
      +
    • +
    +
  • +
+ +
+ + FLAC 1.1.3 (27-Nov-2006) + +
+ +
    +
  • + General: +
      +
    • Improved compression with no impact on format or decoding speed.
    • +
    • Much better recovery for corrupted files
    • +
    • Better multichannel support
    • +
    • Large file (>2GB) support everywhere
    • +
    • flac now supports FLAC and Ogg FLAC as input to the encoder (e.g. can re-encode FLAC to FLAC) and preserve all the metadata like tags, etc.
    • +
    • New PICTURE metadata block for storing things like cover art, new --picture option to flac and --import-picture-from option to metaflac for importing pictures, new --export-picture-to option to metaflac for exporting pictures, and metadata API additions for searching for suitable pictures based on type, size and color constraints.
    • +
    • Support for new REPLAYGAIN_REFERENCE_LOUDNESS tag.
    • +
    • Fixed a bug in Ogg FLAC encoding where metadata was not being updated properly. Existing Ogg FLAC files should be recoded to fix up the metadata, e.g. flac -Vf -S 10s --ogg file.ogg
    • +
    • In the developer libraries, the interface has been simplfied by merging the three decoding layers into a single class; ditto for the encoders. Also, libOggFLAC has been merged into libFLAC and libOggFLAC++ has been merged into libFLAC++ so there is a single API supporting both native FLAC and Ogg FLAC.
    • +
    +
  • +
  • + FLAC format: +
      +
    • New PICTURE metadata block for storing things like cover art.
    • +
    • Speaker assignments and channel orders for 3-6 channels (see frame header).
    • +
    • Further restrictions on the FLAC subset when the sample rate is <=48kHz; in this case the maximum LPC order is now 12 and maximum blocksize is 4608. This is to further limit the processing and memory requirements for hardware implementations while not measurably affecting compression.
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + flac: +
      +
    • Improved the -F option to allow decoding of FLAC files whose metadata is corrupted, and other kinds of severe corruption.
    • +
    • Encoder can now take FLAC and Ogg FLAC as input. The output FLAC file will have all the same metadata as the original unless overridden with options on the command line.
    • +
    • Encoder can now take WAVEFORMATEXTENSIBLE WAVE files as input; decoder will output WAVEFORMATEXTENSIBLE WAVE files when necessary to conform to the latest Microsoft specifications.
    • +
    • Now properly supports AIFF and WAVEFORMATEXTENSIBLE multichannel input, performing necessary channel reordering both for encoding and decoding. WAVEFORMATEXTENSIBLE channel mask is also saved to a tag on encoding and restored on decoding for situations when there is no natural mapping to FLAC channel assignments.
    • +
    • Expanded support for "odd" sample resolutions to WAVE and AIFF input; all resolutions from 4 to 24 bits-per-sample now supported for all input types.
    • +
    • Added a new option --tag-from-file for setting a tag from file (e.g. for importing a cuesheet as a tag).
    • +
    • Added a new option --picture for adding pictures.
    • +
    • Added a new option --apodization for specifying the window function(s) to be used in LPC analysis.
    • +
    • Added support for encoding from non-compressed AIFF-C (SF #1090933).
    • +
    • Importing of non-CDDA-compliant cuesheets now only issues a warning, not an error (see here).
    • +
    • MD5 comparison failures on decoding are now an error instead of a warning and will also return a non-zero exit code (SF #1493725).
    • +
    • The default padding size is now 8K, or 64K if the input audio stream is more than 20 minutes long.
    • +
    • Fixed a bug in cuesheet parsing where it would return an error if the last line of the cuesheet did not end with a newline.
    • +
    • Fixed a bug that caused a crash when -a and -t were used together (SF #1229481).
    • +
    • Fixed a bug with --sector-align where appended samples were not always totally silent (SF #1237707).
    • +
    • Fixed bugs with --sector-align and raw input files.
    • +
    • Fixed a bug printing out unknown AIFF subchunk names (SF #1267476).
    • +
    • Fixed a bug where WAVE files with "data" subchunks of size 0 where accepted (SF #1293830).
    • +
    • Fixed a bug where sync error at end-of-stream of truncated files was not being caught (SF #1244071).
    • +
    • Fixed a problem with filename parsing if file does not have extension but also has a . in the path (SF #1161916).
    • +
    • Fixed a problem with fractional-second parsing for --skip/--until in some locales (SF #1031043).
    • +
    • Increase progress report rate when -p and -e are used together (SF #1580122).
    • +
    +
  • +
  • + metaflac: +
      +
    • Added support for read-only operations on Ogg FLAC files.
    • +
    • Added a new option --set-tag-from-file for setting a tag from file (e.g. for importing a cuesheet as a tag).
    • +
    • Added a new option --import-picture-from for importing pictures.
    • +
    • Added a new option --export-picture-to for exporting pictures.
    • +
    • Added shorthand operation --remove-replay-gain for removing ReplayGain tags.
    • +
    • --export-cuesheet-to now properly specifies the FLAC file name (SF #1272825).
    • +
    • Importing of non-CDDA-compliant cuesheets now issues a warning.
    • +
    • Removed the following deprecated tag editing options; you should use the new option names shown instead: +
        +
      • Removed --show-vc-vendor; use --show-vendor-tag
      • +
      • Removed --show-vc-field; use --show-tag
      • +
      • Removed --remove-vc-all; use --remove-all-tags
      • +
      • Removed --remove-vc-field; use --remove-tag
      • +
      • Removed --remove-vc-firstfield; use --remove-first-tag
      • +
      • Removed --set-vc-field; use --set-tag
      • +
      • Removed --import-vc-from; use --import-tags-from
      • +
      • Removed --export-vc-to; use --export-tags-to
      • +
      +
    • +
    • Disallow multiple input FLAC files when --import-tags-from=- is used (SF #1082577).
    • +
    +
  • +
  • + plugins: +
      +
    • When ReplayGain is on, if tags for the preferred kind of gain (album/track) are not in a stream, the other kind will be used.
    • +
    • Added ReplayGain info to file info box in XMMS plugin
    • +
    • Fixed UTF-8 decoder to disallow non-shortest-form and surrogate sequences (see here).
    • +
    +
  • +
  • + build system: +
      +
    • Added support for building on OS/2 with EMX (SF #1229495)
    • +
    • Added support for building with Borland C++ (SF #1599018)
    • +
    • Added a --disable-xmms-plugin option to configure to prevent building the XMMS plugin (SF #930494).
    • +
    • Added a --disable-doxygen-docs option to configure for disabling Doxygen-based API doc generation (SF #1365935).
    • +
    • Added a --disable-thorough-tests option to configure to do the basic library, stream, and tool tests in a reasonable time (SF #1077948).
    • +
    • Added large file support with AC_SYS_LARGEFILE; use --disable-largefile with configure to disable.
    • +
    +
  • +
  • + libraries: +
      +
    • Merged libOggFLAC into libFLAC; both formats are now supporte through the same API.
    • +
    • Merged libOggFLAC++ into libFLAC++; both formats are now supporte through the same API.
    • +
    • libFLAC and libFLAC++: Simplified encoder setup with new FLAC__stream_encoder_set_compression_level() function.
    • +
    • libFLAC: Improved compression with no impact on FLAC format or decoding time by adding a windowing stage before LPC analysis.
    • +
    • libFLAC: Fixed a bug where missing STREAMINFO fields (min/max framesize, total samples, MD5 sum) and seek point offsets were not getting rewritten back to Ogg FLAC file (SF #1338969).
    • +
    • libFLAC: Fixed a bug in cuesheet parsing where it would return an error if the last line of the cuesheet did not end with a newline.
    • +
    • libFLAC: Fixed UTF-8 decoder to disallow non-shortest-form and surrogate sequences (see here).
    • +
    • libFLAC: Fixed a bug in the return value for FLAC__stream_decoder_set_metadata_respond_application() and FLAC__stream_decoder_set_metadata_ignore_application() when there was a memory allocation error (SF #1235005).
    • +
    +
  • +
  • + Interface changes (see also the porting guide for specific instructions on porting to FLAC 1.1.3): +
      +
    • + all libraries; +
        +
      • Merged libOggFLAC into libFLAC; both formats are now supporte through the same API.
      • +
      • Merged libOggFLAC++ into libFLAC++; both formats are now supporte through the same API.
      • +
      • Merged seekable stream decoder and file decoder into the stream decoder.
      • +
      • Merged seekable stream encoder and file encoder into the stream encoder.
      • +
      • Added #defines for the API version number to make porting easier; see include/lib*FLAC*/export.h.
      • +
      +
    • +
    • + libFLAC: +
        +
      • Added FLAC__stream_encoder_set_apodization()
      • +
      • Added FLAC__stream_encoder_set_compression_level()
      • +
      • Added FLAC__metadata_object_cuesheet_calculate_cddb_id()
      • +
      • Added FLAC__metadata_get_cuesheet()
      • +
      • Added FLAC__metadata_get_picture()
      • +
      • Added FLAC__metadata_chain_read_ogg() and FLAC__metadata_chain_read_ogg_with_callbacks()
      • +
      • Changed FLAC__stream_encoder_finish() now returns a FLAC__bool to signal a verify failure, or error processing last frame or updating metadata.
      • +
      • Changed FLAC__StreamDecoderState: removed state FLAC__STREAM_DECODER_UNPARSEABLE_STREAM
      • +
      • Changed FLAC__StreamDecoderErrorStatus: new error code FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
      • +
      • The above two changes mean that when the decoder encounters what it thinks are unparseable frames from a future decoder, instead of returning a fatal error with the FLAC__STREAM_DECODER_UNPARSEABLE_STREAM state, it just calls the error callback with FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM and leaves the behavior up to the application.
      • +
      +
    • +
    • + libFLAC++: +
        +
      • Added FLAC::Metadata::Picture
      • +
      • Added FLAC::Encoder::Stream::set_apodization()
      • +
      • Added FLAC::Encoder::Stream::set_compression_level()
      • +
      • Added FLAC::Metadata::CueSheet::calculate_cddb_id()
      • +
      • Added FLAC::Metadata::get_cuesheet()
      • +
      • Added FLAC::Metadata::get_picture()
      • +
      • Changed FLAC::Metadata::Chain::read() to accept a flag denoting Ogg FLAC input
      • +
      • Changed FLAC::Decoder::Stream::finish() now returns a bool to signal an MD5 failure like FLAC__stream_decoder_finish() does.
      • +
      • Changed FLAC::Encoder::Stream::finish() now returns a bool to signal a verify failure, or error processing last frame or updating metadata.
      • +
      +
    • +
    • + libOggFLAC: +
        +
      • Merged into libFLAC.
      • +
      +
    • +
    • + libOggFLAC++: +
        +
      • Merged into libFLAC++.
      • +
      +
    • +
    +
  • +
+ +
+ + FLAC 1.1.2 (05-Feb-2005) + +
+ +
    +
  • + General: +
      +
    • Sped up decoding by a few percent overall.
    • +
    • Sped up encoding when not using LPC (i.e. when using flac options -0, -1, -2, or -l 0).
    • +
    • Fixed a decoding bug that could cause sync errors with some ID3v1-tagged FLAC files.
    • +
    • Added HTML documentation for metaflac.
    • +
    +
  • +
  • + FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • (none)
    • +
    +
  • +
  • + flac: +
      +
    • New option --input-size to manually specify the input size when encoding raw samples from stdin.
    • +
    +
  • +
  • + metaflac: +
      +
    • (none)
    • +
    +
  • +
  • + plugins: +
      +
    • Added support for HTTP streaming in XMMS plugin. NOTE: there is a bug in the XMMS mpg123 plugin that hijacks FLAC streams; to fix it you will need to add the '.flac' extension to the list of exceptions in Input/mpg123/mpg123.c:is_our_file() in the XMMS sources and recompile.
    • +
    +
  • +
  • + build system: +
      +
    • (none)
    • +
    +
  • +
  • + libraries: +
      +
    • libFLAC: Sped up Rice block decoding in the bitbuffer, resulting in decoding speed gains of a few percent.
    • +
    • libFLAC: Sped up encoding when not using LPC (i.e. max_lpc_order == 0).
    • +
    • libFLAC: Trailing NUL characters maintained on Vorbis comment entries so they can be treated like C strings.
    • +
    • libFLAC: More FLAC tag (i.e. Vorbis comment) validation.
    • +
    • libFLAC: Fixed a bug in the logic that determines the frame or sample number in a frame header; the bug could cause sync errors with some ID3v1-tagged FLAC files.
    • +
    • libFLAC, libOggFLAC: Can now be compiled to use only integer instructions, including encoding. The decoder is almost completely integer anyway but there were a couple places that needed a fixed-point replacement. There is no fixed-point version of LPC analysis yet, so if libFLAC is compiled integer-only, the encoder will behave as if the max LPC order is 0 (i.e. used fixed predictors only). LPC decoding is supported in all cases as it always was integer-only.
    • +
    +
  • +
  • + Interface changes: +
      +
    • + libFLAC: +
        +
      • Changed: Metadata object interface now maintains a trailing NUL on Vorbis comment entries for convenience.
      • +
      • Changed: Metadata object interface now validates all Vorbis comment entries on input and returns false if an entry does not conform to the Vorbis comment spec.
      • +
      • Added FLAC__format_vorbiscomment_entry_name_is_legal()
      • +
      • Added FLAC__format_vorbiscomment_entry_value_is_legal()
      • +
      • Added FLAC__format_vorbiscomment_entry_is_legal()
      • +
      • Added FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair()
      • +
      • Added FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair()
      • +
      • Changed the signature of FLAC__metadata_object_vorbiscomment_entry_matches(): the first argument is now FLAC__StreamMetadata_VorbisComment_Entry entry (was const FLAC__StreamMetadata_VorbisComment_Entry *entry), i.e. entry is now pass-by-value.
      • +
      +
    • +
    • + libFLAC++: +
        +
      • Changed: Metadata object interface now maintains a trailing NUL on Vorbis comment values for convenience.
      • +
      • Changed: Metadata object interface now validates all Vorbis comment entries on input and returns false if an entry does not conform to the Vorbis comment spec.
      • +
      • Changed: All Metadata objects' operator=() methods now return a reference to themselves.
      • +
      • Added methods to FLAC::Metadata::VorbisComment::Entry for setting comment values from null-terminated strings: +
          +
        • Entry(const char *field)
        • +
        • Entry(const char *field_name, const char *field_value)
        • +
        • bool set_field(const char *field)
        • +
        • bool set_field_value(const char *field_value)
        • +
        +
      • +
      • Changed the signature of FLAC::Metadata::VorbisComment::get_vendor_string() and FLAC::Metadata::VorbisComment::set_vendor_string() to use a UTF-8, NUL-terminated string const FLAC__byte * for the vendor string instead of FLAC::Metadata::VorbisComment::Entry.
      • +
      • Added FLAC::Metadata::*::assign() to all Metadata objects.
      • +
      • Added bool FLAC::Metadata::get_tags(const char *filename, VorbisComment &tags)
      • +
      +
    • +
    • + libOggFLAC: +
        +
      • (none)
      • +
      +
    • +
    • + libOggFLAC++: +
        +
      • (none)
      • +
      +
    • +
    +
  • +
+ +
+ + FLAC 1.1.1 (01-Oct-2004) + +
+ +
    +
  • + General: +
      +
    • Ogg FLAC seeking now works
    • +
    • New optimizations almost double the decoding speed on PowerPC (e.g. Mac G4/G5)
    • +
    • A native OS X release thanks to updated Project Builder and autotools files
    • +
    +
  • +
  • + FLAC format: +
      +
    • Made invalid the metadata block type 127 so that audio frames can always be distinguished from metadata by seeing 0xff as the first byte. (This was also required for the Ogg FLAC mapping.)
    • +
    +
  • +
  • + Ogg FLAC format: +
      +
    • First official FLAC->Ogg bitstream mapping standardized (see new FLAC-to-Ogg mapping specification). See the documentation for the --ogg switch about having to re-encode older Ogg FLAC files.
    • +
    +
  • +
  • + flac: +
      +
    • Print an error when output file already exists instead of automatically overwriting.
    • +
    • New option -f (--force) to force overwriting if the output file already exists.
    • +
    • New option --cue to select a specific section to decode using cuesheet track/index points.
    • +
    • New option --totally-silent to suppress all output.
    • +
    • New (but undocumented) option --apply-replaygain-which-is-not-lossless which applies ReplayGain to the decoded output. See this thread for usage and caveats.
    • +
    • When encoding to Ogg FLAC, use a random serial number (instead of 0 as was done before) when a serial number is not specified.
    • +
    • When encoding multiple Ogg FLAC streams, --serial-number or random serial number sets the first number, which is then incremented for subsequent streams (before, the same serial number was used for all streams).
    • +
    • Decoder no longer exits with an error when writing to stdout and the pipe is broken.
    • +
    • Better explanation of common error messages.
    • +
    • Default extension when writing AIFF files is .aif (before, it was .aiff).
    • +
    • Write more common representation of SANE numbers in AIFF files.
    • +
    • Bug fix: calculating ReplayGain on 48kHz streams.
    • +
    • Bug fix: check for supported block alignments in WAVE files.
    • +
    • Bug fix: "offset" field in AIFF SSND chunk properly handled.
    • +
    • Bug fix: #679166: flac doesn't respect RIFF subchunk padding byte.
    • +
    • Bug fix: #828391: --add-replay-gain segfaults.
    • +
    • Bug fix: #851155: Can't seek to position in flac file.
    • +
    • Bug fix: #851756: flac --skip --until reads entire file.
    • +
    • Bug fix: #877122: problem parsing cuesheet with CATALOG entry.
    • +
    • Bug fix: #896057: parsing ISRC number from cuesheet.
    • +
    +
  • +
  • + metaflac: +
      +
    • Renamed the tag editing options as follows (the ...-vc-... options still work but are deprecated): +
        +
      • --show-vc-vendor becomes --show-vendor-tag
      • +
      • --show-vc-field becomes --show-tag
      • +
      • --remove-vc-all becomes --remove-all-tags
      • +
      • --remove-vc-field becomes --remove-tag
      • +
      • --remove-vc-firstfield becomes --remove-first-tag
      • +
      • --set-vc-field becomes --set-tag
      • +
      • --import-vc-from becomes --import-tags-from
      • +
      • --export-vc-to becomes --export-tags-to
      • +
      +
    • +
    • Better explanation of common error messages.
    • +
    • Bug fix: calculating ReplayGain on 48kHz streams.
    • +
    • Bug fix: incorrect numbers when printing seek points.
    • +
    +
  • +
  • + plugins: +
      +
    • Speed optimization in ReplayGain synthesis.
    • +
    • Speed optimization in XMMS playback.
    • +
    • Support for big-endian architectures in XMMS plugin.
    • +
    • Removed support for ID3 tags.
    • +
    • Bug fix: make hard limiter default to off in XMMS plugin.
    • +
    • Bug fix: stream length calculation bug in XMMS plugin, debian bug #200435; see also.
    • +
    • Bug fix: small memory leak in XMMS plugin.
    • +
    +
  • +
  • + build system: +
      +
    • ordinals.h is now static, not a build-generated file anymore.
    • +
    +
  • +
  • + libraries: +
      +
    • libFLAC: PPC+Altivec optimizations of some decoder routines.
    • +
    • libFLAC: Make stream encoder encode the blocksize and sample rate in the frame header if at all possible (not in STREAMINFO), even if subset encoding was not requested.
    • +
    • libFLAC: Bug fix: fixed seek routine where infinite loop could happen when seeking past end of stream.
    • +
    • libFLAC, libFLAC++: added methods to skip single frames, useful for quickly finding frame boundaries (see interface changes below).
    • +
    • libOggFLAC, libOggFLAC++: New seekable-stream and file encoder and decoder APIs to match native FLAC APIs (see interface changes below).
    • +
    +
  • +
  • + Interface changes: +
      +
    • + libFLAC: +
        +
      • Added FLAC__metadata_get_tags()
      • +
      • Added callback-based versions of metadata editing functions: +
          +
        • FLAC__metadata_chain_read_with_callbacks()
        • +
        • FLAC__metadata_chain_write_with_callbacks()
        • +
        • FLAC__metadata_chain_write_with_callbacks_and_tempfile()
        • +
        • FLAC__metadata_chain_check_if_tempfile_needed()
        • +
        +
      • +
      • Added decoder functions for skipping single frames, also useful for quickly finding frame boundaries: +
          +
        • FLAC__stream_decoder_skip_single_frame()
        • +
        • FLAC__seekable_stream_decoder_skip_single_frame()
        • +
        • FLAC__file_decoder_skip_single_frame()
        • +
        +
      • +
      • Added new required tell callback on seekable stream encoder: +
          +
        • FLAC__SeekableStreamEncoderTellStatus and FLAC__SeekableStreamEncoderTellStatusString[]
        • +
        • FLAC__SeekableStreamEncoderTellCallback
        • +
        • FLAC__seekable_stream_encoder_set_tell_callback()
        • +
        +
      • +
      • Changed FLAC__SeekableStreamEncoderState by adding FLAC__SEEKABLE_STREAM_ENCODER_TELL_ERROR
      • +
      • Changed Tell callback is now required to initialize seekable stream encoder
      • +
      • Deleted erroneous and unimplemented FLAC__file_decoder_process_remaining_frames()
      • +
      +
    • +
    • + libFLAC++: +
        +
      • Added FLAC::Metadata::get_tags()
      • +
      • Added decoder functions for skipping single frames, also useful for quickly finding frame boundaries: +
          +
        • FLAC::Decoder::Stream::skip_single_frame()
        • +
        • FLAC::Decoder::SeekableStream::skip_single_frame()
        • +
        • FLAC::Decoder::File::skip_single_frame()
        • +
        +
      • +
      • Added encoder functions for setting metadata: +
          +
        • FLAC::Encoder::Stream::set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks)
        • +
        • FLAC::Encoder::SeekableStream::set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks)
        • +
        • FLAC::Encoder::File::set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks)
        • +
        +
      • +
      • Added new required tell callback on seekable stream encoder: +
          +
        • pure virtual FLAC::Encoder::SeekableStream::tell_callback()
        • +
        +
      • +
      • Changed Tell callback is now required to initialize seekable stream encoder
      • +
      • Deleted the following methods: +
          +
        • FLAC::Decoder::Stream::State::resolved_as_cstring()
        • +
        • FLAC::Encoder::Stream::State::resolved_as_cstring()
        • +
        +
      • +
      +
    • +
    • + libOggFLAC: +
        +
      • Added OggFLAC__SeekableStreamDecoder interface
      • +
      • Added OggFLAC__FileDecoder interface
      • +
      • Added OggFLAC__SeekableStreamEncoder interface
      • +
      • Added OggFLAC__FileEncoder interface
      • +
      • Added OggFLAC__stream_decoder_get_resolved_state_string()
      • +
      • Added OggFLAC__stream_encoder_get_resolved_state_string()
      • +
      • Added OggFLAC__stream_encoder_set_metadata_callback()
      • +
      • Changed OggFLAC__StreamDecoderState by adding OggFLAC__STREAM_DECODER_END_OF_STREAM
      • +
      +
    • +
    • + libOggFLAC++: +
        +
      • Added OggFLAC::Decoder::SeekableStream interface
      • +
      • Added OggFLAC::Decoder::File interface
      • +
      • Added OggFLAC::Encoder::SeekableStream interface
      • +
      • Added OggFLAC::Encoder::File interface
      • +
      • Added OggFLAC::Decoder::Stream::get_resolved_state_string()
      • +
      • Added OggFLAC::Encoder::Stream::get_resolved_state_string()
      • +
      • Added pure virtual OggFLAC::Encoder::Stream::metadata_callback()
      • +
      +
    • +
    +
  • +
+
+ +
+ + + + + + diff --git a/flac/doc/html/comparison.html b/flac/doc/html/comparison.html new file mode 100644 index 0000000..e2186b5 --- /dev/null +++ b/flac/doc/html/comparison.html @@ -0,0 +1,431 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ Many lossless comparisons look at only compression ratio and speed. FLAC decoding is the fastest among lossless codecs and it has the fastest encoding mode. FLAC's compression is within 3% of even the most complex codecs. Note that the compression ratios of all lossless codecs fall in a quite narrow range; the difference between the very best and very worst is only around 7%, and only 4% for the practical codecs.
+
+ So the evaluation of lossless codecs typically depends mainly on other features, which is what our first table shows; features like how well it is supported in devices and software, licensing, etc. Additionally, as archiving is one of the main applications for a lossless codec, of chief importance is the ability to use and recover data in the future. FLAC stands out as the most widely supported codec, and the only codec that at once is non-proprietary, is unencumbered by patents, has an open-source reference implementation, has a well documented format and API, and has several other independent implementations.
+
+ The rest of the tables show in detail the compression ratios and speed of the codecs in different modes. FLAC's high decoding speed is due to very low complexity and is instrumental to its support by dozens of consumer electronic devices.
+
+ (Note: this comparison leaves out some archaic or impractical codecs; see below for some other comparisons.)
+
+ Reviewed encoders (besides flac of course): +
    +
  • + Apple Lossless - A proprietary codec by Apple. +
  • +
  • + Bonk - An open-source source codec. No player or library support yet. +
  • +
  • + La - A closed source symmetric adaptive codec. Highest compression ratio but extremely slow. +
  • +
  • + Monkey's Audio - A symmetric adaptive codec with good compression. Source is available under a non-OSI license. +
  • +
  • + Ogg Squish - An open source source codec that is no longer maintained. +
  • +
  • + optimFROG - A closed source, Windows/Linux codec, with Winamp and XMMS plugins. Slow but high compression ratios. +
  • +
  • + Shorten - A.J. Robinson's well-known codec; source is available here. +
  • +
  • + Tak - A new and efficient codec, but closed-source and Windows only. +
  • +
  • + WavPack - A fine open-source codec, released under the BSD license. +
  • +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Codec + + Source Available? + + Player Support? + + Hardware Support? + + License Cost + + OS support +
+ flac v1.2.1 + + YES (OSI approved license) + + YES (XMMS, Winamp, AlsaPlayer, Y! Music Engine, MacAmp Lite, dBpowerAMP, Foobar2000, QCD, Apollo, many more) + + YES (Squeezebox, Sonos, PhatBox, Kenwood MusicKeg, iAudio, ReQuest, Olive, Escient, TrekStor, dozens more) + + NONE + + Linux, Windows, Mac OS X, *BSD, Solaris, OS/2, BeOS, Amiga OS, others +
+ WavPack v4.41 + + YES (OSI approved license) + + YES (Winamp, foobar2000, dBpowerAMP, more) + + maybe (some portables via Rockbox firmware replacement) + + NONE + + Linux, Windows, Mac OS X, *BSD, Solaris, others +
+ Shorten v3.2 + + YES (non-OSI license) + + YES (Winamp, XMMS) + + maybe (some portables via Rockbox firmware replacement) + + non-
commercial only +
+ Linux, Windows, Mac OS 9, Mac OS X, *BSD, Solaris, others +
+ Monkey's Audio v3.99 + + YES (non-OSI license) + + YES (Winamp, MediaJukebox, dBpowerAMP, more) + + no + + ? + + Windows, Linux console source +
+ Apple Lossless + + no + + YES (iTunes) + + YES (iPod only) + + unavailable + + Windows, Mac OS X +
+ Ogg Squish 0.98 + + YES (OSI approved license) + + no (?) + + no + + NONE + + Linux, Windows, other UNIX +
+ Bonk 0.5 + + YES (OSI approved license) + + YES (XMMS) + + no + + ? + + Linux, Windows, other UNIX +
+ optimFROG 4.21 + + no + + YES (Winamp, XMMS) + + no + + ? + + Windows, Linux +
+ La 0.3c + + no + + YES (Winamp, XMMS) + + no + + ? + + Windows, Linux +
+ Tak 1.0 + + no + + no + + no + + free for non-commercial use + + Windows +
+
+
+ The machine used for encoding the test files is a PII-333 with 256 megs of RAM, running Windows NT 4.0 SP5. Unfortunately, though flac runs just about everywhere, Windows is the lowest-common-denominator platform for all the encoders. Apple Lossless was tested on a newer machine (P4-2.4GHz Windows 2000); only the overall encoding and decoding times are shown, and the times are scaled to the PII-333 by multiplying by the ratio of flac times on the PII to P4.
+
+ By default when processing files, flac computes the MD5 sum while encoding and decoding. Since MD5 sums are not typically used in playback, and since most codecs either do not support MD5 sums or do not compute them by default, to make the comparison as accurate as possible MD5 checking was disabled for FLAC decoding. However since it is currently not possible to disable MD5 computation for FLAC encoding, the FLAC encoding times here are 4-15% longer than they would be without MD5 checking.
+
+ The audio corpus currently consists entirely of CD music tracks. In the future it may include more kinds of input (like speech, other sample rates/resolutions, etc). There are 14 tracks whose genres range from rock to pop to death metal to classical to chant.
+
+ Here is a summary table of results on the whole corpus, using just the most 'economic' modes (the ones that give the most compression for the least amount of encode/decode time) for each codec. The table is ordered by the average track compression ratio, which is the average of the ratios for each track; this keeps long tracks from having more influence than short ones. Clicking the column header links will take you to complete tables ordered by that column.
+
+ Shown in white, flac in its default mode is right in the middle with respect to compression, relatively fast on the encoding range, and the fastest decoding. This is about what you would expect; FLAC is designed to put most of the processing on the encoding side, which is only done once, whereas the adaptive codecs take as long to decode as encode. FLAC is more suited in this way for playback on low-power devices, borne out by the many hardware devices which support it.
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ + Here are links to the full summary table (all codecs, all modes) and tables for each individual track. The individual track tables are sorted only by compression ratio since the relative encoding and decoding times are the same as for the whole corpus. +

+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__chopin_prelude_24.html b/flac/doc/html/comparison__chopin_prelude_24.html new file mode 100644 index 0000000..e6a9fc0 --- /dev/null +++ b/flac/doc/html/comparison__chopin_prelude_24.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c5:12.995:05.905:02.304:58.199.84 MB35.82%
Monkey's Audio 3.99 (insane)4:31.194:23.904:41.634:38.159.96 MB36.25%
Monkey's Audio 3.99 (extra high)0:59.340:52.761:00.840:55.8010.16 MB36.99%
Tak 1.01 (extra high max)2:21.932:15.970:16.040:10.9610.18 MB37.07%
Tak 1.01 (extra high)0:54.020:47.210:15.790:10.6110.20 MB37.15%
optimFROG 4.21 (mode 4 @ 1x)11:56.8011:49.4311:58.6711:52.3810.34 MB37.64%
optimFROG 4.21 (mode 3 @ 4x)2:03.121:55.852:06.241:59.9310.35 MB37.68%
optimFROG 4.21 (mode 2 @ 4x)1:07.641:00.031:10.961:04.3810.37 MB37.78%
Monkey's Audio 3.99 (high)0:31.660:25.200:33.370:28.0110.40 MB37.88%
optimFROG 4.21 (mode 1 @ 4x)0:50.930:43.240:54.650:47.5510.41 MB37.90%
Monkey's Audio 3.99 (normal)0:27.250:20.660:29.580:23.6210.52 MB38.32%
optimFROG 4.21 (mode 0 @ 4x)0:34.130:26.240:37.360:30.8110.53 MB38.33%
Tak 1.01 (normal)0:24.270:17.590:13.770:07.5910.54 MB38.37%
Tak 1.01 (turbo)0:14.480:07.790:11.540:05.8910.64 MB38.74%
WavPack 4.41 (extra high -x)0:59.090:51.190:21.450:15.5610.66 MB38.83%
WavPack 4.41 (high)0:23.700:16.060:18.580:12.1910.83 MB39.45%
Monkey's Audio 3.99 (fast)0:21.210:14.610:23.150:17.5010.94 MB39.82%
WavPack 4.41 (normal -x)0:28.330:20.540:14.770:08.8810.94 MB39.84%
WavPack 4.41 (normal)0:19.710:11.860:14.610:08.7110.99 MB40.01%
FLAC 1.2.1 (-8)0:52.850:46.140:10.990:04.5411.05 MB40.25%
WavPack 4.41 (fast -x)0:23.340:15.660:12.540:06.6511.14 MB40.55%
FLAC 1.2.1 (-5, default)0:20.100:13.480:10.410:04.3711.19 MB40.73%
FLAC 1.2.1 (-3)0:14.730:08.010:09.950:04.1111.26 MB40.99%
WavPack 4.41 (fast)0:17.610:09.900:12.730:06.7111.30 MB41.15%
Apple Lossless (iTunes 4.5)????11.51 MB41.91%
FLAC 1.2.1 (-1)0:12.290:05.320:10.140:04.4111.84 MB43.11%
Shorten 3.2a (-p0 -b256, default)0:19.930:12.700:13.270:06.5212.05 MB43.86%
Bonk 0.51:45.751:39.191:24.871:18.9112.86 MB46.84%
Shorten 3.2a (-p8 -b2048)0:25.060:17.520:14.190:07.9214.40 MB52.42%
RIFF WAVE0:55.770:55.7727.46 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__dream_theater_600.html b/flac/doc/html/comparison__dream_theater_600.html new file mode 100644 index 0000000..467c136 --- /dev/null +++ b/flac/doc/html/comparison__dream_theater_600.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c11:33.0911:19.0611:12.0311:00.2242.72 MB73.06%
Monkey's Audio 3.99 (insane)9:54.949:41.0810:23.8410:11.9242.99 MB73.52%
Monkey's Audio 3.99 (extra high)2:13.371:56.552:17.032:01.5443.06 MB73.64%
Monkey's Audio 3.99 (high)1:14.010:57.541:17.441:01.8943.21 MB73.91%
optimFROG 4.21 (mode 2 @ 4x)2:29.222:10.342:36.592:21.4243.24 MB73.95%
optimFROG 4.21 (mode 3 @ 4x)4:28.014:09.994:33.404:18.9643.26 MB73.98%
optimFROG 4.21 (mode 4 @ 1x)25:32.6725:17.3325:37.3325:22.0743.26 MB73.98%
optimFROG 4.21 (mode 1 @ 4x)1:54.861:35.382:02.711:45.7543.26 MB73.98%
Monkey's Audio 3.99 (normal)1:04.050:47.221:07.560:52.1343.30 MB74.05%
Tak 1.01 (extra high max)5:17.865:02.220:33.300:17.3843.40 MB74.23%
optimFROG 4.21 (mode 0 @ 4x)1:18.810:59.921:25.631:09.7043.42 MB74.26%
Tak 1.01 (extra high)1:55.031:37.680:33.950:17.3143.45 MB74.31%
Tak 1.01 (normal)0:55.220:38.010:31.570:15.7943.51 MB74.42%
WavPack 4.41 (extra high -x)2:07.331:47.950:54.180:34.9243.55 MB74.49%
WavPack 4.41 (high)0:55.990:35.380:45.020:27.4543.67 MB74.69%
Tak 1.01 (turbo)0:37.120:19.030:30.360:13.6543.80 MB74.91%
Monkey's Audio 3.99 (fast)0:50.450:33.450:55.140:39.0343.86 MB75.01%
WavPack 4.41 (normal -x)1:07.850:48.390:37.250:20.3243.91 MB75.10%
WavPack 4.41 (normal)0:46.860:27.060:37.570:20.3144.01 MB75.26%
FLAC 1.2.1 (-8)2:08.571:51.560:26.910:11.0344.11 MB75.44%
FLAC 1.2.1 (-5, default)0:48.660:31.460:26.540:10.6344.17 MB75.54%
Bonk 0.54:12.593:56.453:26.613:11.0744.35 MB75.85%
FLAC 1.2.1 (-3)0:36.620:19.230:27.010:09.7544.58 MB76.25%
WavPack 4.41 (fast -x)0:57.500:37.910:32.460:15.7244.70 MB76.45%
WavPack 4.41 (fast)0:42.950:22.860:32.450:15.6044.71 MB76.46%
Apple Lossless (iTunes 4.5)????44.74 MB76.53%
Shorten 3.2a (-p8 -b2048)1:00.050:42.060:37.310:20.8744.75 MB76.54%
FLAC 1.2.1 (-1)0:32.130:14.160:27.550:10.7146.60 MB79.70%
Shorten 3.2a (-p0 -b256, default)0:49.940:31.660:32.610:15.5146.68 MB79.84%
RIFF WAVE4:02.174:02.1758.47 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__eddie_warner_titus.html b/flac/doc/html/comparison__eddie_warner_titus.html new file mode 100644 index 0000000..1e3e498 --- /dev/null +++ b/flac/doc/html/comparison__eddie_warner_titus.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
Tak 1.01 (extra high max)2:33.662:26.560:13.830:08.0613.56 MB48.65%
Tak 1.01 (extra high)0:54.330:46.940:14.630:08.7313.58 MB48.71%
Tak 1.01 (normal)0:25.210:17.910:13.810:07.8313.64 MB48.94%
WavPack 4.41 (extra high -x)0:59.690:50.920:23.370:16.6414.16 MB50.82%
WavPack 4.41 (high)0:30.950:21.880:19.700:12.9414.18 MB50.89%
WavPack 4.41 (normal -x)0:31.630:22.960:16.370:10.0714.41 MB51.72%
Tak 1.01 (turbo)0:16.490:09.190:13.150:06.8714.52 MB52.10%
WavPack 4.41 (normal)0:23.610:14.900:17.130:09.5314.56 MB52.23%
FLAC 1.2.1 (-8)0:57.420:49.990:11.880:05.9114.77 MB52.98%
La 0.3c5:22.085:14.865:11.455:06.8814.76 MB52.98%
FLAC 1.2.1 (-5, default)0:22.060:14.610:12.780:05.2814.83 MB53.23%
optimFROG 4.21 (mode 2 @ 4x)1:09.571:01.361:13.871:07.0915.01 MB53.85%
optimFROG 4.21 (mode 1 @ 4x)0:53.690:45.310:55.970:49.6215.01 MB53.85%
optimFROG 4.21 (mode 3 @ 4x)2:05.241:57.362:07.642:01.9215.01 MB53.87%
WavPack 4.41 (fast -x)0:26.810:17.000:14.210:07.8215.01 MB53.87%
optimFROG 4.21 (mode 4 @ 1x)12:01.6911:54.2812:03.3611:57.0615.02 MB53.90%
FLAC 1.2.1 (-3)0:16.250:08.590:12.770:04.9515.08 MB54.12%
optimFROG 4.21 (mode 0 @ 4x)0:36.480:28.050:38.760:32.4615.13 MB54.29%
Monkey's Audio 3.99 (extra high)1:02.130:54.551:03.540:57.5615.15 MB54.36%
WavPack 4.41 (fast)0:20.990:12.280:14.010:07.9415.17 MB54.45%
Monkey's Audio 3.99 (insane)4:39.174:32.264:51.864:47.4715.18 MB54.47%
Monkey's Audio 3.99 (high)0:33.690:26.380:35.470:29.4615.26 MB54.74%
Monkey's Audio 3.99 (normal)0:29.040:21.710:30.210:24.3615.27 MB54.79%
Monkey's Audio 3.99 (fast)0:23.070:15.050:24.990:18.8115.55 MB55.79%
Shorten 3.2a (-p0 -b256, default)0:21.190:13.680:13.500:07.2815.78 MB56.62%
Shorten 3.2a (-p8 -b2048)0:26.260:18.620:15.590:08.7816.21 MB58.18%
FLAC 1.2.1 (-1)0:14.000:06.170:11.790:05.2216.35 MB58.67%
Apple Lossless (iTunes 4.5)????16.36 MB58.71%
Bonk 0.51:54.691:47.691:35.031:28.4716.73 MB60.03%
RIFF WAVE1:16.861:16.8627.87 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__fanfare_de_l_eventail_de_jeanne.html b/flac/doc/html/comparison__fanfare_de_l_eventail_de_jeanne.html new file mode 100644 index 0000000..2c028cd --- /dev/null +++ b/flac/doc/html/comparison__fanfare_de_l_eventail_de_jeanne.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c3:53.853:48.603:46.063:43.426.46 MB31.04%
Tak 1.01 (extra high max)1:40.841:36.140:10.020:06.646.57 MB31.54%
Tak 1.01 (extra high)0:36.930:31.820:10.220:06.786.58 MB31.62%
Monkey's Audio 3.99 (extra high)0:42.130:37.160:43.260:39.926.75 MB32.43%
Monkey's Audio 3.99 (insane)3:09.723:04.723:16.683:14.216.78 MB32.56%
optimFROG 4.21 (mode 4 @ 1x)8:22.498:17.198:22.998:19.166.82 MB32.74%
optimFROG 4.21 (mode 3 @ 4x)1:27.801:22.511:28.891:25.166.91 MB33.20%
Tak 1.01 (normal)0:17.570:12.280:08.760:05.406.92 MB33.24%
Monkey's Audio 3.99 (high)0:22.580:17.460:23.480:20.176.98 MB33.53%
optimFROG 4.21 (mode 2 @ 4x)0:48.740:43.110:51.290:46.987.01 MB33.69%
optimFROG 4.21 (mode 1 @ 4x)0:37.650:31.910:38.280:34.487.09 MB34.06%
optimFROG 4.21 (mode 0 @ 4x)0:24.980:19.190:26.320:22.477.21 MB34.62%
Monkey's Audio 3.99 (normal)0:19.630:14.440:20.770:17.117.28 MB34.95%
Tak 1.01 (turbo)0:10.810:05.750:08.430:04.477.31 MB35.11%
WavPack 4.41 (extra high -x)0:40.930:35.090:15.000:11.297.38 MB35.44%
FLAC 1.2.1 (-8)0:38.780:33.610:07.050:03.527.46 MB35.82%
WavPack 4.41 (high)0:17.840:11.830:13.070:09.227.49 MB35.98%
Monkey's Audio 3.99 (fast)0:15.210:10.130:16.270:12.837.50 MB36.01%
FLAC 1.2.1 (-5, default)0:14.840:09.520:07.390:03.367.51 MB36.08%
WavPack 4.41 (normal -x)0:20.880:14.860:10.540:06.587.52 MB36.12%
WavPack 4.41 (normal)0:14.750:08.790:10.880:06.667.58 MB36.41%
FLAC 1.2.1 (-3)0:10.590:05.380:06.780:02.967.60 MB36.48%
WavPack 4.41 (fast -x)0:17.360:11.370:09.090:05.067.69 MB36.92%
WavPack 4.41 (fast)0:13.190:07.260:08.680:05.107.81 MB37.52%
Apple Lossless (iTunes 4.5)????7.82 MB37.57%
Bonk 0.51:16.801:12.071:00.910:57.067.83 MB37.62%
FLAC 1.2.1 (-1)0:09.190:03.960:07.850:03.488.11 MB38.95%
Shorten 3.2a (-p0 -b256, default)0:14.290:09.130:08.730:04.818.19 MB39.32%
Shorten 3.2a (-p8 -b2048)0:17.660:12.410:10.010:06.258.29 MB39.83%
RIFF WAVE0:36.640:36.6420.82 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__gloria_estefan_conga.html b/flac/doc/html/comparison__gloria_estefan_conga.html new file mode 100644 index 0000000..a0d0838 --- /dev/null +++ b/flac/doc/html/comparison__gloria_estefan_conga.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c8:50.138:38.358:31.048:22.6728.98 MB64.19%
optimFROG 4.21 (mode 4 @ 1x)19:41.5519:29.0019:44.0419:32.9429.43 MB65.17%
Monkey's Audio 3.99 (insane)7:37.657:26.837:59.147:50.7229.48 MB65.28%
Monkey's Audio 3.99 (extra high)1:42.801:29.771:45.421:34.2729.49 MB65.30%
optimFROG 4.21 (mode 3 @ 4x)3:26.623:12.393:30.883:19.4929.49 MB65.31%
optimFROG 4.21 (mode 2 @ 4x)1:55.991:40.982:00.341:49.2129.54 MB65.42%
optimFROG 4.21 (mode 1 @ 4x)1:28.641:13.821:32.591:20.9529.58 MB65.50%
Monkey's Audio 3.99 (high)0:55.850:43.160:58.880:47.7629.69 MB65.76%
Tak 1.01 (extra high max)4:14.194:03.060:25.550:14.3229.74 MB65.87%
Tak 1.01 (extra high)1:31.551:18.820:25.920:14.5229.77 MB65.92%
optimFROG 4.21 (mode 0 @ 4x)1:00.950:46.301:05.540:54.1029.78 MB65.95%
Monkey's Audio 3.99 (normal)0:49.040:36.370:51.890:40.8429.83 MB66.05%
Tak 1.01 (normal)0:42.970:29.860:23.540:12.2829.86 MB66.12%
WavPack 4.41 (extra high -x)1:37.601:22.420:39.740:27.4629.92 MB66.27%
WavPack 4.41 (high)0:41.970:26.810:33.680:21.4530.02 MB66.49%
Monkey's Audio 3.99 (fast)0:37.950:25.200:41.850:30.3630.20 MB66.89%
WavPack 4.41 (normal -x)0:52.600:37.670:27.550:15.5830.32 MB67.15%
Tak 1.01 (turbo)0:27.640:13.980:22.580:11.2230.38 MB67.27%
WavPack 4.41 (normal)0:35.400:20.450:28.550:15.4330.44 MB67.42%
Bonk 0.53:09.652:57.692:35.012:23.8430.64 MB67.85%
FLAC 1.2.1 (-8)1:37.621:24.840:23.650:09.1630.66 MB67.90%
FLAC 1.2.1 (-5, default)0:36.820:23.610:20.770:08.7130.72 MB68.03%
WavPack 4.41 (fast)0:31.000:17.170:24.180:12.3730.75 MB68.10%
WavPack 4.41 (fast -x)0:43.650:29.080:23.780:12.1030.75 MB68.10%
Apple Lossless (iTunes 4.5)????30.91 MB68.47%
FLAC 1.2.1 (-3)0:28.350:14.220:22.350:08.5231.49 MB69.74%
Shorten 3.2a (-p8 -b2048)0:45.470:31.570:27.670:15.9431.76 MB70.34%
FLAC 1.2.1 (-1)0:24.040:10.050:19.460:08.0031.95 MB70.76%
Shorten 3.2a (-p0 -b256, default)0:37.090:23.160:23.320:11.5032.47 MB71.91%
RIFF WAVE2:44.302:44.3045.15 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__hand_in_my_pocket.html b/flac/doc/html/comparison__hand_in_my_pocket.html new file mode 100644 index 0000000..0b44b92 --- /dev/null +++ b/flac/doc/html/comparison__hand_in_my_pocket.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c7:32.827:22.327:15.807:09.3220.77 MB53.12%
Monkey's Audio 3.99 (insane)6:32.306:21.616:49.126:42.8221.22 MB54.27%
optimFROG 4.21 (mode 4 @ 1x)16:52.1716:41.4816:54.9316:45.2521.24 MB54.33%
optimFROG 4.21 (mode 3 @ 4x)2:55.932:44.652:59.072:50.8221.25 MB54.36%
optimFROG 4.21 (mode 2 @ 4x)1:38.571:26.581:41.851:32.9321.33 MB54.55%
optimFROG 4.21 (mode 1 @ 4x)1:14.991:02.511:17.801:09.1021.36 MB54.64%
Monkey's Audio 3.99 (extra high)1:26.611:16.071:30.361:21.4421.40 MB54.75%
Tak 1.01 (extra high max)3:26.433:17.090:23.190:13.4221.49 MB54.96%
Tak 1.01 (extra high)1:15.741:05.080:23.060:14.1621.52 MB55.04%
Monkey's Audio 3.99 (high)0:46.910:36.450:49.980:41.1621.66 MB55.40%
Tak 1.01 (normal)0:35.390:24.390:20.800:12.1421.73 MB55.57%
Monkey's Audio 3.99 (normal)0:41.220:30.240:42.700:34.0521.76 MB55.65%
optimFROG 4.21 (mode 0 @ 4x)0:53.020:40.300:55.090:45.6621.89 MB55.98%
WavPack 4.41 (extra high -x)1:22.521:09.690:33.630:23.7622.04 MB56.37%
Monkey's Audio 3.99 (fast)0:31.610:20.950:34.930:26.0922.13 MB56.60%
WavPack 4.41 (high)0:35.980:22.810:29.070:18.3322.34 MB57.14%
WavPack 4.41 (normal -x)0:45.150:31.710:22.650:13.1122.96 MB58.74%
Tak 1.01 (turbo)0:23.450:11.800:18.300:09.0923.06 MB58.97%
FLAC 1.2.1 (-8)1:22.331:11.760:17.640:08.4823.19 MB59.31%
WavPack 4.41 (normal)0:30.380:17.380:23.350:14.2223.26 MB59.50%
FLAC 1.2.1 (-5, default)0:31.320:20.100:16.760:07.2223.30 MB59.61%
Bonk 0.52:39.842:29.572:09.432:00.0523.35 MB59.72%
Apple Lossless (iTunes 4.5)????23.64 MB60.47%
WavPack 4.41 (fast -x)0:37.370:24.820:19.970:10.5423.81 MB60.91%
WavPack 4.41 (fast)0:28.080:14.530:20.820:11.0223.93 MB61.21%
FLAC 1.2.1 (-3)0:23.760:11.000:16.250:06.8224.04 MB61.48%
Shorten 3.2a (-p8 -b2048)0:38.450:26.710:23.330:13.6724.72 MB63.23%
FLAC 1.2.1 (-1)0:20.600:08.530:16.830:07.1724.78 MB63.40%
Shorten 3.2a (-p0 -b256, default)0:31.140:19.240:21.190:11.2825.34 MB64.81%
RIFF WAVE1:57.731:57.7339.09 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__l_sub_raga_sivapriya.html b/flac/doc/html/comparison__l_sub_raga_sivapriya.html new file mode 100644 index 0000000..5967d34 --- /dev/null +++ b/flac/doc/html/comparison__l_sub_raga_sivapriya.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c40:54.7839:59.0439:22.2038:52.3687.51 MB40.97%
Monkey's Audio 3.99 (insane)35:16.9934:30.8636:59.6336:29.4889.18 MB41.75%
Tak 1.01 (extra high max)17:43.5816:55.922:14.141:27.3990.84 MB42.53%
Tak 1.01 (extra high)6:59.206:04.852:14.621:29.2990.88 MB42.55%
Monkey's Audio 3.99 (extra high)7:46.456:53.718:04.357:21.4490.95 MB42.58%
optimFROG 4.21 (mode 4 @ 1x)93:03.5592:09.3893:14.0992:30.1292.05 MB43.10%
optimFROG 4.21 (mode 3 @ 4x)15:57.6915:02.4316:17.4515:35.3892.09 MB43.11%
optimFROG 4.21 (mode 2 @ 4x)8:48.937:50.699:07.338:24.9992.48 MB43.30%
optimFROG 4.21 (mode 1 @ 4x)6:37.615:38.427:01.966:16.4192.76 MB43.43%
Monkey's Audio 3.99 (high)4:10.523:16.404:28.743:43.2993.15 MB43.61%
Monkey's Audio 3.99 (normal)3:36.142:42.033:55.633:10.3194.32 MB44.16%
Tak 1.01 (normal)3:09.812:14.131:47.440:58.0894.45 MB44.22%
optimFROG 4.21 (mode 0 @ 4x)4:29.253:31.364:51.564:05.6394.74 MB44.36%
Monkey's Audio 3.99 (fast)2:47.971:53.553:05.922:19.0495.34 MB44.64%
WavPack 4.41 (extra high -x)7:25.786:23.832:58.682:08.0696.11 MB45.00%
Tak 1.01 (turbo)1:59.331:02.271:43.560:51.7296.13 MB45.01%
FLAC 1.2.1 (-8)7:18.016:23.651:28.930:40.0096.68 MB45.26%
WavPack 4.41 (high)3:10.072:05.532:30.661:39.3596.80 MB45.32%
FLAC 1.2.1 (-5, default)2:43.851:47.041:26.330:39.0897.00 MB45.41%
WavPack 4.41 (normal -x)3:48.912:43.721:56.401:09.6897.37 MB45.59%
FLAC 1.2.1 (-3)1:58.631:00.671:28.480:39.7797.92 MB45.85%
WavPack 4.41 (normal)2:38.391:32.772:03.211:13.2298.03 MB45.90%
Apple Lossless (iTunes 4.5)????98.57 MB46.15%
WavPack 4.41 (fast -x)3:11.512:05.471:46.710:54.2098.79 MB46.25%
Bonk 0.513:47.9412:57.2511:07.4210:21.5298.94 MB46.33%
WavPack 4.41 (fast)2:21.401:16.781:43.540:54.40100.00 MB46.82%
Shorten 3.2a (-p8 -b2048)3:14.032:16.631:58.491:08.47102.60 MB48.04%
Shorten 3.2a (-p0 -b256, default)2:41.541:43.741:48.330:56.56102.84 MB48.15%
FLAC 1.2.1 (-1)1:44.160:43.351:30.390:36.69103.43 MB48.43%
RIFF WAVE8:16.118:16.11213.56 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__laetatus_sum.html b/flac/doc/html/comparison__laetatus_sum.html new file mode 100644 index 0000000..60cf2d6 --- /dev/null +++ b/flac/doc/html/comparison__laetatus_sum.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c4:39.124:33.044:29.324:25.4811.94 MB49.22%
Monkey's Audio 3.99 (insane)4:04.683:58.314:15.314:11.7412.05 MB49.68%
Monkey's Audio 3.99 (extra high)0:54.040:47.410:55.760:50.8112.09 MB49.81%
Tak 1.01 (extra high)0:46.420:39.870:14.100:08.7312.15 MB50.09%
Tak 1.01 (extra high max)1:55.691:49.710:13.790:08.6612.15 MB50.09%
optimFROG 4.21 (mode 4 @ 1x)10:35.0910:28.5610:36.3910:31.0712.17 MB50.15%
optimFROG 4.21 (mode 3 @ 4x)1:49.811:42.941:51.851:46.8912.19 MB50.23%
Monkey's Audio 3.99 (high)0:28.990:22.510:30.720:25.7112.23 MB50.42%
Tak 1.01 (normal)0:21.770:15.120:11.850:06.6612.25 MB50.47%
optimFROG 4.21 (mode 2 @ 4x)1:00.930:53.701:05.580:59.0612.27 MB50.58%
Monkey's Audio 3.99 (normal)0:25.040:18.610:26.380:21.5712.42 MB51.18%
optimFROG 4.21 (mode 1 @ 4x)0:45.860:38.630:48.380:43.2112.43 MB51.21%
Tak 1.01 (turbo)0:13.730:07.030:11.470:06.4012.54 MB51.67%
optimFROG 4.21 (mode 0 @ 4x)0:31.360:23.990:33.700:28.3612.63 MB52.07%
WavPack 4.41 (extra high -x)0:51.140:43.720:20.370:14.6112.66 MB52.17%
Bonk 0.51:35.751:29.851:17.291:12.0212.71 MB52.37%
FLAC 1.2.1 (-8)0:50.660:44.240:11.600:06.0412.71 MB52.38%
Monkey's Audio 3.99 (fast)0:19.480:13.100:22.330:16.4112.76 MB52.60%
FLAC 1.2.1 (-5, default)0:19.150:12.460:09.230:04.1312.82 MB52.85%
WavPack 4.41 (high)0:21.590:14.300:17.340:11.6412.87 MB53.02%
FLAC 1.2.1 (-3)0:13.620:07.160:10.110:04.7312.90 MB53.17%
WavPack 4.41 (normal -x)0:26.760:19.190:13.350:08.1512.92 MB53.25%
WavPack 4.41 (normal)0:18.280:10.590:14.270:09.1712.95 MB53.38%
Apple Lossless (iTunes 4.5)????13.04 MB53.77%
WavPack 4.41 (fast -x)0:22.180:14.440:11.600:06.5213.05 MB53.80%
WavPack 4.41 (fast)0:16.890:09.020:12.620:06.9613.31 MB54.85%
Shorten 3.2a (-p0 -b256, default)0:18.240:11.630:11.420:06.1513.32 MB54.89%
FLAC 1.2.1 (-1)0:11.560:04.940:09.740:04.1813.32 MB54.92%
Shorten 3.2a (-p8 -b2048)0:22.490:15.870:13.710:08.3213.42 MB55.31%
RIFF WAVE1:07.701:07.7024.26 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__mummified_in_barbed_wire.html b/flac/doc/html/comparison__mummified_in_barbed_wire.html new file mode 100644 index 0000000..0c143bc --- /dev/null +++ b/flac/doc/html/comparison__mummified_in_barbed_wire.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c6:34.386:24.876:21.266:14.5322.69 MB67.98%
Monkey's Audio 3.99 (insane)5:40.585:30.735:55.615:49.3022.83 MB68.39%
Monkey's Audio 3.99 (extra high)1:16.321:05.831:18.271:09.9222.85 MB68.47%
optimFROG 4.21 (mode 4 @ 1x)14:35.3914:25.9814:37.3814:28.8922.95 MB68.77%
optimFROG 4.21 (mode 3 @ 4x)2:32.722:22.242:35.632:27.7423.01 MB68.94%
Tak 1.01 (extra high max)2:45.872:36.910:19.630:11.1723.04 MB69.04%
Tak 1.01 (extra high)1:03.100:53.220:22.920:11.7823.06 MB69.08%
Monkey's Audio 3.99 (high)0:41.330:31.840:43.870:35.6623.18 MB69.45%
optimFROG 4.21 (mode 2 @ 4x)1:26.091:14.651:29.331:20.8723.21 MB69.54%
Monkey's Audio 3.99 (normal)0:35.680:26.310:39.150:30.7723.24 MB69.63%
Tak 1.01 (normal)0:31.430:21.180:18.740:09.9223.24 MB69.64%
optimFROG 4.21 (mode 1 @ 4x)1:04.820:53.531:08.491:00.1123.31 MB69.84%
WavPack 4.41 (extra high -x)1:11.611:00.900:28.810:19.6623.38 MB70.06%
Tak 1.01 (turbo)0:21.430:10.210:17.250:07.9723.49 MB70.37%
FLAC 1.2.1 (-8)1:12.781:03.110:16.260:07.2323.72 MB71.06%
WavPack 4.41 (high)0:31.880:20.250:26.680:16.6923.83 MB71.41%
WavPack 4.41 (normal -x)0:38.920:27.330:20.460:11.8323.91 MB71.63%
optimFROG 4.21 (mode 0 @ 4x)0:44.750:33.750:48.790:40.1123.95 MB71.76%
FLAC 1.2.1 (-5, default)0:28.410:17.730:16.000:06.3924.01 MB71.94%
Monkey's Audio 3.99 (fast)0:28.670:18.670:32.520:23.9824.14 MB72.34%
WavPack 4.41 (normal)0:26.910:15.010:22.340:13.3524.17 MB72.42%
Bonk 0.52:22.132:13.041:58.241:49.1124.36 MB72.97%
Apple Lossless (iTunes 4.5)????24.37 MB73.01%
WavPack 4.41 (fast -x)0:32.790:21.370:19.240:10.1624.86 MB74.47%
WavPack 4.41 (fast)0:25.340:12.540:18.760:09.3024.86 MB74.48%
FLAC 1.2.1 (-3)0:21.480:10.460:15.500:06.6825.05 MB75.04%
Shorten 3.2a (-p8 -b2048)0:34.780:23.740:22.600:13.5525.12 MB75.26%
FLAC 1.2.1 (-1)0:18.750:07.500:16.250:07.2626.07 MB78.12%
Shorten 3.2a (-p0 -b256, default)0:28.670:17.590:19.190:09.9726.61 MB79.72%
RIFF WAVE2:08.632:08.6333.37 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__prokofiev_pcon3_3.html b/flac/doc/html/comparison__prokofiev_pcon3_3.html new file mode 100644 index 0000000..cf4c8ef --- /dev/null +++ b/flac/doc/html/comparison__prokofiev_pcon3_3.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c19:03.4718:38.1618:20.2018:07.7732.65 MB32.43%
Tak 1.01 (extra high max)8:25.738:04.190:59.470:40.0233.30 MB33.06%
Tak 1.01 (extra high)3:11.592:47.241:03.540:44.2133.32 MB33.09%
Monkey's Audio 3.99 (insane)16:09.4315:46.0416:53.9216:41.2533.34 MB33.11%
optimFROG 4.21 (mode 4 @ 1x)43:22.3042:57.3343:26.4943:07.0133.58 MB33.35%
Monkey's Audio 3.99 (extra high)3:33.723:09.653:44.813:26.4633.60 MB33.37%
optimFROG 4.21 (mode 3 @ 4x)7:21.406:59.217:29.737:12.1233.66 MB33.43%
optimFROG 4.21 (mode 2 @ 4x)4:02.673:36.664:10.753:52.1433.73 MB33.50%
optimFROG 4.21 (mode 1 @ 4x)3:00.862:34.683:07.842:49.2533.83 MB33.60%
optimFROG 4.21 (mode 0 @ 4x)1:59.441:34.592:08.441:49.0534.14 MB33.90%
Monkey's Audio 3.99 (high)1:54.151:29.892:06.521:47.7834.16 MB33.92%
Tak 1.01 (normal)1:28.481:02.760:50.740:30.0634.41 MB34.17%
Monkey's Audio 3.99 (normal)1:38.221:13.731:48.431:29.3134.58 MB34.34%
WavPack 4.41 (extra high -x)3:30.153:00.661:24.081:03.8434.82 MB34.58%
Tak 1.01 (turbo)0:53.570:28.130:48.050:27.9534.98 MB34.74%
WavPack 4.41 (high)1:29.500:58.581:09.840:48.8335.24 MB34.99%
WavPack 4.41 (normal -x)1:47.071:17.260:56.040:36.1835.34 MB35.09%
Monkey's Audio 3.99 (fast)1:16.080:51.681:25.821:06.7535.53 MB35.28%
WavPack 4.41 (normal)1:13.130:43.990:55.600:33.2735.69 MB35.44%
FLAC 1.2.1 (-8)3:13.352:49.180:39.620:20.1735.99 MB35.74%
FLAC 1.2.1 (-5, default)1:14.370:49.350:38.860:18.3936.28 MB36.03%
WavPack 4.41 (fast -x)1:27.940:57.860:46.530:25.7636.37 MB36.12%
FLAC 1.2.1 (-3)0:53.070:26.950:41.380:19.1636.65 MB36.40%
WavPack 4.41 (fast)1:07.120:36.210:48.290:28.2537.18 MB36.92%
Apple Lossless (iTunes 4.5)????37.32 MB37.06%
FLAC 1.2.1 (-1)0:46.220:19.530:38.540:17.8639.23 MB38.96%
Shorten 3.2a (-p0 -b256, default)1:13.080:46.860:49.720:28.8539.49 MB39.21%
Bonk 0.56:18.905:55.405:07.274:46.8440.31 MB40.03%
Shorten 3.2a (-p8 -b2048)1:27.831:01.220:57.700:34.3645.34 MB45.02%
RIFF WAVE3:05.103:05.10100.68 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__ravel_sq4_4.html b/flac/doc/html/comparison__ravel_sq4_4.html new file mode 100644 index 0000000..5a0fe16 --- /dev/null +++ b/flac/doc/html/comparison__ravel_sq4_4.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c10:40.8810:27.2210:17.0710:09.6419.94 MB35.50%
Monkey's Audio 3.99 (insane)9:08.888:56.229:37.009:29.3520.17 MB35.90%
Monkey's Audio 3.99 (extra high)2:00.531:47.082:05.061:54.6420.29 MB36.11%
Tak 1.01 (extra high max)4:39.264:27.170:33.470:22.4220.33 MB36.19%
Tak 1.01 (extra high)1:48.731:34.920:35.500:24.1920.35 MB36.22%
optimFROG 4.21 (mode 4 @ 1x)24:26.7424:12.4024:28.8024:17.9820.62 MB36.71%
Monkey's Audio 3.99 (high)1:04.750:50.791:09.210:58.4920.68 MB36.81%
optimFROG 4.21 (mode 3 @ 4x)4:10.493:56.434:13.884:03.9020.72 MB36.88%
optimFROG 4.21 (mode 2 @ 4x)2:17.172:02.142:21.022:10.7820.83 MB37.07%
optimFROG 4.21 (mode 1 @ 4x)1:42.601:27.341:47.211:36.5420.93 MB37.25%
Tak 1.01 (normal)0:48.660:34.630:26.320:15.2020.95 MB37.28%
Monkey's Audio 3.99 (normal)0:55.630:41.681:00.360:49.6621.05 MB37.47%
optimFROG 4.21 (mode 0 @ 4x)1:08.870:53.421:13.721:02.9721.23 MB37.79%
WavPack 4.41 (extra high -x)1:56.001:41.600:44.820:33.1921.42 MB38.13%
Tak 1.01 (turbo)0:30.010:15.730:24.320:12.8921.49 MB38.25%
Monkey's Audio 3.99 (fast)0:43.140:29.290:48.440:37.3921.52 MB38.30%
WavPack 4.41 (high)0:49.040:32.840:37.710:25.3121.59 MB38.42%
WavPack 4.41 (normal -x)0:59.890:43.470:29.430:18.5821.72 MB38.66%
WavPack 4.41 (normal)0:40.760:24.680:30.440:19.0621.75 MB38.70%
FLAC 1.2.1 (-8)1:51.951:38.330:21.080:10.1421.78 MB38.77%
FLAC 1.2.1 (-5, default)0:41.470:27.540:21.210:09.9621.90 MB38.97%
WavPack 4.41 (fast -x)0:49.790:33.440:26.250:14.4322.02 MB39.20%
WavPack 4.41 (fast)0:36.560:20.280:25.550:14.0822.23 MB39.57%
FLAC 1.2.1 (-3)0:29.860:15.760:20.280:09.1022.42 MB39.91%
Apple Lossless (iTunes 4.5)????22.52 MB40.08%
Bonk 0.53:32.503:19.492:50.962:39.4223.18 MB41.25%
FLAC 1.2.1 (-1)0:25.230:10.810:21.380:09.8723.33 MB41.52%
Shorten 3.2a (-p0 -b256, default)0:41.160:26.710:26.700:15.2723.71 MB42.21%
Shorten 3.2a (-p8 -b2048)0:49.310:34.870:30.800:17.9625.59 MB45.54%
RIFF WAVE1:53.061:53.0656.18 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__scarlatti_k42.html b/flac/doc/html/comparison__scarlatti_k42.html new file mode 100644 index 0000000..77d37de --- /dev/null +++ b/flac/doc/html/comparison__scarlatti_k42.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c3:07.283:03.363:00.592:58.146.62 MB40.36%
Monkey's Audio 3.99 (insane)2:43.572:39.842:50.502:48.436.67 MB40.68%
Monkey's Audio 3.99 (extra high)0:35.820:31.800:36.660:33.836.74 MB41.09%
Tak 1.01 (extra high max)1:23.811:20.140:09.050:06.066.78 MB41.37%
Tak 1.01 (extra high)0:32.020:27.950:08.950:05.906.80 MB41.48%
optimFROG 4.21 (mode 4 @ 1x)7:08.277:04.287:09.327:06.006.87 MB41.90%
optimFROG 4.21 (mode 3 @ 4x)1:13.311:09.331:15.161:12.056.88 MB41.96%
Monkey's Audio 3.99 (high)0:19.090:15.100:20.200:17.456.91 MB42.13%
optimFROG 4.21 (mode 2 @ 4x)0:40.290:36.010:41.990:38.606.91 MB42.16%
Tak 1.01 (normal)0:14.620:10.550:07.620:04.676.97 MB42.54%
optimFROG 4.21 (mode 1 @ 4x)0:30.050:25.840:33.760:29.486.98 MB42.55%
Monkey's Audio 3.99 (normal)0:16.380:12.400:17.450:14.326.99 MB42.61%
optimFROG 4.21 (mode 0 @ 4x)0:20.350:16.000:22.490:19.087.07 MB43.10%
Tak 1.01 (turbo)0:08.800:04.680:06.870:03.777.11 MB43.34%
WavPack 4.41 (extra high -x)0:34.070:29.660:13.060:09.607.13 MB43.47%
Monkey's Audio 3.99 (fast)0:12.730:08.680:13.840:10.867.16 MB43.69%
FLAC 1.2.1 (-8)0:33.100:29.010:07.010:03.367.23 MB44.10%
WavPack 4.41 (high)0:13.920:09.610:11.170:07.237.24 MB44.16%
FLAC 1.2.1 (-5, default)0:12.170:08.110:05.970:02.927.26 MB44.28%
WavPack 4.41 (normal -x)0:17.340:12.760:08.720:05.347.27 MB44.34%
FLAC 1.2.1 (-3)0:08.630:04.560:06.140:02.587.29 MB44.46%
WavPack 4.41 (normal)0:11.550:07.090:08.770:05.467.32 MB44.67%
WavPack 4.41 (fast -x)0:14.160:09.770:07.360:04.337.35 MB44.81%
Apple Lossless (iTunes 4.5)????7.44 MB45.41%
Bonk 0.51:02.990:59.100:50.900:47.487.46 MB45.48%
Shorten 3.2a (-p0 -b256, default)0:11.690:07.620:07.490:04.447.48 MB45.64%
FLAC 1.2.1 (-1)0:07.230:03.140:05.870:02.587.51 MB45.82%
WavPack 4.41 (fast)0:10.410:05.970:07.980:04.347.73 MB47.14%
Shorten 3.2a (-p8 -b2048)0:14.340:10.170:08.610:05.228.20 MB50.04%
RIFF WAVE0:37.510:37.5116.39 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__tool_forty_six_and_2.html b/flac/doc/html/comparison__tool_forty_six_and_2.html new file mode 100644 index 0000000..3fd5c58 --- /dev/null +++ b/flac/doc/html/comparison__tool_forty_six_and_2.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c12:28.2912:12.9312:02.2811:51.3937.42 MB58.24%
optimFROG 4.21 (mode 4 @ 1x)27:57.0627:40.8428:01.2927:46.1637.96 MB59.07%
optimFROG 4.21 (mode 3 @ 4x)4:50.124:32.534:57.454:43.2237.99 MB59.13%
Monkey's Audio 3.99 (insane)10:46.5510:32.5811:19.5411:08.0538.00 MB59.14%
Monkey's Audio 3.99 (extra high)2:22.002:05.732:29.802:14.7538.03 MB59.19%
optimFROG 4.21 (mode 2 @ 4x)2:40.992:22.302:49.182:34.0038.08 MB59.27%
optimFROG 4.21 (mode 1 @ 4x)2:01.341:42.412:11.181:55.1938.15 MB59.37%
Monkey's Audio 3.99 (high)1:17.691:00.221:22.991:07.5938.21 MB59.47%
Tak 1.01 (extra high max)5:45.295:29.360:36.160:20.9538.24 MB59.51%
Tak 1.01 (extra high)2:03.191:45.490:36.250:20.6738.28 MB59.58%
Monkey's Audio 3.99 (normal)1:06.860:49.481:13.250:58.0038.38 MB59.73%
Tak 1.01 (normal)0:58.620:40.000:33.280:17.7538.45 MB59.84%
optimFROG 4.21 (mode 0 @ 4x)1:23.431:04.391:31.901:15.6338.68 MB60.20%
WavPack 4.41 (extra high -x)2:15.261:55.850:55.540:38.1838.80 MB60.38%
WavPack 4.41 (high)0:58.090:38.420:46.360:29.4339.01 MB60.72%
Monkey's Audio 3.99 (fast)0:52.400:34.800:57.820:42.7439.09 MB60.84%
WavPack 4.41 (normal -x)1:10.800:51.660:38.470:22.1039.50 MB61.48%
Tak 1.01 (turbo)0:37.400:19.460:33.330:15.8539.88 MB62.07%
WavPack 4.41 (normal)0:48.400:28.640:38.310:22.6839.92 MB62.12%
FLAC 1.2.1 (-8)2:16.291:58.230:31.690:14.5640.04 MB62.32%
FLAC 1.2.1 (-5, default)0:50.890:33.030:28.200:12.6040.19 MB62.55%
WavPack 4.41 (fast)0:43.920:23.940:35.660:17.2240.47 MB62.98%
WavPack 4.41 (fast -x)1:00.670:40.170:35.000:17.8640.47 MB62.98%
Apple Lossless (iTunes 4.5)????40.75 MB63.42%
FLAC 1.2.1 (-3)0:37.480:19.570:30.660:11.1840.84 MB63.56%
Bonk 0.54:25.624:08.653:37.563:21.5940.98 MB63.78%
FLAC 1.2.1 (-1)0:32.210:13.870:27.890:11.4242.66 MB66.39%
Shorten 3.2a (-p8 -b2048)1:02.290:43.530:41.480:23.5143.06 MB67.01%
Shorten 3.2a (-p0 -b256, default)0:51.800:33.150:34.310:17.6443.18 MB67.21%
RIFF WAVE3:32.163:32.1664.25 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison__white_room.html b/flac/doc/html/comparison__white_room.html new file mode 100644 index 0000000..9d00b90 --- /dev/null +++ b/flac/doc/html/comparison__white_room.html @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Ratio +
La 0.3c10:19.1410:06.409:58.769:49.4033.44 MB63.09%
optimFROG 4.21 (mode 3 @ 4x)3:59.683:44.764:06.853:53.6333.90 MB63.95%
optimFROG 4.21 (mode 2 @ 4x)2:13.661:57.832:19.882:07.4433.91 MB63.97%
optimFROG 4.21 (mode 4 @ 1x)22:58.3822:44.9923:03.4922:49.4533.93 MB63.99%
Monkey's Audio 3.99 (insane)8:52.218:40.359:19.419:09.8233.95 MB64.04%
optimFROG 4.21 (mode 1 @ 4x)1:41.141:24.941:48.081:35.1233.96 MB64.05%
Monkey's Audio 3.99 (extra high)1:58.771:44.072:03.721:50.9634.00 MB64.13%
Tak 1.01 (extra high max)4:38.014:24.470:31.770:18.5634.08 MB64.28%
Tak 1.01 (extra high)1:42.151:27.360:31.010:17.9834.11 MB64.34%
Monkey's Audio 3.99 (high)1:04.940:50.221:09.130:56.1734.11 MB64.35%
Tak 1.01 (normal)0:48.570:33.590:28.230:14.7734.25 MB64.60%
Monkey's Audio 3.99 (normal)0:55.970:41.521:00.660:47.6634.25 MB64.60%
optimFROG 4.21 (mode 0 @ 4x)1:11.160:54.081:16.251:02.9634.29 MB64.68%
WavPack 4.41 (extra high -x)1:52.391:35.780:46.170:31.5534.52 MB65.12%
Tak 1.01 (turbo)0:30.950:15.970:27.610:13.1334.66 MB65.39%
WavPack 4.41 (high)0:47.950:31.280:40.190:25.2934.78 MB65.61%
FLAC 1.2.1 (-8)1:53.011:38.200:25.940:12.3334.85 MB65.73%
Monkey's Audio 3.99 (fast)0:44.320:29.300:49.050:36.0234.85 MB65.74%
Bonk 0.53:40.433:26.663:01.262:48.0534.96 MB65.95%
WavPack 4.41 (normal -x)0:58.410:41.810:31.140:17.8634.99 MB66.01%
FLAC 1.2.1 (-5, default)0:43.300:27.640:22.710:09.3735.07 MB66.16%
WavPack 4.41 (normal)0:40.460:23.700:32.230:19.0435.18 MB66.36%
FLAC 1.2.1 (-3)0:30.700:15.860:23.490:08.7635.30 MB66.59%
Shorten 3.2a (-p8 -b2048)0:51.660:36.540:32.680:19.2735.40 MB66.77%
Apple Lossless (iTunes 4.5)????35.46 MB66.89%
WavPack 4.41 (fast -x)0:49.400:32.480:27.760:14.6235.50 MB66.97%
WavPack 4.41 (fast)0:36.810:19.000:28.460:14.9035.61 MB67.18%
Shorten 3.2a (-p0 -b256, default)0:41.620:26.530:28.650:14.8836.42 MB68.70%
FLAC 1.2.1 (-1)0:26.900:11.600:23.190:08.6436.52 MB68.90%
RIFF WAVE3:09.603:09.6053.01 MB100.00%
+
+
+ + Complete summary table
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison_all_cpudectime.html b/flac/doc/html/comparison_all_cpudectime.html new file mode 100644 index 0000000..c0977a0 --- /dev/null +++ b/flac/doc/html/comparison_all_cpudectime.html @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
FLAC 1.2.1 (-8)26:46.7223:21.855:40.252:36.47404.23 MB53.36%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (fast -x)11:54.477:50.846:32.503:25.77411.52 MB54.39%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
Shorten 3.2a (-p8 -b2048)12:09.688:31.467:34.174:24.09438.86 MB58.11%
WavPack 4.41 (normal -x)14:14.5410:13.337:23.144:24.26403.10 MB53.19%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
Tak 1.01 (extra high max)66:52.1563:48.917:39.414:46.01383.70 MB50.60%
Tak 1.01 (extra high)25:14.0021:48.457:50.464:54.86384.06 MB50.66%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
WavPack 4.41 (extra high -x)27:23.5623:29.2610:58.907:48.32396.56 MB52.22%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
Monkey's Audio 3.99 (high)15:26.1612:03.1616:30.0013:40.59389.83 MB51.53%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
optimFROG 4.21 (mode 1 @ 4x)24:25.0420:37.9625:48.9022:52.76389.04 MB51.52%
Monkey's Audio 3.99 (extra high)28:34.0325:12.1429:38.8826:53.34384.55 MB50.87%
optimFROG 4.21 (mode 2 @ 4x)32:20.4628:36.3833:39.9630:49.89387.93 MB51.33%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
optimFROG 4.21 (mode 3 @ 4x)58:21.9454:52.6259:34.1256:51.21386.71 MB51.15%
Monkey's Audio 3.99 (insane)129:07.86126:05.33135:13.19133:12.71381.79 MB50.65%
La 0.3c150:12.30146:54.11144:50.36142:49.41375.76 MB49.86%
optimFROG 4.21 (mode 4 @ 1x)338:34.15335:12.47339:18.57336:25.54386.22 MB51.06%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison_all_cpuenctime.html b/flac/doc/html/comparison_all_cpuenctime.html new file mode 100644 index 0000000..539dab3 --- /dev/null +++ b/flac/doc/html/comparison_all_cpuenctime.html @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
WavPack 4.41 (fast -x)11:54.477:50.846:32.503:25.77411.52 MB54.39%
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
Shorten 3.2a (-p8 -b2048)12:09.688:31.467:34.174:24.09438.86 MB58.11%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
WavPack 4.41 (normal -x)14:14.5410:13.337:23.144:24.26403.10 MB53.19%
Monkey's Audio 3.99 (high)15:26.1612:03.1616:30.0013:40.59389.83 MB51.53%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
optimFROG 4.21 (mode 1 @ 4x)24:25.0420:37.9625:48.9022:52.76389.04 MB51.52%
Tak 1.01 (extra high)25:14.0021:48.457:50.464:54.86384.06 MB50.66%
FLAC 1.2.1 (-8)26:46.7223:21.855:40.252:36.47404.23 MB53.36%
WavPack 4.41 (extra high -x)27:23.5623:29.2610:58.907:48.32396.56 MB52.22%
Monkey's Audio 3.99 (extra high)28:34.0325:12.1429:38.8826:53.34384.55 MB50.87%
optimFROG 4.21 (mode 2 @ 4x)32:20.4628:36.3833:39.9630:49.89387.93 MB51.33%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
optimFROG 4.21 (mode 3 @ 4x)58:21.9454:52.6259:34.1256:51.21386.71 MB51.15%
Tak 1.01 (extra high max)66:52.1563:48.917:39.414:46.01383.70 MB50.60%
Monkey's Audio 3.99 (insane)129:07.86126:05.33135:13.19133:12.71381.79 MB50.65%
La 0.3c150:12.30146:54.11144:50.36142:49.41375.76 MB49.86%
optimFROG 4.21 (mode 4 @ 1x)338:34.15335:12.47339:18.57336:25.54386.22 MB51.06%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison_all_procdectime.html b/flac/doc/html/comparison_all_procdectime.html new file mode 100644 index 0000000..8926e4b --- /dev/null +++ b/flac/doc/html/comparison_all_procdectime.html @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
FLAC 1.2.1 (-8)26:46.7223:21.855:40.252:36.47404.23 MB53.36%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (fast -x)11:54.477:50.846:32.503:25.77411.52 MB54.39%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
WavPack 4.41 (normal -x)14:14.5410:13.337:23.144:24.26403.10 MB53.19%
Shorten 3.2a (-p8 -b2048)12:09.688:31.467:34.174:24.09438.86 MB58.11%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
Tak 1.01 (extra high max)66:52.1563:48.917:39.414:46.01383.70 MB50.60%
Tak 1.01 (extra high)25:14.0021:48.457:50.464:54.86384.06 MB50.66%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
WavPack 4.41 (extra high -x)27:23.5623:29.2610:58.907:48.32396.56 MB52.22%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
Monkey's Audio 3.99 (high)15:26.1612:03.1616:30.0013:40.59389.83 MB51.53%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
optimFROG 4.21 (mode 1 @ 4x)24:25.0420:37.9625:48.9022:52.76389.04 MB51.52%
Monkey's Audio 3.99 (extra high)28:34.0325:12.1429:38.8826:53.34384.55 MB50.87%
optimFROG 4.21 (mode 2 @ 4x)32:20.4628:36.3833:39.9630:49.89387.93 MB51.33%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
optimFROG 4.21 (mode 3 @ 4x)58:21.9454:52.6259:34.1256:51.21386.71 MB51.15%
Monkey's Audio 3.99 (insane)129:07.86126:05.33135:13.19133:12.71381.79 MB50.65%
La 0.3c150:12.30146:54.11144:50.36142:49.41375.76 MB49.86%
optimFROG 4.21 (mode 4 @ 1x)338:34.15335:12.47339:18.57336:25.54386.22 MB51.06%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison_all_procenctime.html b/flac/doc/html/comparison_all_procenctime.html new file mode 100644 index 0000000..dc170d4 --- /dev/null +++ b/flac/doc/html/comparison_all_procenctime.html @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
WavPack 4.41 (fast -x)11:54.477:50.846:32.503:25.77411.52 MB54.39%
Shorten 3.2a (-p8 -b2048)12:09.688:31.467:34.174:24.09438.86 MB58.11%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
WavPack 4.41 (normal -x)14:14.5410:13.337:23.144:24.26403.10 MB53.19%
Monkey's Audio 3.99 (high)15:26.1612:03.1616:30.0013:40.59389.83 MB51.53%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
optimFROG 4.21 (mode 1 @ 4x)24:25.0420:37.9625:48.9022:52.76389.04 MB51.52%
Tak 1.01 (extra high)25:14.0021:48.457:50.464:54.86384.06 MB50.66%
FLAC 1.2.1 (-8)26:46.7223:21.855:40.252:36.47404.23 MB53.36%
WavPack 4.41 (extra high -x)27:23.5623:29.2610:58.907:48.32396.56 MB52.22%
Monkey's Audio 3.99 (extra high)28:34.0325:12.1429:38.8826:53.34384.55 MB50.87%
optimFROG 4.21 (mode 2 @ 4x)32:20.4628:36.3833:39.9630:49.89387.93 MB51.33%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
optimFROG 4.21 (mode 3 @ 4x)58:21.9454:52.6259:34.1256:51.21386.71 MB51.15%
Tak 1.01 (extra high max)66:52.1563:48.917:39.414:46.01383.70 MB50.60%
Monkey's Audio 3.99 (insane)129:07.86126:05.33135:13.19133:12.71381.79 MB50.65%
La 0.3c150:12.30146:54.11144:50.36142:49.41375.76 MB49.86%
optimFROG 4.21 (mode 4 @ 1x)338:34.15335:12.47339:18.57336:25.54386.22 MB51.06%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/comparison_all_ratio.html b/flac/doc/html/comparison_all_ratio.html new file mode 100644 index 0000000..4cb4858 --- /dev/null +++ b/flac/doc/html/comparison_all_ratio.html @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + FLAC - comparison + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ comparison +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + Encode time + + Decode time + + Compression +
+ Codec + + Total + + CPU + + Total + + CPU + + Size + + Avg.ratio +
La 0.3c150:12.30146:54.11144:50.36142:49.41375.76 MB49.86%
Tak 1.01 (extra high max)66:52.1563:48.917:39.414:46.01383.70 MB50.60%
Monkey's Audio 3.99 (insane)129:07.86126:05.33135:13.19133:12.71381.79 MB50.65%
Tak 1.01 (extra high)25:14.0021:48.457:50.464:54.86384.06 MB50.66%
Monkey's Audio 3.99 (extra high)28:34.0325:12.1429:38.8826:53.34384.55 MB50.87%
optimFROG 4.21 (mode 4 @ 1x)338:34.15335:12.47339:18.57336:25.54386.22 MB51.06%
optimFROG 4.21 (mode 3 @ 4x)58:21.9454:52.6259:34.1256:51.21386.71 MB51.15%
optimFROG 4.21 (mode 2 @ 4x)32:20.4628:36.3833:39.9630:49.89387.93 MB51.33%
Tak 1.01 (normal)11:42.598:12.006:36.473:38.14391.16 MB51.39%
optimFROG 4.21 (mode 1 @ 4x)24:25.0420:37.9625:48.9022:52.76389.04 MB51.52%
Monkey's Audio 3.99 (high)15:26.1612:03.1616:30.0013:40.59389.83 MB51.53%
Monkey's Audio 3.99 (normal)13:20.159:56.4014:24.0211:33.71393.17 MB51.97%
WavPack 4.41 (extra high -x)27:23.5623:29.2610:58.907:48.32396.56 MB52.22%
optimFROG 4.21 (mode 0 @ 4x)16:36.9812:51.5817:55.5514:58.99394.69 MB52.24%
Tak 1.01 (turbo)7:25.213:51.026:16.823:10.87399.97 MB52.71%
WavPack 4.41 (high)11:48.477:45.589:19.076:05.35399.90 MB52.73%
Monkey's Audio 3.99 (fast)10:24.296:58.4611:32.078:37.81400.57 MB53.11%
WavPack 4.41 (normal -x)14:14.5410:13.337:23.144:24.26403.10 MB53.19%
FLAC 1.2.1 (-8)26:46.7223:21.855:40.252:36.47404.23 MB53.36%
WavPack 4.41 (normal)9:48.595:46.917:37.264:30.11405.84 MB53.56%
FLAC 1.2.1 (-5, default)10:07.416:35.685:23.162:22.41406.25 MB53.67%
WavPack 4.41 (fast -x)11:54.477:50.846:32.503:25.77411.52 MB54.39%
FLAC 1.2.1 (-3)7:23.773:47.425:31.152:19.07412.42 MB54.57%
WavPack 4.41 (fast)8:52.274:47.746:33.733:28.19415.05 MB54.92%
Apple Lossless (iTunes 4.5)19:53.2719:53.2710:01.8610:01.86414.45 MB54.96%
Bonk 0.551:45.5848:32.1042:02.7639:05.43418.65 MB55.43%
FLAC 1.2.1 (-1)6:24.512:42.935:26.872:17.49431.72 MB56.97%
Shorten 3.2a (-p0 -b256, default)10:01.386:23.406:38.433:30.66433.56 MB57.29%
Shorten 3.2a (-p8 -b2048)12:09.688:31.467:34.174:24.09438.86 MB58.11%
RIFF WAVE73:44.9473:44.94780.56 MB100.00%
+
+
+ Frederic Chopin Prelude No.24 in d minor
+ Dream Theater 6:00
+ Eddie Warner Titus
+ Maurice Ravel Fanfare from "L'eventail de Jeanne"
+ Gloria Estefan Conga
+ Alanis Morissette Hand In My Pocket
+ L. Subramaniam Raga Sivapriya
+ The Benedictine Monks of Santo Domingo de Silos Laetatus Sum
+ Cannibal Corpse Mummified In Barbed Wire
+ Sergei Prokofiev Piano Concerto No.3 (3rd movement)
+ Maurice Ravel String Quartet (4th movement)
+ Domenico Scarlatti Sonata K.42 (arr.Yepes for guitar)
+ Tool Forty-six & 2
+ Cream White Room
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/developers.html b/flac/doc/html/developers.html new file mode 100644 index 0000000..0a3093e --- /dev/null +++ b/flac/doc/html/developers.html @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + FLAC - developers + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ developers +
+
+
+ FLAC is an open source project and we are happy to enlist the help of anyone who wants to contribute, or to help with FLAC support in other programs and devices. The preferred method of communication is the developer mailing list (you must subscribe to post).
+
+ FLAC is open to third-party developers who want to add support for FLAC into their programs. All the necessary functionality is contained the libFLAC libraries which are licensed under Xiph.org's BSD license.
+
+ Some pointers to developer documentation and code:
+ + More resources are available on the FLAC project page on Sourceforge.net. +
+ +
+ +
+ +
+
+ goals +
+
+
+ Since FLAC is an open-source project, it's important to have a set of goals that everyone works to. They may change slightly from time to time but they're a good guideline. Changes should be in line with the goals and should not attempt to embrace any of the anti-goals.
+
+ Goals +
    +
  • + FLAC should be and stay an open format with an open-source reference implementation. +
  • +
  • + FLAC should be lossless. This seems obvious but lossy compression seems to creep into every audio codec. This goal also means that flac should stay archival quality and be truly lossless for all input. Testing of releases should be thorough. +
  • +
  • + FLAC should yield respectable compression, on par or better than other lossless codecs. +
  • +
  • + FLAC should allow at least realtime decoding on even modest hardware. +
  • +
  • + FLAC should support fast sample-accurate seeking. +
  • +
  • + FLAC should allow gapless playback of consecutive streams. This follows from the lossless goal. +
  • +
  • + The FLAC project owes a lot to the many people who have advanced the audio compression field so freely, and aims also to contribute through the open-source development of new ideas. +
  • +
+ Anti-goals
+
    +
  • + Lossy compression. There are already many suitable lossy formats (Ogg Vorbis, MP3, etc.). +
  • +
  • + Copy prevention, DRM, etc. There is no intention to add any copy prevention methods. Of course, we can't stop someone from encrypting a FLAC stream in another container (e.g. the way Apple encrypts AAC in MP4 with FairPlay), that is the choice of the user. +
  • +
+
+ +
+ + + + + + diff --git a/flac/doc/html/documentation.html b/flac/doc/html/documentation.html new file mode 100644 index 0000000..66002cd --- /dev/null +++ b/flac/doc/html/documentation.html @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ documentation +
+
+
+ FLAC is a general purpose audio format supported by many programs. Most of the documentation here is about the FLAC format itself and the tools we provide, but there is also information on using other programs that support FLAC. +
    +
  • Introduction - What is FLAC?
  • +
  • Getting FLAC - How to download what you need to play or make FLAC files.
  • +
  • Using FLAC - If you have some FLAC files and want to do something with them, or want to create FLAC files, look here.
  • +
  • FAQ - Frequently Asked Questions
  • +
+ In more detail: +
    +
  • About the FLAC Format - An overview of the FLAC format for power users.
  • +
  • Official Tools - How to use the flac and metaflac command-line tools.
  • +
  • Comparison - A comparison of FLAC with other lossless codecs.
  • +
  • Bugs - How to report bugs and request features, and a list of known bugs in the FLAC tools.
  • +
  • Request Support - Support for the official FLAC tools. For other programs, use hydrogenaudio.org +
  • FLAC Mailing List - General discussion about FLAC, tools, releases, etc. (You must subscribe to post.)
  • +
+ For developers who want to add FLAC support to their programs: + + Keep in mind that the online version of the documentation will always apply to the latest release. For older releases, check the documentation included with the release package. +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_bugs.html b/flac/doc/html/documentation_bugs.html new file mode 100644 index 0000000..5ebf3b4 --- /dev/null +++ b/flac/doc/html/documentation_bugs.html @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+ +
+
+ The following are major known bugs in the current (1.1.4) release: +
    +
  • + When encoding to Ogg FLAC, if there are too many seek points (>240), the seek table will not have the offsets written back properly after encoding. +
  • +
+
+ +
+ +
+ +
+ +
+
+ To report a bug, please go to the FLAC bug tracker (or appropriately the feature request tracker, patch page, or support page).
+
+ First check that there is not already an existing request. If you do submit a new request, make sure and provide an email contact and use the Monitor feature.
+
+ Note that we get many false bug reports from people with faulty hardware or who overclock their machines that FLAC is not working. Please do due diligence if you are getting FLAC encoding or decoding errors that it is not the fault of the hardware. FLAC encoding tends to highlight problems with bad RAM, corrupted files, and excessive overclocking. +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_example_code.html b/flac/doc/html/documentation_example_code.html new file mode 100644 index 0000000..02dbc86 --- /dev/null +++ b/flac/doc/html/documentation_example_code.html @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + FLAC - developers + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ example code +
+
+
+ The FLAC source code has several small example programs that demonstrate how to use the libraries. The source is available on the download page, or can be checked out from CVS or browsed online. The examples complement the API documentation.
+
+ Currently the examples show how to encode WAV files to FLAC and vice-versa using both libFLAC and libFLAC++. Over time we'll be adding more examples. +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_format_overview.html b/flac/doc/html/documentation_format_overview.html new file mode 100644 index 0000000..70de7e5 --- /dev/null +++ b/flac/doc/html/documentation_format_overview.html @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ format +
+
+
+ The basic structure of a FLAC stream is: +
    +
  • The four byte string "fLaC"
  • +
  • The STREAMINFO metadata block
  • +
  • Zero or more other metadata blocks
  • +
  • One or more audio frames
  • +
+ The first four bytes are to identify the FLAC stream. The metadata that follows contains all the information about the stream except for the audio data itself. After the metadata comes the encoded audio data.
+
+ METADATA
+
+ FLAC defines several types of metadata blocks (see the format page for the complete list). Metadata blocks can be any length and new ones can be defined. A decoder is allowed to skip any metadata types it does not understand. Only one is mandatory: the STREAMINFO block. This block has information like the sample rate, number of channels, etc., and data that can help the decoder manage its buffers, like the minimum and maximum data rate and minimum and maximum block size. Also included in the STREAMINFO block is the MD5 signature of the unencoded audio data. This is useful for checking an entire stream for transmission errors.
+
+ Other blocks allow for padding, seek tables, tags, cuesheets, and application-specific data. There are flac options for adding PADDING blocks or specifying seek points. FLAC does not require seek points for seeking but they can speed up seeks, or be used for cueing in editing applications.
+
+ Also, if you have a need of a custom metadata block, you can define your own and request an ID here. Then you can reserve a PADDING block of the correct size when encoding, and overwrite the padding block with your APPLICATION block after encoding. The resulting stream will be FLAC compatible; decoders that are aware of your metadata can use it and the rest will safely ignore it.
+
+ AUDIO DATA
+
+ After the metadata comes the encoded audio data. Audio data and metadata are not interleaved. Like most audio codecs, FLAC splits the unencoded audio data into blocks, and encodes each block separately. The encoded block is packed into a frame and appended to the stream. The reference encoder uses a single block size for the whole stream but the FLAC format does not require it.
+
+ BLOCKING
+
+ The block size is an important parameter to encoding. If it is too small, the frame overhead will lower the compression. If it is too large, the modeling stage of the compressor will not be able to generate an efficient model. Understanding FLAC's modeling will help you to improve compression for some kinds of input by varying the block size. In the most general case, using linear prediction on 44.1kHz audio, the optimal block size will be between 2-6 ksamples. flac defaults to a block size of 4096 in this case. Using the fast fixed predictors, a smaller block size is usually preferable because of the smaller frame header.
+
+ INTER-CHANNEL DECORRELATION
+
+ In the case of stereo input, once the data is blocked it is optionally passed through an inter-channel decorrelation stage. The left and right channels are converted to center and side channels through the following transformation: mid = (left + right) / 2, side = left - right. This is a lossless process, unlike joint stereo. For normal CD audio this can result in significant extra compression. flac has two options for this: -m always compresses both the left-right and mid-side versions of the block and takes the smallest frame, and -M, which adaptively switches between left-right and mid-side.
+
+ MODELING
+
+ In the next stage, the encoder tries to approximate the signal with a function in such a way that when the approximation is subracted, the result (called the residual, residue, or error) requires fewer bits-per-sample to encode. The function's parameters also have to be transmitted so they should not be so complex as to eat up the savings. FLAC has two methods of forming approximations: 1) fitting a simple polynomial to the signal; and 2) general linear predictive coding (LPC). I will not go into the details here, only some generalities that involve the encoding options.
+
+ First, fixed polynomial prediction (specified with -l 0) is much faster, but less accurate than LPC. The higher the maximum LPC order, the slower, but more accurate, the model will be. However, there are diminishing returns with increasing orders. Also, at some point (usually around order 9) the part of the encoder that guesses what is the best order to use will start to get it wrong and the compression will actually decrease slightly; at that point you will have to you will have to use the exhaustive search option -e to overcome this, which is significantly slower.
+
+ Second, the parameters for the fixed predictors can be transmitted in 3 bits whereas the parameters for the LPC model depend on the bits-per-sample and LPC order. This means the frame header length varies depending on the method and order you choose and can affect the optimal block size.
+
+ RESIDUAL CODING
+
+ Once the model is generated, the encoder subracts the approximation from the original signal to get the residual (error) signal. The error signal is then losslessly coded. To do this, FLAC takes advantage of the fact that the error signal generally has a Laplacian (two-sided geometric) distribution, and that there are a set of special Huffman codes called Rice codes that can be used to efficiently encode these kind of signals quickly and without needing a dictionary.
+
+ Rice coding involves finding a single parameter that matches a signal's distribution, then using that parameter to generate the codes. As the distribution changes, the optimal parameter changes, so FLAC supports a method that allows the parameter to change as needed. The residual can be broken into several contexts or partitions, each with it's own Rice parameter. flac allows you to specify how the partitioning is done with the -r option. The residual can be broken into 2^n partitions, by using the option -r n,n. The parameter n is called the partition order. Furthermore, the encoder can be made to search through m to n partition orders, taking the best one, by specifying -r m,n. Generally, the choice of n does not affect encoding speed but m,n does. The larger the difference between m and n, the more time it will take the encoder to search for the best order. The block size will also affect the optimal order.
+
+ FRAMING
+
+ An audio frame is preceded by a frame header and trailed by a frame footer. The header starts with a sync code, and contains the minimum information necessary for a decoder to play the stream, like sample rate, bits per sample, etc. It also contains the block or sample number and an 8-bit CRC of the frame header. The sync code, frame header CRC, and block/sample number allow resynchronization and seeking even in the absence of seek points. The frame footer contains a 16-bit CRC of the entire encoded frame for error detection. If the reference decoder detects a CRC error it will generate a silent block.
+
+ MISCELLANEOUS
+
+ As a convenience, the reference decoder knows how to skip ID3v1 and ID3v2 tags. Note however that the FLAC specification does not require compliant implementations to support ID3 in any form and their use is strongly discouraged.
+
+ flac has a verify option -V that verifies the output while encoding. With this option, a decoder is run in parallel to the encoder and its output is compared against the original input. If a difference is found flac will stop with an error. +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_tasks.html b/flac/doc/html/documentation_tasks.html new file mode 100644 index 0000000..343482d --- /dev/null +++ b/flac/doc/html/documentation_tasks.html @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ using flac +
+
+
+ Since FLAC is supported by so many different programs, it can be a daunting task for the new user to choose a suitable program. This page will walk you through the steps. First, choose your operating system: + +
+ +
+ +
+ +
+
+ windows +
+
+
+
+ Using iTunes? Sorry, due to iTunes' design we can't add FLAC support; ask Apple to support FLAC!
+
+ If you want to play FLAC files, here is how with some popular players: + + If you want to rip CDs to FLAC, here is a short list of the most popular programs. Experts generally prefer EAC for the most accurate ripping. dbPowerAMP also does a fine job and is easier to set up. + + If you want to burn FLAC files to CD, here is a short list of the most popular programs: +
    +
  • Windows Media Player (WMP) - Sorry, Microsoft has made it impossible to burn FLAC to CD in WMP; hopefully this will change eventually.
  • + +
  • dbPowerAMP CD Writer - Install the FLAC plugin.
  • +
  • Burrrn - Supports burning from FLAC out of the box.
  • +
  • (more)
  • +
+ If you want to convert audio files to/from FLAC, there are quite a few programs: + + If you want to edit the tags in FLAC files: +
    +
  • mp3tag - A free tag editor which supports editing tags, autotagging from online databases, cover art, and more.
  • +
+
+ +
+ +
+ +
+
+ mac os x +
+
+
+
+ Using iTunes? Sorry, due to iTunes' design we can't add FLAC support; ask Apple to support FLAC!
+
+ If you want to play FLAC files, here is how with some popular players: + + If you want to rip CDs to FLAC, there are a few options: + + If you want to burn FLAC files to CD: + + If you want to convert audio files to/from FLAC: + +
+ +
+ +
+ +
+
+ *nix +
+
+
+ In the Unix world, FLAC support is quite widespread and it's usually only a matter of installing packages, so here are a few pointers. See the software links section for many more.
+
+ To play FLAC files: + + To rip CDs to FLAC: +
    +
  • Grip is a great ripping and encoding front end and can be easily configured to use flac. See this thread on how to configure Grip for FLAC.
  • +
  • xmcd is a CD ripper with CDDB support as well as a player.
  • +
  • (more)
  • +
+ To burn FLAC files to CD, here is a short list of the most popular programs: +
    +
  • Arson: KDE ripper/burner
  • +
  • K3B: CD/DVD creator for Linux
  • +
  • (more)
  • +
+ To convert audio files to/from FLAC, there are quite a few programs: + +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_tools.html b/flac/doc/html/documentation_tools.html new file mode 100644 index 0000000..2b2eb0b --- /dev/null +++ b/flac/doc/html/documentation_tools.html @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ tools +
+
+
+ FLAC is a general purpose audio format supported by many programs, but in this section we are concentrating on just the official tools provided by the FLAC project: +
    +
  • flac - The command-line encoder and decoder.
  • +
  • metaflac - The command-line metadata editor.
  • +
  • plugins - Setting up the Winamp and XMMS plugins.
  • +
+ Other resources: +
    +
  • Bugs - How to report bugs and request features, and a list of known bugs in the FLAC tools.
  • +
  • Request Support - Support for the official FLAC tools. For other programs, use hydrogenaudio.org +
  • FLAC Mailing List - General discussion about FLAC, tools, releases, etc. (You must subscribe to post.)
  • +
+
+ See Getting FLAC for instructions on downloading and installing the official FLAC tools, or Using FLAC for instructions and guides on playing FLAC files, ripping CDs to FLAC, etc. +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_tools_flac.html b/flac/doc/html/documentation_tools_flac.html new file mode 100644 index 0000000..f7f4804 --- /dev/null +++ b/flac/doc/html/documentation_tools_flac.html @@ -0,0 +1,1182 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ flac +
+
+
+ Table of Contents + + General Usage
+
+ flac is the command-line file encoder/decoder. The encoder currently supports as input RIFF WAVE, Wave64, RF64, AIFF, FLAC or Ogg FLAC format, or raw interleaved samples. The decoder currently can output to RIFF WAVE, Wave64, RF64, or AIFF format, or raw interleaved samples. flac only supports linear PCM samples (in other words, no A-LAW, uLAW, etc.), and the input must be between 4 and 24 bits per sample. This is not a limitation of the FLAC format, just the reference encoder/decoder.
+
+ flac assumes that files ending in ".wav" or that have the RIFF WAVE header present are WAVE files, files ending in ".w64" or have the Wave64 header present are Wave64 files, files ending in ".rf64" or have the RF64 header present are RF64 files, files ending in ".aif" or ".aiff" or have the AIFF header present are AIFF files, and files ending in ".flac" or have the FLAC header present are FLAC files. This assumption may be overridden with a command-line option. It also assumes that files ending in ".oga" or ".ogg" or have the Ogg FLAC header present are Ogg FLAC files. Other than this, flac makes no assumptions about file extensions, though the convention is that FLAC files have the extension ".flac" (or ".fla" on ancient "8.3" file systems like FAT-16).
+
+ Before going into the full command-line description, a few other things help to sort it out: 1) flac encodes by default, so you must use -d to decode; 2) the options -0 .. -8 (or --fast and --best) that control the compression level actually are just synonyms for different groups of specific encoding options (described later) and you can get the same effect by using the same options; 3) flac behaves similarly to gzip in the way it handles input and output files.
+
+ Skip to the tutorial below for examples of some common tasks.
+
+ flac will be invoked one of four ways, depending on whether you are encoding, decoding, testing, or analyzing: + + In any case, if no inputfile is specified, stdin is assumed. If only one inputfile is specified, it may be "-" for stdin. When stdin is used as input, flac will write to stdout. Otherwise flac will perform the desired operation on each input file to similarly named output files (meaning for encoding, the extension will be replaced with ".flac", or appended with ".flac" if the input file has no extension, and for decoding, the extension will be ".wav" for WAVE output and ".raw" for raw output). The original file is not deleted unless --delete-input-file is specified.
+
+ If you are encoding/decoding from stdin to a file, you should use the -o option like so: +
    +
  • + flac [options] -o outputfile +
  • +
  • + flac -d [options] -o outputfile +
  • +
+ which are better than: +
    +
  • + flac [options] > outputfile +
  • +
  • + flac -d [options] > outputfile +
  • +
+ since the former allows flac to seek backwards to write the STREAMINFO or RIFF WAVE header contents when necessary.
+
+ Also, you can force output data to go to stdout using -c.
+
+ To encode or decode files that start with a dash, use -- to signal the end of options, to keep the filenames themselves from being treated as options: +
    +
  • + flac -V -- -01-filename.wav +
  • +
+ The encoding options affect the compression ratio and encoding speed. The format options are used to tell flac the arrangement of samples if the input file (or output file when decoding) is a raw file. If it is a RIFF WAVE, Wave64, RF64, or AIFF file the format options are not needed since they are read from the file's header.
+
+ In test mode, flac acts just like in decode mode, except no output file is written. Both decode and test modes detect errors in the stream, but they also detect when the MD5 signature of the decoded audio does not match the stored MD5 signature, even when the bitstream is valid.
+
+ flac can also re-encode FLAC files. In other words, you can specify a FLAC or Ogg FLAC file as an input to the encoder and it will decoder it and re-encode it according to the options you specify. It will also preserve all the metadata unless you override it with other options (e.g. specifying new tags, seekpoints, cuesheet, padding, etc.).
+
+ flac has been tuned so that the default settings yield a good speed vs. compression tradeoff for many kinds of input. However, if you are looking to maximize the compression rate or speed, or want to use the full power of FLAC's metadata system, see About the FLAC Format.
+
+ + Tutorial
+
+ Some common encoding tasks using flac:
+
+ flac abc.wav
+ Encode abc.wav to abc.flac using the default compression setting. abc.wav is not deleted.
+
+ flac --delete-input-file abc.wav
+ Like above, except abc.wav is deleted if there were no errors.
+
+ flac --delete-input-file -w abc.wav
+ Like above, except abc.wav is deleted if there were no errors or warnings.
+
+ flac --best abc.wav
+ Encode abc.wav to abc.flac using the highest compression setting.
+
+ flac --verify abc.wav
+ Encode abc.wav to abc.flac and internally decode abc.flac to make sure it matches abc.wav.
+
+ flac -o my.flac abc.wav
+ Encode abc.wav to my.flac.
+
+ flac -T "TITLE=Bohemian Rhapsody" -T "ARTIST=Queen" abc.wav
+ Encode abc.wav and add some tags at the same time to abc.flac.
+
+ flac *.wav
+ Encode all .wav files in the current directory. NOTE: Wildcards on Windows
+
+ flac abc.aiff
+ Encode abc.aiff to abc.flac.
+
+ flac abc.rf64
+ Encode abc.rf64 to abc.flac.
+
+ flac abc.w64
+ Encode abc.w64 to abc.flac.
+
+ flac abc.flac --force
+ This one's a little tricky: notice that flac is in encode mode by default (you have to specify -d to decode) so this command actually recompresses abc.flac back to abc.flac. --force is needed to make sure you really want to overwrite abc.flac with a new version. Why would you want to do this? It allows you to recompress an existing FLAC file with (usually) higher compression options or a newer version of FLAC and preserve all the metadata like tags too.
+
+ + Some common decoding tasks using flac:
+
+ flac -d abc.flac
+ Decode abc.flac to abc.wav. abc.flac is not deleted. NOTE: Without -d it means re-encode abc.flac to abc.flac (see above).
+
+ flac -d --force-aiff-format abc.flac
+ flac -d -o abc.aiff abc.flac
+ Two different ways of decoding abc.flac to abc.aiff (AIFF format). abc.flac is not deleted.
+
+ flac -d --force-rf64-format abc.flac
+ flac -d -o abc.rf64 abc.flac
+ Two different ways of decoding abc.flac to abc.rf64 (RF64 format). abc.flac is not deleted.
+
+ flac -d --force-wave64-format abc.flac
+ flac -d -o abc.w64 abc.flac
+ Two different ways of decoding abc.flac to abc.w64 (Wave64 format). abc.flac is not deleted.
+
+ flac -d -F abc.flac
+ Decode abc.flac to abc.wav and don't abort if errors are found (useful for recovering as much as possible from corrupted files).
+
+ flac has many other useful options, described below.
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ General Options +
+ + -v, --version + + Show the flac version number. +
+ + -h, --help + + Show basic usage and a list of all options. Running flac without arguments shows the short help screen by default. +
+ + -H, --explain + + Show detailed explanation of usage and all options. Running flac without arguments shows the short help screen by default. +
+ + -d, --decode + + Decode (flac encodes by default). flac will exit with an exit code of 1 (and print a message, even in silent mode) if there were any errors during decoding, including when the MD5 checksum does not match the decoded output. Otherwise the exit code will be 0. +
+ + -t, --test + + Test (same as -d except no decoded file is written). The exit codes are the same as in decode mode. +
+ + -a, --analyze + + Analyze (same as -d except an analysis file is written). The exit codes are the same as in decode mode. This option is mainly for developers; the output will be a text file that has data about each frame and subframe. +
+ + -c, --stdout + + Write output to stdout. +
+ + -s, --silent + + Silent: do not show encoding/decoding statistics. +
+ + --totally-silent + + Do not print anything of any kind, including warnings or errors. The exit code will be the only way to determine successful completion. +
+ + --no-utf8-convert + + Do not convert tags from local charset to UTF-8. This is useful for scripts, and setting tags in situations where the locale is wrong. This option must appear before any tag options! +
+ + -w, --warnings-as-errors + + Treat all warnings as errors (which cause flac to terminate with a non-zero exit code). +
+ + -f, --force + + Force overwriting of output files. By default, flac warns that the output file already exists and continues to the next file. +
+ + -o filename,
--output-name=filename +
+ Force the output file name (usually flac just changes the extension). May only be used when encoding a single file. May not be used in conjunction with --output-prefix. +
+ + --output-prefix=string + + Prefix each output file name with the given string. This can be useful for encoding/decoding files to a different directory. Make sure if your string is a path name that it ends with a trailing '/' slash. +
+ + --delete-input-file + + Automatically delete the input file after a successful encode or decode. If there was an error (including a verify error) the input file is left intact. +
+ + --preserve-modtime + + Output files have their timestamps/permissions set to match those of their inputs (this is default). Use --no-preserve-modtime to make output files have the current time and default permissions. +
+ + --keep-foreign-metadata + + If encoding, save WAVE, Wave64, RF64, or AIFF non-audio chunks in FLAC metadata. If decoding, restore any saved non-audio chunks from FLAC metadata when writing the decoded file. Foreign metadata cannot be transcoded, e.g. WAVE chunks saved in a FLAC file cannot be restored when decoding to AIFF. Input and output must be regular files (not stdin or stdout).
+ +
+ + --skip={#|mm:ss.ss} + + Skip over the first # of samples of the input. This works for both encoding and decoding, but not testing. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second.
+
+ Examples:
+
+ --skip=123 : skip the first 123 samples of the input
+ --skip=1:23.45 : skip the first 1 minute and 23.45 seconds of the input +
+ + --until={#|[+|-]mm:ss.ss} + + Stop at the given sample number for each input file. This works for both encoding and decoding, but not testing. The given sample number is not included in the decoded output. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second. If a + sign is at the beginning, the --until point is relative to the --skip point. If a - sign is at the beginning, the --until point is relative to end of the audio.
+
+ Examples:
+
+ --until=123 : decode only the first 123 samples of the input (samples 0-122, stopping at 123)
+ --until=1:23.45 : decode only the first 1 minute and 23.45 seconds of the input
+ --skip=1:00 --until=+1:23.45 : decode 1:00.00 to 2:23.45
+ --until=-1:23.45 : decode everything except the last 1 minute and 23.45 seconds
+ --until=-0:00 : decode until the end of the input (the same as not specifying --until) +
+ + --ogg + + When encoding, generate Ogg FLAC output instead of native FLAC. Ogg FLAC streams are FLAC streams wrapped in an Ogg transport layer. The resulting file should have an '.oga' extension and will still be decodable by flac.
+
+ When decoding, force the input to be treated as Ogg FLAC. This is useful when piping input from stdin or when the filename does not end in '.oga' or '.ogg'.
+
+ NOTE: Ogg FLAC files created prior to flac 1.1.1 used an ad-hoc mapping and do not support seeking. They should be decoded and re-encoded with flac 1.1.1 or later. +
+ + --serial-number=# + + When used with --ogg, specifies the serial number to use for the first Ogg FLAC stream, which is then incremented for each additional stream. When encoding and no serial number is given, flac uses a random number for the first stream, then increments it for each additional stream. When decoding and no number is given, flac uses the serial number of the first page. +
+
+ +
+ +
+ + + + + + + + + + + + +
+ Analysis Options +
+ + --residual-text + + Includes the residual signal in the analysis file. This will make the file very big, much larger than even the decoded file. +
+ + --residual-gnuplot + + Generates a gnuplot file for every subframe; each file will contain the residual distribution of the subframe. This will create a lot of files. +
+
+ +
+ +
+ + + + + + + + + + + + + +
+ Decoding Options +
+ + --cue=[#.#][-[#.#]] + + Set the beginning and ending cuepoints to decode. The optional first #.# is the track and index point at which decoding will start; the default is the beginning of the stream. The optional second #.# is the track and index point at which decoding will end; the default is the end of the stream. If the cuepoint does not exist, the closest one before it (for the start point) or after it (for the end point) will be used. If those don't exist, the start of the stream (for the start point) or end of the stream (for the end point) will be used. The cuepoints are merely translated into sample numbers then used as --skip and --until.
+
+ Examples:
+
+ --cue=- : decode the entire stream
+ --cue=4.1 : decode from track 4, index 1 to the end of the stream
+ --cue=4.1- : decode from track 4, index 1 to the end of the stream
+ --cue=-4.1 : decode from the beginning of the stream up to, but not including, track 4, index 1
+ --cue=2.1-2.4 : decode from track 2, index 1, up to, but not including, track 2, index 4
+ --cue=9.1-10.1 : decode from track 9 the way it would be played on a CD player; this works even if the CD has no 10th track. +
+ + -F,
--decode-through-errors +
+ By default flac stops decoding with an error and removes the partially decoded file if it encounters a bitstream error. With -F, errors are still printed but flac will continue decoding to completion. Note that errors may cause the decoded audio to be missing some samples or have silent sections. +
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Encoding Options +
+ + -V, --verify + + Verify the encoding process. With this option, flac will create a parallel decoder that decodes the output of the encoder and compares the result against the original. It will abort immediately with an error if a mismatch occurs. -V increases the total encoding time but is guaranteed to catch any unforseen bug in the encoding process. +
+ + --lax + + Allow encoder to generate non-Subset files. The resulting FLAC file may not be streamable or might have trouble being played in all players (especially hardware devices), so you should only use this option in combination with custom encoding options meant for archival. +
+ + --replay-gain + + Calculate ReplayGain values and store them as FLAC tags, similar to VorbisGain. Title gains/peaks will be computed for each input file, and an album gain/peak will be computed for all files. All input files must have the same resolution, sample rate, and number of channels. Only mono and stereo files are allowed, and the sample rate must be one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1, or 48 kHz. Also note that this option may leave a few extra bytes in a PADDING block as the exact size of the tags is not known until all files are processed.
+
+ Note that this option cannot be used when encoding to standard output (stdout). +
+ + --cuesheet=FILENAME + + Import the given cuesheet file and store it in a CUESHEET metadata block. This option may only be used when encoding a single file. A seekpoint will be added for each index point in the cuesheet to the SEEKTABLE unless --no-cued-seekpoints is specified.
+
+ The cuesheet file must be of the sort written by CDRwin, CDRcue, EAC, etc. See also cuesheet syntax. +
+ + --picture={FILENAME|SPECIFICATION} + + Import a picture and store it in a PICTURE metadata block. More than one --picture command can be specified. Either a filename for the picture file or a more complete specification form can be used. The SPECIFICATION is a string whose parts are separated by | (pipe) characters. Some parts may be left empty to invoke default values. FILENAME is just shorthand for ||||FILENAME. The format of SPECIFICATION is
+
+   [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE
+
+ TYPE is optional; it is a number from one of:
+
    +
  • 0: Other
  • +
  • 1: 32x32 pixels 'file icon' (PNG only)
  • +
  • 2: Other file icon
  • +
  • 3: Cover (front)
  • +
  • 4: Cover (back)
  • +
  • 5: Leaflet page
  • +
  • 6: Media (e.g. label side of CD)
  • +
  • 7: Lead artist/lead performer/soloist
  • +
  • 8: Artist/performer
  • +
  • 9: Conductor
  • +
  • 10: Band/Orchestra
  • +
  • 11: Composer
  • +
  • 12: Lyricist/text writer
  • +
  • 13: Recording Location
  • +
  • 14: During recording
  • +
  • 15: During performance
  • +
  • 16: Movie/video screen capture
  • +
  • 17: A bright coloured fish
  • +
  • 18: Illustration
  • +
  • 19: Band/artist logotype
  • +
  • 20: Publisher/Studio logotype
  • +
+ The default is 3 (front cover). There may only be one picture each of type 1 and 2 in a file.
+
+ MIME-TYPE is optional; if left blank, it will be detected from the file. For best compatibility with players, use pictures with MIME type image/jpeg or image/png. The MIME type can also be --> to mean that FILE is actually a URL to an image, though this use is discouraged.
+
+ DESCRIPTION is optional; the default is an empty string.
+
+ The next part specfies the resolution and color information. If the MIME-TYPE is image/jpeg, image/png, or image/gif, you can usually leave this empty and they can be detected from the file. Otherwise, you must specify the width in pixels, height in pixels, and color depth in bits-per-pixel. If the image has indexed colors you should also specify the number of colors used. When manually specified, it is not checked against the file for accuracy.
+
+ FILE is the path to the picture file to be imported, or the URL if MIME type is -->
+
+ For example, the specification |image/jpeg|||../cover.jpg will embed the JPEG file at ../cover.jpg, defaulting to type 3 (front cover) and an empty description. The resolution and color info will be retrieved from the file itself.
+
+ The specification 4|-->|CD|320x300x24/173|http://blah.blah/backcover.tiff will embed the given URL, with type 4 (back cover), description "CD", and a manually specified resolution of 320x300, 24 bits-per-pixel, and 173 colors. The file at the URL will not be fetched; the URL itself is stored in the PICTURE metadata block. +
+ + --sector-align + + Align encoding of multiple CD format files on sector boundaries. This option is only allowed when encoding files all of which have a 44.1kHz sample rate and 2 channels. With --sector-align, the encoder will align the resulting .flac streams so that their lengths are even multiples of a CD sector (1/75th of a second, or 588 samples). It does this by carrying over any partial sector at the end of each file to the next stream. The last stream will be padded to alignment with zeroes.
+
+ This option will have no effect if the files are already aligned (as is the normally the case with WAVE files ripped from a CD). flac can only align a set of files given in one invocation of flac.
+
+ WARNING: The ordering of files is important! If you give a command like 'flac --sector-align *.wav' the shell may not expand the wildcard to the order you expect. To be safe you should 'echo *.wav' first to confirm the order, or be explicit like 'flac --sector-align 8.wav 9.wav 10.wav'.
+
+ NOTE:This option is DEPRECATED and may not exist in future version of flac. shntool provides similar functionality. +
+ + -S {#|X|#x|#s},
--seekpoint={#|X|#x|#s} +
+ Include a point or points in a SEEKTABLE:
+
    +
  • + : a specific sample number for a seek point +
  • +
  • + : a placeholder point (always goes at the end of the SEEKTABLE) +
  • +
  • + #x : # evenly spaced seekpoints, the first being at sample 0 +
  • +
  • + #s : a seekpoint every # seconds; # does not have to be a whole number, it can be, for example, 9.5, meaning a seekpoint every 9.5 seconds +
  • +
+ You may use many -S options; the resulting SEEKTABLE will be the unique-ified union of all such values.
+ With no -S options, flac defaults to '-S 10s'. Use --no-seektable for no SEEKTABLE.
+ NOTE: -S #x and -S #s will not work if the encoder can't determine the input size before starting.
+ NOTE: if you use -S # and # is >= samples in the input, there will be either no seek point entered (if the input size is determinable before encoding starts) or a placeholder point (if input size is not determinable).
+
+ + -P #, --padding=# + + Tell the encoder to write a PADDING metadata block of the given length (in bytes) after the STREAMINFO block. This is useful if you plan to tag the file later with an APPLICATION block; instead of having to rewrite the entire file later just to insert your block, you can write directly over the PADDING block. Note that the total length of the PADDING block will be 4 bytes longer than the length given because of the 4 metadata block header bytes. You can force no PADDING block at all to be written with --no-padding. The encoder writes a PADDING block of 8192 bytes by default (or 65536 bytes if the input audio stream is more than 20 minutes long). +
+ + -T FIELD=VALUE,
--tag=FIELD=VALUE +
+ Add a FLAC tag. The comment must adhere to the Vorbis comment spec (which FLAC tags implement), i.e. the FIELD must contain only legal characters, terminated by an 'equals' sign. Make sure to quote the comment if necessary. This option may appear more than once to add several comments. NOTE: all tags will be added to all encoded files. +
+ + --tag-from-file=FIELD=FILENAME + + Like --tag, except FILENAME is a file whose contents will be read verbatim to set the tag value. The contents will be converted to UTF-8 from the local charset. This can be used to store a cuesheet in a tag (e.g. --tag-from-file="CUESHEET=image.cue"). Do not try to store binary data in tag fields! Use APPLICATION blocks for that. +
+ + -b #, --blocksize=# + + Specify the block size in samples. Subset streams must use one of 192/576/1152/2304/4608/256/512/1024/2048/4096 (and 8192/16384 if the sample rate is >48kHz). The reference encoder uses the same block size for the entire stream. +
+ + -m, --mid-side + + Enable mid-side coding (only for stereo streams). Tends to increase compression by a few percent on average. For each block both the stereo pair and mid-side versions of the block will be encoded, and smallest resulting frame will be stored. +
+ + -M, --adaptive-mid-side + + Enable adaptive mid-side coding (only for stereo streams). Like -m but the encoder adaptively switches between independent and mid-side coding, which is faster but yields less compression than -m (which does an exhaustive search). +
+ + -0 .. -8 + + Fastest compression .. highest compression. The default is -5. +
+ + -0, --compression-level-0 + + Synonymous with -l 0 -b 1152 -r 3 +
+ + -1, --compression-level-1 + + Synonymous with -l 0 -b 1152 -M -r 3 +
+ + -2, --compression-level-2 + + Synonymous with -l 0 -b 1152 -m -r 3 +
+ + -3, --compression-level-3 + + Synonymous with -l 6 -b 4096 -r 4 +
+ + -4, --compression-level-4 + + Synonymous with -l 8 -b 4096 -M -r 4 +
+ + -5, --compression-level-5 + + Synonymous with -l 8 -b 4096 -m -r 5 +
+ + -6, --compression-level-6 + + Synonymous with -l 8 -b 4096 -m -r 6 +
+ + -7, --compression-level-7 + + Synonymous with -l 8 -b 4096 -m -e -r 6 +
+ + -8, --compression-level-8 + + Synonymous with -l 12 -b 4096 -m -e -r 6 +
+ + --fast + + Fastest compression. Currently synonymous with -0 +
+ + --best + + Highest compression. Currently synonymous with -8 +
+ + -e,
--exhaustive-model-search +
+ Exhaustive model search (expensive!). Normally the encoder estimates the best model to use and encodes once based on the estimate. With an exhaustive model search, the encoder will generate subframes for every order and use the smallest. If the max LPC order is high this can significantly increase the encode time but can shave off another 0.5%. +
+ + -A "function", --apodization="function" + + Window audio data with given the apodization function. The functions are: bartlett, bartlett_hann, blackman, blackman_harris_4term_92db, connes, flattop, gauss(STDDEV), hamming, hann, kaiser_bessel, nuttall, rectangle, triangle, tukey(P), welch.
+ For gauss(STDDEV), STDDEV is the standard deviation (0<STDDEV<=0.5).
+ For tukey(P), P specifies the fraction of the window that is tapered (0<=P<=1; P=0 corresponds to "rectangle" and P=1 corresponds to "hann").
+ More than one -A option (up to 32) may be used. Any function that is specified erroneously is silently dropped. The encoder chooses suitable defaults in the absence of any -A options; any -A option specified replaces the default(s).
+ When more than one function is specified, then for every subframe the encoder will try each of them separately and choose the window that results in the smallest compressed subframe. Multiple functions can greatly increase the encoding time.
+
+ + -l #, --max-lpc-order=# + + Specifies the maximum LPC order. This number must be <= 32. For Subset streams, it must be <=12 if the sample rate is <=48kHz. If 0, the encoder will not attempt generic linear prediction, and use only fixed predictors. Using fixed predictors is faster but usually results in files being 5-10% larger. +
+ + -q #,
--qlp-coeff-precision=# +
+ Specifies the precision of the quantized LP coefficients, in bits. The default is -q 0, which means let the encoder decide based on the signal. Unless you really know your input file it's best to leave this up to the encoder. +
+ + -p,
--qlp-coeff-precision-search +
+ Do exhaustive LP coefficient quantization optimization. This option overrides any -q option. It is expensive and typically will only improve the compression a tiny fraction of a percent. -q has no effect when -l 0 is used. +
+ + -r [#,]#,
--rice-partition-order=[#,]# +
+ Set the [min,]max residual partition order. The min value defaults to 0 if unspecified.
+
+ By default the encoder uses a single Rice parameter for the subframe's entire residual. With this option, the residual is iteratively partitioned into 2^min# .. 2^max# pieces, each with its own Rice parameter. Higher values of max# yield diminishing returns. The most bang for the buck is usually with -r 2,2 (more for higher block sizes). This usually shaves off about 1.5%. The technique tends to peak out about when blocksize/(2^n)=128. Use -r 0,16 to force the highest degree of optimization. +
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Format Options +
+ + --endian={big|little} + + Specify big-endian or little-endian byte order in the raw file. +
+ + --channels=# + + Specify the number of channels in the raw file. +
+ + --bps=# + + Specify the number of bits per sample in the raw file. +
+ + --sample-rate=# + + Specify the sample rate of the raw file. +
+ + --sign={signed|unsigned} + + Specify that the samples in the raw file are signed or unsigned (the default is signed). +
+ + --input-size=# + + Specify the size of the raw input in bytes. If you are encoding raw samples from stdin, you must set this option in order to be able to use --skip, --until, --cue-sheet, or other options that need to know the size of the input beforehand. If the size given is greater than what is found in the input stream, the encoder will complain about an unexpected end-of-file. If the size given is less, samples will be truncated. +
+ + --force-raw-format + + Treat the input file (or output file if decoding) as a raw file, regardless of the extension. +
+ + --force-aiff-format + + Force the decoder to output AIFF format. This option is not needed if the output filename (as set by -o) ends with .aif or .aiff. Also, this option has no effect when encoding since input AIFF is auto-detected. +
+ + --force-rf64-format + + Force the decoder to output RF64 format. This option is not needed if the output filename (as set by -o) ends with .rf64. Also, this option has no effect when encoding since input RF64 is auto-detected. +
+ + --force-wave64-format + + Force the decoder to output Wave64 format. This option is not needed if the output filename (as set by -o) ends with .w64. Also, this option has no effect when encoding since input Wave64 is auto-detected. +
+
+ +
+ +
+ + + + + + + + +
+ Negative Options +
+ --no-adaptive-mid-side
+ --no-decode-through-errors
+ --no-delete-input-file
+ --no-escape-coding
+ --no-exhaustive-model-search
+ --no-lax
+ --no-mid-side
+ --no-ogg
+ --no-padding
+ --no-qlp-coeff-precision-search
+ --no-residual-gnuplot
+ --no-residual-text
+ --no-sector-align
+ --no-seektable
+ --no-silent
+ --no-verify + --no-warnings-as-errors +
+ Can all be used to turn off a particular option. +
+
+ +
+ Option Index
+
+ -0
+ -1
+ -2
+ -3
+ -4
+ -5
+ -6
+ -7
+ -8
+ -A
+ -a
+ --adaptive-mid-side
+ --analyze
+ --apodization
+ + -b
+ --best
+ --blocksize
+ --bps
+ -c
+ --channels
+ --compression-level-0
+ --compression-level-1
+ --compression-level-2
+ --compression-level-3
+ --compression-level-4
+ --compression-level-5
+ --compression-level-6
+ --compression-level-7
+ --compression-level-8
+ --cue
+ --cuesheet
+ -d
+ --decode
+ --decode-through-errors
+ --delete-input-file
+ -e
+ --endian
+ --exhaustive-model-search
+ --explain
+ -F
+ -f
+ --fast
+ --force-raw-format
+ --force-aiff-format
+ --force-rf64-format
+ --force-wave64-format
+ --force
+ -H
+ -h
+ --help
+ --input-size
+ --keep-foreign-metadata
+ -l
+ --lax
+ -M
+ -m
+ --max-lpc-order
+ --mid-side
+ --no-adaptive-mid-side
+ --no-decode-through-errors
+ --no-delete-input-file
+ --no-escape-coding
+ --no-exhaustive-model-search
+ --no-keep-foreign-metadata
+ --no-lax
+ --no-mid-side
+ --no-ogg
+ --no-padding
+ --no-preserve-modtime
+ --no-qlp-coeff-precision-search
+ --no-residual-gnuplot
+ --no-residual-text
+ --no-sector-align
+ --no-seektable
+ --no-silent
+ --no-verify
+ --no-warnings-as-errors
+ --no-utf8-convert
+ -o
+ --ogg
+ --output-name
+ --output-prefix
+ -P
+ -p
+ --padding
+ --picture
+ -q
+ --qlp-coeff-precision
+ --qlp-coeff-precision-search
+ -r
+ --replay-gain
+ --residual-gnuplot
+ --residual-text
+ --rice-partition-order
+ -S
+ -s
+ --sample-rate
+ --sector-align
+ --seekpoint
+ --serial-number
+ --sign
+ --silent
+ --skip
+ --stdout
+ -T
+ -t
+ --tag
+ --tag-from-file
+ --test
+ --totally-silent
+ --until
+ -V
+ -v
+ --verify
+ -w
+ --warnings-as-errors
+ --version
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_tools_metaflac.html b/flac/doc/html/documentation_tools_metaflac.html new file mode 100644 index 0000000..59c2f8b --- /dev/null +++ b/flac/doc/html/documentation_tools_metaflac.html @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ metaflac +
+
+
+ Table of Contents + + General Usage
+
+ metaflac is the command-line .flac file metadata editor. You can use it to list the contents of metadata blocks, edit, delete or insert blocks, and manage padding.
+
+ metaflac takes a set of "options" (though some are not optional) and a set of FLAC files to operate on. There are three kinds of "options": +
    +
  • + Major operations, which specify a mode of operation like listing blocks, removing blocks, etc. These will have sub-operations describing exactly what is to be done. +
  • +
  • + Shorthand operations, which are convenient synonyms for major operations. For example, there is a shorthand operation --show-sample-rate that shows just the sample rate field from the STREAMINFO metadata block. +
  • +
  • + Global options, which affect all the operations. +
  • +
+ All of these are described in the tables below. At least one shorthand or major operation must be supplied. You can use multiple shorthand operations to do more than one thing to a file or set of files. Most of the common things to do to metadata have shorthand operations. As an example, here is how to show the MD5 signatures for a set of three FLAC files:
+
+ metaflac --show-md5sum file1.flac file2.flac file3.flac
+
+ Another example; this removes all DESCRIPTION and COMMENT tags in a set of FLAC files, and uses the --preserve-modtime global option to keep the FLAC file modification times the same (usually when files are edited the modification time is set to the current time):
+
+ metaflac --preserve-modtime --remove-tag=DESCRIPTION --remove-tag=COMMENT file1.flac file2.flac file3.flac
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ Global Options +
+ + --preserve-modtime + + Preserve the original modification time in spite of edits. +
+ + --with-filename + + Prefix each output line with the FLAC file name (the default if more than one FLAC file is specified). +
+ + --no-filename + + Do not prefix each output line with the FLAC file name (the default if only one FLAC file is specified) +
+ + --no-utf8-convert + + Do not convert tags from UTF-8 to local charset, or vice versa. This is useful for scripts, and setting tags in situations where the locale is wrong. +
+ + --dont-use-padding + + By default metaflac tries to use padding where possible to avoid rewriting the entire file if the metadata size changes. Use this option to tell metaflac to not take advantage of padding this way. +
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Shorthand Operations +
+ + --show-md5sum + + Show the MD5 signature from the STREAMINFO block. +
+ + --show-min-blocksize + + Show the minimum block size from the STREAMINFO block. +
+ + --show-max-blocksize + + Show the maximum block size from the STREAMINFO block. +
+ + --show-min-framesize + + Show the minimum frame size from the STREAMINFO block. +
+ + --show-max-framesize + + Show the maximum frame size from the STREAMINFO block. +
+ + --show-sample-rate + + Show the sample rate from the STREAMINFO block. +
+ + --show-channels + + Show the number of channels from the STREAMINFO block. +
+ + --show-bps + + Show the # of bits per sample from the STREAMINFO block. +
+ + --show-total-samples + + Show the total # of samples from the STREAMINFO block. +
+ + --show-vendor-tag + + Show the vendor string from the VORBIS_COMMENT block. +
+ + --show-tag=NAME + + Show all tags where the the field name matches NAME. +
+ + --remove-tag=NAME + + Remove all tags whose field name is NAME. +
+ + --remove-first-tag=NAME + + Remove first tag whose field name is NAME. +
+ + --remove-all-tags + + Remove all tags, leaving only the vendor string. +
+ + --set-tag=FIELD + + Add a tag. The FIELD must comply with the Vorbis comment spec, of the form NAME=VALUE. If there is currently no tag block, one will be created. +
+ + --set-tag-from-file=FIELD + + Like --set-tag, except the VALUE is a filename whose contents will be read verbatim to set the tag value. Unless --no-utf8-convert is specified, the contents will be converted to UTF-8 from the local charset. This can be used to store a cuesheet in a tag (e.g. --set-tag-from-file="CUESHEET=image.cue"). Do not try to store binary data in tag fields! Use APPLICATION blocks for that. +
+ + --import-tags-from=FILE + + Import tags from a file. Use - for stdin. Each line should be of the form NAME=VALUE. Multi-line comments are currently not supported. Specify --remove-all-tags and/or --no-utf8-convert before --import-tags-from if necessary. If FILE is - (stdin), only one FLAC file may be specified. +
+ + --export-tags-to=FILE + + Export tags to a file. Use - for stdin. Each line will be of the form NAME=VALUE. Specify --no-utf8-convert if necessary. +
+ + --import-cuesheet-from=FILE + + Import a cuesheet from a file. Use - for stdin. Only one FLAC file may be specified. A seekpoint will be added for each index point in the cuesheet to the SEEKTABLE unless --no-cued-seekpoints is specified. +
+ + --export-cuesheet-to=FILE + + Export CUESHEET block to a cuesheet file, suitable for use by CD authoring software. Use - for stdout. Only one FLAC file may be specified on the command line. +
+ + --import-picture-from={FILENAME|SPECIFICATION} + + Import a picture and store it in a PICTURE metadata block. See the flac option --picture for an explanation of the SPECIFICATION syntax. +
+ + --export-picture-to=FILE + + Export PICTURE block to a file. Use - for stdout. Only one FLAC file may be specified on the command line. The first PICTURE block will be exported unless --export-picture-to is preceded by a --block-number=# option to specify the exact metadata block to extract. Note that the block number is the one shown by --list. +
+ + --add-replay-gain + + Calculates the title and album gains/peaks of the given FLAC files as if all the files were part of one album, then stores them as FLAC tags. The tags are the same as those used by vorbisgain. Existing ReplayGain tags will be replaced. If only one FLAC file is given, the album and title gains will be the same. Since this operation requires two passes, it is always executed last, after all other operations have been completed and written to disk. All FLAC files specified must have the same resolution, sample rate, and number of channels. The sample rate must be one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1, or 48 kHz. +
+ + --remove-replay-gain + + Removes the ReplayGain tags. +
+ + --add-seekpoint={#|X|#x|#s} + + Add seek points to a SEEKTABLE block:
+
    +
  • + : a specific sample number for a seek point +
  • +
  • + : a placeholder point (always goes at the end of the SEEKTABLE) +
  • +
  • + #x : # evenly spaced seekpoints, the first being at sample 0 +
  • +
  • + #s : a seekpoint every # seconds; # does not have to be a whole number, it can be, for example, 9.5, meaning a seekpoint every 9.5 seconds +
  • +
+ If no SEEKTABLE block exists, one will be created. If one already exists, points will be added to the existing table, and any duplicates will be turned into placeholder points.
+ You may use many --add-seekpoint options; the resulting SEEKTABLE will be the unique-ified union of all such values. Example: --add-seekpoint=100x --add-seekpoint=3.5s will add 100 evenly spaced seekpoints and a seekpoint every 3.5 seconds.
+
+ + --add-padding=# + + Add a padding block of the given length (in bytes). The overall length of the new block will be 4 + length; the extra 4 bytes is for the metadata block header. +
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Major Operations +
+ + --version + + Show the metaflac version number. +
+ + --list + + List the contents of one or more metadata blocks to stdout. By default, all metadata blocks are listed in text format. Use the following options to change this behavior:
+
+ + --block-number=#[,#[...]]
+ An optional comma-separated list of block numbers to display. The first block, the STREAMINFO block, is block 0.
+
+ + --block-type=type[,type[...]]
+ --except-block-type=type[,type[...]]
+ An optional comma-separated list of block types to be included or ignored with this option. Use only one of --block-type or --except-block-type. The valid block types are: STREAMINFO, PADDING, APPLICATION, SEEKTABLE, VORBIS_COMMENT. You may narrow down the types of APPLICATION blocks displayed as follows:
+ + + + + + + + + +
APPLICATION:abcdThe APPLICATION block(s) whose textual representation of the 4-byte ID is "abcd"
APPLICATION:0xXXXXXXXXThe APPLICATION block(s) whose hexadecimal big- endian representation of the 4-byte ID is "0xXXXXXXXX". For the example "abcd" above the hexadecimal equivalalent is 0x61626364
+
+ + NOTE: if both --block-number and --[except-]block-type are specified, the result is the logical AND of both arguments.
+
+ + --application-data-format=hexdump|text
+ If the application block you are displaying contains binary data but your --data-format=text, you can display a hex dump of the application data contents instead using --application-data-format=hexdump. +
+ + --remove + + Remove one or more metadata blocks from the metadata. Unless --dont-use-padding is specified, the blocks will be replaced with padding. You may not remove the STREAMINFO block.
+
+ + --block-number=#[,#[...]]
+ --block-type=type[,type[...]]
+ --except-block-type=type[,type[...]]
+ See --list above for usage.
+
+ + NOTE: if both --block-number and --[except-]block-type are specified, the result is the logical AND of both arguments. +
+ + --remove-all + + Remove all metadata blocks (except the STREAMINFO block) from the metadata. Unless --dont-use-padding is specified, the blocks will be replaced with padding. +
+ + --merge-padding + + Merge adjacent PADDING blocks into single blocks. +
+ + --sort-padding + + Move all PADDING blocks to the end of the metadata and merge them into a single block. +
+
+ +
+ Option Index
+
+ --add-padding
+ --add-replay-gain
+ --add-seekpoint
+ --dont-use-padding
+ --export-cuesheet-to
+ --export-picture-to
+ --export-tags-to
+ --import-cuesheet-from
+ --import-picture-from
+ --import-tags-from
+ --list
+ --merge-padding
+ --no-filename
+ --no-utf8-convert
+ --preserve-modtime
+ --remove-all-tags
+ --remove-all
+ --remove-first-tag
+ --remove-replay-gain
+ --remove-tag
+ --remove
+ --set-tag-from-file
+ --set-tag
+ --show-bps
+ --show-channels
+ --show-max-blocksize
+ --show-max-framesize
+ --show-md5sum
+ --show-min-blocksize
+ --show-min-framesize
+ --show-sample-rate
+ --show-tag
+ --show-total-samples
+ --show-vendor-tag
+ --sort-padding
+ --version
+ --with-filename
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/documentation_tools_plugins.html b/flac/doc/html/documentation_tools_plugins.html new file mode 100644 index 0000000..1355ce4 --- /dev/null +++ b/flac/doc/html/documentation_tools_plugins.html @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + FLAC - documentation + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+ +
+
+ Normally the FLAC plugin for XMMS is installed with a package, but some of the binary builds have a compiled plugin. All that is necessary is to copy libxmms-flac.so to the directory where XMMS looks for input plugins (usually /usr/lib/xmms/Input or $HOME/.xmms/Input). There is nothing else to configure. Make sure to restart XMMS before trying to play any .flac files. +
+ +
+ +
+ +
+ +
+
+ Since Winamp 5.31, Nullsoft has supplied a FLAC plugin with their Full install; nothing else is needed to get FLAC to play in Wnamp.
+
+ Before Winamp 5.31 it was necessary to use our FLAC plugin. If you have an older version of Winamp, our plugin is still available in the FLAC Installer for Windows. The Winamp plugin should work for both Winamp2 and Winamp5. All that is necessary is to copy in_flac.dll to the Plugins/ directory of your Winamp installation. There is nothing else to configure. Make sure to restart Winamp before trying to play any .flac files. +
+ +
+ + + + + + diff --git a/flac/doc/html/download.html b/flac/doc/html/download.html new file mode 100644 index 0000000..127d97b --- /dev/null +++ b/flac/doc/html/download.html @@ -0,0 +1,284 @@ + + + + + + + + + + + + + + + + FLAC - download + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ download +
+
+
+ Many different programs support FLAC. If you are not sure what to download, see Using FLAC for instructions and guides on playing FLAC files, ripping CDs to FLAC, etc.
+
+ This section is for the official FLAC tools. See the extras section below for other third-party tools.
+
+ All source code and binaries are freely available and distributed under Open Source licenses. The codec libraries are distributed under Xiph.org's BSD license, and the plugins and command-line utilites (flac and metaflac) are distributed under the GPL. If you would like to redistribute parts or all of FLAC under different terms, contact Josh Coalson. (For more information, see the license page.) + +
+ +
+ +
+ +
+
+ extras +
+
+
+ NOTE: these extras are not part of the FLAC project. Most (except those marked [$]) are freely available but distributed under their authors' own terms.
+
+ NOTE: make sure to check out the links page for a large list of open-source software supporting FLAC.
+
+ GUI encoding/decoding front-ends: +
    +
  • + Windows +
      +
    • AutoFLAC for automated ripping and encoding to FLAC with EAC (ExactAudioCopy); also has a write mode for burning back to CD for an exact copy
    • +
    • dBpowerAMP, a swiss army knife that can convert and play many formats, including FLAC.
    • +
    • Flacattack: an all-in-one tool that works with ExactAudioCopy to encode a CD image to FLAC, embed the cuesheet, add ReplayGain, create lossy files, etc. all in a customizable directory structure.
    • +
    • FLACdrop, an Oggdrop-like frontend for Windows.
    • +
    • FLAC frontend, a Windows GUI, or the even more versatile Multi frontend.
    • +
    • FLACTester, can test a whole tree of FLAC files for errors and generate a report.
    • +
    • Frontah, a new frontend to many codecs, including FLAC. Still in beta but has good reviews.
    • +
    • GX::Transcoder
    • +
    • MAREO is a "virtual" encoder that can be used with ExactAudioCopy to encode to multiple formats (including FLAC) at once while ripping.
    • +
    • MediaCoder converts between many audio and video formats.
    • +
    • MediaMonkey can organize, encode, decode, edit tags, and rip to FLAC and other formats.
    • +
    • Yahoo! Music Engine
    • +
    +
  • +
  • + Mac OS X +
      +
    • iTunes-to-FLAC, an AppleScript for converting between FLAC and WAVE/AIFF with tagging via iTunes.
    • +
    • MacFLAC, a FLAC distribution which also includes nice graphical front-end.
    • +
    • Max, a CD ripper and encoder that supports several formats including FLAC.
    • +
    • MediaRage, for editing FLAC metadata (also supports Vorbis and other formats).
    • +
    • RipBeak is a nice GUI encoding frond-end that supports FLAC as well as Vorbis and MP3.
    • +
    • xACT, another FLAC distribution with a graphical front-end to FLAC and other formats.
    • +
    +
  • +
  • + Unix +
      +
    • Grip is a great ripping and encoding front end and can be easily configured to use flac. See this thread on how to configure Grip for FLAC.
    • +
    • xmcd is a CD ripper with CDDB support as well as a player.
    • +
    • (many more)
    • +
    +
  • +
  • + Pocket PC + +
  • +
+ CD burning: + + Players and plugins: + +
+ +
+ + + + + + diff --git a/flac/doc/html/faq.html b/flac/doc/html/faq.html new file mode 100644 index 0000000..241d9d8 --- /dev/null +++ b/flac/doc/html/faq.html @@ -0,0 +1,402 @@ + + + + + + + + + + + + + + + + FLAC - faq + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ faq +
+
+
+ General + + Tools + + API + + Project + + +

+ General +

+ + What is FLAC?
+
+ FLAC stands for Free Lossless Audio Codec, an audio format similar to MP3, but lossless, meaning that audio is compressed in FLAC without any loss in quality. This is similar to how Zip works, except with FLAC you will get much better compression because it is designed specifically for audio, and you can play back compressed FLAC files in your favorite player (or your car or home stereo, see supported devices) just like you would an MP3 file.
+
+ For more details, see What is FLAC?
+
+ I have a FLAC file, how do I play it?
+ How can I create FLAC files?
+
+ See Using FLAC.
+
+ What licensing applies to the FLAC format and software?
+
+ See the license page.
+
+ What kinds of tags does FLAC support?
+
+ FLAC has it's own native tagging system which is identical to that of Vorbis. They are called alternately "FLAC tags" and "Vorbis comments". It is the only tagging system required and guaranteed to be supported by FLAC implementations.
+
+ Out of convenience, the reference decoder knows how to skip ID3 tags so that they don't interfere with decoding. But you should not expect any tags beside FLAC tags to be supported in applications; some implementations may not even be able to decode a FLAC file with ID3 tags.
+
+ What software support FLAC?
+
+ This list is so large now it is difficult to maintain and keep up-to-date. For a partial list of open-source software that supports FLAC, see the software section of the links page. For a partial list of the most popular software used to encode, decode, play, tag, and rip FLAC files, see the download page.
+
+ How can I play FLAC in Windows Media Player?
+
+ See this guide.
+
+ What hardware products support FLAC?
+
+ See the hardware section of the links page.
+
+ What is the difference between (native) FLAC and Ogg FLAC?
+
+ You can think of an audio codec as having two layers. The inside layer is the raw compressed data, and the outside layer is the "container" or "transport layer" that splits and arranges the compressed data in pieces so it can be seeked through, edited, etc.
+
+ "Native" FLAC is the compressed FLAC data stored in a very minimalist container, designed to be very efficient at storing single audio streams.
+
+ Ogg FLAC is the compressed FLAC data stored in an Ogg container. Ogg is a much more powerful transport layer that enables mixing several kinds of different streams (audio, data, metadata, etc). The overhead is slightly higher than with native FLAC.
+
+ In either case, the compressed FLAC data is the same and one can be converted to the other without re-encoding.
+
+ Which should I use, (native) FLAC or Ogg FLAC?
+
+ The short answer right now is probably "native FLAC". If all you are doing is compressing audio to be played back later, native FLAC will do everything you need, is more widely supported, and will yield smaller files. If you plan to edit the compressed audio, or want to multiplex the audio with video later in an Ogg container, Ogg FLAC is a better choice.
+
+ Why aren't PERFORMER/TITLE/etc tags stored in the FLAC CUESHEET block?
+
+ This has turned out to be a pretty polarizing issue and requires a long explanation.
+
+ The original purpose of a cue sheet in CD authoring software was to lay out the disc, essentially specifying how the audio will be organized on the disc; some of the information ends up as the CD table of contents: the track numbers and locations, and the index points. Later CD-TEXT was added. But CD-TEXT is a very complex spec, and actually goes in the CD subcode data. It is internationalized, not through Unicode, but with several different character sets, some of them multi-byte. It even allows for graphics. In cue sheets, the TITLE/PERFORMER/etc tags are just a limited shorthand for authoring CD-TEXT, but when you rip, you almost never parse the CD-TEXT, you get it from another database, and it doesn't really belong in the FLAC CUESHEET block.
+
+ For FLAC the intention is that applications can calculate the CDDB or CDindex ID from the CUESHEET block and look it up in an online or local database just like CD rippers and players do. But if you really want it in the file itself, the track metadata should be stored separate from the CUESHEET, and already can be because of FLAC's metadata system. There just isn't a method specified yet because as soon as it is, people will say that it's not flexible enough. From experience (and you can see this come up time and time again in many lists), anyone who is going to the trouble of keeping a lossless collection in the first place will already be picky about metadata, and it is hard to come up with a standard that will please even the majority. That is the big problem with metadata and is why Xiph has deferred on it, waiting for someone to come up with a good metadata spec that can be multiplexed together with data.
+
+ Some players (for example Foobar2000) allow you to store the CDDB data as FLAC tags and can parse that.
+
+ Why doesn't FLAC store all WAVE metadata?
+ If flac compresses WAVE files, why isn't it technically a WAVE file compressor?
+
+ (By default, flac does not store WAVE metadata, but it can with the --keep-foreign-metadata option described below.)
+
+ FLAC is a general-purpose audio format, not just a compressed WAVE file format. There's a subtle difference. WAVE is a complicated standard; many kinds of data besides audio data can be put in it. FLAC's purpose is not to reproduce a WAVE file, including all the non-audio data that is in it, it is to losslessly compress the audio.
+
+ However, if you really need to store the non-audio parts of a WAVE or AIFF file, you can use the --keep-foreign-metadata option to flac when encoding to store it in FLAC metadata, then use the option again when decoding to restore in to the decoded WAVE/AIFF file.
+
+ Why do some lossless comparisons say FLAC does not support RIFF chunks?
+
+ This is a limitation that no longer exists with FLAC (see above).
+
+ Why do the encoder settings have a big effect on the encoding time but not the decoding time?
+
+ It's hard to explain without going into the codec design, but to oversimplify, the encoder is looking for functions that approximate the signal. Higher settings make the encoder search more to find better approximations. The functions are themselves encoded in the FLAC file. Decoding only requires computing the one chosen function, and the complexity of the function is very stable. This is by design, to make decoding easier, and is one of the things that makes FLAC easy to implement in hardware.
+
+ Why use FLAC instead of other codecs that compress more?
+
+ For most users, a small difference in filesize is usually far outweighed by FLAC's advantages: open patent free codec, portable open source (BSD) reference implementation, documented API, multi-platform support, hardware support, multi-channel support, etc. Improving FLAC to get a little more compression is not worth making it more complex and more compute-intensive to decode, and hence, less likely to be supported in hardware.
+
+ Why can't you make FLAC encode faster?
+
+ FLAC already encodes pretty fast. It is faster than real-time even on weak systems and is not much slower than even the fastest codecs. And it is faster than the CD ripping process with which it is usually paired, meaning even if it went faster, it would not speed up the ripping-encoding process anyway.
+
+ Part of the reason is that FLAC is asymmetric (see also). That means that it is optimized for decoding speed at the expense of encoding speed, because it makes it easier to decode on low-powered hardware, and because you only encode once but you decode many times.
+
+ How can I be sure FLAC is lossless?
+ How much testing has been done on FLAC?
+
+ First, FLAC is probably the only lossless compressor that has a published and comprehensive test suite. With the others you rely on the author's personal testing or the longevity of the program. But with FLAC you can download the whole test suite and run it on any version you like, or alter it to test your own data. The test suite checks every function in the API, as well as running many thousands of streams through an encode-decode-verify process, to test every nook and cranny of the system. Even on a fast machine the full test suite takes hours. The full test suite must pass on several platforms before a release is made.
+
+ Second, you can always use the -V option with flac (also supported by most GUI frontends) to verify while encoding. With this option, a decoder is run in parallel to the encoder and its output is compared against the original input. If a difference is found flac will stop with an error.
+
+ Finally, FLAC is used by many people and has been judged stable enough by many software and hardware makers to be incorporated into their products.
+
+ What is the lowest bitrate (or highest compression) achievable with FLAC?
+
+ With FLAC you do not specify a bitrate like with some lossy codecs. It's more like specifying a quality with Vorbis or MPC, except with FLAC the quality is always "lossless" and the resulting bitrate is roughly proportional to the amount of information in the original signal. You cannot control the bitrate much and the result can be from around 100% of the input rate (if you are encoding noise), down to almost 0 (encoding silence).
+
+ How many channels does FLAC support?
+
+ FLAC supports from 1 to 8 channels per stream. Channels are only grouped in FLAC to take advantage of interchannel correlation and to define common channel assignments (like stereo L/R, 5.1 surround, et cetera). When encoding a large number of independent channels it is expected that they are coded separately and if required, multiplexed together in a suitable container like Ogg or Matroska.
+
+ What kind of audio samples does FLAC support?
+
+ FLAC supports linear PCM samples with a resolution between 4 and 32 bits per sample. FLAC does not support floating point samples. In some cases it is possible to losslessly transform samples from an incompatible range to a FLAC-compatible range before encoding.
+
+ FLAC supports linear sample rates from 1Hz - 655350Hz in 1Hz increments. + +

+ Tools +

+ + How do I set up EAC to rip directly to FLAC?
+
+ See Case's excellent EAC configuration page. Or use AutoFLAC, Omni Encoder, or MAREO to rip to FLAC or multiple formats at once.
+
+ Why am I getting "Run-time error '75': Path/File access error" with FLAC Frontend?
+
+ Depending on how FLAC Frontend is installed, it could be one of two things: 1) you are trying to encode to file to a directory where you do not have write permission; 2) the FLAC Frontend program must be set to run as Administrator by opening Windows Explorer, navigating to C:\Program Files\FLAC (or wherever FLAC was installed), then right-clicking on FLAC Frontend.exe and checking "Run this program as an administrator".
+
+ How do I encode a file that starts with a dash?
+
+ When using flac to encode on the command-line, a file that starts with a dash will be treated as an option, but there is a simple workaround. Use -- to signal the end of options and the beginning of filenames, like so:
+
+ flac -V -- -01-name.wav
+
+ Why does it take so long to edit some FLAC files with metaflac?
+
+ Since metadata is stored at the beginning of a FLAC file, changing the length of it can sometimes cause the whole file to be rewritten. You can avoid this by adding padding with flac when you encode, or with metaflac after encoding. By default, flac adds 8k of padding; you can change this amount if you need more or less.
+
+ Why don't Unicode file names work with flac/metaflac on Windows?
+
+ Windows implements Unicode filenames differently than all other operating systems, and can only be supported via Windows APIs (non-portable). Also the method is different for different versions of Windows. It's so hard to get right that most programs that have to work for other operating systems also do not support it. A workaround can be found here.
+
+ Why don't wildcards for file names like *.flac or *.wav work with flac/metaflac on Windows?
+
+ The Windows command shells (cmd.exe, command.com) implement wildcard handling differently than most other shells, leaving it up to the program to do everything including difficult and ambiguous cases. For an explanation of why wildcards on cmd.exe/command.com are dangerous, see here. Better command shells for Windows exist, e.g. from Cygwin. A workaround with the Windows shells is to do something like:
+
+ for %F in (*.wav) do flac "%F"
+
+ but care must still be taken that the command will execute as intended.
+
+ I compressed a file to FLAC with verify on, and flac said "Verify FAILED!" Why?
+
+ The only known cause of verify errors is faulty hardware. The dead giveaway is that if you repeat the exact same command, the error occurs in a different place or not at all. This can also happen when decoding or testing a FLAC file. If this is happening it is your hardware and not a FLAC bug.
+
+ The problem is usually caused by overclocking/overheating the CPU or bad RAM. Try one of the many free programs available for testing hardware (e.g. Memtest86+). We have had reports of a few cases where a system is passing with flying colors and still getting unrepeatable FLAC errors, and the one thing many (all?) of these systems have in common is an ASUS motherboard (A7V133 or P3V4X) which we suspect is buggy in some way. (See also)
+
+ If you ever have a verify error that fails at the same place every time, please file a bug, uploading a sample according to the instructions found at the bottom of this bug report.
+
+ I compressed a WAVE file to FLAC, then decompressed to WAVE, and the two weren't identical. Why?
+ I compressed a WAVE file to FLAC and it said "warning: skipping unknown sub-chunk LIST". Why?
+
+ WAVE is a complicated standard; many kinds of data besides audio data can be put in it. Most likely what has happened is that the application that created the original WAVE file also added some extra information for it's own use, which FLAC does not store or recreate by default (but can with the --keep-foreign-metadata option) (see also). The audio data in the two WAVE files will be identical. There are other tools to compare just the audio content of two WAVE files; ExactAudioCopy has such a feature.
+
+ For the more technically inclined, by default FLAC only stores what is in the 'fmt ' and 'data' sub-chunks of a WAVE file. (see also)
+
+ I decoded a FLAC file and the WAVE is 2 bytes shorter than the original. Why?
+
+ The difference is probably that between an 18-byte 'fmt ' subchunk in the original WAVE vs. a 16-byte one in the decoded WAVE. With WAVE there is more than one way to write identical formatting information, but FLAC always writes the most common legal form. (see also)
+
+ Why did I get "ERROR initializing encoder, state = FLAC__STREAM_ENCODER_NOT_STREAMABLE"?
+
+ You specified encoding options that are outside the Streamable subset. If that is what you really wanted and you understand the consequences, you can use flac --lax to generate a non-Subset stream. The resulting file may not be streamable or play in all players.
+
+ Why doesn't the same file compressed on different machines with the same options yield the same FLAC file?
+
+ It's not supposed to, and neither does it mean either encoding was bad. There are many variations between different machines or even different builds of flac on the same machine that can lead to small differences in the FLAC file, even if they have the exact same final size. This is normal. + +

+ API +

+ + Why does your API change for point releases?
+
+ The FLAC release numbering scheme of MAJOR.MINOR.MICRO reflects the state of the FLAC format, not the API. This is most intuitive for users, at the expense of flustering developers. The shared library number (derived from the libtool current:revision:age number) is the indicator of binary API compatibility. As of FLAC 1.1.3, the current, revision, and age numbers are also #defined in the library headers to make porting easier; see the porting guide.
+
+ How can I determine the encoded frame length?
+
+ With native FLAC, it is not possible to determine the frame length without decoding. Probably if I had it all to do again I would have constrained the possible block sizes, which would have made it more practical to put the frame length in the frame header. For an example of how to find the frame boundaries in a stream, see the source code to metaflac, in the functionality that adds seek points.
+
+ With Ogg FLAC, it can be calculated from the Ogg page header. + +

+ Project +

+ + Where are the mailing lists, forums, discussion areas, etc.?
+
+ There are a few places. The main discussions happen on the official FLAC mailing lists (you must subscribe to post). Also, there is a lot of discussion relating to FLAC on Hydrogen Audio.
+
+ How do I submit a bug report?
+
+ First, visit the bug tracking page and do a little searching of both open and closed bugs to see if yours is already there. If you have something truly new, submit a new bug. Make sure to monitor the bug or include your email address in the description. Include as much information as possible: the version of FLAC that you are running, the name and version of any frontend you are running, your operating system and version, your CPU type and speed, the amount of memory you have, where you downloaded FLAC from, the exact error message (if any) copied from the console, and anything else you may think will help. +
+ +
+ + + + + + diff --git a/flac/doc/html/favicon.ico b/flac/doc/html/favicon.ico new file mode 100644 index 0000000..a49b6d8 Binary files /dev/null and b/flac/doc/html/favicon.ico differ diff --git a/flac/doc/html/features.html b/flac/doc/html/features.html new file mode 100644 index 0000000..e356ff6 --- /dev/null +++ b/flac/doc/html/features.html @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + FLAC - features + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+ +
+
+ FLAC stands for Free Lossless Audio Codec, an audio format similar to MP3, but lossless, meaning that audio is compressed in FLAC without any loss in quality. This is similar to how Zip works, except with FLAC you will get much better compression because it is designed specifically for audio, and you can play back compressed FLAC files in your favorite player (or your car or home stereo, see supported devices) just like you would an MP3 file.
+
+ FLAC stands out as the fastest and most widely supported lossless audio codec, and the only one that at once is non-proprietary, is unencumbered by patents, has an open-source reference implementation, has a well documented format and API, and has several other independent implementations.
+
+ FLAC supports tagging, cover art, and fast seeking. FLAC is freely available and supported on most operating systems, including Windows, "unix" (Linux, *BSD, Solaris, OS X, IRIX), BeOS, OS/2, and Amiga.
+
+ There are many programs and devices that support FLAC, but the core FLAC project here maintains the format and provides programs and libraries for working with FLAC files. See Getting FLAC for instructions on downloading and installing the official FLAC tools, or Using FLAC for instructions and guides on playing FLAC files, ripping CDs to FLAC, etc.
+
+ When we say that FLAC is "Free" it means more than just that it is available at no cost. It means that the specification of the format is fully open to the public to be used for any purpose (the FLAC project reserves the right to set the FLAC specification and certify compliance), and that neither the FLAC format nor any of the implemented encoding/decoding methods are covered by any known patent. It also means that all the source code is available under open-source licenses. It is the first truly open and free lossless audio format. (For more information, see the license page.)
+
+ Notable features of FLAC: +
    +
  • + Lossless: The encoding of audio (PCM) data incurs no loss of information, and the decoded audio is bit-for-bit identical to what went into the encoder. Each frame contains a 16-bit CRC of the frame data for detecting transmission errors. The integrity of the audio data is further insured by storing an MD5 signature of the original unencoded audio data in the file header, which can be compared against later during decoding or testing. +
  • +
  • + Fast: FLAC is asymmetric in favor of decode speed. Decoding requires only integer arithmetic, and is much less compute-intensive than for most perceptual codecs. Real-time decode performance is easily achievable on even modest hardware. +
  • +
  • + Hardware support: FLAC is supported by dozens of consumer electronic devices, from portable players, to home stereo equipment, to car stereo. +
  • +
  • + Flexible metadata: FLAC's metadata system supports tags, cover art, seek tables, and cue sheets. Applications can write their own APPLICATION metadata once they register an ID. New metadata blocks can be defined and implemented in future versions of FLAC without breaking older streams or decoders. +
  • +
  • + Seekable: FLAC supports fast sample-accurate seeking. Not only is this useful for playback, it makes FLAC files suitable for use in editing applications. +
  • +
  • + Streamable: Each FLAC frame contains enough data to decode that frame. FLAC does not even rely on previous or following frames. FLAC uses sync codes and CRCs (similar to MPEG and other formats), which, along with framing, allow decoders to pick up in the middle of a stream with a minimum of delay. +
  • +
  • + Suitable for archiving: FLAC is an open format, and there is no generation loss if you need to convert your data to another format in the future. In addition to the frame CRCs and MD5 signature, flac has a verify option that decodes the encoded stream in parallel with the encoding process and compares the result to the original, aborting with an error if there is a mismatch. +
  • +
  • + Convenient CD archiving: FLAC has a "cue sheet" metadata block for storing a CD table of contents and all track and index points. For instance, you can rip a CD to a single file, then import the CD's extracted cue sheet while encoding to yield a single file representation of the entire CD. If your original CD is damaged, the cue sheet can be exported later in order to burn an exact copy. +
  • +
  • + Error resistant: Because of FLAC's framing, stream errors limit the damage to the frame in which the error occurred, typically a small fraction of a second worth of data. Contrast this with some other lossless codecs, in which a single error destroys the remainder of the stream. +
  • +
+ What FLAC is not: +
    +
  • + Lossy. FLAC is intended for lossless compression only, as there are many good lossy formats already, such as Vorbis, MPC, and MP3 (see LAME for an excellent open-source implementation). +
  • +
  • + DRM. There is no intention to add any copy prevention methods. Of course, we can't stop someone from encrypting a FLAC stream in another container (e.g. the way Apple encrypts AAC in MP4 with FairPlay), that is the choice of the user. +
  • +
+
+ +
+ + + + + + diff --git a/flac/doc/html/flac.css b/flac/doc/html/flac.css new file mode 100644 index 0000000..a52eb7d --- /dev/null +++ b/flac/doc/html/flac.css @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2005,2006,2007,2008 Josh Coalson + * Permission is granted to copy, distribute and/or modify this document + * under the terms of the GNU Free Documentation License, Version 1.1 + * or any later version published by the Free Software Foundation; + * with no invariant sections. + * A copy of the license can be found at http://www.gnu.org/copyleft/fdl.html + */ + +body +{ + background-color: #99CC99; + color: black; + margin: 0px; + padding: 0px; +} + +div +{ + background-color: #99CC99; + margin: 0px; + padding: 0px; +} + +div.logo +{ + background-color: black; + padding: 1px; + text-align: center; +} + +div.navbar +{ + border-width: 2px 0px 2px 0px; + border-style: solid; + border-color: black; + background-color: #D3D4C5; + padding: 3px; + text-align: center; +} + +div.langbar +{ + border-width: 0px 0px 2px 0px; + border-style: solid; + border-color: black; + background-color: #EEEED4; + padding: 3px; + text-align: center; +} + +div.above_nav +{ + height: 25px; +} + +div.below_nav +{ + height: 25px; +} + +div.body_with_sidebar +{ +/* text-align: left; */ +} + +div.box +{ + text-align: left; + margin: 0px 8px 0px 8px; + background-color: #EEEED4; +} + +div.box_title +{ + border-width: 1px 0px 0px 0px; + border-style: solid; + border-color: black; + background-color: #D3D4C5; + padding: 3px; + font-family: lucida, verdana, helvetica, arial, sans-serif; + font-weight: bold; + font-size: 150%; +} + +div.box_header +{ + border-width: 1px 0px 0px 0px; + border-style: solid; + border-color: black; + background-color: #EEEED4; + padding: 3px; +} + +div.box_footer +{ + border-width: 0px 0px 1px 0px; + border-style: solid; + border-color: black; + background-color: #EEEED4; + padding: 3px; +} + +div.box_body +{ + background-color: #EEEED4; + padding: 0px 3px 0px 3px; + font-family: lucida, verdana, helvetica, arial, sans-serif; + font-weight: normal; + font-size: 100%; +} + +div.smallbox +{ + text-align: left; + margin: 0px 8px 0px 0px; + background-color: #EEEED4; +} + +div.smallbox_title +{ + text-align: center; + border-width: 1px 0px 0px 0px; + border-style: solid; + border-color: black; + background-color: #D3D4C5; + padding: 3px; + font-family: lucida, verdana, helvetica, arial, sans-serif; + font-weight: bold; + font-size: 100%; +} + +div.smallbox_header +{ + border-width: 1px 0px 0px 0px; + border-style: solid; + border-color: black; + background-color: #EEEED4; + padding: 3px; +} + +div.smallbox_footer +{ + border-width: 0px 0px 1px 0px; + border-style: solid; + border-color: black; + background-color: #EEEED4; + padding: 3px; +} + +div.smallbox_body +{ + background-color: #EEEED4; + padding: 0px 3px 0px 3px; + font-family: lucida, verdana, helvetica, arial, sans-serif; + font-weight: normal; + font-size: 80%; +} + +div.copyright +{ + text-align: left; + margin: 10px; +} + +span.commandname +{ + font-family: monospace; + font-weight: bold; +} + +span.command +{ + font-family: monospace; + font-weight: bold; +} + +span.argument +{ + font-family: monospace; +} + +span.code +{ + font-family: monospace; +} + +a:link {color:#336699; background-color:transparent} +a:visited {color:#336699; background-color:transparent} +a:active {color:#336699; background-color:transparent} +a:hover {color:#336699; background-color:transparent} diff --git a/flac/doc/html/format.html b/flac/doc/html/format.html new file mode 100644 index 0000000..3c93e7b --- /dev/null +++ b/flac/doc/html/format.html @@ -0,0 +1,1852 @@ + + + + + + + + + + + + + + + + FLAC - format + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ format +
+
+
+ This is a detailed description of the FLAC format. There is also a companion document that describes FLAC-to-Ogg mapping.
+
+ For a user-oriented overview, see About the FLAC Format.
+
+ Table of Contents + + Acknowledgments
+
+ FLAC owes much to the many people who have advanced the audio compression field so freely. For instance: +
    +
  • + A. J. Robinson for his work on Shorten; his paper is a good starting point on some of the basic methods used by FLAC. FLAC trivially extends and improves the fixed predictors, LPC coefficient quantization, and Rice coding used in Shorten. +
  • +
  • + S. W. Golomb and Robert F. Rice; their universal codes are used by FLAC's entropy coder. +
  • +
  • + N. Levinson and J. Durbin; the reference encoder uses an algorithm developed and refined by them for determining the LPC coefficients from the autocorrelation coefficients. +
  • +
  • + And of course, Claude Shannon +
  • +
+ Scope
+
+ It is a known fact that no algorithm can losslessly compress all possible input, so most compressors restrict themselves to a useful domain and try to work as well as possible within that domain. FLAC's domain is audio data. Though it can losslessly code any input, only certain kinds of input will get smaller. FLAC exploits the fact that audio data typically has a high degree of sample-to-sample correlation.
+
+ Within the audio domain, there are many possible subdomains. For example: low bitrate speech, high-bitrate multi-channel music, etc. FLAC itself does not target a specific subdomain but many of the default parameters of the reference encoder are tuned to CD-quality music data (i.e. 44.1kHz, 2 channel, 16 bits per sample). The effect of the encoding parameters on different kinds of audio data will be examined later.
+
+ Architecture
+
+ Similar to many audio coders, a FLAC encoder has the following stages: +
    +
  • + Blocking. The input is broken up into many contiguous blocks. With FLAC, the blocks may vary in size. The optimal size of the block is usually affected by many factors, including the sample rate, spectral characteristics over time, etc. Though FLAC allows the block size to vary within a stream, the reference encoder uses a fixed block size. +
  • +
  • + Interchannel Decorrelation. In the case of stereo streams, the encoder will create mid and side signals based on the average and difference (respectively) of the left and right channels. The encoder will then pass the best form of the signal to the next stage. +
  • +
  • + Prediction. The block is passed through a prediction stage where the encoder tries to find a mathematical description (usually an approximate one) of the signal. This description is typically much smaller than the raw signal itself. Since the methods of prediction are known to both the encoder and decoder, only the parameters of the predictor need be included in the compressed stream. FLAC currently uses four different classes of predictors (described in the prediction section), but the format has reserved space for additional methods. FLAC allows the class of predictor to change from block to block, or even within the channels of a block. +
  • +
  • + Residual coding. If the predictor does not describe the signal exactly, the difference between the original signal and the predicted signal (called the error or residual signal) must be coded losslessy. If the predictor is effective, the residual signal will require fewer bits per sample than the original signal. FLAC currently uses only one method for encoding the residual (see the Residual coding section), but the format has reserved space for additional methods. FLAC allows the residual coding method to change from block to block, or even within the channels of a block. +
  • +
+ In addition, FLAC specifies a metadata system, which allows arbitrary information about the stream to be included at the beginning of the stream.
+
+ Definitions
+
+ Many terms like "block" and "frame" are used to mean different things in differenct encoding schemes. For example, a frame in MP3 corresponds to many samples across several channels, whereas an S/PDIF frame represents just one sample for each channel. The definitions we use for FLAC follow. Note that when we talk about blocks and subblocks we are referring to the raw unencoded audio data that is the input to the encoder, and when we talk about frames and subframes, we are referring to the FLAC-encoded data. +
    +
  • + Block: One or more audio samples that span several channels. +
  • +
  • + Subblock: One or more audio samples within a channel. So a block contains one subblock for each channel, and all subblocks contain the same number of samples. +
  • +
  • + Blocksize: The number of samples in any of a block's subblocks. For example, a one second block sampled at 44.1KHz has a blocksize of 44100, regardless of the number of channels. +
  • +
  • + Frame: A frame header plus one or more subframes. +
  • +
  • + Subframe: A subframe header plus one or more encoded samples from a given channel. All subframes within a frame will contain the same number of samples. +
  • +
+ Blocking
+
+ The size used for blocking the audio data has a direct effect on the compression ratio. If the block size is too small, the resulting large number of frames mean that excess bits will be wasted on frame headers. If the block size is too large, the characteristics of the signal may vary so much that the encoder will be unable to find a good predictor. In order to simplify encoder/decoder design, FLAC imposes a minimum block size of 16 samples, and a maximum block size of 65535 samples. This range covers the optimal size for all of the audio data FLAC supports.
+
+ Currently the reference encoder uses a fixed block size, optimized on the sample rate of the input. Future versions may vary the block size depending on the characteristics of the signal.
+
+ Blocked data is passed to the predictor stage one subblock (channel) at a time. Each subblock is independently coded into a subframe, and the subframes are concatenated into a frame. Because each channel is coded separately, it means that one channel of a stereo frame may be encoded as a constant subframe, and the other an LPC subframe.
+
+ Interchannel Decorrelation
+
+ In stereo streams, many times there is an exploitable amount of correlation between the left and right channels. FLAC allows the frames of stereo streams to have different channel assignments, and an encoder may choose to use the best representation on a frame-by-frame basis. +
    +
  • + Independent. The left and right channels are coded independently. +
  • +
  • + Mid-side. The left and right channels are transformed into mid and side channels. The mid channel is the midpoint (average) of the left and right signals, and the side is the difference signal (left minus right). +
  • +
  • + Left-side. The left channel and side channel are coded. +
  • +
  • + Right-side. The right channel and side channel are coded +
  • +
+ Surprisingly, the left-side and right-side forms can be the most efficient in many frames, even though the raw number of bits per sample needed for the original signal is slightly more than that needed for independent or mid-side coding.
+
+ Prediction
+
+ FLAC uses four methods for modeling the input signal: +
    +
  • + Verbatim. This is essentially a zero-order predictor of the signal. The predicted signal is zero, meaning the residual is the signal itself, and the compression is zero. This is the baseline against which the other predictors are measured. If you feed random data to the encoder, the verbatim predictor will probably be used for every subblock. Since the raw signal is not actually passed through the residual coding stage (it is added to the stream 'verbatim'), the encoding results will not be the same as a zero-order linear predictor. +
  • +
  • + Constant. This predictor is used whenever the subblock is pure DC ("digital silence"), i.e. a constant value throughout. The signal is run-length encoded and added to the stream. +
  • +
  • + Fixed linear predictor. FLAC uses a class of computationally-efficient fixed linear predictors (for a good description, see audiopak and shorten). FLAC adds a fourth-order predictor to the zero-to-third-order predictors used by Shorten. Since the predictors are fixed, the predictor order is the only parameter that needs to be stored in the compressed stream. The error signal is then passed to the residual coder. +
  • +
  • + FIR Linear prediction. For more accurate modeling (at a cost of slower encoding), FLAC supports up to 32nd order FIR linear prediction (again, for information on linear prediction, see audiopak and shorten). The reference encoder uses the Levinson-Durbin method for calculating the LPC coefficients from the autocorrelation coefficients, and the coefficients are quantized before computing the residual. Whereas encoders such as Shorten used a fixed quantization for the entire input, FLAC allows the quantized coefficient precision to vary from subframe to subframe. The FLAC reference encoder estimates the optimal precision to use based on the block size and dynamic range of the original signal. +
  • +
+ Residual Coding
+
+ FLAC currently defines two similar methods for the coding of the error signal from the prediction stage. The error signal is coded using Rice codes in one of two ways: 1) the encoder estimates a single Rice parameter based on the variance of the residual and Rice codes the entire residual using this parameter; 2) the residual is partitioned into several equal-length regions of contiguous samples, and each region is coded with its own Rice parameter based on the region's mean. (Note that the first method is a special case of the second method with one partition, except the Rice parameter is based on the residual variance instead of the mean.)
+
+ The FLAC format has reserved space for other coding methods. Some possiblities for volunteers would be to explore better context-modeling of the Rice parameter, or Huffman coding. See LOCO-I and pucrunch for descriptions of several universal codes.
+
+ Format
+
+ This section specifies the FLAC bitstream format. FLAC has no format version information, but it does contain reserved space in several places. Future versions of the format may use this reserved space safely without breaking the format of older streams. Older decoders may choose to abort decoding or skip data encoded with newer methods. Apart from reserved patterns, in places the format specifies invalid patterns, meaning that the patterns may never appear in any valid bitstream, in any prior, present, or future versions of the format. These invalid patterns are usually used to make the synchronization mechanism more robust.
+
+ All numbers used in a FLAC bitstream are integers; there are no floating-point representations. All numbers are big-endian coded. All numbers are unsigned unless otherwise specified.
+
+ Before the formal description of the stream, an overview might be helpful. +
    +
  • + A FLAC bitstream consists of the "fLaC" marker at the beginning of the stream, followed by a mandatory metadata block (called the STREAMINFO block), any number of other metadata blocks, then the audio frames. +
  • +
  • + FLAC supports up to 128 kinds of metadata blocks; currently the following are defined: +
      +
    • STREAMINFO: This block has information about the whole stream, like sample rate, number of channels, total number of samples, etc. It must be present as the first metadata block in the stream. Other metadata blocks may follow, and ones that the decoder doesn't understand, it will skip.
    • +
    • APPLICATION: This block is for use by third-party applications. The only mandatory field is a 32-bit identifier. This ID is granted upon request to an application by the FLAC maintainers. The remainder is of the block is defined by the registered application. Visit the registration page if you would like to register an ID for your application with FLAC.
    • +
    • PADDING: This block allows for an arbitrary amount of padding. The contents of a PADDING block have no meaning. This block is useful when it is known that metadata will be edited after encoding; the user can instruct the encoder to reserve a PADDING block of sufficient size so that when metadata is added, it will simply overwrite the padding (which is relatively quick) instead of having to insert it into the right place in the existing file (which would normally require rewriting the entire file).
    • +
    • SEEKTABLE: This is an optional block for storing seek points. It is possible to seek to any given sample in a FLAC stream without a seek table, but the delay can be unpredictable since the bitrate may vary widely within a stream. By adding seek points to a stream, this delay can be significantly reduced. Each seek point takes 18 bytes, so 1% resolution within a stream adds less than 2k. There can be only one SEEKTABLE in a stream, but the table can have any number of seek points. There is also a special 'placeholder' seekpoint which will be ignored by decoders but which can be used to reserve space for future seek point insertion.
    • +
    • VORBIS_COMMENT: This block is for storing a list of human-readable name/value pairs. Values are encoded using UTF-8. It is an implementation of the Vorbis comment specification (without the framing bit). This is the only officially supported tagging mechanism in FLAC. There may be only one VORBIS_COMMENT block in a stream. In some external documentation, Vorbis comments are called FLAC tags to lessen confusion.
    • +
    • CUESHEET: This block is for storing various information that can be used in a cue sheet. It supports track and index points, compatible with Red Book CD digital audio discs, as well as other CD-DA metadata such as media catalog number and track ISRCs. The CUESHEET block is especially useful for backing up CD-DA discs, but it can be used as a general purpose cueing mechanism for playback.
    • +
    • PICTURE: This block is for storing pictures associated with the file, most commonly cover art from CDs. There may be more than one PICTURE block in a file. The picture format is similar to the APIC frame in ID3v2. The PICTURE block has a type, MIME type, and UTF-8 description like ID3v2, and supports external linking via URL (though this is discouraged). The differences are that there is no uniqueness constraint on the description field, and the MIME type is mandatory. The FLAC PICTURE block also includes the resolution, color depth, and palette size so that the client can search for a suitable picture without having to scan them all.
    • +
    +
  • +
  • + The audio data is composed of one or more audio frames. Each frame consists of a frame header, which contains a sync code, information about the frame like the block size, sample rate, number of channels, et cetera, and an 8-bit CRC. The frame header also contains either the sample number of the first sample in the frame (for variable-blocksize streams), or the frame number (for fixed-blocksize streams). This allows for fast, sample-accurate seeking to be performed. Following the frame header are encoded subframes, one for each channel, and finally, the frame is zero-padded to a byte boundary. Each subframe has its own header that specifies how the subframe is encoded. +
  • +
  • + Since a decoder may start decoding in the middle of a stream, there must be a method to determine the start of a frame. A 14-bit sync code begins each frame. The sync code will not appear anywhere else in the frame header. However, since it may appear in the subframes, the decoder has two other ways of ensuring a correct sync. The first is to check that the rest of the frame header contains no invalid data. Even this is not foolproof since valid header patterns can still occur within the subframes. The decoder's final check is to generate an 8-bit CRC of the frame header and compare this to the CRC stored at the end of the frame header. +
  • +
  • + Again, since a decoder may start decoding at an arbitrary frame in the stream, each frame header must contain some basic information about the stream because the decoder may not have access to the STREAMINFO metadata block at the start of the stream. This information includes sample rate, bits per sample, number of channels, etc. Since the frame header is pure overhead, it has a direct effect on the compression ratio. To keep the frame header as small as possible, FLAC uses lookup tables for the most commonly used values for frame parameters. For instance, the sample rate part of the frame header is specified using 4 bits. Eight of the bit patterns correspond to the commonly used sample rates of 8/16/22.05/24/32/44.1/48/96 kHz. However, odd sample rates can be specified by using one of the 'hint' bit patterns, directing the decoder to find the exact sample rate at the end of the frame header. The same method is used for specifying the block size and bits per sample. In this way, the frame header size stays small for all of the most common forms of audio data. +
  • +
  • + Individual subframes (one for each channel) are coded separately within a frame, and appear serially in the stream. In other words, the encoded audio data is NOT channel-interleaved. This reduces decoder complexity at the cost of requiring larger decode buffers. Each subframe has its own header specifying the attributes of the subframe, like prediction method and order, residual coding parameters, etc. The header is followed by the encoded audio data for that channel. +
  • +
  • + FLAC specifies a subset of itself as the Subset format. The purpose of this is to ensure that any streams encoded according to the Subset are truly "streamable", meaning that a decoder that cannot seek within the stream can still pick up in the middle of the stream and start decoding. It also makes hardware decoder implementations more practical by limiting the encoding parameters such that decoder buffer sizes and other resource requirements can be easily determined. flac generates Subset streams by default unless the "--lax" command-line option is used. The Subset makes the following limitations on what may be used in the stream: +
      +
    • + The blocksize bits in the frame header must be 0001-1110. The blocksize must be <=16384; if the sample rate is <= 48000Hz, the blocksize must be <=4608. +
    • +
    • + The sample rate bits in the frame header must be 0001-1110. +
    • +
    • + The bits-per-sample bits in the frame header must be 001-111. +
    • +
    • + If the sample rate is <= 48000Hz, the filter order in LPC subframes must be less than or equal to 12, i.e. the subframe type bits in the subframe header may not be 101100-111111. +
    • +
    • + The Rice partition order in a Rice-coded residual section must be less than or equal to 8. +
    • +
    +
  • +
+ + The following tables constitute a formal description of the FLAC format. Numbers in angle brackets indicate how many bits are used for a given field.
+
+ +
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + +
+ STREAM +
+ <32> + + "fLaC", the FLAC stream marker in ASCII, meaning byte 0 of the stream is 0x66, followed by 0x4C 0x61 0x43 +
+ METADATA_BLOCK + + This is the mandatory STREAMINFO metadata block that has the basic properties of the stream +
+ METADATA_BLOCK* + + Zero or more metadata blocks +
+ FRAME+ + + One or more audio frames +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ METADATA_BLOCK +
+ METADATA_BLOCK_HEADER + + A block header that specifies the type and size of the metadata block data. +
+ METADATA_BLOCK_DATA + +   +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + +
+ METADATA_BLOCK_HEADER +
+ <1> + + Last-metadata-block flag: '1' if this block is the last metadata block before the audio blocks, '0' otherwise. +
+ <7> + + BLOCK_TYPE
+
    +
  • + 0 : STREAMINFO +
  • +
  • + 1 : PADDING +
  • +
  • + 2 : APPLICATION +
  • +
  • + 3 : SEEKTABLE +
  • +
  • + 4 : VORBIS_COMMENT +
  • +
  • + 5 : CUESHEET +
  • +
  • + 6 : PICTURE +
  • +
  • + 7-126 : reserved +
  • +
  • + 127 : invalid, to avoid confusion with a frame sync code +
  • +
+
+ <24> + + Length (in bytes) of metadata to follow (does not include the size of the METADATA_BLOCK_HEADER) +
+
+
+ +
+ +
+
+ + + + + + + + +
+ METADATA_BLOCK_DATA +
+ METADATA_BLOCK_STREAMINFO
+ || METADATA_BLOCK_PADDING
+ || METADATA_BLOCK_APPLICATION
+ || METADATA_BLOCK_SEEKTABLE
+ || METADATA_BLOCK_VORBIS_COMMENT
+ || METADATA_BLOCK_CUESHEET
+ || METADATA_BLOCK_PICTURE +
+ The block data must match the block type in the block header. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ METADATA_BLOCK_STREAMINFO +
+ <16> + + The minimum block size (in samples) used in the stream. +
+ <16> + + The maximum block size (in samples) used in the stream. (Minimum blocksize == maximum blocksize) implies a fixed-blocksize stream. +
+ <24> + + The minimum frame size (in bytes) used in the stream. May be 0 to imply the value is not known. +
+ <24> + + The maximum frame size (in bytes) used in the stream. May be 0 to imply the value is not known. +
+ <20> + + Sample rate in Hz. Though 20 bits are available, the maximum sample rate is limited by the structure of frame headers to 655350Hz. Also, a value of 0 is invalid. +
+ <3> + + (number of channels)-1. FLAC supports from 1 to 8 channels +
+ <5> + + (bits per sample)-1. FLAC supports from 4 to 32 bits per sample. Currently the reference encoder and decoders only support up to 24 bits per sample. +
+ <36> + + Total samples in stream. 'Samples' means inter-channel sample, i.e. one second of 44.1Khz audio will have 44100 samples regardless of the number of channels. A value of zero here means the number of total samples is unknown. +
+ <128> + + MD5 signature of the unencoded audio data. This allows the decoder to determine if an error exists in the audio data even when the error does not result in an invalid bitstream. +
+ + NOTES
+
    +
  • + FLAC specifies a minimum block size of 16 and a maximum block size of 65535, meaning the bit patterns corresponding to the numbers 0-15 in the minimum blocksize and maximum blocksize fields are invalid. +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + +
+ METADATA_BLOCK_PADDING +
+ <n> + + n '0' bits (n must be a multiple of 8) +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ METADATA_BLOCK_APPLICATION +
+ <32> + + Registered application ID. (Visit the registration page to register an ID with FLAC.) +
+ <n> + + Application data (n must be a multiple of 8) +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ METADATA_BLOCK_SEEKTABLE +
+ SEEKPOINT+ + + One or more seek points. +
+ + NOTE
+
    +
  • + The number of seek points is implied by the metadata header 'length' field, i.e. equal to length / 18. +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + +
+ SEEKPOINT +
+ <64> + + Sample number of first sample in the target frame, or 0xFFFFFFFFFFFFFFFF for a placeholder point. +
+ <64> + + Offset (in bytes) from the first byte of the first frame header to the first byte of the target frame's header. +
+ <16> + + Number of samples in the target frame. +
+ + NOTES
+
    +
  • + For placeholder points, the second and third field values are undefined. +
  • +
  • + Seek points within a table must be sorted in ascending order by sample number. +
  • +
  • + Seek points within a table must be unique by sample number, with the exception of placeholder points. +
  • +
  • + The previous two notes imply that there may be any number of placeholder points, but they must all occur at the end of the table. +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + +
+ METADATA_BLOCK_VORBIS_COMMENT +
+ <n> + + Also known as FLAC tags, the contents of a vorbis comment packet as specified here (without the framing bit). Note that the vorbis comment spec allows for on the order of 2 ^ 64 bytes of data where as the FLAC metadata block is limited to 2 ^ 24 bytes. Given the stated purpose of vorbis comments, i.e. human-readable textual information, this limit is unlikely to be restrictive. Also note that the 32-bit field lengths are little-endian coded according to the vorbis spec, as opposed to the usual big-endian coding of fixed-length integers in the rest of FLAC. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ METADATA_BLOCK_CUESHEET +
+ <128*8> + + Media catalog number, in ASCII printable characters 0x20-0x7e. In general, the media catalog number may be 0 to 128 bytes long; any unused characters should be right-padded with NUL characters. For CD-DA, this is a thirteen digit number, followed by 115 NUL bytes. +
+ <64> + + The number of lead-in samples. This field has meaning only for CD-DA cuesheets; for other uses it should be 0. For CD-DA, the lead-in is the TRACK 00 area where the table of contents is stored; more precisely, it is the number of samples from the first sample of the media to the first sample of the first index point of the first track. According to the Red Book, the lead-in must be silence and CD grabbing software does not usually store it; additionally, the lead-in must be at least two seconds but may be longer. For these reasons the lead-in length is stored here so that the absolute position of the first track can be computed. Note that the lead-in stored here is the number of samples up to the first index point of the first track, not necessarily to INDEX 01 of the first track; even the first track may have INDEX 00 data. +
+ <1> + + 1 if the CUESHEET corresponds to a Compact Disc, else 0. +
+ <7+258*8> + + Reserved. All bits must be set to zero. +
+ <8> + + The number of tracks. Must be at least 1 (because of the requisite lead-out track). For CD-DA, this number must be no more than 100 (99 regular tracks and one lead-out track). +
+ CUESHEET_TRACK+ + + One or more tracks. A CUESHEET block is required to have a lead-out track; it is always the last track in the CUESHEET. For CD-DA, the lead-out track number must be 170 as specified by the Red Book, otherwise is must be 255. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ CUESHEET_TRACK +
+ <64> + + Track offset in samples, relative to the beginning of the FLAC audio stream. It is the offset to the first index point of the track. (Note how this differs from CD-DA, where the track's offset in the TOC is that of the track's INDEX 01 even if there is an INDEX 00.) For CD-DA, the offset must be evenly divisible by 588 samples (588 samples = 44100 samples/sec * 1/75th of a sec). +
+ <8> + + Track number. A track number of 0 is not allowed to avoid conflicting with the CD-DA spec, which reserves this for the lead-in. For CD-DA the number must be 1-99, or 170 for the lead-out; for non-CD-DA, the track number must for 255 for the lead-out. It is not required but encouraged to start with track 1 and increase sequentially. Track numbers must be unique within a CUESHEET. +
+ <12*8> + + Track ISRC. This is a 12-digit alphanumeric code; see here and here. A value of 12 ASCII NUL characters may be used to denote absence of an ISRC. +
+ <1> + + The track type: 0 for audio, 1 for non-audio. This corresponds to the CD-DA Q-channel control bit 3. +
+ <1> + + The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. This corresponds to the CD-DA Q-channel control bit 5; see here. +
+ <6+13*8> + + Reserved. All bits must be set to zero. +
+ <8> + + The number of track index points. There must be at least one index in every track in a CUESHEET except for the lead-out track, which must have zero. For CD-DA, this number may be no more than 100. +
+ CUESHEET_TRACK_INDEX+ + + For all tracks except the lead-out track, one or more track index points. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + +
+ CUESHEET_TRACK_INDEX +
+ <64> + + Offset in samples, relative to the track offset, of the index point. For CD-DA, the offset must be evenly divisible by 588 samples (588 samples = 44100 samples/sec * 1/75th of a sec). Note that the offset is from the beginning of the track, not the beginning of the audio data. +
+ <8> + + The index point number. For CD-DA, an index number of 0 corresponds to the track pre-gap. The first index in a track must have a number of 0 or 1, and subsequently, index numbers must increase by 1. Index numbers must be unique within a track. +
+ <3*8> + + Reserved. All bits must be set to zero. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ METADATA_BLOCK_PICTURE +
+ <32> + + The picture type according to the ID3v2 APIC frame:
+
    +
  • 0 - Other
  • +
  • 1 - 32x32 pixels 'file icon' (PNG only)
  • +
  • 2 - Other file icon
  • +
  • 3 - Cover (front)
  • +
  • 4 - Cover (back)
  • +
  • 5 - Leaflet page
  • +
  • 6 - Media (e.g. label side of CD)
  • +
  • 7 - Lead artist/lead performer/soloist
  • +
  • 8 - Artist/performer
  • +
  • 9 - Conductor
  • +
  • 10 - Band/Orchestra
  • +
  • 11 - Composer
  • +
  • 12 - Lyricist/text writer
  • +
  • 13 - Recording Location
  • +
  • 14 - During recording
  • +
  • 15 - During performance
  • +
  • 16 - Movie/video screen capture
  • +
  • 17 - A bright coloured fish
  • +
  • 18 - Illustration
  • +
  • 19 - Band/artist logotype
  • +
  • 20 - Publisher/Studio logotype
  • +
+ Others are reserved and should not be used. There may only be one each of picture type 1 and 2 in a file. +
+ <32> + + The length of the MIME type string in bytes. +
+ <n*8> + + The MIME type string, in printable ASCII characters 0x20-0x7e. The MIME type may also be --> to signify that the data part is a URL of the picture instead of the picture data itself. +
+ <32> + + The length of the description string in bytes. +
+ <n*8> + + The description of the picture, in UTF-8. +
+ <32> + + The width of the picture in pixels. +
+ <32> + + The height of the picture in pixels. +
+ <32> + + The color depth of the picture in bits-per-pixel. +
+ <32> + + For indexed-color pictures (e.g. GIF), the number of colors used, or 0 for non-indexed pictures. +
+ <32> + + The length of the picture data in bytes. +
+ <n*8> + + The binary picture data. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + +
+ FRAME +
+ FRAME_HEADER + +   +
+ SUBFRAME+ + + One SUBFRAME per channel. +
+ <?> + + Zero-padding to byte alignment. +
+ FRAME_FOOTER + +   +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ FRAME_HEADER +
+ <14> + + Sync code '11111111111110' +
+ <1> + + Reserved:
+
    +
  • + 0 : mandatory value +
  • +
  • + 1 : reserved for future use +
  • +
+
+ <1> + + Blocking strategy:
+
    +
  • + 0 : fixed-blocksize stream; frame header encodes the frame number +
  • +
  • + 1 : variable-blocksize stream; frame header encodes the sample number +
  • +
+
+ <4> + + Block size in inter-channel samples:
+
    +
  • + 0000 : reserved +
  • +
  • + 0001 : 192 samples +
  • +
  • + 0010-0101 : 576 * (2^(n-2)) samples, i.e. 576/1152/2304/4608 +
  • +
  • + 0110 : get 8 bit (blocksize-1) from end of header +
  • +
  • + 0111 : get 16 bit (blocksize-1) from end of header +
  • +
  • + 1000-1111 : 256 * (2^(n-8)) samples, i.e. 256/512/1024/2048/4096/8192/16384/32768 +
  • +
+
+ <4> + + Sample rate:
+
    +
  • + 0000 : get from STREAMINFO metadata block +
  • +
  • + 0001 : 88.2kHz +
  • +
  • + 0010 : 176.4kHz +
  • +
  • + 0011 : 192kHz +
  • +
  • + 0100 : 8kHz +
  • +
  • + 0101 : 16kHz +
  • +
  • + 0110 : 22.05kHz +
  • +
  • + 0111 : 24kHz +
  • +
  • + 1000 : 32kHz +
  • +
  • + 1001 : 44.1kHz +
  • +
  • + 1010 : 48kHz +
  • +
  • + 1011 : 96kHz +
  • +
  • + 1100 : get 8 bit sample rate (in kHz) from end of header +
  • +
  • + 1101 : get 16 bit sample rate (in Hz) from end of header +
  • +
  • + 1110 : get 16 bit sample rate (in tens of Hz) from end of header +
  • +
  • + 1111 : invalid, to prevent sync-fooling string of 1s +
  • +
+
+ <4> + + Channel assignment +
    +
  • + 0000-0111 : (number of independent channels)-1. Where defined, the channel order follows SMPTE/ITU-R recommendations. The assignments are as follows: +
      +
    • 1 channel: mono
    • +
    • 2 channels: left, right
    • +
    • 3 channels: left, right, center
    • +
    • 4 channels: left, right, back left, back right
    • +
    • 5 channels: left, right, center, back/surround left, back/surround right
    • +
    • 6 channels: left, right, center, LFE, back/surround left, back/surround right
    • +
    • 7 channels: not defined
    • +
    • 8 channels: not defined
    • +
    +
  • +
  • + 1000 : left/side stereo: channel 0 is the left channel, channel 1 is the side(difference) channel +
  • +
  • + 1001 : right/side stereo: channel 0 is the side(difference) channel, channel 1 is the right channel +
  • +
  • + 1010 : mid/side stereo: channel 0 is the mid(average) channel, channel 1 is the side(difference) channel +
  • +
  • + 1011-1111 : reserved +
  • +
+
+ <3> + + Sample size in bits:
+
    +
  • + 000 : get from STREAMINFO metadata block +
  • +
  • + 001 : 8 bits per sample +
  • +
  • + 010 : 12 bits per sample +
  • +
  • + 011 : reserved +
  • +
  • + 100 : 16 bits per sample +
  • +
  • + 101 : 20 bits per sample +
  • +
  • + 110 : 24 bits per sample +
  • +
  • + 111 : reserved +
  • +
+
+ <1> + + Reserved:
+
    +
  • + 0 : mandatory value +
  • +
  • + 1 : reserved for future use +
  • +
+
+ <?> + + if(variable blocksize)
+    <8-56>:"UTF-8" coded sample number (decoded number is 36 bits)
+ else
+    <8-48>:"UTF-8" coded frame number (decoded number is 31 bits) +
+ <?> + + if(blocksize bits == 011x)
+    8/16 bit (blocksize-1) +
+ <?> + + if(sample rate bits == 11xx)
+    8/16 bit sample rate +
+ <8> + + CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0) of everything before the crc, including the sync code +
+ + NOTES
+
    +
  • + The "blocking strategy" bit must be the same throughout the entire stream. +
  • +
  • + The "blocking strategy" bit determines how to calculate the sample number of the first sample in the frame. If the bit is 0 (fixed-blocksize), the frame header encodes the frame number as above, and the frame's starting sample number will be the frame number times the blocksize. If it is 1 (variable-blocksize), the frame header encodes the frame's starting sample number itself. (In the case of a fixed-blocksize stream, only the last block may be shorter than the stream blocksize; its starting sample number will be calculated as the frame number times the previous frame's blocksize, or zero if it is the first frame). +
  • +
  • + The "UTF-8" coding used for the sample/frame number is the same variable length code used to store compressed UCS-2, extended to handle larger input. +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + +
+ FRAME_FOOTER +
+ <16> + + CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with 0) of everything before the crc, back to and including the frame header sync code +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ SUBFRAME +
+ SUBFRAME_HEADER + +   +
+ SUBFRAME_CONSTANT
|| SUBFRAME_FIXED
|| SUBFRAME_LPC
|| SUBFRAME_VERBATIM +
+ The SUBFRAME_HEADER specifies which one. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + +
+ SUBFRAME_HEADER +
+ <1> + + Zero bit padding, to prevent sync-fooling string of 1s +
+ <6> + + Subframe type: + +
+ <1+k> + + 'Wasted bits-per-sample' flag: +
    +
  • + 0 : no wasted bits-per-sample in source subblock, k=0 +
  • +
  • + 1 : k wasted bits-per-sample in source subblock, k-1 follows, unary coded; e.g. k=3 => 001 follows, k=7 => 0000001 follows. +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + +
+ SUBFRAME_CONSTANT +
+ <n> + + Unencoded constant value of the subblock, n = frame's bits-per-sample. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ SUBFRAME_FIXED +
+ <n> + + Unencoded warm-up samples (n = frame's bits-per-sample * predictor order). +
+ RESIDUAL + + Encoded residual +
+
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ SUBFRAME_LPC +
+ <n> + + Unencoded warm-up samples (n = frame's bits-per-sample * lpc order). +
+ <4> + + (Quantized linear predictor coefficients' precision in bits)-1 (1111 = invalid). +
+ <5> + + Quantized linear predictor coefficient shift needed in bits (NOTE: this number is signed two's-complement). +
+ <n> + + Unencoded predictor coefficients (n = qlp coeff precision * lpc order) (NOTE: the coefficients are signed two's-complement). +
+ RESIDUAL + + Encoded residual +
+
+
+ +
+ +
+
+ + + + + + + + +
+ SUBFRAME_VERBATIM +
+ <n*i> + + Unencoded subblock; n = frame's bits-per-sample, i = frame's blocksize. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ RESIDUAL +
+ <2> + + Residual coding method:
+
    +
  • + 00 : partitioned Rice coding with 4-bit Rice parameter; RESIDUAL_CODING_METHOD_PARTITIONED_RICE follows +
  • +
  • + 01 : partitioned Rice coding with 5-bit Rice parameter; RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 follows +
  • +
  • + 10-11 : reserved +
  • +
+
+ RESIDUAL_CODING_METHOD_PARTITIONED_RICE ||
+ RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 +
+   +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ RESIDUAL_CODING_METHOD_PARTITIONED_RICE +
+ <4> + + Partition order. +
+ RICE_PARTITION+ + + There will be 2^order partitions. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ RICE_PARTITION +
+ <4(+5)> + + Encoding parameter:
+
    +
  • + 0000-1110 : Rice parameter. +
  • +
  • + 1111 : Escape code, meaning the partition is in unencoded binary form using n bits per sample; n follows as a 5-bit number. +
  • +
+
+ <?> + + Encoded residual. The number of samples (n) in the partition is determined as follows:
+
    +
  • + if the partition order is zero, n = frame's blocksize - predictor order +
  • +
  • + else if this is not the first partition of the subframe, n = (frame's blocksize / (2^partition order)) +
  • +
  • + else n = (frame's blocksize / (2^partition order)) - predictor order +
  • +
+
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 +
+ <4> + + Partition order. +
+ RICE2_PARTITION+ + + There will be 2^order partitions. +
+
+
+ +
+ +
+
+ + + + + + + + + + + + +
+ RICE2_PARTITION +
+ <5(+5)> + + Encoding parameter:
+
    +
  • + 0000-11110 : Rice parameter. +
  • +
  • + 11111 : Escape code, meaning the partition is in unencoded binary form using n bits per sample; n follows as a 5-bit number. +
  • +
+
+ <?> + + Encoded residual. The number of samples (n) in the partition is determined as follows:
+
    +
  • + if the partition order is zero, n = frame's blocksize - predictor order +
  • +
  • + else if this is not the first partition of the subframe, n = (frame's blocksize / (2^partition order)) +
  • +
  • + else n = (frame's blocksize / (2^partition order)) - predictor order +
  • +
+
+
+
+ + + + + + diff --git a/flac/doc/html/id.html b/flac/doc/html/id.html new file mode 100644 index 0000000..ab2567d --- /dev/null +++ b/flac/doc/html/id.html @@ -0,0 +1,297 @@ + + + + + + + + + + + + + + + + FLAC - id + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ register +
+
+
+ FLAC allows third-party applications to register an ID for use with FLAC APPLICATION metadata blocks. Use the following form to request an ID, or to submit a change to an existing ID.
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
* Application ID:
* Application name:
* Contact e-mail:
Application URL:
Specification URL:
Comment:
(* = mandatory)
+
+
+ The ID request should be 8 hexadecimal digits and not conflict with any existing IDs (see the table below for all currently registered IDs). This 32-bit number will be stored big-endian in the block.
+
+ Information about your application (but not your e-mail address) will show up on this page in the ID directory. You can also provide a URL to your application and a URL reference to the specification of your application's APPLICATION block.
+
+ You will be notified via e-mail about your submission. +
+ +
+ +
+ +
+ +
+ +
+
+ Here is a list of all registered IDs and their applications:
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ID + + Application +
+ 41544348 - "ATCH" + + FlacFile +
+ 43756573 - "Cues" + + GoldWave cue points (specification) +
+ 4D754D4C - "MuML" + + MusicML: Music Metadata Language +
+ 46696361 - "Fica" + + CUE Splitter +
+ 46746F6C - "Ftol" + + flac-tools +
+ 4D505345 - "MPSE" + + MP3 Stream Editor +
+ 52494646 - "RIFF" + + Sound Devices RIFF chunk storage +
+ 5346464C - "SFFL" + + Sound Font FLAC +
+ 534F4E59 - "SONY" + + Sony Creative Software +
+ 5351455A - "SQEZ" + + flacsqueeze +
+ 61696666 - "aiff" + + FLAC AIFF chunk storage +
+ 7065656D - "peem" + + Parseable Embedded Extensible Metadata (specification) +
+ 71667374 - "qfst" + + QFLAC Studio +
+ 72696666 - "riff" + + FLAC RIFF chunk storage +
+ 74756E65 - "tune" + + TagTuner +
+ 77363420 - "w64 " + + FLAC Wave64 chunk storage +
+ 78626174 - "xbat" + + XBAT +
+ 786D6364 - "xmcd" + + xmcd +
+
+
+ +
+ + + + + + diff --git a/flac/doc/html/images/1x1.gif b/flac/doc/html/images/1x1.gif new file mode 100644 index 0000000..f14ea13 Binary files /dev/null and b/flac/doc/html/images/1x1.gif differ diff --git a/flac/doc/html/images/Makefile.am b/flac/doc/html/images/Makefile.am new file mode 100644 index 0000000..8ecd03f --- /dev/null +++ b/flac/doc/html/images/Makefile.am @@ -0,0 +1,30 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = hw + +docdir = $(datadir)/doc/$(PACKAGE)-$(VERSION)/html/images + +doc_DATA = \ + 1x1.gif \ + cafebug.gif \ + logo100.gif \ + logo130.gif + +EXTRA_DIST = $(doc_DATA) diff --git a/flac/doc/html/images/cafebug.gif b/flac/doc/html/images/cafebug.gif new file mode 100644 index 0000000..3d0c90f Binary files /dev/null and b/flac/doc/html/images/cafebug.gif differ diff --git a/flac/doc/html/images/hw/Blackbird_Front_low3_325x87.jpg b/flac/doc/html/images/hw/Blackbird_Front_low3_325x87.jpg new file mode 100644 index 0000000..ac8e17e Binary files /dev/null and b/flac/doc/html/images/hw/Blackbird_Front_low3_325x87.jpg differ diff --git a/flac/doc/html/images/hw/MS300frontsmall_270x108.jpg b/flac/doc/html/images/hw/MS300frontsmall_270x108.jpg new file mode 100644 index 0000000..e713335 Binary files /dev/null and b/flac/doc/html/images/hw/MS300frontsmall_270x108.jpg differ diff --git a/flac/doc/html/images/hw/Makefile.am b/flac/doc/html/images/hw/Makefile.am new file mode 100644 index 0000000..58cbc0b --- /dev/null +++ b/flac/doc/html/images/hw/Makefile.am @@ -0,0 +1,52 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +AUTOMAKE_OPTIONS = foreign + +docdir = $(datadir)/doc/$(PACKAGE)-$(VERSION)/html/images/hw + +doc_DATA = \ + Blackbird_Front_low3_325x87.jpg \ + MS300frontsmall_270x108.jpg \ + MediaBox_Frt_170x325.jpg \ + SB_Hero_Black_325x182.jpg \ + Sooloos-ControlOne_325x328.jpg \ + Z500_front_325x94.jpg \ + a2_01_325x252.jpg \ + arcus_325x135.jpg \ + bmp-1430_325x241.jpg \ + cs505_front_lrg_325x113.jpg \ + enus_3-4lft-hires_product_eva8000_325x127.jpg \ + escient_ProductLine_325x163.jpg \ + hifidelio_bl_front_Z_RGB_325x163.jpg \ + i-station-mini-dx_325x237.jpg \ + iwod-g10_325x257.jpg \ + knc_hr-2800_325x209.jpg \ + mediaready_prodmain_MRMCa_325x232.jpg \ + meizu_m6_325x206.jpg \ + musica_artwork_325x90.jpg \ + neodigits_x5000_325x124.jpg \ + onda-vx737_325x240.jpg \ + request_n_front_325x103.jpg \ + rio_karma_279x254.jpg \ + sonos_family_RGB_325x200.jpg \ + teclast-tl29_325x244.jpg \ + transporter_hero_grey_325x208.jpg \ + tvix-4000_325x204.jpg \ + vibez_nofm_combi_black_b_325x220.jpg + +EXTRA_DIST = $(doc_DATA) diff --git a/flac/doc/html/images/hw/MediaBox_Frt_170x325.jpg b/flac/doc/html/images/hw/MediaBox_Frt_170x325.jpg new file mode 100644 index 0000000..6fc2ed4 Binary files /dev/null and b/flac/doc/html/images/hw/MediaBox_Frt_170x325.jpg differ diff --git a/flac/doc/html/images/hw/SB_Hero_Black_325x182.jpg b/flac/doc/html/images/hw/SB_Hero_Black_325x182.jpg new file mode 100644 index 0000000..ddaf443 Binary files /dev/null and b/flac/doc/html/images/hw/SB_Hero_Black_325x182.jpg differ diff --git a/flac/doc/html/images/hw/Sooloos-ControlOne_325x328.jpg b/flac/doc/html/images/hw/Sooloos-ControlOne_325x328.jpg new file mode 100644 index 0000000..5e173a5 Binary files /dev/null and b/flac/doc/html/images/hw/Sooloos-ControlOne_325x328.jpg differ diff --git a/flac/doc/html/images/hw/Z500_front_325x94.jpg b/flac/doc/html/images/hw/Z500_front_325x94.jpg new file mode 100644 index 0000000..4b8036e Binary files /dev/null and b/flac/doc/html/images/hw/Z500_front_325x94.jpg differ diff --git a/flac/doc/html/images/hw/a2_01_325x252.jpg b/flac/doc/html/images/hw/a2_01_325x252.jpg new file mode 100644 index 0000000..10d7170 Binary files /dev/null and b/flac/doc/html/images/hw/a2_01_325x252.jpg differ diff --git a/flac/doc/html/images/hw/arcus_325x135.jpg b/flac/doc/html/images/hw/arcus_325x135.jpg new file mode 100644 index 0000000..b3dc9fe Binary files /dev/null and b/flac/doc/html/images/hw/arcus_325x135.jpg differ diff --git a/flac/doc/html/images/hw/bmp-1430_325x241.jpg b/flac/doc/html/images/hw/bmp-1430_325x241.jpg new file mode 100644 index 0000000..1d91b95 Binary files /dev/null and b/flac/doc/html/images/hw/bmp-1430_325x241.jpg differ diff --git a/flac/doc/html/images/hw/cs505_front_lrg_325x113.jpg b/flac/doc/html/images/hw/cs505_front_lrg_325x113.jpg new file mode 100644 index 0000000..34123d2 Binary files /dev/null and b/flac/doc/html/images/hw/cs505_front_lrg_325x113.jpg differ diff --git a/flac/doc/html/images/hw/enus_3-4lft-hires_product_eva8000_325x127.jpg b/flac/doc/html/images/hw/enus_3-4lft-hires_product_eva8000_325x127.jpg new file mode 100644 index 0000000..9f3ad22 Binary files /dev/null and b/flac/doc/html/images/hw/enus_3-4lft-hires_product_eva8000_325x127.jpg differ diff --git a/flac/doc/html/images/hw/escient_ProductLine_325x163.jpg b/flac/doc/html/images/hw/escient_ProductLine_325x163.jpg new file mode 100644 index 0000000..cc6008e Binary files /dev/null and b/flac/doc/html/images/hw/escient_ProductLine_325x163.jpg differ diff --git a/flac/doc/html/images/hw/hifidelio_bl_front_Z_RGB_325x163.jpg b/flac/doc/html/images/hw/hifidelio_bl_front_Z_RGB_325x163.jpg new file mode 100644 index 0000000..ca98f30 Binary files /dev/null and b/flac/doc/html/images/hw/hifidelio_bl_front_Z_RGB_325x163.jpg differ diff --git a/flac/doc/html/images/hw/i-station-mini-dx_325x237.jpg b/flac/doc/html/images/hw/i-station-mini-dx_325x237.jpg new file mode 100644 index 0000000..b18b33a Binary files /dev/null and b/flac/doc/html/images/hw/i-station-mini-dx_325x237.jpg differ diff --git a/flac/doc/html/images/hw/iwod-g10_325x257.jpg b/flac/doc/html/images/hw/iwod-g10_325x257.jpg new file mode 100644 index 0000000..1baf2f8 Binary files /dev/null and b/flac/doc/html/images/hw/iwod-g10_325x257.jpg differ diff --git a/flac/doc/html/images/hw/knc_hr-2800_325x209.jpg b/flac/doc/html/images/hw/knc_hr-2800_325x209.jpg new file mode 100644 index 0000000..737236c Binary files /dev/null and b/flac/doc/html/images/hw/knc_hr-2800_325x209.jpg differ diff --git a/flac/doc/html/images/hw/mediaready_prodmain_MRMCa_325x232.jpg b/flac/doc/html/images/hw/mediaready_prodmain_MRMCa_325x232.jpg new file mode 100644 index 0000000..4f1dd2d Binary files /dev/null and b/flac/doc/html/images/hw/mediaready_prodmain_MRMCa_325x232.jpg differ diff --git a/flac/doc/html/images/hw/meizu_m6_325x206.jpg b/flac/doc/html/images/hw/meizu_m6_325x206.jpg new file mode 100644 index 0000000..b915e2e Binary files /dev/null and b/flac/doc/html/images/hw/meizu_m6_325x206.jpg differ diff --git a/flac/doc/html/images/hw/musica_artwork_325x90.jpg b/flac/doc/html/images/hw/musica_artwork_325x90.jpg new file mode 100644 index 0000000..03d559c Binary files /dev/null and b/flac/doc/html/images/hw/musica_artwork_325x90.jpg differ diff --git a/flac/doc/html/images/hw/neodigits_x5000_325x124.jpg b/flac/doc/html/images/hw/neodigits_x5000_325x124.jpg new file mode 100644 index 0000000..0f752f0 Binary files /dev/null and b/flac/doc/html/images/hw/neodigits_x5000_325x124.jpg differ diff --git a/flac/doc/html/images/hw/onda-vx737_325x240.jpg b/flac/doc/html/images/hw/onda-vx737_325x240.jpg new file mode 100644 index 0000000..e6e399f Binary files /dev/null and b/flac/doc/html/images/hw/onda-vx737_325x240.jpg differ diff --git a/flac/doc/html/images/hw/request_n_front_325x103.jpg b/flac/doc/html/images/hw/request_n_front_325x103.jpg new file mode 100644 index 0000000..bfea9f6 Binary files /dev/null and b/flac/doc/html/images/hw/request_n_front_325x103.jpg differ diff --git a/flac/doc/html/images/hw/rio_karma_279x254.jpg b/flac/doc/html/images/hw/rio_karma_279x254.jpg new file mode 100644 index 0000000..fb11523 Binary files /dev/null and b/flac/doc/html/images/hw/rio_karma_279x254.jpg differ diff --git a/flac/doc/html/images/hw/sonos_family_RGB_325x200.jpg b/flac/doc/html/images/hw/sonos_family_RGB_325x200.jpg new file mode 100644 index 0000000..8dfa030 Binary files /dev/null and b/flac/doc/html/images/hw/sonos_family_RGB_325x200.jpg differ diff --git a/flac/doc/html/images/hw/teclast-tl29_325x244.jpg b/flac/doc/html/images/hw/teclast-tl29_325x244.jpg new file mode 100644 index 0000000..c780267 Binary files /dev/null and b/flac/doc/html/images/hw/teclast-tl29_325x244.jpg differ diff --git a/flac/doc/html/images/hw/transporter_hero_grey_325x208.jpg b/flac/doc/html/images/hw/transporter_hero_grey_325x208.jpg new file mode 100644 index 0000000..558413b Binary files /dev/null and b/flac/doc/html/images/hw/transporter_hero_grey_325x208.jpg differ diff --git a/flac/doc/html/images/hw/tvix-4000_325x204.jpg b/flac/doc/html/images/hw/tvix-4000_325x204.jpg new file mode 100644 index 0000000..576e7b8 Binary files /dev/null and b/flac/doc/html/images/hw/tvix-4000_325x204.jpg differ diff --git a/flac/doc/html/images/hw/vibez_nofm_combi_black_b_325x220.jpg b/flac/doc/html/images/hw/vibez_nofm_combi_black_b_325x220.jpg new file mode 100644 index 0000000..2be9e43 Binary files /dev/null and b/flac/doc/html/images/hw/vibez_nofm_combi_black_b_325x220.jpg differ diff --git a/flac/doc/html/images/logo100.gif b/flac/doc/html/images/logo100.gif new file mode 100644 index 0000000..a078a4b Binary files /dev/null and b/flac/doc/html/images/logo100.gif differ diff --git a/flac/doc/html/images/logo130.gif b/flac/doc/html/images/logo130.gif new file mode 100644 index 0000000..5d0da8b Binary files /dev/null and b/flac/doc/html/images/logo130.gif differ diff --git a/flac/doc/html/index.html b/flac/doc/html/index.html new file mode 100644 index 0000000..a725be0 --- /dev/null +++ b/flac/doc/html/index.html @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + FLAC - Free Lossless Audio Codec + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ + + + + + + + +
+ +
+ +
+
+ FLAC stands for Free Lossless Audio Codec, an audio format similar to MP3, but lossless, meaning that audio is compressed in FLAC without any loss in quality. This is similar to how Zip works, except with FLAC you will get much better compression because it is designed specifically for audio, and you can play back compressed FLAC files in your favorite player (or your car or home stereo, see supported devices) just like you would an MP3 file.
+
+ FLAC stands out as the fastest and most widely supported lossless audio codec, and the only one that at once is non-proprietary, is unencumbered by patents, has an open-source reference implementation, has a well documented format and API, and has several other independent implementations.
+
+ See About FLAC for more, or Using FLAC for how to play FLAC files, rip CDs to FLAC, etc. +
+ +
+ +
+ +
+ +
+
+ FLAC 1.2.1 released  New in this release is support for all RIFF/AIFF metadata, including Broadcast Wave Format (BWF). There are many other small improvements and bug fixes; see the changelog entry for complete details.
+
+ The new Denon AVR-4308DAB receiver supports FLAC.
+
+ Sound Forge 9.0b supports FLAC, for both reading and writing.
+
+ An installer for flac-1.1.4 on OS X is now available. This includes universal binaries that will work on both Intel and PowerPC machines. A 1.2.0 update will be available soon.
+
+ Czech Radio has released complete recordings of Bach's Brandenburg concertos in FLAC format, free to download.
+
+ A handful of new devices support FLAC: for home stereo, there are Denon's upcoming tabletop players SE-32 and SE-52 and Escient's FireBall SE500; for portables, the Blast from OPPO, Hyundai's NH-260, the Zarva MV209, this generically-named Portable Media Player, and the Gemei X-750.
+
+ last updated 2007-Sep-17 +
+ +
+ +
+ +
+
+ news +
+
+
+ 17-Sep-2007 :
FLAC 1.2.1 released

+ 16-Aug-2007 :
Sound Forge 9.0b supports FLAC

+ 03-Aug-2007 :
Czech Radio releases free FLAC recordings

+ 23-Jul-2007 :
FLAC 1.2.0 released

+ 13-Feb-2007 :
FLAC 1.1.4 released

+ 27-Nov-2006 :
FLAC 1.1.3 released

+ 25-Oct-2006 :
Winamp 5.31 ships with FLAC support

+ 20-Dec-2005 :
Volvo's Digital Jukebox plays FLAC

+ 21-Sep-2005 :
Live2496 now records directly to FLAC

+ 10-Aug-2005 :
Olive's new Symphony component supports FLAC

+ 11-May-2005 :
YME supports FLAC and Vorbis

+ 10-May-2005 :
PONTIS' MS330 supports FLAC and Vorbis

+ 02-May-2005 :
Sonos now supports FLAC and Vorbis

+ 23-Apr-2005 :
iAUDIO X5 portable supports FLAC and Vorbis

+ 09-Mar-2005 :
Squeezebox2 supports FLAC on the box

+ 05-Feb-2005 :
Version 1.1.2 released

+ (all news) +
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/itunes.html b/flac/doc/html/itunes.html new file mode 100644 index 0000000..bab6c3e --- /dev/null +++ b/flac/doc/html/itunes.html @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + FLAC - itunes + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ flac + itunes +
+
+
+ Would you like iTunes to support FLAC? So would we!
+
+ Due to the design of iTunes, only Apple can add support for FLAC [1]. And why wouldn't they? FLAC usage is accelerating, many bands like Pearl Jam, Phish, Dave Matthews Band, Metallica -- the same hip, influential people whose fans Apple courts -- are already distributing music in FLAC format, and users are clamoring for it in the iTunes forums:
+
    +
  • [2] "I have seen a lot of people on live music message boards turn away from the iPod because there are other music players that support FLAC. I am on the verge... and I am an Apple die-hard!"
  • +
  • [3] "If your source material is FLAC (as many bands have gone this way to distribute online music) your choice is to use another music player ..."
  • +
  • [4] (many more requests)
  • +
+ Make your voice heard! Fill out the iTunes feedback form (politely!) and let them know. Feel free to also direct them to this page. We at the FLAC project stand ready to help as well.
+
+
+
+ [1] XiphQT, through tremendous effort by developers, goes as far as possible in allowing some playback capability via QuickTime. But proper iTunes support -- tag handling, no import delays, etc. -- is not possible without Apple.
+
+ +
+ + + + + + diff --git a/flac/doc/html/license.html b/flac/doc/html/license.html new file mode 100644 index 0000000..b3dc0e7 --- /dev/null +++ b/flac/doc/html/license.html @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + FLAC - license + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ license +
+
+
+ FLAC is a free codec in the fullest sense. This page explicitly states all that you may do with the format and software.
+
+ The FLAC and Ogg FLAC formats themselves, and their specifications, are fully open to the public to be used for any purpose (the FLAC project reserves the right to set the FLAC specification and certify compliance). They are free for commercial or noncommercial use. That means that commercial developers may independently write FLAC or Ogg FLAC software which is compatible with the specifications for no charge and without restrictions of any kind. There are no licensing fees or royalties of any kind for use of the formats or their specifications, or for distributing, selling, or streaming media in the FLAC or Ogg FLAC formats.
+
+ The FLAC project also makes available software that implements the formats, which is distributed according to Open Source licenses as follows:
+
+ The reference implementation libraries are licensed under the New BSD License. In simple terms, these libraries may be used by any application, Open or proprietary, linked or incorporated in whole, so long as acknowledgement is made to Xiph.org Foundation when using the source code in whole or in derived works. The Xiph License is free enough that the libraries have been used in commercial products to implement FLAC, including in the firmware of hardware devices where other Open Source licenses can be problematic. In the source code these libraries are called libFLAC and libFLAC++.
+
+ The rest of the software that the FLAC project provides is licensed under the GNU General Public License (GPL). This software includes various utilities for converting files to and from FLAC format, plugins for audio players, et cetera. In general, the GPL allows redistribution as long as derived works are also made available in source code form according to compatible terms.
+
+ Neither the FLAC nor Ogg FLAC formats nor any of the implemented encoding/decoding methods are covered by any known patent.
+
+ FLAC is one of a family of codecs of the Xiph.org Foundation, all created according to the same free ideals. For some other codecs' descriptions of the Xiph License see the Speex and Vorbis license pages.
+
+ If you would like to redistribute parts or all of FLAC under different terms, contact Josh Coalson. +
+ +
+ + + + + + diff --git a/flac/doc/html/links.html b/flac/doc/html/links.html new file mode 100644 index 0000000..9653831 --- /dev/null +++ b/flac/doc/html/links.html @@ -0,0 +1,485 @@ + + + + + + + + + + + + + + + + FLAC - links + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ links +
+
+
+ The links page is the place for all things FLAC. The hardware section lists the home stereo, car stereo, and portable devices that support the FLAC format. The music section has links to artists, labels, and legal trading/sharing sites that offer works encoded in FLAC. The software section is a loosely categorized list of open-source software that supports the FLAC format. Some of the most popular (some non-free) software can be found on the download page in the extras section. +
+ +
+ +
+ +
+
+ hardware +
+
+
+ Below are some devices that support the FLAC format. For the ones we have hands-on experience with, there is a linked review (see all reviews). Manufacturers, if you would like your product reviewed here, please contact us.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Home stereo:
Squeezebox
(our review)
Transporter
(our review)
Sonos
(our review)
EscientHifidelioOlive
Arcus DAR300BlackbirdMcIntosh MS300
Helios X5000Netgear EVA8000ReQuest
MediaREADY MCZensonic Z500Ziova
SooloosHD MediaBoxTViX 4/5000 Series
+
+ Other home stereo: + +
+
+ Car stereo: + +
Portable/Handheld:
Cowon iAUDIOi-Station mini DXIwod G10
KNC HR-2800Meizu M6 MiniplayerOnda VX737
Rio KarmaTeclast TL-29TrekStor Vibez
Bluedot BMP-1430
+
+ Other Portable/Handheld: + +
+
+ Other: +
    +
  • Numark's DJ equipment like the HDX and CDX turntables with integrated hard drive and CD player, and the HDMIX mixer
  • +
  • The Pico CD/DVD Duplicator
  • +
+
+ Reviews:
+ The main purpose of these reviews is to give an idea of how well particular devices support FLAC. Other subjective comments here are based on our general impressions and are not meant to be thorough or authoritative. We only review devices we have tested directly ourselves.
+
+
Sonos: A very slick networked audio system. Each ZonePlayer connects to an amplifier or speakers, accessing music over the network. ZonePlayers are controlled by a wireless remote with color LCD and clickwheel; they can network together wired or wireless and play in sync or independently. FLAC support is excellent; nearly the full subset (i.e. mono and stereo files, sample rates from 16kHz-48kHz, 16-bits per sample) including all standard encoding modes are supported. Also supported: gapless playback, FLAC tags, and ReplayGain.
+
+
Squeezebox: A fantastic networked audio player from Slim Devices with analog and digital outputs for connecting to an amplifier/receiver. Has an easy-to-read vacuum fluorescent display, wired or wireless networking, multi-room synchronization, and a bunch of other features. The server-side software, SlimServer, is open-source, runs on Windows, Mac OS X, Linux, etc. and has an active community. FLAC support is excellent; nearly the full subset (i.e. mono and stereo files, sample rates from 8kHz-48kHz, 16- and 24-bits per sample) including all standard encoding modes are supported. Also supported: gapless playback, FLAC tags, ReplayGain, automatic transcoding on the server of many audio formats to FLAC for transmission to the box, and external cuesheet support (internal cuesheet support is in the works).
+
+ Transporter: Top-of-the-line networked audio player from Slim Devices. Offers all the features of the Squeezebox (see just above), but loaded with pro-grade connectors (including balanced analog outputs and optical/coax/BNC/XLR digital ins and outs), top-end components, and a larger display. FLAC support is also excellent; all standard FLAC encoding modes and tags are supported, as are gapless playback, ReplayGain, cuesheets ... everything the Squeezebox supports, plus support for sample rates up to 96kHz.
+
+ + + + + +
Compression
modes
ChannelsSample
rates
Sample
resolution
GaplessFLAC tagsCover artReplayGainCuesheets
Sonos0-8stereo,mono16kHz-48kHz16bpsYYNYN
Squeezebox0-8stereo,mono8kHz-48kHz16bps, 24bpsYYNYY (external)
Transporter0-8stereo,mono8kHz-96kHz16bps, 24bpsYYNYY (external)
+
+ +
+ +
+ +
+
+ music +
+
+
+ Several labels and artists have adopted FLAC as a distribution format for their works, offering them for sale or free download online. And many online trading communities that share legal, band-sanctioned recordings of live shows distribute them in FLAC format. These are just some of them.
+
+ Artists + + Labels and Stores + + Venues: + + Communities: + +
+ +
+ +
+ +
+
+ software +
+
+
+ A large and growing list of software supports the FLAC format. This list is a sample of open-source software supporting FLAC. Some of the most popular non-free software can be found on the download page in the extras section.
+
+ Audio encoders/decoders/converters/taggers: +
    +
  • BonkEnc: Windows CD ripper, audio encoder and converter
  • +
  • EasyTAG versatile tagger
  • +
  • Entagged, a Java audio file tagger
  • +
  • etree-scripts: command-line tools for verifying, tagging, converting, and burning lossless audio files
  • +
  • FLAC frontend (Windows GUI)
  • +
  • Flac-Jacket: a set of scripts for creating FLAC files and an HTML index
  • +
  • FLACTAG: tags single album FLAC files with embedded CUE sheets using data from the MusicBrainz service
  • + +
  • MacFLAC Mac OS X FLAC distribution
  • +
  • MediaCoder converts between many audio and video formats.
  • +
  • MP3FS, a read-only FUSE filesystem which can transcode FLAC to MP3 on the fly
  • +
  • rawrec/rawplay recording/playback tools
  • +
  • sonice FLAC to Vorbis transcoder
  • +
  • Split_wav WAV+CUE splitter
  • +
  • Tag comprehensive tagger (frontend available)
  • +
  • XLD (X Lossless Decoder), a Universal Binary command-line decoder for Mac OS X
  • +
+ Audio editors: + + Audio players/servers: + + CD ripping/burning: +
    +
  • Arson: KDE ripper/burner
  • +
  • AutoFLAC: automated ripping and encoding to FLAC with EAC (ExactAudioCopy); also has a write mode for burning back to CD for an exact copy
  • +
  • CDex: ripper for Windows can rip to FLAC via external command
  • +
  • crip: console ripper/encoder/tagger
  • +
  • Flacattack: an all-in-one tool that works with EAC (ExactAudioCopy) to encode a CD image to FLAC, embed the cuesheet, add ReplayGain, create lossy files, etc. all in a customizable directory structure
  • +
  • grip: ripper for Linux can rip to FLAC via external command
  • +
  • K3B: CD/DVD creator for Linux
  • +
  • MAREO multi-format encoder for EAC
  • +
  • Max, a CD ripper and encoder for OS X
  • +
  • Omni Encoder, a graphical multi-format encoder for EAC
  • +
  • rip command-line ripper/encoder
  • +
  • RipIT, a console-based front-end to several ripping and encoding tools
  • +
  • Wack, the successor to Flacattack which can encode to multiple formats at once
  • +
+ Organizers: +
    +
  • Ampache, a PHP-based tool for managing, updating and playing files via a web interface
  • +
  • GNUpod includes on-the-fly FLAC conversion to iPod
  • +
  • MPEG Audio Collection
  • +
  • prokyon3, a Qt-based music manager and tag editor
  • +
  • Rhythmbox, music management application for GNOME
  • +
+ Plugins, developer tools and libraries: + + Scientific, Audio Analysis: +
    + +
  • HASAS HydroAcoustical Signal Analysis System
  • +
+ +
+ +
+ + + + + + diff --git a/flac/doc/html/news.html b/flac/doc/html/news.html new file mode 100644 index 0000000..f8c1ebd --- /dev/null +++ b/flac/doc/html/news.html @@ -0,0 +1,697 @@ + + + + + + + + + + + + + + + + FLAC - news + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ news +
+
+
+ + 17-Sep-2007: +
    +
  • + FLAC 1.2.1 released  New in this release is support for all RIFF/AIFF metadata, including Broadcast Wave Format (BWF). There are many other small improvements and bug fixes; see the changelog entry for complete details. +
  • +
+ + 16-Aug-2007: + + + 03-Aug-2007: + + + 23-Jul-2007: +
    +
  • + FLAC 1.2.0 released  New in this release are small speed improvements, and some new options and bug fixes. Also the decoder has been updated to pave the way for some format improvements, so if your software supports FLAC be sure to check it out. See the changelog entry for complete details. +
  • +
+ + 13-Feb-2007: +
    +
  • + FLAC 1.1.4 released  Increased compression and dramatic speedups for both encoding and decoding are the big improvements in FLAC 1.1.4. There are also several new options and bugfixes. See the changelog entry for complete details. +
  • +
+ + 27-Nov-2006: +
    +
  • + FLAC 1.1.3 released  Almost 2 years in the making, FLAC 1.1.3 is a major release with improved compression, improved cover art and multichannel support, better recovery for corrupted files, many new features and options in the command-line tools, and several bug fixes. For developers, the decoder and encoder APIs have also been simplified and there is a new porting guide. See the changelog entry for complete details. +
  • +
+ + 25-Oct-2006: +
    +
  • + Winamp 5.31 ships with FLAC support
    +
    + Winamp 5.31 now includes Nullsoft FLAC plugins for encoding and decoding. The decoder is based on our reference decoder plugin. However the current encoder plugin is based on a pre-release of flake and we recommend to not use it for archival yet. +
  • +
+ + 20-Dec-2005: +
    +
  • + Volvo's Digital Jukebox plays FLAC
    +
    + Want some FLAC with your Volvo? Volvo's Digital Jukebox, developed with PhatNoise, is fully integrated with the car's audio system and available for the S60, V70, XC70, and S80. PhatNoise's PhatBox in 2002 was the first device to support FLAC natively and has gained a loyal following. The Digital Jukebox and PhatBox also support Ogg Vorbis. +
  • +
+ + 21-Sep-2005: +
    +
  • + Live2496 now records directly to FLAC
    +
    + Live2496, a program that can record 24-bit audio up to 96kHz on a Pocket PC (using Core Sound's PDAudio interface) now supports recording directly to FLAC. +
  • +
+ + 10-Aug-2005: +
    +
  • + Olive's new Symphony component supports FLAC
    +
    + The new Symphony wireless digital music center by Olive supports FLAC. +
  • +
+ + 11-May-2005: +
    +
  • + YME supports FLAC and Vorbis
    +
    + Yahoo! Music Engine supports FLAC and Ogg Vorbis, for playback and ripping/encoding. +
  • +
+ + 10-May-2005: +
    +
  • + PONTIS' MS330 supports FLAC and Vorbis
    +
    + The new MS330 Media Server from PONTIS supports FLAC and Ogg Vorbis. In addition to playing from the internal hard disk, CD drive, and 6-in-1 flash card slot, it can also be connected to a network, and even a TV for graphical navigation, cover art, photo viewing, etc. +
  • +
+ + 02-May-2005: + + + 23-Apr-2005: +
    +
  • + iAUDIO X5 portable supports FLAC and Vorbis
    +
    + The new portable iAUDIO X5 from COWON supports FLAC and Ogg Vorbis. +
  • +
+ + 09-Mar-2005: +
    +
  • + Squeezebox2 supports FLAC on the box
    +
    + Slim Devices' new Squeezebox2 supports FLAC decoding on the box, reducing the amount of precious wireless bandwidth required for FLAC playback. +
  • +
+ + 05-Feb-2005: +
    +
  • + FLAC 1.1.2 released  New in this release are small decoding speedups for all platforms, small encoding speedups in fast (non-LPC) mode, streaming support in the XMMS plugin, and several bug fixes. For developers there are also a few additions and changes to the metadata API to make working with tags easier. See the changelog entry for complete details. This release actually wasn't supposed to happen so soon, but needed to be made to fix library naming and build problems in FLAC 1.1.1 that caused trouble for package maintainers, so unless you are having trouble with one of the particular bugs that got fixed in 1.1.2 then there is not much of a need to upgrade. +
  • +
+ + 17-Jan-2005: + + + 12-Nov-2004: +
    +
  • + Escient's new FireBall E2-300 supports FLAC
    +
    + Escient has a new home stereo component that supports FLAC, the FireBall E2-300. +
  • +
+ + 02-Nov-2004: +
    +
  • + New Mindawn music store offers FLAC and Vorbis
    +
    + Mindawn, a new online music service offering FLAC and Ogg Vorbis, is now open. They also have a multi-platform (Windows, Linux, Mac OS X) CD ripper/encoder and are finishing up a multi-platform player. +
  • +
+ + 01-Oct-2004: +
    +
  • + FLAC 1.1.1 released  There is a new changelog with a complete list of changes/fixes/improvements, but here is a summary of some of the main ones: +
      +
    • Better Ogg FLAC support including seeking and an official Ogg FLAC mapping.
    • +
    • Significant decoding speedup (almost 2x) on PowerPC (includes Macs with G4/G5).
    • +
    • Speedups in the plugins.
    • +
    • Several new options to flac and metaflac by popular demand.
    • +
    • Several API additions requested by developers.
    • +
    • Many bugfixes.
    • +
    +
  • +
+ + 27-Jul-2004: + + + 21-Jun-2004: + + + 03-Mar-2004: + + + 03-Feb-2004: + + + 19-Nov-2003: +
    +
  • + PhatNoise's new Home Digital Media Player supports FLAC
    +
    + PhatNoise (makers of the PhatBox, which also plays FLAC) just released their Home Digital Media Player. It includes a DMS cartridge slot so you can pop out your FLAC tunes and pop 'em in your car. +
  • +
+ + 18-Nov-2003: +
    +
  • + Slim's new 'Squeezebox' supports FLAC
    +
    + Slim Devices' new Squeezebox, the wireless follow-on to the SliMP3 networked audio player, is available and supports FLAC and Ogg Vorbis. +
  • +
+ + 11-Nov-2003: +
    +
  • + Primus offers live shows in FLAC
    +
    + Primus is offering soundboard recordings from 2003 Tour de Fromage in FLAC and MP3 on primuslive.com. More info here and here. +
  • +
+ + 13-Oct-2003: + + + 11-Aug-2003: +
    +
  • + New Rio Karma supports FLAC
    +
    + Rio has announced a new portable, the Rio Karma, which supports FLAC and Ogg Vorbis. +
  • +
+ + 23-Jun-2003: +
    +
  • + livephish.com offers FLAC shows
    +
    + livephish.com is now offering soundboard recordings of live shows in FLAC format in addition to MP3. +
  • +
+ + 09-Feb-2003: + + + 29-Jan-2003: +
    +
  • + FLAC has joined the Xiph project  See here for the press release.
    +
    + Xiph.org is behind other free codecs such as Vorbis, Theora, and Speex. Our merger with Xiph will bring FLAC into the ranks and lead to better integration with the Ogg multimedia framework.
    +
    + Note that the FLAC format is not changing, native FLAC will continue to exist, and the command-line tools and plugins will continue to work as before. The codec libraries will now be available under Xiph's BSD-like license.
    +
    + Over the next few days we will be transitioning normal operations off SourceForge and over to Xiph.org; first will be CVS and the web pages, followed by the mailing lists, bug tracker, and file release area. We will keep a mirror here until the transition is complete. It's OK to send patches to the flac-dev list but they won't be able to be integrated until CVS is fully moved over. +
  • +
+ + 26-Jan-2003: +
    +
  • + FLAC 1.1.0 released  I didn't get everything in that I wanted, but it's high time for a release.
    +
    + Note that the minor version has incremented, meaning forward compatibility was broken (forward compatibility means an earlier decoder can play all streams made by a later decoder). This is only because of a bug in 1.0.4 and prior where the decoder could not properly skip unknown metadata. The stream format itself has not changed and FLAC is still fully backward-compatible. All it means is that a FLAC file containing cue sheet metadata will not decode in older decoders. This bug is fixed in 1.1.0.
    +
    + Here's what's new:
    +
    + General: +
      +
    • All code is now Valgrind-clean!
    • +
    • New CUESHEET metadata block for storing CD TOC and index point information. Now a CD can be completely backed up to a single FLAC file for archival.
    • +
    • ReplayGain support.
    • +
    • Better compression of 24-bit files.
    • +
    • More complete AIFF support.
    • +
    • 3DNow! optimizations enabled by default.
    • +
    • Complete MSVC build system with .dsp projects for everything, which can build both static libs and DLLs, and in debug or release mode, all in the same source tree.
    • +
    + flac: +
      +
    • Can now decode FLAC to AIFF; new --force-aiff-format option.
    • +
    • New --cuesheet option for reading and storing a cuesheet when encoding a whole CD. Automatically creates seek points for track and index points unless --no-cued-seekpoints is used.
    • +
    • New --replay-gain option for calculating ReplayGain values and storing them as tags.
    • +
    • New --until option complements --skip to stop decoding at a specified point in the stream.
    • +
    • --skip and --until now also accept mm:ss.ss format.
    • +
    • New -S #s flavor to specify seekpoints every '#' number of seconds.
    • +
    • flac now defaults to -S 10s instead of -S 100x for the seek table.
    • +
    • flac now adds a 4k PADDING block by default (turn off with --no-padding).
    • +
    • Fixed a bug with --skip and AIFF-to-FLAC encoding.
    • +
    • Fixed a bug where decoding a FLAC file whose total_samples==0 in the STREAMINFO would corrupt the WAVE header.
    • +
    + metaflac: +
      +
    • New --import-cuesheet-from option for reading and storing a cuesheet to a FLAC-encoded CD. Automatically creates seek points for track and index points unless --no-cued-seekpoints is used.
    • +
    • New --export-cuesheet-to option for writing a cuesheet from a FLAC file for use with CD authoring software.
    • +
    • New --add-replay-gain option for calculating ReplayGain values and storing them as tags.
    • +
    • New --add-seekpoint option to add seekpoints to an existing FLAC file. Includes new --add-seekpoint=#s flavor to add seekpoints every '#' number of seconds.
    • +
    + XMMS plugin: +
      +
    • Configurable sample resolution conversion with dither.
    • +
    • ReplayGain support with customizable noise shaping, pre-amp, and optional hard limiter.
    • +
    • New Vorbis comment editor.
    • +
    • File info now works.
    • +
    • Bitrate now shows the smoothed instantaneous bitrate.
    • +
    • Uses the ARTIST tag if there is no PERFORMER tag.
    • +
    + Winamp2 plugin: +
      +
    • Configurable sample resolution conversion with dither.
    • +
    • ReplayGain support with customizable noise shaping, pre-amp, and optional hard limiter.
    • +
    • File info now works.
    • +
    • Uses the ARTIST tag if there is no PERFORMER tag.
    • +
    + Libraries (developers take note!): +
      +
    • All code and tests are instrumented for Valgrind. All tests run Valgrind-clean, meaning no memory leaks or buffer over/under-runs.
    • +
    • Separate 64-bit datapath through the filter in libFLAC for better compression of >16 bps files.
    • +
    • FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT) now sets the vendor string.
    • +
    • The documentation on the usage of FLAC::Iterator::get_block() in libFLAC++ has an important correction. If you use this class make sure to read this.
    • +
    +
  • +
+ + 24-Sep-2002: +
    +
  • + FLAC 1.0.4 released  There are a lot of improvements since 1.0.3; let's get right to it:
    +
    + Plugins: +
      +
    • Support for Vorbis comments, ID3 v1 and v2 tags.
    • +
    • Configurable title formatting and charset conversion in XMMS plugin.
    • +
    • Support for 8- and 24-bit FLAC files. There is a compile-time option for raw 24-bit output or 24bps-to-16bps linear dithering (the default).
    • +
    + flac: +
      +
    • Improved option parser (now uses getopt).
    • +
    • AIFF input support (thanks to Brady Patterson).
    • +
    • Small decoder speedup.
    • +
    • --sector-align now supported for raw input files.
    • +
    • New -T, --tag options for adding Vorbis comments while encoding.
    • +
    • New --serial-number option for use with --ogg.
    • +
    • Automatically writes vendor string in Vorbis comments.
    • +
    • Drastically reduced memory requirements.
    • +
    • Fixed bug where extra fmt/data chunks that were supposed to be skipped were not getting skipped.
    • +
    • Fixed bug in granulepos setting for Ogg FLAC streams.
    • +
    • Fixed memory leak when encoding multiple files with -V.
    • +
    + metaflac: +
      +
    • UTF-8 support in Vorbis comments.
    • +
    • New --import-vc-from and --export-vc-to commands for importing/exporting Vorbis comments from/to a file. For example, the following can be used to copy tags back and forth:
      + + metaflac --export-vc-to=- --no-utf8-convert file.flac | vorbiscomment --raw -w file.ogg
      + vorbiscomment --raw -l file.ogg | metaflac --import-vc-from=- --no-utf8-convert file.flac
      +
      +
    • +
    • Fixed bug #606796 where metaflac was failing on read-only files.
    • +
    + Libraries: +
      +
    • All APIs now meticulously documented via Doxygen. See here.
    • +
    • New libOggFLAC and libOggFLAC++ libraries. These wrap around libFLAC to provide encoding and decoding of Ogg FLAC streams, providing interfaces similar to the ones of the native FLAC libraries. These are also documented via Doxygen.
    • +
    • New FLAC__SeekableStreamEncoder and FLAC__FileEncoder in libFLAC simplify common encoding tasks.
    • +
    • New verify mode in all encoders.
    • +
    • FLAC__stream_encoder_finish() now resets the defaults just like the stream decoders.
    • +
    • Drastically reduced memory requirements of encoders and decoders.
    • +
    • Encoder now automatically writes vendor string in VORBIS_COMMENT block.
    • +
    • Encoding speedup of fixed predictors and MD5 speedup for 16bps mono/stereo signals on x86 (thanks to Miroslav Lichvar).
    • +
    • Fixed bug in metadata interface where a bps in STREAMINFO > 16 was incorrectly parsed.
    • +
    • Fixed bug where aborting stream decoder could cause infinite loop.
    • +
    • Behavior change: simplified decoder *_process() commands.
    • +
    • Behavior change: calling FLAC__stream_encoder_init() calls write callback once for "fLaC" signature and once for each metadata block.
    • +
    • Behavior change: deprecated do_escape_coding and rice_parameter_search_distance in encoder.
    • +
    +
  • +
+ + 22-Aug-2002: +
    +
  • + Rio Receiver  FLAC support has been added to the Rio Receiver and Dell Digital Audio Receiver via David Flowerday's RioPlay client. See here for the announcement. +
  • +
+ + 03-Jul-2002: +
    +
  • + FLAC 1.0.3 released  Although by version number only a 0.0.1 increment, this release is significant. Remember, micro-revisions mean the FLAC format remains both forward and backward compatible, however, the libFLAC API has changed for the better.
    +
    + New features: +
      +
    • 24-bit input support restored in flac.
    • +
    • Decoder speedup in libFLAC, which is directly passed on to the command-line decoder and plugins.
    • +
    • New -F option to flac to continue decoding in spite of errors.
    • +
    • Correctly set granulepos in Ogg packets so seeking Ogg FLAC streams will be easier.
    • +
    • New VORBIS_COMMENT metadata block for tagging with Vorbis-style comments.
    • +
    • Vastly improved metaflac, now with many editing and tagging options.
    • +
    • Partial id3v1 support in Winamp plugins.
    • +
    • Updated Winamp 3 plugin.
    • +
    • Note: new semantics for -P option in flac.
    • +
    • Note: removed -R option in flac.
    • +
    + New library features: +
      +
    • Previously mentioned decoder speedup in libFLAC.
    • +
    • New metadata interface to libFLAC for manipulating metadata in FLAC files.
    • +
    • New libFLAC++ API, an object wrapper around libFLAC.
    • +
    • New VORBIS_COMMENT metadata block for tagging with Vorbis-style comments.
    • +
    • Customizable metadata filtering by type in decoders.
    • +
    • Stream encoder can take an arbitrary list of metadata blocks, instead of just one SEEKTABLE and/or PADDING block.
    • +
    + Bugs fixed: +
      +
    • Fixed bug with using pipes under Windows.
    • +
    • Fixed several bugs in the plugins and made them more robust in general.
    • +
    • Fixed bug in flac where decoding to WAVE of a FLAC file with 0 for total_samples in the STREAMINFO block yielded a WAVE chunk of 0 size.
    • +
    • Fixed bug in Ogg packet numbering.
    • +
    +
  • +
+ + 13-Feb-2002: +
    +
  • + FLAC goes hardware!  PhatNoise has become the first commercial hardware platform to support FLAC. Firmware is now available for the Phatbox player to play FLAC files. See here for details. +
  • +
+ + 03-Dec-2001: +
    +
  • + FLAC 1.0.2 released  This release is only to fix a bug that was causing some of the plugins to crash sporadically. It can also affect libFLAC users that reuse one file decoder instance for multiple files; see here for more. +
  • +
+ + 14-Nov-2001: +
    +
  • + FLAC 1.0.1 released  The core codec is unchanged but there have been some features added and some bugs fixed:
    +
    + New features for users: +
      +
    • Support for Ogg-FLAC, i.e. flac can now read and write FLAC streams using Ogg as the transport layer.
    • +
    • New Winamp 3 plugin based on the Wasabi Beta 1 SDK.
    • +
    • New utilities for adding FLAC support to the Monkey's Audio GUI (see how).
    • +
    • Mac OS X support. The download area now contains an OS X binary release.
    • +
    • Mingw32 support.
    • +
    • Better handling of MS-specific 'fmt' chunks in WAVE files.
    • +
    + New features for developers: +
      +
    • Added a SeekableStreamDecoder layer between StreamDecoder and FileDecoder. This makes it easier to use libFLAC in situations where files have been abstracted away. See the latest documentation for more. The interface for the StreamDecoder and FileDecoder remain the same and are still binary-compatible with libFLAC 1.0.
    • +
    • Drastically reduced the stack requirements of the encoder.
    • +
    + Bug fixes: +
      +
    • Fixed a serious bug with flac and raw input where the encoder was trying to rewind when it shouldn't, which would add 12 junk samples to the encoded file. This was not present in WAVE encoding.
    • +
    • Fixed a minor bug in libFLAC with setting the file name to stdin on a file decoder.
    • +
    • Fixed a minor bug in libFLAC where multiple calls to setting the file name on a file decoder caused leaked memory.
    • +
    • Fixed a minor bug in metaflac, now correctly skips an id3v2 tag if present.
    • +
    • Fixed a minor bug in metaflac, now correctly skips long metadata blocks.
    • +
    +
  • +
+ + 20-Jul-2001: +
    +
  • + FLAC 1.0 is out!  It's finally here. There are a few new features but mostly it is minor bug fixes since 0.10: +
      +
    • New '--sector-align' option to flac which aligns a group of encoded files on CD audio sector boundaries.
    • +
    • New '--output-prefix' option to flac to allow the user to prepend a prefix to all output filenames (useful, for example, for encoding/decoding to a different directory).
    • +
    • Better WAVE autodetection (doesn't rely on ungetc() anymore).
    • +
    • Cleaner one-line encoding/decoding stats.
    • +
    • Changes to the libFLAC interface and type names to make binary compatibility easier to maintain in the future.
    • +
    • New '--sse-os' option to 'configure' to enable faster SSE-based routines.
    • +
    • Another (hopefully last) fix to the Winamp 2 plugin.
    • +
    • Slightly improved Rice parameter estimation.
    • +
    • Bug fixes for some very rare corner cases when encoding.
    • +
    +
  • +
+ + 07-Jun-2001: +
    +
  • + FLAC 0.10 released.  This is probably the final beta. There have been many improvements in the last two months: +
      +
    • Both the encoder and decoder have been significantly sped up. Aside from C improvements, the code base now has an assembly infrastructure that allows assembly routines for different architectures to be easily integrated. Many key routines have now have faster IA-32 implementations (thanks to Miroslav).
    • +
    • A new metadata block SEEKTABLE has been defined to hold an arbitrary number of seek points, which speeds up seeking within a stream.
    • +
    • flac now has a command-line usage similar to 'gzip'; make sure to see the latest documentation for the new usage. It also attempts to preserve the input file's timestamp and permissions.
    • +
    • The -# options in flac have been tweaked to yield the best compression-to-encode-time ratios. The new default is -5.
    • +
    • flac can now usually autodetect WAVE files when encoding so that -fw is usually not needed when encoding from stdin.
    • +
    • The WAVE reader in flac now just ignores (with a warning) unsupported sub-chunks instead of aborting with an error.
    • +
    • Added an option '--delete-input-file' to flac which automatically deletes the input after a successful encode/decode.
    • +
    • Added an option '-o' to flac to force the output file name (the old usage of "flac - outputfilename" is no longer supported).
    • +
    • Changed the XMMS plugin to send smaller chunks of samples (now 512) so that visualization is not slow.
    • +
    • Fixed a bug in the stream decoder where the decoded samples counter got corrupted after a seek.
    • +
    + It should be a short hop to 1.0. +
  • +
+ + 31-Mar-2001: +
    +
  • + FLAC 0.9 released.  There were some format changes that broke backwards compatibility but these should be the last (see below). Also, there have been several bug fixes and some new features: +
      +
    • FLAC's sync code has been lengthened to 14 bits from 9 bits. This should enable a faster and more robust synchronization mechanism.
    • +
    • Two reserved bits were added to the frame header.
    • +
    • A CRC-16 was added to the FLAC frame footer, and the decoder now does frame integrity checking based on the CRC.
    • +
    • The format now includes a new subframe field to indicate when a subblock has one or more 0 LSBs for all samples. This increases compression on some kinds of data.
    • +
    • Added two options to the analysis mode, one for including the residual signal in the analysis file, and one for generating gnuplot files of each subframe's residual distribution with some statistics. See the latest documentation.
    • +
    • XMMS plugin now supports 8-bit files.
    • +
    • Fixed a bug in the Winamp2 plugin where the audio sounded garbled.
    • +
    • Fixed a bug in the Winamp2 plugin where Winamp would hang sporadically at the end of a track (c.f. bug #231197).
    • +
    + FLAC is on track for an official 1.0 release soon. +
  • +
+ + 05-Mar-2001: +
    +
  • + FLAC 0.8 released.  This release is a result of extensive testing and fixes several bugs encountered when pushing the encoder to the limit. I'm pretty confident in the stability of the encoder/decoder now for all kinds of input. There have also been several features added. Here is a complete list of the changes since 0.7: +
      +
    • Created a new utility called metaflac. It is a metadata editor for .flac files. Right now it just lists the contents of the metadata blocks but eventually it will allow update/insertion/deletion.
    • +
    • Added two new metadata blocks: PADDING which has an obvious function, and APPLICATION, which is meant to be open to third party applications. See the latest format docs for more info, or the new id registration page.
    • +
    • Added a -P option to flac to reserve a PADDING block when encoding.
    • +
    • Added support for 24-bit files to flac (the FLAC format always supported it).
    • +
    • Started the Winamp3 plugin.
    • +
    • Greatly expanded the test suite, adding more streams (24-bit streams, noise streams, non-audio streams, more patterns) and more option combinations to the encoder. The test suite runs about 30 streams and over 5000 encodings now.
    • +
    • Fixed a bug in libFLAC that happened when using an exhaustive LPC coefficient quantization search with 8 bps input.
    • +
    • Fixed a bug in libFLAC where the error estimation in the fixed predictor could overflow.
    • +
    • Fixed a bug in libFLAC where LPC was attempted even when the autocorrelation coefficients implied it wouldn't help.
    • +
    • Reworked the LPC coefficient quantizer, which also fixed another bug that might occur in rare cases.
    • +
    • Really fixed the '-V overflow' bug (c.f. bug #231976).
    • +
    • Fixed a bug in flac related to the decode buffer sizing.
    • +
    + FLAC is very close to being ready for an official release. The only known problems left are with the Winamp plugins, which should be fixed soon, and pipes with MSVC. +
  • +
+ + 12-Feb-2001: +
    +
  • + FLAC 0.7 released.  This is mainly a bug fix release, specifically: +
      +
    • Fixed a bug that happened when both -fr and --seek were used at the same time.
    • +
    • Fixed a bug with -p (c.f. bug #230992).
    • +
    • Fixed a bug that happened when using large (>32K) blocksizes and -V (c.f. bug #231976).
    • +
    • Fixed a bug where encoder was double-closing a file.
    • +
    • Expanded the test suite.
    • +
    • Added more optimization flags for gcc, which should speed up flac.
    • +
    +
  • +
+ + 28-Jan-2001: +
    +
  • + FLAC 0.6 released.  The encoder is now much faster. The -m option has been sped up by 4x and -r improved, meaning that in the default compression mode (-6), encoding should be at least 3 times faster. Other changes: +
      +
    • Some bugs related to flac and pipes were fixed (see here for the discussion).
    • +
    • A "loose mid-side" (-M) option to the encoder has been added, which adaptively switches between independent and mid-side coding, instead of the exhaustive search that -m does.
    • +
    • An analyze mode (-a) has been added to flac. This is useful mainly for developers; currently it will dump info about each frame and subframe to a file. It's a text file in a format that can be easily processed by scripts; a separate analysis program is in the works.
    • +
    • The source now has an autoconf/libtool-based build system. This should allow the source to build "out-of-the-box" on many more platforms.
    • +
    +
  • +
+ + 15-Jan-2001: +
    +
  • + FLAC 0.5 released.  This is the first beta version of FLAC. Being beta, there will be no changes to the format that will break older streams, unless a serious bug involving the format is found. What this means is that, barring such a bug, streams created with 0.5 will be decodable by future versions. This version also includes some new features: +
      +
    • An MD5 signature of the unencoded audio is computed during encoding, and stored in the Encoding metadata block in the stream header. When decoding, flac will now compute the MD5 signature of the decoded data and compare it against the signature in the stream header.
    • +
    • A test mode (-t) has been added to flac. It works like decode mode but doesn't write an output file.
    • +
    +
  • +
+ + 23-Dec-2000: +
    +
  • FLAC 0.4 released.  This version fixes a bug in the constant subframe detection. More importantly, a verify option (-V) has been added to flac that verifies the encoding process. With this option turned on, flac will create a parallel decoder while encoding to make sure that the encoded output decodes to exactly match the original input. In this way, any unknown bug in the encoder will be caught and flac will abort with an error message.
  • +
+ + 10-Dec-2000: +
    +
  • FLAC debuts on SourceForge.  The FLAC project is now being hosted on SourceForge. Visit the FLAC project page to join the mailing list or sign up as a developer.
  • +
+
+ +
+ + + + + + diff --git a/flac/doc/html/ogg_mapping.html b/flac/doc/html/ogg_mapping.html new file mode 100644 index 0000000..7633858 --- /dev/null +++ b/flac/doc/html/ogg_mapping.html @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + FLAC - ogg mapping + + + + + + +
+ + + +
+  english  | +  russian  +
+ +
+ +
+
+ ogg mapping +
+
+
+ This page specifies the way in which compressed FLAC data is encapsulated in an Ogg transport layer. It assumes basic knowledge of the FLAC format and Ogg structure and framing.
+
+ The original FLAC format includes a very thin transport system. This system of compressed FLAC audio data mixed with a thin transport has come to be known as 'native FLAC'. The transport consists of audio frame headers and footers which contain synchronization patterns, timecodes, and checksums (but notably not frame lengths), and a metadata system. It is very lightweight and does not support more elaborate transport mechanisms such as multiple logical streams, but it has served its purpose well.
+
+ The native FLAC transport is not a transport "layer" in the way of standard codec design because it cannot be entirely separated from the payload. Though the metadata system can be separated, the frame header includes both data that belongs in the transport (sync pattern, timecode, checksum) and data that belongs in the compressed packets (audio parameters like channel assignments, sample rate, etc).
+
+ This presents a problem when trying to encapsulate FLAC in other true transport layers; the choice has to be made between redundancy and complexity. In pursuit of correctness, a mapping could be created that removed from native FLAC the transport data, and merged the remaining frame header information into the audio packets. The disadvantage is that current native FLAC decoder software could not be used to decode because of the tight coupling with the transport. Either a separate decoding implementation would have to be created and maintained, or an Ogg FLAC decoder would have to synthesize native FLAC frames from Ogg FLAC packets and feed them to a native FLAC decoder.
+
+ The alternative is to treat native FLAC frames as Ogg packets and accept the transport redundancy. It turns out that this is not much of a penalty; a maximum of 12 bytes per frame will be wasted. Given the common case of stereo CD audio encoded with a blocksize of 4096 samples, a compressed frame will be 4-16 Kbytes. The redundancy amounts to a fraction of a percent.
+
+ In the interest of simplicity and expediency, the second method was chosen for the first official FLAC->Ogg mapping. A mapping version is included in the first packet so that a less redundant mapping can be defined in the future.
+
+ It should also be noted that support for encapsulating FLAC in Ogg has been present in the FLAC tools since version 1.0.1. However, the mappings used were never formalized and have insurmountable problems. For that reason, Ogg FLAC streams created with flac versions before 1.1.1 should be decoded and re-encoded with flac 1.1.1 or later (flac 1.1.1 can decode all previous Ogg FLAC files, but files made prior to 1.1.0 don't support seeking). Since the support for Ogg FLAC before FLAC 1.1.1 was limited, we hope this will not result in too much inconvenience.
+
+ Version 1.0 of the FLAC-to-Ogg mapping then is a simple identifying header followed by pure native FLAC data, as follows: +
    +
  • + The first packet of a stream consists of: +
      +
    • The one-byte packet type 0x7F
    • +
    • The four-byte ASCII signature "FLAC", i.e. 0x46, 0x4C, 0x41, 0x43
    • +
    • A one-byte binary major version number for the mapping, e.g. 0x01 for mapping version 1.0
    • +
    • A one-byte binary minor version number for the mapping, e.g. 0x00 for mapping version 1.0
    • +
    • A two-byte, big-endian binary number signifying the number of header (non-audio) packets, not including this one. This number may be zero (0x0000) to signify 'unknown' but be aware that some decoders may not be able to handle such streams.
    • +
    • The four-byte ASCII native FLAC signature "fLaC" according to the FLAC format specification
    • +
    • The STREAMINFO metadata block for the stream.
    • +
    + This first packet is the only packet in the first page of the stream. This results in a first Ogg page of exactly 79 bytes at the very beginning of the logical stream. +
  • +
  • + This first page is marked 'beginning of stream' in the page flags. +
  • +
  • + The first packet is followed by one or more header packets. Each such packet will contain a single native FLAC metadata block. The first of these must be a VORBIS_COMMENT block. These packets may span page boundaries but the last will finish the page on which it ends, so that the first audio packet begins a page. The first byte of these metadata packets serves also as the packet type, and has a legal range of (0x01-0x7E,0x81-0xFE). +
  • +
  • + The granule position of these first pages containing only headers is zero. +
  • +
  • + The first audio packet of the logical stream begins a fresh Ogg page. +
  • +
  • + Native FLAC audio frames appear as subsequent packets in the stream. Each packet corresponds to one FLAC audio frame. The first byte of each packet serves as the packet type. Since audio packets are native FLAC frames, this first byte will be always 0xFF according to the native FLAC format specification. +
  • +
  • + The last page is marked 'end of stream' in the page flags. +
  • +
  • + FLAC packets may span page boundaries. +
  • +
  • + The granule position of pages containing FLAC audio follows the same semantics as that for Ogg-encapsulated Vorbis as described here. +
  • +
  • + Redundant fields in the STREAMINFO packet may be set to zero (indicating "unknown" in native FLAC), which also facilitates single-pass encoding. These fields are: the minimum and maximum frame sizes, the total samples count, and the MD5 signature. "Unknown" values for these fields will not prevent a compliant native FLAC or Ogg FLAC decoder from decoding the stream. +
  • +
+ It is intended that the first six bytes of any version of FLAC-to-Ogg mapping will share the same structure, namely, the four-byte signature and two-byte version number.
+
+ There is an implicit hint to the decoder in the mapping version number; mapping versions which share the same major version number should be decodable by decoders of the same major version number, e.g. a 1.x Ogg FLAC decoder should be able to decode any 1.y Ogg FLAC stream, even when x<y. If a mapping breaks this forward compatibility the major version number will be incremented. +
+ +
+ + + + + + diff --git a/flac/doc/html/ru/Makefile.am b/flac/doc/html/ru/Makefile.am new file mode 100644 index 0000000..1956561 --- /dev/null +++ b/flac/doc/html/ru/Makefile.am @@ -0,0 +1,36 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +AUTOMAKE_OPTIONS = foreign + +docdir = $(datadir)/doc/$(PACKAGE)-$(VERSION)/html/ru + +doc_DATA = \ + authors.html \ + comparison.html \ + developers.html \ + documentation.html \ + download.html \ + features.html \ + format.html \ + goals.html \ + id.html \ + index.html \ + links.html \ + news.html + +EXTRA_DIST = $(doc_DATA) diff --git a/flac/doc/html/ru/authors.html b/flac/doc/html/ru/authors.html new file mode 100644 index 0000000..c888e03 --- /dev/null +++ b/flac/doc/html/ru/authors.html @@ -0,0 +1,112 @@ + + + + + + + + + + +FLAC: + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
| | | | | | |
|id | | | | | +  |
+ +

+ + + + + +
|english | +  |

+ + +

FLAC:

+ +

FLAC (http://flac.sourceforge.net/) - , , (Josh Coalson).

+ +

:

+ +
+ +

(Miroslav Lichvar) +

+
  • libFLAC IA-32.
  • +

    + +

    (Matt Zimmerman) +

    +
  • libtool/autoconf/automake.
  • +

    + +

    (Andrey Astafiev) +

    +
  • .
  • +

    + +

    (Brady Patterson) +

    +
  • AIFF.
  • +

    + +

    (Daisuke Shimamura) +

    +
  • id3 v1/v2 i18n XMMS.
  • +

    + +

    X-Fixer

    +
    +
  • , Winamp2.

    +
  • +
    + +

     Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

    + + + diff --git a/flac/doc/html/ru/comparison.html b/flac/doc/html/ru/comparison.html new file mode 100644 index 0000000..ba78f2b --- /dev/null +++ b/flac/doc/html/ru/comparison.html @@ -0,0 +1,864 @@ + + + + + + + + + + +FLAC: + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    | | | | | | |
    |id | +  | | | | |
    + +

    + + + + + +
    |english | +  |

    + + +

    FLAC:

    + +

    FLAC . /, . , :

    + +

    +
  • , (FLAC WavPack) ( Shorten Monket's Audio , ). , , , . , . , .
  • + +
  • flac . FLAC, . , .
  • + +
  • FLAC , .
  • +

    + +

    , , - , .

    + +

    ( flac):

    + +

    +
  • Bonk - . .
  • + +
  • Kexis - . , . .
  • + +
  • La - , . Windows Linux. , .
  • + +
  • LPAC - . Windows, Winamp.
  • + +
  • Monkey's Audio - , . . : . .
  • + +
  • Ogg Squish - , . 0.98 , . Windows , , Unix, "" .
  • + +
  • optimFROG - Windows Linux Winamp XMMS. , .
  • + +
  • Pegasus-SPS - Windows.
  • + +
  • RKAU - Windows. 2 .
  • + +
  • Shorten - .
  • + +
  • WaveZIP - Windows. MUSICompress[tm], , , . , WaveZIP (GadgetLabs), (, , ).
  • + +
  • WavPack - Windows, BSD. .
  • +

    + +

    AudioPack WavARC.

    + +

    ( , ), , . , , . , . - / .

    + +

    1. .

    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + ? + ? + ? +? +? + +
    flac v1.1.0 (OSI) (XMMS, AlsaPlayer, Winamp, MacAmp Lite, dBpowerAMP, Foobar2000, Apollo) (PhatBox, Kenwood MusicKeg, Rio Receiver, Dell Digital Audio Receiver, Turtle Beach AudioTron).Linux, Windows, Mac OS X, *BSD, Solaris, OS/2, BeOS
    Shorten v3.2 (.) (Winamp, XMMS) ( v3).Linux, Windows, Mac OS 9, Mac OS X, *BSD, Solaris
    WavPack v3.97a (Winamp).Windows
    Monkey's Audio v3.96 (.) (Winamp, MediaJukebox, dBpowerAMP).Windows, Linux
    Ogg Squish 0.98?.Linux, Windows, UNIX
    Bonk 0.5 (XMMS).Linux, Windows, UNIX
    La 0.3c (Winamp, XMMS).Windows, Linux
    optimFrog 4.21 (Winamp, XMMS).Windows, Linux
    LPAC v1.31 (codec 3.0) (Winamp)?.Windows, Linux, Solaris
    RKAU v1.07 (Winamp).Windows
    Kexis 0.2.2.Linux, Windows, UNIX
    WaveZIP v2. (24- $)Windows
    Pegasus-SPS$39 (trial)Windows

    + +

    PII-333 256M Windows NT SP5. , Windows , .

    + +

    , -CD. (, , ..). 14 .

    + +

    . . ,

    + +

    , , . ( = / ).

    + +

    :

    +
      +
    • flac -5 " ", . . , FLAC , , . FLAC , FLAC .
    • +
    • LPAC -r ( ).
    • +
    • RKAU 'high' ( ).
    • +
    • , . SPS , .
    • + +

      "" ( ).

      + +

      2. .

      +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +







      La 0.3c151:13.16145:49.78375.76 MB0.48140.4986
      Monkey's Audio 3.96 (extra high)26:52.0728:44.55386.96 MB0.49580.5119
      optimFROG 4.21 (mode 1 @ 4x)24:19.5825:37.44389.04 MB0.49840.5151
      Monkey's Audio 3.96 (high)13:59.0715:30.69391.76 MB0.50190.5179
      optimFROG 4.21 (mode 0 @ 4x)16:34.9617:57.28394.69 MB0.50560.5223
      Monkey's Audio 3.96 (normal)11:42.3413:11.29395.04 MB0.50610.5223
      RKAU 1.07 (normal)53:46.7423:31.10395.71 MB0.50700.5229
      RKAU 1.07 (fast)26:35.3420:13.22399.25 MB0.51150.5262
      WavPack 3.97a (high)13:32.0214:39.12399.60 MB0.51190.5278
      LPAC 1.40 (-r, medium)18:52.7910:43.32403.52 MB0.51700.5319
      Monkey's Audio 3.96 (fast)9:05.5910:51.09401.63 MB0.51450.5327
      WavPack 3.97a (normal)6:50.128:13.41409.33 MB0.52440.5424
      flac 1.1.0 (-5, default)12:54.197:08.80413.46 MB0.52970.5459
      Bonk 0.536:56.3627:09.35418.65 MB0.53640.5543
      flac 1.1.0 (-3)9:51.587:00.92419.29 MB0.53720.5544
      Ogg Squish 0.98??431.08 MB0.55220.5714
      Shorten 3.2a (-p0 -b256, default)9:44.486:31.74433.56 MB0.55550.5729
      Kexis 0.2.217:49.0614:53.90434.33 MB0.55640.5750
      WavPack 3.97a (fast)5:20.175:12.38441.88 MB0.56610.5857
      WaveZIP8:41.72?452.95 MB0.58020.5986
      RIFF WAVE70:11.9070:11.90780.56 MB1.00001.0000

      + + +

      .

      + +

      3. .

      +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +







      La 0.3c151:13.16145:49.78375.76 MB0.48140.4986
      optimFROG 4.21 (mode 4 @ 2x)183:05.29184:13.42386.13 MB0.49470.5105
      optimFROG 4.21 (mode 4 @ 1x)338:34.96339:23.24386.22 MB0.49480.5105
      optimFROG 4.21 (mode 4 @ 4x)105:15.85106:36.23386.21 MB0.49480.5107
      optimFROG 4.21 (mode 3 @ 2x)92:48.7993:49.75386.52 MB0.49520.5110
      optimFROG 4.21 (mode 3 @ 1x)161:51.00162:10.62386.55 MB0.49520.5110
      optimFROG 4.21 (mode 3 @ 4x)58:18.4059:30.51386.71 MB0.49540.5114
      Monkey's Audio 3.96 (extra high)26:52.0728:44.55386.96 MB0.49580.5119
      optimFROG 4.21 (mode 2 @ 1x)68:22.5869:29.50387.71 MB0.49670.5128
      optimFROG 4.21 (mode 2 @ 2x)44:17.5545:31.33387.72 MB0.49670.5129
      optimFROG 4.21 (mode 2 @ 4x)32:16.8533:30.92387.93 MB0.49700.5133
      optimFROG 4.21 (mode 1 @ 1x)43:00.9144:13.07388.71 MB0.49800.5146
      optimFROG 4.21 (mode 1 @ 2x)30:35.0031:50.50388.81 MB0.49810.5147
      optimFROG 4.21 (mode 1 @ 4x)24:19.5825:37.44389.04 MB0.49840.5151
      Monkey's Audio 3.96 (high)13:59.0715:30.69391.76 MB0.50190.5179
      optimFROG 4.21 (mode 0 @ 1x)20:51.2122:08.44394.35 MB0.50520.5218
      optimFROG 4.21 (mode 0 @ 2x)17:59.8619:20.53394.48 MB0.50540.5220
      optimFROG 4.21 (mode 0 @ 4x)16:34.9617:57.28394.69 MB0.50560.5223
      Monkey's Audio 3.96 (normal)11:42.3413:11.29395.04 MB0.50610.5223
      RKAU 1.07 (normal)53:46.7423:31.10395.71 MB0.50700.5229
      RKAU 1.07 (high)136:56.6227:55.98395.89 MB0.50720.5235
      RKAU 1.07 (fast)26:35.3420:13.22399.25 MB0.51150.5262
      WavPack 3.97a (high)13:32.0214:39.12399.60 MB0.51190.5278
      LPAC 1.40 (-r, medium)18:52.7910:43.32403.52 MB0.51700.5319
      LPAC 1.40 (-r, extra high)30:30.9312:20.26404.08 MB0.51770.5322
      LPAC 1.40 (-r, high)24:56.5611:51.64404.03 MB0.51760.5323
      Monkey's Audio 3.96 (fast)9:05.5910:51.09401.63 MB0.51450.5327
      WavPack 3.97a (normal)6:50.128:13.41409.33 MB0.52440.5424
      flac 1.1.0 (-8)55:02.387:07.59411.88 MB0.52770.5437
      flac 1.1.0 (-5, default)12:54.197:08.80413.46 MB0.52970.5459
      Bonk 0.536:56.3627:09.35418.65 MB0.53640.5543
      flac 1.1.0 (-3)9:51.587:00.92419.29 MB0.53720.5544
      flac 1.1.0 (-1)8:37.947:15.87432.32 MB0.55390.5706
      Ogg Squish 0.98??431.08 MB0.55220.5714
      Shorten 3.2a (-p0 -b256, default)9:44.486:31.74433.56 MB0.55550.5729
      Kexis 0.2.217:49.0614:53.90434.33 MB0.55640.5750
      Shorten 3.2a (-p8 -b2048)12:00.047:25.12438.86 MB0.56220.5810
      WavPack 3.97a (fast)5:20.175:12.38441.88 MB0.56610.5857
      WaveZIP8:41.72?452.95 MB0.58020.5986
      RIFF WAVE70:11.9070:11.90780.56 MB1.00001.0000
      + + +

      4. .

      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +
      +
      +
      +
      + Dream Theater
      6:00 +
      La 0.3c11:37.6911:15.3742.72 MB0.7306
      Monkey's Audio 3.96 (extra high)2:05.362:13.4443.24 MB0.7395
      optimFROG 4.21 (mode 1 @ 4x)1:53.282:00.4543.26 MB0.7398
      optimFROG 4.21 (mode 4 @ 1x)25:32.4125:38.1543.26 MB0.7398
      Monkey's Audio 3.96 (high)1:07.921:13.2043.39 MB0.7421
      optimFROG 4.21 (mode 0 @ 4x)1:17.951:25.6743.42 MB0.7426
      Monkey's Audio 3.96 (normal)0:57.041:03.3743.48 MB0.7436
      WavPack 3.97a (high)1:10.341:08.6143.49 MB0.7438
      RKAU 1.07 (normal)1:57.681:33.3843.81 MB0.7493
      Monkey's Audio 3.96 (fast)0:44.330:51.2243.97 MB0.7520
      LPAC 1.40 (-r, normal)1:27.610:56.1844.12 MB0.7545
      flac 1.1.0 (-8)4:18.720:37.2844.33 MB0.7582
      WavPack 3.97a (normal)0:40.240:40.7044.34 MB0.7583
      Bonk 0.52:56.032:11.5844.35 MB0.7585
      flac 1.1.0 (-5, default)1:01.310:37.0144.41 MB0.7595
      Shorten 3.2a (-p8 -b2048)0:58.810:37.6344.75 MB0.7654
      flac 1.1.0 (-3)0:49.050:36.4444.78 MB0.7659
      Ogg Squish 0.98??45.17 MB0.7725
      Pegasus-SPS4:45.00?45.40 MB0.7765
      WavPack 3.97a (fast)0:18.660:18.5946.31 MB0.7920
      Kexis 0.2.21:24.831:10.9346.52 MB0.7956
      flac 1.1.0 (-1)0:44.000:36.9146.65 MB0.7978
      Shorten 3.2a (-p0 -b256, default)0:47.750:32.5646.68 MB0.7984
      WaveZIP0:38.99?47.22 MB0.8077
      RIFF WAVE5:47.565:47.5658.47 MB1.0000
       
      + Eddie Warner
      Titus +
      La 0.3c5:24.565:13.2914.76 MB0.5298
      LPAC 1.40 (-r, normal)0:40.760:21.2114.77 MB0.5298
      flac 1.1.0 (-8)1:57.870:15.0515.01 MB0.5385
      optimFROG 4.21 (mode 1 @ 4x)0:53.390:55.5215.01 MB0.5385
      optimFROG 4.21 (mode 4 @ 1x)12:02.5412:03.7615.02 MB0.5390
      flac 1.1.0 (-5, default)0:28.170:15.0515.12 MB0.5424
      optimFROG 4.21 (mode 0 @ 4x)0:36.810:39.1915.13 MB0.5429
      RKAU 1.07 (normal)0:54.820:42.7115.15 MB0.5435
      Monkey's Audio 3.96 (extra high)0:58.521:01.8115.25 MB0.5471
      Monkey's Audio 3.96 (high)0:30.880:33.5515.34 MB0.5505
      Monkey's Audio 3.96 (normal)0:25.450:28.3715.35 MB0.5509
      flac 1.1.0 (-3)0:22.210:14.7215.43 MB0.5538
      WavPack 3.97a (high)0:32.150:31.1815.57 MB0.5585
      Monkey's Audio 3.96 (fast)0:19.850:22.9015.58 MB0.5592
      Shorten 3.2a (-p0 -b256, default)0:21.160:13.5515.78 MB0.5662
      WavPack 3.97a (normal)0:18.250:17.6715.86 MB0.5692
      Shorten 3.2a (-p8 -b2048)0:26.820:16.7516.21 MB0.5818
      flac 1.1.0 (-1)0:19.750:15.7616.39 MB0.5880
      Bonk 0.51:22.011:00.1216.73 MB0.6003
      Ogg Squish 0.98??17.03 MB0.6112
      Kexis 0.2.20:38.720:32.2517.40 MB0.6242
      WavPack 3.97a (fast)0:08.190:08.7917.49 MB0.6275
      WaveZIP0:17.55?17.89 MB0.6420
      RIFF WAVE2:35.672:35.6727.87 MB1.0000
       
      + Tool
      Forty-six & 2 +
      La 0.3c12:34.9712:09.0837.42 MB0.5824
      optimFROG 4.21 (mode 4 @ 1x)27:58.2828:01.8737.96 MB0.5907
      optimFROG 4.21 (mode 1 @ 4x)2:03.432:09.2738.15 MB0.5937
      Monkey's Audio 3.96 (extra high)2:14.702:24.3038.23 MB0.5950
      Monkey's Audio 3.96 (high)1:09.821:18.0938.42 MB0.5979
      Monkey's Audio 3.96 (normal)0:58.691:07.0238.59 MB0.6005
      optimFROG 4.21 (mode 0 @ 4x)1:24.441:30.9738.68 MB0.6020
      WavPack 3.97a (high)1:02.471:14.5438.86 MB0.6048
      Monkey's Audio 3.96 (fast)0:46.500:55.4139.18 MB0.6098
      RKAU 1.07 (normal)2:16.001:41.8439.42 MB0.6135
      WavPack 3.97a (normal)0:29.070:42.8739.92 MB0.6213
      LPAC 1.40 (-r, normal)1:38.010:57.5640.25 MB0.6263
      flac 1.1.0 (-8)4:35.080:39.4040.89 MB0.6363
      Bonk 0.53:07.202:21.2840.98 MB0.6378
      flac 1.1.0 (-5, default)1:05.540:39.6541.04 MB0.6388
      flac 1.1.0 (-3)0:50.180:38.9241.74 MB0.6496
      Ogg Squish 0.98??42.27 MB0.6578
      flac 1.1.0 (-1)0:45.830:40.8942.70 MB0.6646
      Kexis 0.2.21:30.091:16.2942.75 MB0.6652
      Shorten 3.2a (-p8 -b2048)1:02.420:37.8443.06 MB0.6701
      Shorten 3.2a (-p0 -b256, default)0:51.290:34.5943.18 MB0.6721
      WavPack 3.97a (fast)0:31.260:28.7943.65 MB0.6794
      WaveZIP0:42.84?44.52 MB0.6930
      RIFF WAVE6:21.926:21.9264.25 MB1.0000
       
      + Cannibal Corpse
      Mummified In Barbed Wire +
      La 0.3c6:35.946:23.5722.69 MB0.6798
      Monkey's Audio 3.96 (extra high)1:10.941:15.9222.95 MB0.6876
      optimFROG 4.21 (mode 4 @ 1x)14:34.2814:37.6922.95 MB0.6877
      Monkey's Audio 3.96 (high)0:37.630:41.3423.19 MB0.6948
      Monkey's Audio 3.96 (normal)0:31.710:34.8723.26 MB0.6968
      optimFROG 4.21 (mode 1 @ 4x)1:03.961:08.8523.31 MB0.6984
      RKAU 1.07 (normal)1:09.710:56.6623.34 MB0.6993
      LPAC 1.40 (-r, normal)1:05.380:36.2023.53 MB0.7050
      WavPack 3.97a (high)0:32.990:40.0523.57 MB0.7062
      optimFROG 4.21 (mode 0 @ 4x)0:44.140:48.7123.95 MB0.7176
      flac 1.1.0 (-8)2:25.590:20.8524.18 MB0.7245
      Monkey's Audio 3.96 (fast)0:25.050:28.9924.20 MB0.7250
      flac 1.1.0 (-5, default)0:34.660:21.4224.30 MB0.7282
      Bonk 0.51:40.381:14.5824.36 MB0.7297
      WavPack 3.97a (normal)0:15.990:23.5024.76 MB0.7418
      Shorten 3.2a (-p8 -b2048)0:33.740:22.4725.12 MB0.7526
      flac 1.1.0 (-3)0:27.400:20.1125.16 MB0.7539
      Ogg Squish 0.98??25.23 MB0.7558
      Kexis 0.2.20:47.130:40.6726.03 MB0.7799
      flac 1.1.0 (-1)0:24.040:21.6826.10 MB0.7819
      WavPack 3.97a (fast)0:16.790:21.6426.17 MB0.7841
      Shorten 3.2a (-p0 -b256, default)0:28.200:20.4626.61 MB0.7972
      WaveZIP0:22.25?26.89 MB0.8058
      RIFF WAVE3:18.363:18.3633.37 MB1.0000
       
      + Alanis Morisette
      Hand In My Pocket +
      La 0.3c7:35.217:20.1920.77 MB0.5312
      optimFROG 4.21 (mode 4 @ 1x)16:51.8216:54.3421.24 MB0.5433
      optimFROG 4.21 (mode 1 @ 4x)1:14.291:18.0621.36 MB0.5464
      Monkey's Audio 3.96 (extra high)1:21.381:27.2821.54 MB0.5509
      Monkey's Audio 3.96 (high)0:42.540:47.4121.75 MB0.5563
      Monkey's Audio 3.96 (normal)0:35.450:39.6521.84 MB0.5586
      optimFROG 4.21 (mode 0 @ 4x)0:51.390:54.9721.89 MB0.5598
      Monkey's Audio 3.96 (fast)0:28.230:33.2122.16 MB0.5668
      WavPack 3.97a (high)0:45.070:43.8822.28 MB0.5699
      WavPack 3.97a (normal)0:25.400:24.8022.80 MB0.5832
      RKAU 1.07 (normal)1:21.181:01.6022.80 MB0.5833
      LPAC 1.40 (-r, normal)1:01.110:33.7923.25 MB0.5948
      Bonk 0.51:53.411:23.5223.35 MB0.5972
      flac 1.1.0 (-8)2:46.090:23.1423.45 MB0.5998
      flac 1.1.0 (-5, default)0:39.820:21.8123.56 MB0.6026
      Ogg Squish 0.98??24.11 MB0.6167
      flac 1.1.0 (-3)0:30.580:22.0524.32 MB0.6221
      Shorten 3.2a (-p8 -b2048)0:37.490:22.9324.72 MB0.6323
      Kexis 0.2.20:54.260:45.6424.80 MB0.6345
      flac 1.1.0 (-1)0:26.460:22.1424.82 MB0.6348
      WavPack 3.97a (fast)0:16.670:17.0224.94 MB0.6381
      Shorten 3.2a (-p0 -b256, default)0:29.710:18.9225.34 MB0.6481
      WaveZIP0:28.05?25.95 MB0.6638
      RIFF WAVE3:52.363:52.3639.09 MB1.0000
       
      + Gloria Estefan
      Conga +
      La 0.3c8:52.938:34.8128.98 MB0.6419
      optimFROG 4.21 (mode 4 @ 1x)19:40.5319:44.4729.43 MB0.6517
      optimFROG 4.21 (mode 1 @ 4x)1:26.641:32.2329.58 MB0.6550
      Monkey's Audio 3.96 (extra high)1:35.651:42.1129.65 MB0.6567
      optimFROG 4.21 (mode 0 @ 4x)0:59.591:05.2929.78 MB0.6595
      Monkey's Audio 3.96 (high)0:50.170:56.4029.85 MB0.6610
      WavPack 3.97a (high)0:53.500:51.9029.92 MB0.6625
      Monkey's Audio 3.96 (normal)0:42.270:47.7429.97 MB0.6637
      WavPack 3.97a (normal)0:29.840:29.9230.28 MB0.6706
      Monkey's Audio 3.96 (fast)0:33.460:39.2230.30 MB0.6710
      RKAU 1.07 (normal)1:37.851:12.1530.34 MB0.6719
      Bonk 0.52:13.341:39.4430.64 MB0.6785
      flac 1.1.0 (-8)3:16.070:27.5330.76 MB0.6811
      LPAC 1.40 (-r, normal)1:14.080:44.6430.81 MB0.6823
      flac 1.1.0 (-5, default)0:46.300:26.7430.86 MB0.6834
      Ogg Squish 0.98??31.06 MB0.6879
      WavPack 3.97a (fast)0:13.310:14.1531.61 MB0.7000
      flac 1.1.0 (-3)0:35.880:27.6531.63 MB0.7006
      Shorten 3.2a (-p8 -b2048)0:44.760:27.4831.76 MB0.7034
      Kexis 0.2.21:03.910:53.5431.86 MB0.7056
      flac 1.1.0 (-1)0:32.510:27.3031.99 MB0.7085
      Shorten 3.2a (-p0 -b256, default)0:35.740:23.6432.47 MB0.7191
      WaveZIP0:29.42?33.02 MB0.7313
      RIFF WAVE4:28.394:28.3945.15 MB1.0000
       
      + Cream
      White Room +
      La 0.3c10:24.0810:03.1633.44 MB0.6309
      optimFROG 4.21 (mode 4 @ 1x)22:59.0523:02.9833.93 MB0.6399
      optimFROG 4.21 (mode 1 @ 4x)1:42.281:47.5533.96 MB0.6405
      Monkey's Audio 3.96 (extra high)1:51.772:00.3734.14 MB0.6441
      Monkey's Audio 3.96 (high)0:58.451:04.5934.29 MB0.6468
      optimFROG 4.21 (mode 0 @ 4x)1:10.301:15.9934.29 MB0.6468
      Monkey's Audio 3.96 (normal)0:49.320:56.8934.42 MB0.6493
      WavPack 3.97a (high)0:51.501:02.7134.55 MB0.6516
      RKAU 1.07 (normal)1:50.801:24.9834.60 MB0.6527
      LPAC 1.40 (-r, normal)1:25.160:48.6734.84 MB0.6572
      Bonk 0.52:35.361:56.2034.96 MB0.6595
      Monkey's Audio 3.96 (fast)0:38.750:46.8034.99 MB0.6601
      flac 1.1.0 (-8)3:48.730:31.9134.99 MB0.6601
      WavPack 3.97a (normal)0:24.430:36.0935.08 MB0.6617
      flac 1.1.0 (-5, default)0:54.890:33.8235.16 MB0.6633
      flac 1.1.0 (-3)0:41.380:32.0035.36 MB0.6671
      Shorten 3.2a (-p8 -b2048)0:51.440:33.0235.40 MB0.6677
      Ogg Squish 0.98??35.74 MB0.6742
      WavPack 3.97a (fast)0:26.000:24.8336.32 MB0.6852
      Shorten 3.2a (-p0 -b256, default)0:41.140:28.9136.42 MB0.6870
      flac 1.1.0 (-1)0:36.870:33.3936.56 MB0.6897
      Kexis 0.2.21:13.871:02.9036.64 MB0.6911
      WaveZIP0:35.77?37.13 MB0.7004
      RIFF WAVE5:15.115:15.1153.01 MB1.0000
       
      + Maurice Ravel
      Fanfare from "L'eventail de Jeanne" +
      La 0.3c3:55.403:47.606.46 MB0.3104
      optimFROG 4.21 (mode 4 @ 1x)8:22.428:23.326.82 MB0.3274
      Monkey's Audio 3.96 (extra high)0:39.930:41.696.85 MB0.3289
      optimFROG 4.21 (mode 1 @ 4x)0:36.570:38.267.09 MB0.3406
      Monkey's Audio 3.96 (high)0:21.220:23.047.16 MB0.3437
      RKAU 1.07 (normal)0:40.670:28.527.18 MB0.3451
      optimFROG 4.21 (mode 0 @ 4x)0:24.980:26.377.21 MB0.3462
      LPAC 1.40 (-r, normal)0:29.010:15.117.33 MB0.3520
      Monkey's Audio 3.96 (normal)0:18.190:19.547.44 MB0.3575
      WavPack 3.97a (high)0:22.630:21.867.45 MB0.3577
      Monkey's Audio 3.96 (fast)0:13.700:15.727.64 MB0.3671
      flac 1.1.0 (-8)1:20.730:09.517.69 MB0.3692
      flac 1.1.0 (-5, default)0:18.950:09.457.71 MB0.3703
      flac 1.1.0 (-3)0:14.980:09.197.77 MB0.3734
      WavPack 3.97a (normal)0:12.560:11.957.83 MB0.3760
      Bonk 0.50:55.920:40.237.83 MB0.3762
      flac 1.1.0 (-1)0:12.970:10.398.12 MB0.3902
      Ogg Squish 0.98??8.15 MB0.3914
      Shorten 3.2a (-p0 -b256, default)0:13.810:08.888.19 MB0.3932
      Shorten 3.2a (-p8 -b2048)0:17.450:10.308.29 MB0.3983
      Kexis 0.2.20:26.780:21.908.52 MB0.4091
      WaveZIP0:13.11?8.72 MB0.4193
      WavPack 3.97a (fast)0:05.350:06.338.87 MB0.4259
      RIFF WAVE2:03.762:03.7620.82 MB1.0000
       
      + Maurice Ravel
      String Quartet (4th movement) +
      La 0.3c10:45.8010:21.4419.94 MB0.3550
      Monkey's Audio 3.96 (extra high)1:54.092:01.7220.47 MB0.3642
      optimFROG 4.21 (mode 4 @ 1x)24:26.9924:29.3620.62 MB0.3671
      Monkey's Audio 3.96 (high)0:58.141:06.4520.80 MB0.3702
      optimFROG 4.21 (mode 1 @ 4x)1:42.571:47.4820.93 MB0.3725
      Monkey's Audio 3.96 (normal)0:48.610:54.7321.14 MB0.3763
      optimFROG 4.21 (mode 0 @ 4x)1:09.171:13.1421.23 MB0.3779
      RKAU 1.07 (normal)1:52.651:25.3921.30 MB0.3791
      Monkey's Audio 3.96 (fast)0:37.300:44.7921.54 MB0.3835
      WavPack 3.97a (high)0:52.481:02.2621.55 MB0.3835
      LPAC 1.40 (-r, normal)1:20.840:42.7321.96 MB0.3909
      WavPack 3.97a (normal)0:23.290:34.2822.11 MB0.3935
      flac 1.1.0 (-8)3:53.930:28.0222.61 MB0.4025
      flac 1.1.0 (-5, default)0:54.340:27.9222.68 MB0.4036
      Bonk 0.52:33.531:51.9423.18 MB0.4125
      flac 1.1.0 (-3)0:40.000:28.1523.21 MB0.4132
      flac 1.1.0 (-1)0:34.990:27.7323.36 MB0.4158
      Kexis 0.2.21:15.051:03.8623.42 MB0.4168
      Shorten 3.2a (-p0 -b256, default)0:39.960:27.3623.71 MB0.4221
      Ogg Squish 0.98??24.12 MB0.4293
      WavPack 3.97a (fast)0:24.340:22.1725.08 MB0.4463
      Shorten 3.2a (-p8 -b2048)0:49.060:29.9425.59 MB0.4554
      WaveZIP0:36.60?25.84 MB0.4600
      RIFF WAVE5:33.955:33.9556.18 MB1.0000
       
      + Sergei Prokofiev
      Piano Concerto No.3 (3rd movement) +
      La 0.3c19:11.6118:28.8032.65 MB0.3243
      optimFROG 4.21 (mode 4 @ 1x)43:21.8843:26.1833.58 MB0.3335
      Monkey's Audio 3.96 (extra high)3:21.333:35.9133.72 MB0.3349
      optimFROG 4.21 (mode 1 @ 4x)3:00.573:08.1933.83 MB0.3360
      optimFROG 4.21 (mode 0 @ 4x)2:00.852:09.5234.14 MB0.3390
      Monkey's Audio 3.96 (high)1:43.171:55.3134.23 MB0.3400
      Monkey's Audio 3.96 (normal)1:26.191:35.9034.66 MB0.3442
      RKAU 1.07 (normal)3:08.702:26.1735.21 MB0.3496
      LPAC 1.40 (-r, normal)2:06.211:11.9235.27 MB0.3502
      WavPack 3.97a (high)1:32.781:50.7435.35 MB0.3510
      Monkey's Audio 3.96 (fast)1:06.281:18.5635.43 MB0.3518
      WavPack 3.97a (normal)0:40.681:00.2936.99 MB0.3673
      flac 1.1.0 (-8)6:51.480:49.4738.07 MB0.3781
      flac 1.1.0 (-5, default)1:35.220:47.5738.17 MB0.3791
      flac 1.1.0 (-3)1:10.670:46.4038.51 MB0.3824
      flac 1.1.0 (-1)1:01.440:53.4039.30 MB0.3903
      Shorten 3.2a (-p0 -b256, default)1:10.570:50.0039.49 MB0.3921
      Kexis 0.2.22:12.391:49.0039.89 MB0.3962
      Bonk 0.54:33.713:19.3840.31 MB0.4003
      Ogg Squish 0.98??41.86 MB0.4157
      WavPack 3.97a (fast)0:43.240:40.1743.03 MB0.4273
      WaveZIP1:05.60?43.67 MB0.4337
      Shorten 3.2a (-p8 -b2048)1:26.840:53.1945.34 MB0.4502
      RIFF WAVE9:58.479:58.47100.68 MB1.0000
       
      + Frederic Chopin
      Prelude No.24 in d minor +
      La 0.3c5:14.835:03.089.84 MB0.3582
      Monkey's Audio 3.96 (extra high)0:55.830:59.5210.25 MB0.3734
      optimFROG 4.21 (mode 4 @ 1x)11:56.2411:58.7710.34 MB0.3764
      optimFROG 4.21 (mode 1 @ 4x)0:50.070:53.4910.41 MB0.3790
      Monkey's Audio 3.96 (high)0:28.520:31.3210.47 MB0.3812
      optimFROG 4.21 (mode 0 @ 4x)0:34.060:38.7010.53 MB0.3833
      Monkey's Audio 3.96 (normal)0:23.700:27.6110.59 MB0.3854
      LPAC 1.40 (-r, normal)0:34.910:20.0110.74 MB0.3911
      WavPack 3.97a (high)0:31.430:28.9510.76 MB0.3919
      RKAU 1.07 (normal)0:54.460:41.5410.88 MB0.3963
      Monkey's Audio 3.96 (fast)0:18.530:21.8010.94 MB0.3982
      WavPack 3.97a (normal)0:16.900:15.1711.34 MB0.4128
      flac 1.1.0 (-8)1:53.310:13.0611.69 MB0.4256
      flac 1.1.0 (-5, default)0:26.050:13.5011.71 MB0.4265
      flac 1.1.0 (-3)0:19.820:13.2511.74 MB0.4274
      flac 1.1.0 (-1)0:17.610:13.8011.86 MB0.4319
      Shorten 3.2a (-p0 -b256, default)0:19.200:11.8912.05 MB0.4386
      Kexis 0.2.20:36.700:30.2612.14 MB0.4419
      Bonk 0.51:15.450:55.0712.86 MB0.4684
      WaveZIP0:18.75?13.08 MB0.4765
      Ogg Squish 0.98??13.31 MB0.4845
      WavPack 3.97a (fast)0:06.740:08.5113.67 MB0.4978
      Shorten 3.2a (-p8 -b2048)0:24.430:14.3214.40 MB0.5242
      RIFF WAVE2:43.232:43.2327.46 MB1.0000
       
      + Domenico Scarlatti
      Sonata K.42 (arr.Yepes for guitar) +
      La 0.3c3:09.333:01.826.62 MB0.4036
      Monkey's Audio 3.96 (extra high)0:33.990:35.536.80 MB0.4145
      optimFROG 4.21 (mode 4 @ 1x)7:08.777:09.526.87 MB0.4190
      Monkey's Audio 3.96 (high)0:17.470:19.116.94 MB0.4230
      optimFROG 4.21 (mode 1 @ 4x)0:30.470:31.956.98 MB0.4255
      Monkey's Audio 3.96 (normal)0:14.840:16.177.02 MB0.4284
      RKAU 1.07 (normal)0:37.090:26.567.05 MB0.4297
      optimFROG 4.21 (mode 0 @ 4x)0:20.680:22.067.07 MB0.4310
      WavPack 3.97a (high)0:15.500:18.317.12 MB0.4340
      Monkey's Audio 3.96 (fast)0:11.390:12.957.19 MB0.4384
      LPAC 1.40 (-r, normal)0:29.990:14.337.21 MB0.4397
      WavPack 3.97a (normal)0:07.010:10.277.31 MB0.4460
      flac 1.1.0 (-8)1:08.580:07.997.37 MB0.4498
      flac 1.1.0 (-5, default)0:15.900:08.717.40 MB0.4513
      flac 1.1.0 (-3)0:11.840:08.267.43 MB0.4530
      Bonk 0.50:45.590:32.637.46 MB0.4548
      Shorten 3.2a (-p0 -b256, default)0:11.670:07.177.48 MB0.4564
      Kexis 0.2.20:22.060:18.627.50 MB0.4572
      flac 1.1.0 (-1)0:10.170:07.857.53 MB0.4591
      WavPack 3.97a (fast)0:04.110:06.577.58 MB0.4624
      Ogg Squish 0.98??7.74 MB0.4723
      WaveZIP0:10.56?7.83 MB0.4781
      Shorten 3.2a (-p8 -b2048)0:14.290:09.078.20 MB0.5004
      RIFF WAVE1:37.431:37.4316.39 MB1.0000
       
      + The Benedictine Monks of
      Santo Domingo de Silos
      Laetatus sum +
      La 0.3c4:40.714:32.2911.94 MB0.4922
      Monkey's Audio 3.96 (extra high)0:50.720:54.2012.15 MB0.5006
      optimFROG 4.21 (mode 4 @ 1x)10:34.7510:36.8312.17 MB0.5015
      Monkey's Audio 3.96 (high)0:26.360:28.5212.25 MB0.5048
      RKAU 1.07 (normal)0:57.640:41.3912.25 MB0.5049
      optimFROG 4.21 (mode 1 @ 4x)0:45.200:48.4512.43 MB0.5121
      Monkey's Audio 3.96 (normal)0:21.810:24.3312.47 MB0.5139
      LPAC 1.40 (-r, normal)0:45.660:23.2912.62 MB0.5200
      optimFROG 4.21 (mode 0 @ 4x)0:31.030:33.6912.63 MB0.5207
      WavPack 3.97a (high)0:28.010:27.4312.65 MB0.5213
      Bonk 0.51:08.180:49.7012.71 MB0.5237
      Monkey's Audio 3.96 (fast)0:16.910:20.6012.80 MB0.5277
      flac 1.1.0 (-8)1:43.740:13.2312.82 MB0.5286
      flac 1.1.0 (-5, default)0:24.120:13.0812.92 MB0.5325
      WavPack 3.97a (normal)0:15.610:15.3512.98 MB0.5348
      flac 1.1.0 (-3)0:18.800:13.8512.98 MB0.5349
      WavPack 3.97a (fast)0:11.070:10.3813.30 MB0.5481
      Kexis 0.2.20:33.430:28.1113.30 MB0.5481
      Shorten 3.2a (-p0 -b256, default)0:17.800:11.4613.32 MB0.5489
      flac 1.1.0 (-1)0:15.600:12.8213.34 MB0.5500
      Ogg Squish 0.98??13.41 MB0.5528
      Shorten 3.2a (-p8 -b2048)0:22.300:13.8713.42 MB0.5531
      WaveZIP0:16.37?13.72 MB0.5655
      RIFF WAVE2:24.212:24.2124.26 MB1.0000
       
      + L. Subramaniam
      Raga Sivapriya +
      La 0.3c41:10.1039:35.2887.51 MB0.4097
      Monkey's Audio 3.96 (extra high)7:17.867:50.7591.73 MB0.4295
      optimFROG 4.21 (mode 4 @ 1x)93:05.0093:16.0092.05 MB0.4310
      optimFROG 4.21 (mode 1 @ 4x)6:36.866:57.6992.76 MB0.4343
      Monkey's Audio 3.96 (high)3:46.784:12.3693.69 MB0.4387
      optimFROG 4.21 (mode 0 @ 4x)4:29.574:53.0194.74 MB0.4436
      Monkey's Audio 3.96 (normal)3:09.073:35.1094.81 MB0.4439
      Monkey's Audio 3.96 (fast)2:25.312:58.9295.70 MB0.4481
      RKAU 1.07 (normal)7:16.095:30.3395.91 MB0.4490
      WavPack 3.97a (high)3:41.173:56.7096.51 MB0.4518
      LPAC 1.40 (-r, normal)4:34.062:37.6896.84 MB0.4534
      WavPack 3.97a (normal)1:50.852:10.5597.75 MB0.4577
      flac 1.1.0 (-8)15:02.461:51.1598.02 MB0.4589
      flac 1.1.0 (-5, default)3:28.921:53.0798.42 MB0.4608
      Bonk 0.59:56.257:13.6898.94 MB0.4633
      flac 1.1.0 (-3)2:38.791:49.9399.22 MB0.4645
      Ogg Squish 0.98??101.88 MB0.4770
      Shorten 3.2a (-p8 -b2048)3:10.191:56.31102.60 MB0.4804
      Shorten 3.2a (-p0 -b256, default)2:36.481:42.35102.84 MB0.4815
      Kexis 0.2.24:49.843:59.93103.57 MB0.4849
      flac 1.1.0 (-1)2:15.701:51.81103.60 MB0.4851
      WavPack 3.97a (fast)1:34.441:24.44103.86 MB0.4863
      WaveZIP2:25.86?107.47 MB0.5032
      RIFF WAVE21:09.4721:09.47213.56 MB1.0000
      + + +

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/developers.html b/flac/doc/html/ru/developers.html new file mode 100644 index 0000000..10b8ea5 --- /dev/null +++ b/flac/doc/html/ru/developers.html @@ -0,0 +1,109 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | | | |
      |id | | +  | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      FLAC

      + +

      FLAC - , - . -- , diff -c ( ). , , , , .

      + +

      :

      + +

      +
    • Windows.
    • + +
    • .
    • +

      + +

      :

      + +

      +
    • .
    • + +
    • FLAC Audiofile. + +
    • !
    • +

      + +

      + +

      FLAC , FLAC . libFLAC libFLAC++, LGPL. :

      + + + +

      libFLAC libFLAC++. , .

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/documentation.html b/flac/doc/html/ru/documentation.html new file mode 100644 index 0000000..36f5f23 --- /dev/null +++ b/flac/doc/html/ru/documentation.html @@ -0,0 +1,516 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | | | |
      |id | | | +  | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      + +

      :

      + + + +

      , ( ) .

      + + +

      + +

      flac / . .

      + +

      :

      + +

      + +

      FLAC. , .

      + + +

      + +

      FLAC ( ). , . . STREAMINFO. , .., . MD5 . .

      + +

      , , , . PADDING . FLAC , , .

      + +

      , . PADDING . FLAC, , .

      + + +

      + +

      . . FLAC . . , .

      + + +

      + +

      - . , , . , . . 44.1 2-6 . - 4608. , , .

      + + +

      + +

      , . : = ( + )/2, = - . joint stereo . - . flac : -m -M, .

      + + +

      + +

      , ( , , ) . , . FLAC : 1) 2) (LPC).

      + +

      -, (-l 0) , , LPC. LPC, , . . ( 9) , , . , ( -e), .

      + +

      -, , LPC LPC. , .

      + + +

      + +

      , , () , . , , , .

      + +

      , , . , . , . flac , , -r. 2^n , -r n,n. n . m n , , -r m,n. n . m n , , . .

      + + +

      + +

      , , . . , CRC / . . , .

      + + +

      + +

      , ID3V1 ID3V2, . ID3V2 "fLaC", ID3V1 - .

      + +

      flac (-V) . . , flac .

      + + + +

      flac

      + +

      flac - , . RIFF WAVE, AIFF . flac PCM ( , A-LAW, uLAW, .. ). , 8, 16 24-. , .

      + +

      flac , RIFF WAVE ".wav", AIFF ".aif", ".aiff" AIFF; . , ".ogg" Ogg-FLAC. flac , FLAC ".flac" ( ".fla" FAT-16).

      + +

      , flac, : 1) flac ( -d); 2) -0..-8, --fast --best, , . , ; 3) flac gzip.

      + +

      flac :

      + +

      + +

      , , . , "-" (stdin). , flac (stdout). flac ( ".flac" , , ; .) , --delete-input-file.

      + +

      / .

      + +

      +
        +
      • flac [] - _
      • + +
      • flac -d [] - _
      • +
      + +

      + +
        +
      • flac [] > _
      • + +
      • flac -d [] > _
      • +
      +

      + +

      , RIFF WAVE STREAMINFO.

      + +

      -c.

      + +

      . , . RIFF WAVE AIFF, , .

      + +

      flac , . , MD5 , .

      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -v, --version flac.
      -h, --help . flac .
      -H, --explain . flac .
      -d, --decode ( flac ). flac 1, MD5 . , 0.
      -t, --test ( , , ). .
      -a, --analyze ( , , ). . . .
      -c, --stdout (stdout).
      -s, --silent /.
      -o
      --output-name=
      , flac .
      --output-prefix= . / . , , '/'.
      --delete-input-file / . , .
      --skip={#|mm:ss.ss} # . , . mm:ss.ss , , .
      +:
      +--skip=123 : 123
      +--skip=1:23.45 : 1 23.45 +
      --until={#|[+|-]mm:ss.ss} . , . . mm:ss.ss , , . +, , - -, .
      +:
      +--until=123 : 123 ( 0-122)
      +--until=1:23.45 : 1 23.45
      +--skip=1:00 --until=+1:23.45 : 1:00.00 2:23.45
      +--until=-1:23.45 : , 1 23.45
      +--until=-0:00 : +
      --ogg

      Ogg-FLAC "" FLAC. Ogg-FLAC FLAC Ogg. '.ogg' flac.

      +

      Ogg-FLAC. '.ogg'.

      --serial-number=# --ogg FLAC. flac '0'. .
      + + +

      + + + + + + +
      --residual-text . .
      --residual-gnuplot - . . .
      + + +

      + + + +
      -F,
      --decode-through-errors
      flac . -F , , flac . , .
      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -V . flac , . , . , , , .
      --lax , FLAC. , . .
      --replay-gain ReplayGain Vorbis, , VorbisGain. . ( ). , . , 8, 11.025, 12, 16, 22.05, 24, 32, 44.1 48 . , PADDING, , .
      + , .
      --cuesheet=_ CUESHEET. . SEEKTABLE, --no-cued-seekpoints.
      + , CDRwin, CDRcue, EAC .
      --sector-align +

      WAVE , , . WAVE , 44.1 . .flac , + CD-Audio ( 1/75 588 ). WAVE . .

      +

      , (, ). flac .

      + +

      : ! 'flac --sector-align *.wav', , . , , , 'flac --sector-align 8.wav 9.wav 10.wav'. +

      -S {#|X|#x|#s},
      --seekpoint={#|X|#x|#s}
      SEEKTABLE. + +
        +
      • : .
      • + +
      • : ( SEEKTABLE).
      • + +
      • #x : # , 0 .
      • + +
      • #s : # ; , , -S 9.5s , 9.5
      • +
      + +

      -S . , .
      + flac -S 10s. , -S-.
      +: -S #x -S #s , .
      +: # , , , .

      +
      -P #, --padding PADDING, ( ), STREAMINFO. --no-padding , PADDING ( ). , . , , PADDING. , PADDING 4 , 4 .
      -T =, --tag== Vorbis, , .. , . . . .
      -b #, --blocksize . 1152 -l 0, 4608. : 192/576/1152/2304/4608/256/512/1024/2048/4096/8192/16384/32768. .
      -m, --mid-side ( ). . , . , 16 .
      -M, --adaptive-mid-side ( ). -m, . , , -m .
      -0..-8 ... . -5.
      -0, --compression-level-0 -l 0 -b 1152 -r 2,2.
      -1, --compression-level-1 -l 0 -b 1152 -r 2,2 -M.
      -2, --compression-level-2 -l 0 -b 1152 -r 3 -m.
      -3, --compression-level-3 -l 6 -b 4608 -r 3,3
      -4, --compression-level-4 -l 8 -b 4608 -r 3,3 -M.
      -5, --compression-level-5 -l 8 -b 4608 -r 3,3 -m.
      -6, --compression-level-6 -l 8 -b 4608 -r 4 -m.
      -7, --compression-level-7 -l 8 -b 4608 -r 6 -m -e.
      -8, --compression-level-8 -l 12 -b 4608 -r 6 -m -e.
      --fast . -0.
      --best . -8.
      -e,
      --exhaustive-model-search
      ( !). . . LPC , . 0.5%.
      -E,
      --escape-coding
      . , . , 1%.
      -l #,
      --max-lpc-order=#
      LPC ( ). 32. 0, . , 5-10% .
      -q #,
      --qlp-coeff-precision=#
      . -q 0, . .
      -p,
      --qlp-coeff-precision-search
      LPC. -q. , . -q , -l 0.
      -r [#,]#,
      --rice-partition-order=[#,]#
      [min,]max . , 0. . , 2^min# ... 2^max , . max . -r 2,2 ( ). 1.5%. _/(2^n)=128. -r 0,16.
      + + +

      + + + + + + + + + + + + + + + + + + + + + +
      --endian={big|little} big-endian | little-endian.
      --channels=# .
      --bps=# .
      --sample-rate=# .
      --sign={signed|unsigned}, ( ).
      --force-aiff-format AIFF. , ( -o) .aiff.
      --force-raw-format ( ) .
      + + +

      + + + +
      +--no-adaptive-mid-side
      +--no-decode-through-errors
      +--no-delete-input-file
      +--no-escape-coding
      +--no-exhaustive-model-search
      +--no-lax
      +--no-mid-side
      +--no-ogg
      +--no-padding
      +--no-qlp-coeff-precision-search
      +--no-residual-gnuplot
      +--no-residual-text
      +--no-sector-align
      +--no-seektable
      +--no-silent
      +--no-verify
      .
      + + +
      +

      metaflac

      + +

      metaflac - , . , .flac , PADDING, .

      + +

      metaflac HTML , , metaflac --help man-.

      + +
      +

      XMMS

      + +

      libxmms-flac.so , XMMS ( /usr/lib/xmms/Input). . .flac XMMS.

      + +
      +

      Winamp

      + +

      Winamp: 2.x, 3.x. Winamp 2.x, in_flac.dll , Winamp ( /Plugins). . .flac Winamp.

      + +
      +

      Winamp

      + +

      Winamp: 2.x, 3.x. Winamp 3.x, cnv_flacpcm.wac , Winamp ( /Wacs). . .flac Winamp.

      + +
      +

      + +

      , SourceForge. , , e-mail .

      + +

      (1.1.0):

      + +
        +
      • .
      • +
      + +

      1.0.4 :

      + +
        +
      • . FLAC, flac 1.1.0 CUESHEET, .
      • +
      • metaflac , Vorbis, FLAC.
      • +
      + + + +

      monkey

      + +

      Monkey's Audio . , FLAC. FLAC Windows , FLAC. :

      + +
        +
      • flac.exe flac_ren.exe External/ Monkey's Audio.
      • + +
      • , : +
          +
        • Shorten - flac_mac.exe External/shortn32.exe
        • +
        • WavPack - flac_mac.exe External/wavpack.exe External/wvunpack.exe
        • +
        • RKAU - flac_mac.exe External/rkau.exe
        • +
        + WavPack, FLAC WavPack Configuration.
      • +
      • FLAC. flac_mac.exe flac.exe, flac_ren.exe .flac.
      • +
      +

      + +

      .

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/download.html b/flac/doc/html/ru/download.html new file mode 100644 index 0000000..dc032e1 --- /dev/null +++ b/flac/doc/html/ru/download.html @@ -0,0 +1,109 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | +  | | | |
      |id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      "" . -- LGPL, (flac metaflac) -- GPL. FLAC , .

      + + +

      SourceForge . , Linux, Windows Darwin ( OS X).

      + +

      RPM Planet CCRMA rpmfind.net. + +

      Debian .

      + +

      Mac OS X MacFLAC -- FLAC OS X, .pkg . Fink, FLAC Fink. + +

      CVS.

      + +

      + +

      + +

      + + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/features.html b/flac/doc/html/ru/features.html new file mode 100644 index 0000000..1b750da --- /dev/null +++ b/flac/doc/html/ru/features.html @@ -0,0 +1,124 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | +  | | |
      |id |  + |  + | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      FLAC - Free Lossless Audio Codec ( , ). FLAC :

      + +

        +
      • ;
      • +
      • ;
      • +
      • flac, , .flac;
      • +
      • metaflac, .flac;
      • +
      • .
      • +

      + +

      "" , ( FLAC ), , , / . , , .

      + +

      FLAC : Unixes (Linux, *BSD, Solaris, OS X), Windows, BeOS OS/2. autoconf/automake, MSVC, Watcom C Project Builder.

      + +

      FLAC:

      + +
    • FLAC / .
    • + + +

        +
      • : PCM , , . , 16- . MD5 , , .
      • + +
      • : . , , . .
      • + +
      • : FLAC , , .
      • + +
      • : FLAC . FLAC . FLAC , .
      • + +
      • : FLAC , , FLAC .
      • + +
      • : FLAC . . , . APPLICATION ID.
      • + +
      • : FLAC , . , .flac . MD5, flac , , . , .
      • + +
      • : FLAC CUESHEET, . , , , . , , .
      • + +
      • : , , ( ). .
      • +

      + + +

      FLAC?

      + +

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/format.html b/flac/doc/html/ru/format.html new file mode 100644 index 0000000..4c5947b --- /dev/null +++ b/flac/doc/html/ru/format.html @@ -0,0 +1,1006 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | | | +  |
      |id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + + +

      + +

      FLAC.

      + + +

      + +

      -, , , , , . :

      + +

      +
    • . Shorten. , FLAC. FLAC , Shorten.
    • + +
    • . . .
    • + +
    • . . . LPC .
    • + +
    • , , . .
    • +

      + +

      --

      + + + +

      + +

      , , . . FLAC . , , . FLAC , .

      + +

      . , , .. FLAC - , CD- (.. 44.1, 2 , 16 ). .

      + +
      +

      + +

      , FLAC :

      + +

      +
    • . , . , , .. , FLAC , .
    • + +
    • . , . .
    • + +
    • . ( ). . , . FLAC ( ), . FLAC .
    • + +
    • . , ( ) . , , . FLAC (. ), . FLAC .
    • +

      + +

      , .

      + + + +

      + +

      , "" "", . , mp3 , S/PDIF . , , "" "", , "" "" FLAC.

      + +

      +
    • - , .
    • + +
    • - . , .
    • + +
    • - . , 44.1 44100 .
    • + +
    • - .
    • + +
    • - . .
    • +

      + + +
      +

      + +

      . , , , . , , . , FLAC 16 , 65535 . , FLAC.

      + +

      , . .

      + +

      . , . , , , LPC .

      + + +
      +

      + +

      . FLAC , .

      + +

      +
    • . .
    • + +
    • . . - , - ( ).
    • + +
    • . .
    • + +
    • . .
    • +

      + +

      , , , , .

      + + +
      +

      + +

      FLAC :

      + +

      +
    • . . , . , . , . , .
    • + +
    • . , , .. . .
    • + +
    • . FLAC ( Shorten AudioPak). FLAC Shorten . , . .
    • + +
    • FIR. ( ) FLAC FIR 32 (. Shorten AudioPak). - LPC . Shorten , FLAC . FLAC , .
    • +

      + + +

      + +

      FLAC . :

      + +
        +
      1. , . .
      2. + +
      3. , .
      4. +
      + +

      , . , , .

      + +

      FLAC . - . LOCO-I pucrunch.

      + + + +

      + +

      . FLAC , . . , , . , . .

      + +

      FLAC , (big-endian). , , .

      + +
      +

      FLAC ID3v1 ( ) ID3v2 ( ). , .

      + +

      .

      + +

      +
    • FLAC "fLaC" , STREAMINFO, , .
    • + +
    • FLAC 128 . :
    • + +
      + +
    • . , , ( , , ..) . ( ) ( ). . ( ) , , , . , .
    • + +
    • , . 14- . . , , . . , , .
    • + +
    • , STREAMINFO . , , .. , . , FLAC . , , , 4 . (8/16/22.05/24/32/44.1/48/96 ). , , . . .
    • + +
    • ( ) . , . , ( , ..). .
    • + +
      +
    • FLAC (Subset format). , , , . , , . flac , . --lax . , :
    • + +
        +
      • , , 0001-0101 1000-1110. ( ), STREAMINFO .
      • +
      • 0001-1011.
      • +
      • 001-111.
      • +
      +

      + +

      FLAC. , .

      + + +

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      <32>"fLaC", FLAC ASCII, , 0x66, 0x4C, 0x61, 0x43
      _ STREAMINFO,
      _*
      +

      + + +

      + + + + + + + + + + + + + + + +
      _
      __,
      __ 

      + + +

      + + + + + + + + + + + + + + + + + + + +
      __
      <1> 1, , 0
      <7> : +
        +
      • 0 : STREAMINFO
      • +
      • 1 : PADDING
      • +
      • 2 : APPLICATION
      • +
      • 3 : SEEKTABLE
      • +
      • 4 : VORBIS_COMMENT
      • +
      • 5 : CUESHEET
      • +
      • 6-127 :
      • +
      +
      <24> ( __)

      + + +

      + + + + + + + + + + +
      __
      __STREAMINFO || __PADDING || __APPLICATION || __SEEKTABLE || __VORBIS_COMMENT || METADATA_BLOCK_CUESHEET ,

      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      __STREAMINFO
      <16> .
      <16> .
      <24> . , 0
      <24> . , 0
      <20> .
      <3>( ) - 1. FLAC 1 8 .
      <5>( ) - 1. FLAC 1 32 . 24 .
      <36> . 0, .
      <128> MD5 , , .
       : +
        +
      • FLAC 16 - 65535. , 0 15 .
      • +
      +

      + + +

      + + + + + + + + + + +
      __PADDING
      <n>n 0. n 8.

      + + +

      + + + + + + + + + + + + + + + +
      __APPLICATION
      <32> id (. )
      <n> . n 8.

      + + +

      + + + + + + + + + + + + + + + +
      __SEEKTABLE
      SEEKPOINT+ .
       : +
        +
      • "" / 18.
      • +
      +

      + + +

      + + + + + + + + + + + + + + + + + + + + + + + + +
      __SEEKPOINT
      <64> 0xFFFFFFFFFFFFFFFF .
      <64> .
      <16> .
       : +
        +
      • .
      • +
      • .
      • +
      • , , , .
      • +
      • , , .
      • +
      +

      + + +

      + + + + + + + + + +
      __VORBIS_COMMENT
      <n> Vorbis, . , Vorbis 2 ^ 64 , FLAC 2 ^ 24 . Vorbis 32- , , , , FLAC.

      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      __CUESHEET
      <128*8> , ASCII 0x20-0x7e. 0 128 , , , 0x00. 13 , 115 .
      <64> . , 0. TRACK 00, . : . Red Book , . . , . , , INDEX 01 , INDEX 00.
      <1>1, CUESHEET , 0.
      <7+258*8>. 0.
      <8> . , 100 (99 ).
      CUESHEET_TRACK+ . CUESHEET @@@@. Red Book 170.

      + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      CUESHEET_TRACK
      <64> FLAC. . ( , INDEX 01, INDEX 00.) 588 (588 = 44100 /. * 1/75 .).
      <8> . 0 , , . 1 99 170 . , 1 . .
      <12*8> (ISRC) . 12- , ; . . 12 ASCII , ISRC.
      <1> : 0 - , 1 - . Q- .
      <1> : 0 -- , 1. 5 Q- ; . .
      <6+13*8>. 0.
      <8> . , , . 100.
      ___+ .

      + + +

      + + + + + + + + + + + + + + +
      ___
      <64> . 588 (588 = 44100 /. * 1/75 .). , , .
      <8> . 0 1, 1. .
      <3*8>. 0.

      + +

      + + + + + + + + + + + + + + + + + + + + + + + 1 + +
      _ 
      +
      <?>
      _ 

      + + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      _
      <14> 11111111111110
      <2>: +
        +
      • 00 :
      • +
      • 01-11 :
      • +
      +
      <4> : +
        +
      • 0000 : STREAMINFO
      • +
      • 0001 : 192
      • +
      • 0010-0101 : 576 * (2^(2-n)) , .. 576/1152/2304/4608
      • +
      • 0110 : 8 ( -1)
      • +
      • 0111 : 16 ( -1)
      • +
      • 1000-1111 : 256 * (2^(n-8)) , .. 256/512/1024/2048/4096/8192/16384/32768
      • +
      +
      <4> : +
        +
      • 0000 : STREAMINFO
      • +
      • 0001-0011 :
      • +
      • 0100 : 8
      • +
      • 0101 : 16
      • +
      • 0110 : 22.05
      • +
      • 0111 : 24
      • +
      • 1000 : 32
      • +
      • 1001 : 44.1
      • +
      • 1010 : 48
      • +
      • 1011 : 96
      • +
      • 1100 : 8- ( )
      • +
      • 1101 : 16- ( )
      • +
      • 1110 : 16- ( )
      • +
      • 1111 : ,
      • +
      +
      <4> : +
        +
      • 0000-0111 : ( )-1. == 0001, 0 , 1 -
      • +
      • 1000 : : 0 , 1 -
      • +
      • 1001 : : 0 , 1 -
      • +
      • 1010 : : 0 , 1 - +
      • 1011-1111 :
      • +
      +
      <3> : +
        +
      • 000 : STREAMINFO
      • +
      • 001 : 8
      • +
      • 010 : 12
      • +
      • 011 :
      • +
      • 100 : 16
      • +
      • 101 : 20
      • +
      • 110 : 24
      • +
      • 111 :
      • +
      +
      <1> ,
      <?> ( )
      +    <8-56> : UTF-8 ( 36 )
      +
      +    <8-48> : UTF-8 ( 31 )
      <?> ( == 11x)
      +    8/16 ( - 1)
      <?> ( == 11xx)
      +     8/16
      <8>8- (x^8 + x^2 + x^1 + x^0) , (x ).
       : +
        +
      • 0000-0101 . 0110-0111 , , . : 0110-0111 , , .
      • +
      +

      + + +

      + + + + + + + + + + +
      _
      <16>16- (x^16 + x^15 + x^2 + x^0) (x ).

      + + +

      + + + + + + + + + + + + + + + +
      _ 
      _CONSTANT || _FIXED ||
      _LPC || _VERBATIM
      ,

      + + +

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      _
      <1> 0, .
      <6> : +
        +
      • 000000 : _CONSTANT
      • +
      • 000001 : _VERBATIM
      • +
      • 00001x :
      • +
      • 0001xx :
      • +
      • 001xxx : (xxx <= 4) _FIXED, xxx = ;
      • +
      • 01xxxx :
      • +
      • 1xxxxx : _LPC, xxxxx = -1
      • +
      +
      <1+k> ' ': +
        +
      • 0 : ' ', k=0
      • +
      • 1 : k ' ' , ; .. k=3 001, k=7 - 0000001.
      • +
      +
       : +
        +
      • ' ' , n m. k = n - m ' '. , 16- 'xxxxxxxxxxxxx000', 13 , , 3 ''.
      • +
      +

      + + +

      + + + + + +
      + +_CONSTANT
      +<n> , n

      + + +

      + + + + + + + + + + + + + + + +
      _FIXED
      <n> (n , ).

      + + +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      _LPC
      <n> (n , ).
      <4>( (QLP)) - 1. 1111 .
      <5> . (: - ).
      <n> (n = QLP * LPC) (: ).

      + + +

      + + + + + + + + + + +
      _VERBATIM
      <n*i> , n , i -

      + + +

      + + + + + + + + + + + + + + + + + + + + +
      <2> : +
        +
      • 00 :
      • +
      • 01-11 :
      • +
      +
      ___ 
       : +
        +
      • FLAC
      • +
      +

      + + +

      + + + + + + + + + + + + + + + +
      ___
      <4>
      _+ 2^

      + + +

      + + + + + + + + + + + + + + + +
      _
      <4(+5)> : +
        +
      • 0000-1110 : .
      • +
      • 1111 : , , n . n 5- . +
      +
      <?> . n : +
        +
      • 0, n .
      • +
      • , n = ( / (2^ ))
      • +
      • n = ( / (2^ )) -
      • +
      +

      + + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/goals.html b/flac/doc/html/ru/goals.html new file mode 100644 index 0000000..baa8fd4 --- /dev/null +++ b/flac/doc/html/ru/goals.html @@ -0,0 +1,104 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      |  + | | | | +  | |
      |id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + +

      FLAC:

      + +

      FLAC - , , . , . .

      + + +

      + +

        +
      • FLAC . LGPL, GPL.
      • + +
      • FLAC . , , . , FLAC . .
      • + +
      • FLAC .
      • + +
      • FLAC .
      • + +
      • FLAC .
      • + +
      • FLAC .
      • + +
      • FLAC , , .
      • +

      + + +

      + +

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/id.html b/flac/doc/html/ru/id.html new file mode 100644 index 0000000..73425bc --- /dev/null +++ b/flac/doc/html/ru/id.html @@ -0,0 +1,128 @@ + + + + + + + + + + +FLAC: id + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | | | |
      | + id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC: id

      + +

      FLAC id APPLICATION. id id, ( ).

      + +
      + +
      + + + + + + + + + +
      * id :
      * :
      * e-mail:
      url :
      url :
      + +

      :

      + + +

      (* - )

      +
      + +

      id [0..F] ( id). 32- .

      + +

      ( e-mail) id. APPLICATION .

      + +

      .

      + +

      +
      + +

      id

      +

      id.

      + +

      + + + + + + + + + + + + + + + +
      ID
      5346464C - "SFFL"Sound Font FLAC
      46746F6C - "Ftol"flac-tools
      + + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/index.html b/flac/doc/html/ru/index.html new file mode 100644 index 0000000..7157bb8 --- /dev/null +++ b/flac/doc/html/ru/index.html @@ -0,0 +1,121 @@ + + + + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | +  | | | | | |
      |id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      + +

      26 2003: FLAC 1.1.0

      + +

      FLAC 1.1.0. ReplayGain . 24- . .

      + +

      , , (.. , ). - 1.0.4 , - . , . , FLAC 1.1.0, .

      + +

      FLAC , , . .

      + +

      FLAC?

      + +

      FLAC - Free Lossless Audio Codec ( , ). FLAC :

      + +

        +
      • ;
      • +
      • ;
      • +
      • flac, , .flac;
      • +
      • metaflac, .flac;
      • +
      • .
      • +

      + +

      "" , ( FLAC ), , , / . , , .

      + +

      FLAC : Unixes (Linux, *BSD, Solaris, OS X), Windows, BeOS OS/2. autoconf/automake, MSVC, Watcom C Project Builder.

      + +

      FLAC, , . , , , .

      + + +

      + +

      , , SourceForge.

      + + +

      + +

      . flac . FLAC .

      + + +

      id

      + +

      , FLAC, , , .

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/links.html b/flac/doc/html/ru/links.html new file mode 100644 index 0000000..1d433a6 --- /dev/null +++ b/flac/doc/html/ru/links.html @@ -0,0 +1,124 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | | | | | |
      |id | | | | +  | |
      + +

      + + + + + +
      |english | +  |

      + + +

      FLAC:

      + +

      :

      +

      + + +

      , FLAC:

      +

      + + +

      , FLAC:

      +

      + +

      , FLAC:

      +

      + + +

       Copyright (c) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/doc/html/ru/news.html b/flac/doc/html/ru/news.html new file mode 100644 index 0000000..ba67798 --- /dev/null +++ b/flac/doc/html/ru/news.html @@ -0,0 +1,304 @@ + + + + + + + + + + +FLAC: + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      | | +  | | | | |
      |id | | | | | |
      + +

      + + + + + +
      |english | +  |

      + +

      FLAC:

      + +

    • 26.01.2003
      + FLAC 1.1.0, , , .

      + +

      , , (.. ). - 1.0.4 , - . , . , FLAC 1.1.0, .

      + +

      :

      + +

        +
      • :
      • + + + +
      • flac:
      • +
          +
        • FLAC AIFF; --force-aiff-format.
        • +
        • --cuesheet . , , --no-cued-seekpoints.
        • +
        • --replay-gain ReplayGain.
        • +
        • --until --skip .
        • +
        • --skip --until :..
        • +
        • -S #s , '#' .
        • +
        • flac -S 10s -S 100x.
        • +
        • flac PADDING 4 ( --no-padding).
        • +
        • --skip AIFF FLAC.
        • +
        • , WAVE , FLAC, STREAMINFO total_samples==0.
        • +
        + +
      • metaflac:
      • +
          +
        • --import-cuesheet-from . , , --no-cued-seekpoints.
        • +
        • --export-cuesheet-to FLAC.
        • +
        • --add-replay-gain ReplayGain .
        • +
        • --add-seekpoint FLAC.
        • +
        + +
      • XMMS:
      • +
          +
        • .
        • +
        • ReplayGain , .
        • +
        • Vorbis.
        • +
        • .
        • +
        • ARTIST, PERFORMER.
        • +
        + +
      • ( ):
      • +
          +
        • Valgrind. Valgrind, , .
        • +
        • FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT) .
        • +
        +

      + +

    • 24.09.2002
      + FLAC 1.0.4, :

      + +

        +
      • :
      • + +
          + +
        • Vorbis, ID3 v1 v2.
        • +
        • XMMS.
        • +
        • 8- 24- . 24- , 16- ( ).
        • +
        + +
      • flac
      • + +
          +
        • ( getopt).
        • +
        • AIFF ( ).
        • +
        • .
        • +
        • --sector-align .
        • +
        • -T, --tag Vorbis .
        • +
        • --serial-number, --ogg.
        • +
        • Vorbis.
        • +
        • .
        • +
        • , - RIFF WAVE .
        • +
        • granulepos Ogg FLAC.
        • +
        • -V.
        • +
        + +
      • metaflac
      • +
          +
        • UTF-8 Vorbis.
        • +
        • --import-vc-from --export-vc-to commands / Vorbis. , :
          + $ metaflac --export-vc-to=- --no-utf8-convert file.flac | vorbiscomment --raw -w file.ogg +
          $ vorbiscomment --raw -l file.ogg | metaflac --import-vc-from=- --no-utf8-convert file.flac
        • +
        • , ,
        • +
        + +
      • :
      • + +
          +
        • API cbcntvs Doxygen. . .
        • +
        • libOggFLAC libOggFLAC++, libFLAC libFLAC++, Ogg FLAC.
        • +
        • FLAC__SeekableStreamEncoder FLAC__FileEncoder libFLAC , .
        • +
        • .
        • +
        • , .
        • +
        • VORBIS_COMMENT.
        • +
        • , MD5 16- - x86 ( ).
        • +
        • , - STREAMINFO .
        • +
        • , - .
        • +
        + +

      + +

    • 22.08.2002
      + FLAC Rio Receiver Dell Digital Audio Receiver RioPlay . . .

      + +

    • 13.02.2002
      + FLAC. Phatnoise , FLAC. FLAC Phatbox . .

      + +

    • 03.12.2001
      + FLAC 1.0.2. , "" . libFLAC, . . .

      + +

    • 14.11.2001
      + FLAC 1.0.1. , .

      + +

        + +
      • :
      • + +
          +
        • Ogg-FLAC, .. flac Ogg.
        • + +
        • Winamp 3, Wasabi Beta 1 SDK.
        • + +
        • FLAC Monkey Audio GUI; . .
        • + +
        • Mac OS X. OS X.
        • + +
        • Mingw32.
        • + +
        • MS 'fmt' WAVE.
        • +
        + +
      • :
      • + +
          +
        • + SeekableStreamDecoder StreamDecoder FileDecoder. libFLAC , . . StreamDecoder FileDecoder , , libFLAC 1.0.
        • + +
        • .
        • +
        + +
      • :
      • + +
          +
        • raw , 12 . WAVE .
        • + +
        • libFLAC, stdin .
        • + +
        • libFLAC, .
        • + +
        • metaflac id3v2.
        • + +
        • metaflac .
        • +
        + +

      + + +

    • 20.07.2001
      + FLAC 1.0! , .

      + +

        + +
      • '--sector-align' Audio-CD.
      • + +
      • '--output-prefix' (, , ).
      • + +
      • WAVE ( ungetc()).
      • + +
      • /.
      • + +
      • libFLAC .
      • + +
      • '
      • --sse-os
      • ' , SSE. + +
      • ( ) Winamp 2.
      • + +
      • .
      • + +
      • , .
      • +

      + + +

    • 07.06.2001

    • + FLAC 0.10. . .

      + +

        +
      • . IA-32.
      • + +
      • SEEKTABLE, , .
      • + +
      • flac gzip.
      • + +
      • -# / . -5.
      • + +
      • WAVE- .
      • + +
      • --delete-input-file, /.
      • + +
      • XMMS, .
      • + +
      • , .
      • +

      + + +

    • 31.03.2001

    • + 0.9. Winamp XMMS. (, ). .

      + + +

    • 24.03.2001

    • + 0.9, Winamp. , ( , ).

      + + +

    • 21.03.2001

    • + FLAC - 0.8. .

      + + +

    • 10.12.2000

    • +FLAC SourceForge. , .

      + +

       Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson

      + + + diff --git a/flac/examples/Makefile.am b/flac/examples/Makefile.am new file mode 100644 index 0000000..665f382 --- /dev/null +++ b/flac/examples/Makefile.am @@ -0,0 +1,27 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +if FLaC__WITH_CPPLIBS +CPPLIBS_DIRS = cpp +endif + +SUBDIRS = c $(CPPLIBS_DIRS) + +EXTRA_DIST = \ + examples.dsp \ + Makefile.lite \ + README diff --git a/flac/examples/Makefile.lite b/flac/examples/Makefile.lite new file mode 100644 index 0000000..bdf6089 --- /dev/null +++ b/flac/examples/Makefile.lite @@ -0,0 +1,49 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +.PHONY: all example_c_decode_file example_c_encode_file example_cpp_decode_file example_cpp_encode_file +all: example_c_decode_file example_c_encode_file example_cpp_decode_file example_cpp_encode_file + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +debug : CONFIG = debug +valgrind: CONFIG = valgrind +release : CONFIG = release + +debug : all +valgrind: all +release : all + +example_c_decode_file: + (cd c/decode/file && $(MAKE) -f Makefile.lite $(CONFIG)) + +example_c_encode_file: + (cd c/encode/file && $(MAKE) -f Makefile.lite $(CONFIG)) + +example_cpp_decode_file: + (cd cpp/decode/file && $(MAKE) -f Makefile.lite $(CONFIG)) + +example_cpp_encode_file: + (cd cpp/encode/file && $(MAKE) -f Makefile.lite $(CONFIG)) + +clean: + -(cd c/decode/file && $(MAKE) -f Makefile.lite clean) + -(cd c/encode/file && $(MAKE) -f Makefile.lite clean) + -(cd cpp/decode/file && $(MAKE) -f Makefile.lite clean) + -(cd cpp/encode/file && $(MAKE) -f Makefile.lite clean) diff --git a/flac/examples/README b/flac/examples/README new file mode 100644 index 0000000..aa79c15 --- /dev/null +++ b/flac/examples/README @@ -0,0 +1,12 @@ +Here are several small example programs that use the libraries in different +ways. + +The "c" directory has programs that are all in C and use libFLAC. + +The "cpp" directory has analogous programs that are all in C++ and use libFLAC++. + +The programs are: +c/decode/file/ - example_c_decode_file - Simple FLAC file decoder using libFLAC +c/encode/file/ - example_c_encode_file - Simple FLAC file encoder using libFLAC +cpp/decode/file/ - example_cpp_decode_file - Simple FLAC file decoder using libFLAC++ +cpp/encode/file/ - example_cpp_encode_file - Simple FLAC file encoder using libFLAC++ diff --git a/flac/examples/c/Makefile.am b/flac/examples/c/Makefile.am new file mode 100644 index 0000000..e20c7f0 --- /dev/null +++ b/flac/examples/c/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = decode encode diff --git a/flac/examples/c/decode/Makefile.am b/flac/examples/c/decode/Makefile.am new file mode 100644 index 0000000..3f168b6 --- /dev/null +++ b/flac/examples/c/decode/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = file diff --git a/flac/examples/c/decode/file/Makefile.am b/flac/examples/c/decode/file/Makefile.am new file mode 100644 index 0000000..a07a379 --- /dev/null +++ b/flac/examples/c/decode/file/Makefile.am @@ -0,0 +1,29 @@ +# example_c_decode_file - Simple FLAC file decoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + example_c_decode_file.dsp \ + example_c_decode_file.vcproj + +noinst_PROGRAMS = example_c_decode_file +example_c_decode_file_LDADD = \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +example_c_decode_file_SOURCES = main.c diff --git a/flac/examples/c/decode/file/Makefile.lite b/flac/examples/c/decode/file/Makefile.lite new file mode 100644 index 0000000..6371768 --- /dev/null +++ b/flac/examples/c/decode/file/Makefile.lite @@ -0,0 +1,39 @@ +# example_c_decode_file - Simple FLAC file decoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = example_c_decode_file + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/examples/c/decode/file/example_c_decode_file.dsp b/flac/examples/c/decode/file/example_c_decode_file.dsp new file mode 100644 index 0000000..aa564d7 --- /dev/null +++ b/flac/examples/c/decode/file/example_c_decode_file.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="example_c_decode_file" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=example_c_decode_file - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example_c_decode_file.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example_c_decode_file.mak" CFG="example_c_decode_file - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example_c_decode_file - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "example_c_decode_file - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example_c_decode_file - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\..\obj\release\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "example_c_decode_file - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\..\obj\debug\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "example_c_decode_file - Win32 Release" +# Name "example_c_decode_file - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/examples/c/decode/file/example_c_decode_file.vcproj b/flac/examples/c/decode/file/example_c_decode_file.vcproj new file mode 100644 index 0000000..8d2ec03 --- /dev/null +++ b/flac/examples/c/decode/file/example_c_decode_file.vcproj @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/examples/c/decode/file/main.c b/flac/examples/c/decode/file/main.c new file mode 100644 index 0000000..fff6c8c --- /dev/null +++ b/flac/examples/c/decode/file/main.c @@ -0,0 +1,190 @@ +/* example_c_decode_file - Simple FLAC file decoder using libFLAC + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This example shows how to use libFLAC to decode a FLAC file to a WAVE + * file. It only supports 16-bit stereo files. + * + * Complete API documentation can be found at: + * http://flac.sourceforge.net/api/ + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "FLAC/stream_decoder.h" + +static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + +static FLAC__uint64 total_samples = 0; +static unsigned sample_rate = 0; +static unsigned channels = 0; +static unsigned bps = 0; + +static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF + ; +} + +static FLAC__bool write_little_endian_int16(FILE *f, FLAC__int16 x) +{ + return write_little_endian_uint16(f, (FLAC__uint16)x); +} + +static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x >> 16, f) != EOF && + fputc(x >> 24, f) != EOF + ; +} + +int main(int argc, char *argv[]) +{ + FLAC__bool ok = true; + FLAC__StreamDecoder *decoder = 0; + FLAC__StreamDecoderInitStatus init_status; + FILE *fout; + + if(argc != 3) { + fprintf(stderr, "usage: %s infile.flac outfile.wav\n", argv[0]); + return 1; + } + + if((fout = fopen(argv[2], "wb")) == NULL) { + fprintf(stderr, "ERROR: opening %s for output\n", argv[2]); + return 1; + } + + if((decoder = FLAC__stream_decoder_new()) == NULL) { + fprintf(stderr, "ERROR: allocating decoder\n"); + fclose(fout); + return 1; + } + + (void)FLAC__stream_decoder_set_md5_checking(decoder, true); + + init_status = FLAC__stream_decoder_init_file(decoder, argv[1], write_callback, metadata_callback, error_callback, /*client_data=*/fout); + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing decoder: %s\n", FLAC__StreamDecoderInitStatusString[init_status]); + ok = false; + } + + if(ok) { + ok = FLAC__stream_decoder_process_until_end_of_stream(decoder); + fprintf(stderr, "decoding: %s\n", ok? "succeeded" : "FAILED"); + fprintf(stderr, " state: %s\n", FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(decoder)]); + } + + FLAC__stream_decoder_delete(decoder); + fclose(fout); + + return 0; +} + +FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + FILE *f = (FILE*)client_data; + const FLAC__uint32 total_size = (FLAC__uint32)(total_samples * channels * (bps/8)); + size_t i; + + (void)decoder; + + if(total_samples == 0) { + fprintf(stderr, "ERROR: this example only works for FLAC files that have a total_samples count in STREAMINFO\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + if(channels != 2 || bps != 16) { + fprintf(stderr, "ERROR: this example only supports 16bit stereo streams\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + + /* write WAVE header before we write the first frame */ + if(frame->header.number.sample_number == 0) { + if( + fwrite("RIFF", 1, 4, f) < 4 || + !write_little_endian_uint32(f, total_size + 36) || + fwrite("WAVEfmt ", 1, 8, f) < 8 || + !write_little_endian_uint32(f, 16) || + !write_little_endian_uint16(f, 1) || + !write_little_endian_uint16(f, (FLAC__uint16)channels) || + !write_little_endian_uint32(f, sample_rate) || + !write_little_endian_uint32(f, sample_rate * channels * (bps/8)) || + !write_little_endian_uint16(f, (FLAC__uint16)(channels * (bps/8))) || /* block align */ + !write_little_endian_uint16(f, (FLAC__uint16)bps) || + fwrite("data", 1, 4, f) < 4 || + !write_little_endian_uint32(f, total_size) + ) { + fprintf(stderr, "ERROR: write error\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + /* write decoded PCM samples */ + for(i = 0; i < frame->header.blocksize; i++) { + if( + !write_little_endian_int16(f, (FLAC__int16)buffer[0][i]) || /* left channel */ + !write_little_endian_int16(f, (FLAC__int16)buffer[1][i]) /* right channel */ + ) { + fprintf(stderr, "ERROR: write error\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + (void)decoder, (void)client_data; + + /* print some stats */ + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + /* save for later */ + total_samples = metadata->data.stream_info.total_samples; + sample_rate = metadata->data.stream_info.sample_rate; + channels = metadata->data.stream_info.channels; + bps = metadata->data.stream_info.bits_per_sample; + + fprintf(stderr, "sample rate : %u Hz\n", sample_rate); + fprintf(stderr, "channels : %u\n", channels); + fprintf(stderr, "bits per sample: %u\n", bps); +#ifdef _MSC_VER + fprintf(stderr, "total samples : %I64u\n", total_samples); +#else + fprintf(stderr, "total samples : %llu\n", total_samples); +#endif + } +} + +void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + (void)decoder, (void)client_data; + + fprintf(stderr, "Got error callback: %s\n", FLAC__StreamDecoderErrorStatusString[status]); +} diff --git a/flac/examples/c/encode/Makefile.am b/flac/examples/c/encode/Makefile.am new file mode 100644 index 0000000..3f168b6 --- /dev/null +++ b/flac/examples/c/encode/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = file diff --git a/flac/examples/c/encode/file/Makefile.am b/flac/examples/c/encode/file/Makefile.am new file mode 100644 index 0000000..231c9e0 --- /dev/null +++ b/flac/examples/c/encode/file/Makefile.am @@ -0,0 +1,29 @@ +# example_c_encode_file - Simple FLAC file encoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + example_c_encode_file.dsp \ + example_c_encode_file.vcproj + +noinst_PROGRAMS = example_c_encode_file +example_c_encode_file_LDADD = \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +example_c_encode_file_SOURCES = main.c diff --git a/flac/examples/c/encode/file/Makefile.lite b/flac/examples/c/encode/file/Makefile.lite new file mode 100644 index 0000000..c11a152 --- /dev/null +++ b/flac/examples/c/encode/file/Makefile.lite @@ -0,0 +1,39 @@ +# example_c_encode_file - Simple FLAC file encoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = example_c_encode_file + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/examples/c/encode/file/example_c_encode_file.dsp b/flac/examples/c/encode/file/example_c_encode_file.dsp new file mode 100644 index 0000000..faa7f5b --- /dev/null +++ b/flac/examples/c/encode/file/example_c_encode_file.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="example_c_encode_file" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=example_c_encode_file - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example_c_encode_file.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example_c_encode_file.mak" CFG="example_c_encode_file - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example_c_encode_file - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "example_c_encode_file - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example_c_encode_file - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\..\obj\release\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "example_c_encode_file - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\..\obj\debug\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "example_c_encode_file - Win32 Release" +# Name "example_c_encode_file - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/examples/c/encode/file/example_c_encode_file.vcproj b/flac/examples/c/encode/file/example_c_encode_file.vcproj new file mode 100644 index 0000000..4f24bb6 --- /dev/null +++ b/flac/examples/c/encode/file/example_c_encode_file.vcproj @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/examples/c/encode/file/main.c b/flac/examples/c/encode/file/main.c new file mode 100644 index 0000000..061d664 --- /dev/null +++ b/flac/examples/c/encode/file/main.c @@ -0,0 +1,173 @@ +/* example_c_encode_file - Simple FLAC file encoder using libFLAC + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This example shows how to use libFLAC to encode a WAVE file to a FLAC + * file. It only supports 16-bit stereo files in canonical WAVE format. + * + * Complete API documentation can be found at: + * http://flac.sourceforge.net/api/ + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include "FLAC/metadata.h" +#include "FLAC/stream_encoder.h" + +static void progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data); + +#define READSIZE 1024 + +static unsigned total_samples = 0; /* can use a 32-bit number due to WAVE size limitations */ +static FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */ +static FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/]; + +int main(int argc, char *argv[]) +{ + FLAC__bool ok = true; + FLAC__StreamEncoder *encoder = 0; + FLAC__StreamEncoderInitStatus init_status; + FLAC__StreamMetadata *metadata[2]; + FLAC__StreamMetadata_VorbisComment_Entry entry; + FILE *fin; + unsigned sample_rate = 0; + unsigned channels = 0; + unsigned bps = 0; + + if(argc != 3) { + fprintf(stderr, "usage: %s infile.wav outfile.flac\n", argv[0]); + return 1; + } + + if((fin = fopen(argv[1], "rb")) == NULL) { + fprintf(stderr, "ERROR: opening %s for output\n", argv[1]); + return 1; + } + + /* read wav header and validate it */ + if( + fread(buffer, 1, 44, fin) != 44 || + memcmp(buffer, "RIFF", 4) || + memcmp(buffer+8, "WAVEfmt \020\000\000\000\001\000\002\000", 16) || + memcmp(buffer+32, "\004\000\020\000data", 8) + ) { + fprintf(stderr, "ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\n"); + fclose(fin); + return 1; + } + sample_rate = ((((((unsigned)buffer[27] << 8) | buffer[26]) << 8) | buffer[25]) << 8) | buffer[24]; + channels = 2; + bps = 16; + total_samples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / 4; + + /* allocate the encoder */ + if((encoder = FLAC__stream_encoder_new()) == NULL) { + fprintf(stderr, "ERROR: allocating encoder\n"); + fclose(fin); + return 1; + } + + ok &= FLAC__stream_encoder_set_verify(encoder, true); + ok &= FLAC__stream_encoder_set_compression_level(encoder, 5); + ok &= FLAC__stream_encoder_set_channels(encoder, channels); + ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, bps); + ok &= FLAC__stream_encoder_set_sample_rate(encoder, sample_rate); + ok &= FLAC__stream_encoder_set_total_samples_estimate(encoder, total_samples); + + /* now add some metadata; we'll add some tags and a padding block */ + if(ok) { + if( + (metadata[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL || + (metadata[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == NULL || + /* there are many tag (vorbiscomment) functions but these are convenient for this particular use: */ + !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "ARTIST", "Some Artist") || + !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) || /* copy=false: let metadata object take control of entry's allocated string */ + !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "YEAR", "1984") || + !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) + ) { + fprintf(stderr, "ERROR: out of memory or tag error\n"); + ok = false; + } + + metadata[1]->length = 1234; /* set the padding length */ + + ok = FLAC__stream_encoder_set_metadata(encoder, metadata, 2); + } + + /* initialize encoder */ + if(ok) { + init_status = FLAC__stream_encoder_init_file(encoder, argv[2], progress_callback, /*client_data=*/NULL); + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[init_status]); + ok = false; + } + } + + /* read blocks of samples from WAVE file and feed to encoder */ + if(ok) { + size_t left = (size_t)total_samples; + while(ok && left) { + size_t need = (left>READSIZE? (size_t)READSIZE : (size_t)left); + if(fread(buffer, channels*(bps/8), need, fin) != need) { + fprintf(stderr, "ERROR: reading from WAVE file\n"); + ok = false; + } + else { + /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ + size_t i; + for(i = 0; i < need*channels; i++) { + /* inefficient but simple and works on big- or little-endian machines */ + pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2*i+1] << 8) | (FLAC__int16)buffer[2*i]); + } + /* feed samples to encoder */ + ok = FLAC__stream_encoder_process_interleaved(encoder, pcm, need); + } + left -= need; + } + } + + ok &= FLAC__stream_encoder_finish(encoder); + + fprintf(stderr, "encoding: %s\n", ok? "succeeded" : "FAILED"); + fprintf(stderr, " state: %s\n", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]); + + /* now that encoding is finished, the metadata can be freed */ + FLAC__metadata_object_delete(metadata[0]); + FLAC__metadata_object_delete(metadata[1]); + + FLAC__stream_encoder_delete(encoder); + fclose(fin); + + return 0; +} + +void progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data) +{ + (void)encoder, (void)client_data; + +#ifdef _MSC_VER + fprintf(stderr, "wrote %I64u bytes, %I64u/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); +#else + fprintf(stderr, "wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); +#endif +} diff --git a/flac/examples/cpp/Makefile.am b/flac/examples/cpp/Makefile.am new file mode 100644 index 0000000..e20c7f0 --- /dev/null +++ b/flac/examples/cpp/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = decode encode diff --git a/flac/examples/cpp/decode/Makefile.am b/flac/examples/cpp/decode/Makefile.am new file mode 100644 index 0000000..3f168b6 --- /dev/null +++ b/flac/examples/cpp/decode/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = file diff --git a/flac/examples/cpp/decode/file/Makefile.am b/flac/examples/cpp/decode/file/Makefile.am new file mode 100644 index 0000000..6269055 --- /dev/null +++ b/flac/examples/cpp/decode/file/Makefile.am @@ -0,0 +1,30 @@ +# example_cpp_decode_file - Simple FLAC file decoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + example_cpp_decode_file.dsp \ + example_cpp_decode_file.vcproj + +noinst_PROGRAMS = example_cpp_decode_file +example_cpp_decode_file_LDADD = \ + $(top_builddir)/src/libFLAC++/libFLAC++.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +example_cpp_decode_file_SOURCES = main.cpp diff --git a/flac/examples/cpp/decode/file/Makefile.lite b/flac/examples/cpp/decode/file/Makefile.lite new file mode 100644 index 0000000..5f7ed25 --- /dev/null +++ b/flac/examples/cpp/decode/file/Makefile.lite @@ -0,0 +1,41 @@ +# example_cpp_decode_file - Simple FLAC file decoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = example_cpp_decode_file + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC++.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC++ -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_CPP = main.cpp + +include $(topdir)/build/exe.mk + +LINK = $(CCC) $(LINKAGE) + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/examples/cpp/decode/file/example_cpp_decode_file.dsp b/flac/examples/cpp/decode/file/example_cpp_decode_file.dsp new file mode 100644 index 0000000..51343d7 --- /dev/null +++ b/flac/examples/cpp/decode/file/example_cpp_decode_file.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="example_cpp_decode_file" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=example_cpp_decode_file - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example_cpp_decode_file.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example_cpp_decode_file.mak" CFG="example_cpp_decode_file - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example_cpp_decode_file - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "example_cpp_decode_file - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example_cpp_decode_file - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\..\obj\release\lib\libFLAC++_static.lib ..\..\..\..\obj\release\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "example_cpp_decode_file - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\..\obj\debug\lib\libFLAC++_static.lib ..\..\..\..\obj\debug\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "example_cpp_decode_file - Win32 Release" +# Name "example_cpp_decode_file - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/examples/cpp/decode/file/example_cpp_decode_file.vcproj b/flac/examples/cpp/decode/file/example_cpp_decode_file.vcproj new file mode 100644 index 0000000..7b2564c --- /dev/null +++ b/flac/examples/cpp/decode/file/example_cpp_decode_file.vcproj @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/examples/cpp/decode/file/main.cpp b/flac/examples/cpp/decode/file/main.cpp new file mode 100644 index 0000000..b278fbc --- /dev/null +++ b/flac/examples/cpp/decode/file/main.cpp @@ -0,0 +1,189 @@ +/* example_cpp_decode_file - Simple FLAC file decoder using libFLAC + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This example shows how to use libFLAC++ to decode a FLAC file to a WAVE + * file. It only supports 16-bit stereo files. + * + * Complete API documentation can be found at: + * http://flac.sourceforge.net/api/ + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "FLAC++/decoder.h" + +static FLAC__uint64 total_samples = 0; +static unsigned sample_rate = 0; +static unsigned channels = 0; +static unsigned bps = 0; + +static bool write_little_endian_uint16(FILE *f, FLAC__uint16 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF + ; +} + +static bool write_little_endian_int16(FILE *f, FLAC__int16 x) +{ + return write_little_endian_uint16(f, (FLAC__uint16)x); +} + +static bool write_little_endian_uint32(FILE *f, FLAC__uint32 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x >> 16, f) != EOF && + fputc(x >> 24, f) != EOF + ; +} + +class OurDecoder: public FLAC::Decoder::File { +public: + OurDecoder(FILE *f_): FLAC::Decoder::File(), f(f_) { } +protected: + FILE *f; + + virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]); + virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata); + virtual void error_callback(::FLAC__StreamDecoderErrorStatus status); +}; + +int main(int argc, char *argv[]) +{ + bool ok = true; + FILE *fout; + + if(argc != 3) { + fprintf(stderr, "usage: %s infile.flac outfile.wav\n", argv[0]); + return 1; + } + + if((fout = fopen(argv[2], "wb")) == NULL) { + fprintf(stderr, "ERROR: opening %s for output\n", argv[2]); + return 1; + } + + OurDecoder decoder(fout); + + if(!decoder) { + fprintf(stderr, "ERROR: allocating decoder\n"); + fclose(fout); + return 1; + } + + (void)decoder.set_md5_checking(true); + + FLAC__StreamDecoderInitStatus init_status = decoder.init(argv[1]); + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing decoder: %s\n", FLAC__StreamDecoderInitStatusString[init_status]); + ok = false; + } + + if(ok) { + ok = decoder.process_until_end_of_stream(); + fprintf(stderr, "decoding: %s\n", ok? "succeeded" : "FAILED"); + fprintf(stderr, " state: %s\n", decoder.get_state().resolved_as_cstring(decoder)); + } + + fclose(fout); + + return 0; +} + +::FLAC__StreamDecoderWriteStatus OurDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) +{ + const FLAC__uint32 total_size = (FLAC__uint32)(total_samples * channels * (bps/8)); + size_t i; + + if(total_samples == 0) { + fprintf(stderr, "ERROR: this example only works for FLAC files that have a total_samples count in STREAMINFO\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + if(channels != 2 || bps != 16) { + fprintf(stderr, "ERROR: this example only supports 16bit stereo streams\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + + /* write WAVE header before we write the first frame */ + if(frame->header.number.sample_number == 0) { + if( + fwrite("RIFF", 1, 4, f) < 4 || + !write_little_endian_uint32(f, total_size + 36) || + fwrite("WAVEfmt ", 1, 8, f) < 8 || + !write_little_endian_uint32(f, 16) || + !write_little_endian_uint16(f, 1) || + !write_little_endian_uint16(f, (FLAC__uint16)channels) || + !write_little_endian_uint32(f, sample_rate) || + !write_little_endian_uint32(f, sample_rate * channels * (bps/8)) || + !write_little_endian_uint16(f, (FLAC__uint16)(channels * (bps/8))) || /* block align */ + !write_little_endian_uint16(f, (FLAC__uint16)bps) || + fwrite("data", 1, 4, f) < 4 || + !write_little_endian_uint32(f, total_size) + ) { + fprintf(stderr, "ERROR: write error\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + /* write decoded PCM samples */ + for(i = 0; i < frame->header.blocksize; i++) { + if( + !write_little_endian_int16(f, (FLAC__int16)buffer[0][i]) || /* left channel */ + !write_little_endian_int16(f, (FLAC__int16)buffer[1][i]) /* right channel */ + ) { + fprintf(stderr, "ERROR: write error\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void OurDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) +{ + /* print some stats */ + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + /* save for later */ + total_samples = metadata->data.stream_info.total_samples; + sample_rate = metadata->data.stream_info.sample_rate; + channels = metadata->data.stream_info.channels; + bps = metadata->data.stream_info.bits_per_sample; + + fprintf(stderr, "sample rate : %u Hz\n", sample_rate); + fprintf(stderr, "channels : %u\n", channels); + fprintf(stderr, "bits per sample: %u\n", bps); +#ifdef _MSC_VER + fprintf(stderr, "total samples : %I64u\n", total_samples); +#else + fprintf(stderr, "total samples : %llu\n", total_samples); +#endif + } +} + +void OurDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status) +{ + fprintf(stderr, "Got error callback: %s\n", FLAC__StreamDecoderErrorStatusString[status]); +} diff --git a/flac/examples/cpp/encode/Makefile.am b/flac/examples/cpp/encode/Makefile.am new file mode 100644 index 0000000..3f168b6 --- /dev/null +++ b/flac/examples/cpp/encode/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = file diff --git a/flac/examples/cpp/encode/file/Makefile.am b/flac/examples/cpp/encode/file/Makefile.am new file mode 100644 index 0000000..c91245a --- /dev/null +++ b/flac/examples/cpp/encode/file/Makefile.am @@ -0,0 +1,30 @@ +# example_cpp_encode_file - Simple FLAC file encoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + example_cpp_encode_file.dsp \ + example_cpp_encode_file.vcproj + +noinst_PROGRAMS = example_cpp_encode_file +example_cpp_encode_file_LDADD = \ + $(top_builddir)/src/libFLAC++/libFLAC++.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +example_cpp_encode_file_SOURCES = main.cpp diff --git a/flac/examples/cpp/encode/file/Makefile.lite b/flac/examples/cpp/encode/file/Makefile.lite new file mode 100644 index 0000000..dbba7ad --- /dev/null +++ b/flac/examples/cpp/encode/file/Makefile.lite @@ -0,0 +1,41 @@ +# example_cpp_encode_file - Simple FLAC file encoder using libFLAC +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = example_cpp_encode_file + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC++.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC++ -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_CPP = main.cpp + +include $(topdir)/build/exe.mk + +LINK = $(CCC) $(LINKAGE) + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/examples/cpp/encode/file/example_cpp_encode_file.dsp b/flac/examples/cpp/encode/file/example_cpp_encode_file.dsp new file mode 100644 index 0000000..99001f5 --- /dev/null +++ b/flac/examples/cpp/encode/file/example_cpp_encode_file.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="example_cpp_encode_file" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=example_cpp_encode_file - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example_cpp_encode_file.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example_cpp_encode_file.mak" CFG="example_cpp_encode_file - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example_cpp_encode_file - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "example_cpp_encode_file - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example_cpp_encode_file - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\..\obj\release\lib\libFLAC++_static.lib ..\..\..\..\obj\release\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "example_cpp_encode_file - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\..\obj\debug\lib\libFLAC++_static.lib ..\..\..\..\obj\debug\lib\libFLAC_static.lib ..\..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "example_cpp_encode_file - Win32 Release" +# Name "example_cpp_encode_file - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/examples/cpp/encode/file/example_cpp_encode_file.vcproj b/flac/examples/cpp/encode/file/example_cpp_encode_file.vcproj new file mode 100644 index 0000000..443ff1d --- /dev/null +++ b/flac/examples/cpp/encode/file/example_cpp_encode_file.vcproj @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/examples/cpp/encode/file/main.cpp b/flac/examples/cpp/encode/file/main.cpp new file mode 100644 index 0000000..4342aeb --- /dev/null +++ b/flac/examples/cpp/encode/file/main.cpp @@ -0,0 +1,176 @@ +/* example_cpp_encode_file - Simple FLAC file encoder using libFLAC + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This example shows how to use libFLAC++ to encode a WAVE file to a FLAC + * file. It only supports 16-bit stereo files in canonical WAVE format. + * + * Complete API documentation can be found at: + * http://flac.sourceforge.net/api/ + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include "FLAC++/metadata.h" +#include "FLAC++/encoder.h" + +class OurEncoder: public FLAC::Encoder::File { +public: + OurEncoder(): FLAC::Encoder::File() { } +protected: + virtual void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate); +}; + +#define READSIZE 1024 + +static unsigned total_samples = 0; /* can use a 32-bit number due to WAVE size limitations */ +static FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */ +static FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/]; +static FLAC__int32 *pcm_[2] = { pcm, pcm+READSIZE }; + +int main(int argc, char *argv[]) +{ + bool ok = true; + OurEncoder encoder; + FLAC__StreamEncoderInitStatus init_status; + FLAC__StreamMetadata *metadata[2]; + FLAC__StreamMetadata_VorbisComment_Entry entry; + FILE *fin; + unsigned sample_rate = 0; + unsigned channels = 0; + unsigned bps = 0; + + if(argc != 3) { + fprintf(stderr, "usage: %s infile.wav outfile.flac\n", argv[0]); + return 1; + } + + if((fin = fopen(argv[1], "rb")) == NULL) { + fprintf(stderr, "ERROR: opening %s for output\n", argv[1]); + return 1; + } + + /* read wav header and validate it */ + if( + fread(buffer, 1, 44, fin) != 44 || + memcmp(buffer, "RIFF", 4) || + memcmp(buffer+8, "WAVEfmt \020\000\000\000\001\000\002\000", 16) || + memcmp(buffer+32, "\004\000\020\000data", 8) + ) { + fprintf(stderr, "ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\n"); + fclose(fin); + return 1; + } + sample_rate = ((((((unsigned)buffer[27] << 8) | buffer[26]) << 8) | buffer[25]) << 8) | buffer[24]; + channels = 2; + bps = 16; + total_samples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / 4; + + /* check the encoder */ + if(!encoder) { + fprintf(stderr, "ERROR: allocating encoder\n"); + fclose(fin); + return 1; + } + + ok &= encoder.set_verify(true); + ok &= encoder.set_compression_level(5); + ok &= encoder.set_channels(channels); + ok &= encoder.set_bits_per_sample(bps); + ok &= encoder.set_sample_rate(sample_rate); + ok &= encoder.set_total_samples_estimate(total_samples); + + /* now add some metadata; we'll add some tags and a padding block */ + if(ok) { + if( + (metadata[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL || + (metadata[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == NULL || + /* there are many tag (vorbiscomment) functions but these are convenient for this particular use: */ + !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "ARTIST", "Some Artist") || + !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) || /* copy=false: let metadata object take control of entry's allocated string */ + !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "YEAR", "1984") || + !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) + ) { + fprintf(stderr, "ERROR: out of memory or tag error\n"); + ok = false; + } + + metadata[1]->length = 1234; /* set the padding length */ + + ok = encoder.set_metadata(metadata, 2); + } + + /* initialize encoder */ + if(ok) { + init_status = encoder.init(argv[2]); + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[init_status]); + ok = false; + } + } + + /* read blocks of samples from WAVE file and feed to encoder */ + if(ok) { + size_t left = (size_t)total_samples; + while(ok && left) { + size_t need = (left>READSIZE? (size_t)READSIZE : (size_t)left); + if(fread(buffer, channels*(bps/8), need, fin) != need) { + fprintf(stderr, "ERROR: reading from WAVE file\n"); + ok = false; + } + else { + /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ + size_t i; + for(i = 0; i < need*channels; i++) { + /* inefficient but simple and works on big- or little-endian machines */ + pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2*i+1] << 8) | (FLAC__int16)buffer[2*i]); + } + /* feed samples to encoder */ + ok = encoder.process_interleaved(pcm, need); + } + left -= need; + } + } + + ok &= encoder.finish(); + + fprintf(stderr, "encoding: %s\n", ok? "succeeded" : "FAILED"); + fprintf(stderr, " state: %s\n", encoder.get_state().resolved_as_cstring(encoder)); + + /* now that encoding is finished, the metadata can be freed */ + FLAC__metadata_object_delete(metadata[0]); + FLAC__metadata_object_delete(metadata[1]); + + fclose(fin); + + return 0; +} + +void OurEncoder::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate) +{ +#ifdef _MSC_VER + fprintf(stderr, "wrote %I64u bytes, %I64u/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); +#else + fprintf(stderr, "wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); +#endif +} diff --git a/flac/examples/examples.dsp b/flac/examples/examples.dsp new file mode 100644 index 0000000..cd4a397 --- /dev/null +++ b/flac/examples/examples.dsp @@ -0,0 +1,67 @@ +# Microsoft Developer Studio Project File - Name="examples" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Generic Project" 0x010a + +CFG=examples - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "examples.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "examples.mak" CFG="examples - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "examples - Win32 Release" (based on "Win32 (x86) Generic Project") +!MESSAGE "examples - Win32 Debug" (based on "Win32 (x86) Generic Project") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "all" +# PROP Scc_LocalPath "." +MTL=midl.exe + +!IF "$(CFG)" == "examples - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\obj\release" +# PROP Intermediate_Dir "..\obj\release" +# PROP Target_Dir "" + +!ELSEIF "$(CFG)" == "examples - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\obj\debug" +# PROP Intermediate_Dir "..\obj\debug" +# PROP Target_Dir "" + +!ENDIF + +# Begin Target + +# Name "examples - Win32 Release" +# Name "examples - Win32 Debug" +# Begin Source File + +SOURCE=.\README +# End Source File +# End Target +# End Project diff --git a/flac/flac.pbproj/Makefile.am b/flac/flac.pbproj/Makefile.am new file mode 100644 index 0000000..d2a2e99 --- /dev/null +++ b/flac/flac.pbproj/Makefile.am @@ -0,0 +1,19 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + project.pbxproj diff --git a/flac/flac.pbproj/project.pbxproj b/flac/flac.pbproj/project.pbxproj new file mode 100644 index 0000000..f1ef841 --- /dev/null +++ b/flac/flac.pbproj/project.pbxproj @@ -0,0 +1,4479 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 34; + objects = { + F513F76501976EFF01A8006D = { + buildActionMask = 2147483647; + files = ( + ); + generatedFileNames = ( + ); + isa = PBXShellScriptBuildPhase; + name = "Shell Script"; + neededFileNames = ( + ); + shellPath = /bin/sh; + shellScript = $SRCROOT/build/project_builder_prebuild_phase.sh; + }; + F51C735C0199C3DF01A8006D = { + isa = PBXFileReference; + path = seekable_stream_decoder.h; + refType = 4; + }; + F51C735D0199C3DF01A8006D = { + fileRef = F51C735C0199C3DF01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F51C735E0199C42101A8006D = { + isa = PBXFileReference; + path = seekable_stream_decoder.h; + refType = 4; + }; + F51C735F0199C42101A8006D = { + isa = PBXFileReference; + path = seekable_stream_decoder.c; + refType = 4; + }; + F51C73600199C42101A8006D = { + fileRef = F51C735E0199C42101A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F51C73610199C42101A8006D = { + fileRef = F51C735F0199C42101A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F51F398106F771C3015798D4 = { + isa = PBXFileReference; + name = ogg_mapping.c; + path = libOggFLAC/ogg_mapping.c; + refType = 4; + }; + F51F398206F771C4015798D4 = { + fileRef = F51F398106F771C3015798D4; + isa = PBXBuildFile; + settings = { + }; + }; + F51F398306F771F4015798D4 = { + isa = PBXFileReference; + path = ogg_mapping.h; + refType = 4; + }; + F51F398406F771F5015798D4 = { + fileRef = F51F398306F771F4015798D4; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE6406B46AC4014FDB82 = { + isa = PBXLibraryReference; + path = libOggFLAC.a; + refType = 3; + }; + F54AFE6506B46AC4014FDB82 = { + buildPhases = ( + F54AFE6606B46AC4014FDB82, + F54AFE6706B46AC4014FDB82, + F54AFE6806B46AC4014FDB82, + F54AFE6906B46AC4014FDB82, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "/sw/include src/libOggFLAC/include include"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libOggFLAC.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libOggFLAC; + productInstallPath = /usr/local/lib; + productName = libOggFLAC; + productReference = F54AFE6406B46AC4014FDB82; + shouldUseHeadermap = 0; + }; + F54AFE6606B46AC4014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFEB406B46FF0014FDB82, + F54AFEB506B46FF0014FDB82, + F54AFEB606B46FF0014FDB82, + F54AFEB706B46FF0014FDB82, + F54AFEB806B46FF0014FDB82, + F54AFEB906B46FF0014FDB82, + F54AFEBA06B46FF0014FDB82, + F54AFEBB06B46FF0014FDB82, + F54AFED506B4703C014FDB82, + F54AFED606B4703C014FDB82, + F54AFED706B4703C014FDB82, + F54AFED806B4703C014FDB82, + F51F398406F771F5015798D4, + F54AFED906B4703C014FDB82, + F54AFEDA06B4703C014FDB82, + F54AFEDB06B4703C014FDB82, + F54AFEDC06B4703C014FDB82, + F54AFEDD06B4703C014FDB82, + F54AFEDE06B4703C014FDB82, + F54AFEDF06B4703C014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F54AFE6706B46AC4014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFEE006B4703C014FDB82, + F54AFEE106B4703C014FDB82, + F54AFEE206B4703C014FDB82, + F54AFEE306B4703C014FDB82, + F54AFEE406B4703C014FDB82, + F51F398206F771C4015798D4, + F54AFEE506B4703C014FDB82, + F54AFEE606B4703C014FDB82, + F54AFEE706B4703C014FDB82, + F54AFEE806B4703C014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F54AFE6806B46AC4014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F54AFE6906B46AC4014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F54AFE6A06B46CDB014FDB82 = { + isa = PBXFileReference; + path = callback.h; + refType = 4; + }; + F54AFE6B06B46CDB014FDB82 = { + isa = PBXFileReference; + path = export.h; + refType = 4; + }; + F54AFE6C06B46CDB014FDB82 = { + isa = PBXFileReference; + path = file_encoder.h; + refType = 4; + }; + F54AFE6D06B46CDB014FDB82 = { + isa = PBXFileReference; + path = ordinals.h; + refType = 4; + }; + F54AFE6E06B46CDB014FDB82 = { + isa = PBXFileReference; + path = seekable_stream_encoder.h; + refType = 4; + }; + F54AFE6F06B46CDC014FDB82 = { + fileRef = F54AFE6A06B46CDB014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7006B46CDC014FDB82 = { + fileRef = F54AFE6B06B46CDB014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7106B46CDC014FDB82 = { + fileRef = F54AFE6C06B46CDB014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7206B46CDC014FDB82 = { + fileRef = F54AFE6D06B46CDB014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7306B46CDC014FDB82 = { + fileRef = F54AFE6E06B46CDB014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7406B46DD3014FDB82 = { + isa = PBXFileReference; + name = file_encoder.c; + path = src/libFLAC/file_encoder.c; + refType = 2; + }; + F54AFE7506B46DD3014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_encoder.c; + path = src/libFLAC/seekable_stream_encoder.c; + refType = 2; + }; + F54AFE7606B46DD3014FDB82 = { + fileRef = F54AFE7406B46DD3014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7706B46DD3014FDB82 = { + fileRef = F54AFE7506B46DD3014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7806B46E73014FDB82 = { + isa = PBXFileReference; + path = export.h; + refType = 4; + }; + F54AFE7906B46E73014FDB82 = { + isa = PBXFileReference; + path = format.h; + refType = 4; + }; + F54AFE7A06B46E73014FDB82 = { + isa = PBXFileReference; + path = file_encoder.h; + refType = 4; + }; + F54AFE7B06B46E73014FDB82 = { + isa = PBXFileReference; + path = seekable_stream_encoder.h; + refType = 4; + }; + F54AFE7C06B46E73014FDB82 = { + isa = PBXFileReference; + path = file_encoder.cpp; + refType = 4; + }; + F54AFE7D06B46E73014FDB82 = { + isa = PBXFileReference; + path = seekable_stream_encoder.cpp; + refType = 4; + }; + F54AFE7E06B46E73014FDB82 = { + fileRef = F54AFE7906B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE7F06B46E73014FDB82 = { + fileRef = F54AFE7A06B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8006B46E73014FDB82 = { + fileRef = F54AFE7B06B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8106B46E73014FDB82 = { + fileRef = F54AFE7806B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8206B46E73014FDB82 = { + fileRef = F54AFE7C06B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8306B46E73014FDB82 = { + fileRef = F54AFE7D06B46E73014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8406B46EBF014FDB82 = { + isa = PBXFileReference; + path = local_string_utils.c; + refType = 4; + }; + F54AFE8506B46EBF014FDB82 = { + isa = PBXFileReference; + path = local_string_utils.h; + refType = 4; + }; + F54AFE8606B46EBF014FDB82 = { + isa = PBXFileReference; + path = utils.c; + refType = 4; + }; + F54AFE8706B46EBF014FDB82 = { + isa = PBXFileReference; + path = utils.h; + refType = 4; + }; + F54AFE8806B46EBF014FDB82 = { + isa = PBXFileReference; + path = vorbiscomment.c; + refType = 4; + }; + F54AFE8906B46EBF014FDB82 = { + isa = PBXFileReference; + path = vorbiscomment.h; + refType = 4; + }; + F54AFE8A06B46EBF014FDB82 = { + fileRef = F54AFE8506B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8B06B46EBF014FDB82 = { + fileRef = F54AFE8706B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8C06B46EBF014FDB82 = { + fileRef = F54AFE8906B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8D06B46EBF014FDB82 = { + fileRef = F54AFE8406B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8E06B46EBF014FDB82 = { + fileRef = F54AFE8606B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE8F06B46EBF014FDB82 = { + fileRef = F54AFE8806B46EBF014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE9006B46F13014FDB82 = { + isa = PBXFileReference; + path = operations_shorthand_cuesheet.c; + refType = 4; + }; + F54AFE9106B46F13014FDB82 = { + isa = PBXFileReference; + path = operations_shorthand_seektable.c; + refType = 4; + }; + F54AFE9206B46F13014FDB82 = { + isa = PBXFileReference; + path = operations_shorthand_streaminfo.c; + refType = 4; + }; + F54AFE9306B46F13014FDB82 = { + isa = PBXFileReference; + path = operations_shorthand_vorbiscomment.c; + refType = 4; + }; + F54AFE9406B46F13014FDB82 = { + isa = PBXFileReference; + path = operations.c; + refType = 4; + }; + F54AFE9506B46F13014FDB82 = { + isa = PBXFileReference; + path = operations.h; + refType = 4; + }; + F54AFE9606B46F13014FDB82 = { + isa = PBXFileReference; + path = options.c; + refType = 4; + }; + F54AFE9706B46F13014FDB82 = { + isa = PBXFileReference; + path = options.h; + refType = 4; + }; + F54AFE9806B46F13014FDB82 = { + isa = PBXFileReference; + path = usage.c; + refType = 4; + }; + F54AFE9906B46F13014FDB82 = { + isa = PBXFileReference; + path = usage.h; + refType = 4; + }; + F54AFE9A06B46F13014FDB82 = { + isa = PBXFileReference; + path = utils.c; + refType = 4; + }; + F54AFE9B06B46F13014FDB82 = { + isa = PBXFileReference; + path = utils.h; + refType = 4; + }; + F54AFE9C06B46F13014FDB82 = { + fileRef = F54AFE9506B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE9D06B46F13014FDB82 = { + fileRef = F54AFE9706B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE9E06B46F13014FDB82 = { + fileRef = F54AFE9906B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFE9F06B46F13014FDB82 = { + fileRef = F54AFE9B06B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA006B46F13014FDB82 = { + fileRef = F54AFE9006B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA106B46F13014FDB82 = { + fileRef = F54AFE9106B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA206B46F13014FDB82 = { + fileRef = F54AFE9206B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA306B46F13014FDB82 = { + fileRef = F54AFE9306B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA406B46F13014FDB82 = { + fileRef = F54AFE9406B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA506B46F13014FDB82 = { + fileRef = F54AFE9606B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA606B46F13014FDB82 = { + fileRef = F54AFE9806B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA706B46F13014FDB82 = { + fileRef = F54AFE9A06B46F13014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEA806B46FF0014FDB82 = { + children = ( + F54AFEA906B46FF0014FDB82, + F54AFEAA06B46FF0014FDB82, + F54AFEAB06B46FF0014FDB82, + F54AFEAC06B46FF0014FDB82, + F54AFEAD06B46FF0014FDB82, + F54AFEAE06B46FF0014FDB82, + F54AFEAF06B46FF0014FDB82, + F54AFEB006B46FF0014FDB82, + ); + isa = PBXGroup; + name = OggFLAC; + refType = 4; + }; + F54AFEA906B46FF0014FDB82 = { + isa = PBXFileReference; + name = all.h; + path = OggFLAC/all.h; + refType = 4; + }; + F54AFEAA06B46FF0014FDB82 = { + isa = PBXFileReference; + name = export.h; + path = OggFLAC/export.h; + refType = 4; + }; + F54AFEAB06B46FF0014FDB82 = { + isa = PBXFileReference; + name = file_decoder.h; + path = OggFLAC/file_decoder.h; + refType = 4; + }; + F54AFEAC06B46FF0014FDB82 = { + isa = PBXFileReference; + name = file_encoder.h; + path = OggFLAC/file_encoder.h; + refType = 4; + }; + F54AFEAD06B46FF0014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_decoder.h; + path = OggFLAC/seekable_stream_decoder.h; + refType = 4; + }; + F54AFEAE06B46FF0014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_encoder.h; + path = OggFLAC/seekable_stream_encoder.h; + refType = 4; + }; + F54AFEAF06B46FF0014FDB82 = { + isa = PBXFileReference; + name = stream_decoder.h; + path = OggFLAC/stream_decoder.h; + refType = 4; + }; + F54AFEB006B46FF0014FDB82 = { + isa = PBXFileReference; + name = stream_encoder.h; + path = OggFLAC/stream_encoder.h; + refType = 4; + }; + F54AFEB106B46FF0014FDB82 = { + children = ( + F54AFEBE06B4703C014FDB82, + F54AFEBF06B4703C014FDB82, + F54AFEC006B4703C014FDB82, + F54AFECE06B4703C014FDB82, + F54AFECF06B4703C014FDB82, + F54AFED006B4703C014FDB82, + F54AFED106B4703C014FDB82, + F54AFED206B4703C014FDB82, + F54AFED306B4703C014FDB82, + F54AFED406B4703C014FDB82, + F51F398106F771C3015798D4, + ); + isa = PBXGroup; + name = libOggFLAC; + path = src; + refType = 2; + }; + F54AFEB206B46FF0014FDB82 = { + isa = PBXFileReference; + path = metadata_utils.c; + refType = 4; + }; + F54AFEB306B46FF0014FDB82 = { + isa = PBXFileReference; + path = metadata_utils.h; + refType = 4; + }; + F54AFEB406B46FF0014FDB82 = { + fileRef = F54AFEA906B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEB506B46FF0014FDB82 = { + fileRef = F54AFEAA06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEB606B46FF0014FDB82 = { + fileRef = F54AFEAB06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEB706B46FF0014FDB82 = { + fileRef = F54AFEAC06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEB806B46FF0014FDB82 = { + fileRef = F54AFEAD06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEB906B46FF0014FDB82 = { + fileRef = F54AFEAE06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEBA06B46FF0014FDB82 = { + fileRef = F54AFEAF06B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEBB06B46FF0014FDB82 = { + fileRef = F54AFEB006B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEBC06B46FF0014FDB82 = { + fileRef = F54AFEB306B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEBD06B46FF0014FDB82 = { + fileRef = F54AFEB206B46FF0014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEBE06B4703C014FDB82 = { + isa = PBXFileReference; + name = file_decoder.c; + path = libOggFLAC/file_decoder.c; + refType = 4; + }; + F54AFEBF06B4703C014FDB82 = { + isa = PBXFileReference; + name = file_encoder.c; + path = libOggFLAC/file_encoder.c; + refType = 4; + }; + F54AFEC006B4703C014FDB82 = { + children = ( + F54AFEC106B4703C014FDB82, + F54AFEC606B4703C014FDB82, + ); + isa = PBXGroup; + name = include; + path = libOggFLAC/include; + refType = 4; + }; + F54AFEC106B4703C014FDB82 = { + children = ( + F54AFEC206B4703C014FDB82, + F54AFEC306B4703C014FDB82, + F54AFEC406B4703C014FDB82, + F54AFEC506B4703C014FDB82, + F51F398306F771F4015798D4, + ); + isa = PBXGroup; + path = private; + refType = 4; + }; + F54AFEC206B4703C014FDB82 = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F54AFEC306B4703C014FDB82 = { + isa = PBXFileReference; + path = ogg_decoder_aspect.h; + refType = 4; + }; + F54AFEC406B4703C014FDB82 = { + isa = PBXFileReference; + path = ogg_encoder_aspect.h; + refType = 4; + }; + F54AFEC506B4703C014FDB82 = { + isa = PBXFileReference; + path = ogg_helper.h; + refType = 4; + }; + F54AFEC606B4703C014FDB82 = { + children = ( + F54AFEC706B4703C014FDB82, + F54AFEC806B4703C014FDB82, + F54AFEC906B4703C014FDB82, + F54AFECA06B4703C014FDB82, + F54AFECB06B4703C014FDB82, + F54AFECC06B4703C014FDB82, + F54AFECD06B4703C014FDB82, + ); + isa = PBXGroup; + path = protected; + refType = 4; + }; + F54AFEC706B4703C014FDB82 = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F54AFEC806B4703C014FDB82 = { + isa = PBXFileReference; + path = file_decoder.h; + refType = 4; + }; + F54AFEC906B4703C014FDB82 = { + isa = PBXFileReference; + path = file_encoder.h; + refType = 4; + }; + F54AFECA06B4703C014FDB82 = { + isa = PBXFileReference; + path = seekable_stream_decoder.h; + refType = 4; + }; + F54AFECB06B4703C014FDB82 = { + isa = PBXFileReference; + path = seekable_stream_encoder.h; + refType = 4; + }; + F54AFECC06B4703C014FDB82 = { + isa = PBXFileReference; + path = stream_decoder.h; + refType = 4; + }; + F54AFECD06B4703C014FDB82 = { + isa = PBXFileReference; + path = stream_encoder.h; + refType = 4; + }; + F54AFECE06B4703C014FDB82 = { + isa = PBXFileReference; + name = ogg_decoder_aspect.c; + path = libOggFLAC/ogg_decoder_aspect.c; + refType = 4; + }; + F54AFECF06B4703C014FDB82 = { + isa = PBXFileReference; + name = ogg_encoder_aspect.c; + path = libOggFLAC/ogg_encoder_aspect.c; + refType = 4; + }; + F54AFED006B4703C014FDB82 = { + isa = PBXFileReference; + name = ogg_helper.c; + path = libOggFLAC/ogg_helper.c; + refType = 4; + }; + F54AFED106B4703C014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_decoder.c; + path = libOggFLAC/seekable_stream_decoder.c; + refType = 4; + }; + F54AFED206B4703C014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_encoder.c; + path = libOggFLAC/seekable_stream_encoder.c; + refType = 4; + }; + F54AFED306B4703C014FDB82 = { + isa = PBXFileReference; + name = stream_decoder.c; + path = libOggFLAC/stream_decoder.c; + refType = 4; + }; + F54AFED406B4703C014FDB82 = { + isa = PBXFileReference; + name = stream_encoder.c; + path = libOggFLAC/stream_encoder.c; + refType = 4; + }; + F54AFED506B4703C014FDB82 = { + fileRef = F54AFEC206B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFED606B4703C014FDB82 = { + fileRef = F54AFEC306B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFED706B4703C014FDB82 = { + fileRef = F54AFEC406B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFED806B4703C014FDB82 = { + fileRef = F54AFEC506B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFED906B4703C014FDB82 = { + fileRef = F54AFEC706B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDA06B4703C014FDB82 = { + fileRef = F54AFEC806B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDB06B4703C014FDB82 = { + fileRef = F54AFEC906B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDC06B4703C014FDB82 = { + fileRef = F54AFECA06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDD06B4703C014FDB82 = { + fileRef = F54AFECB06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDE06B4703C014FDB82 = { + fileRef = F54AFECC06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEDF06B4703C014FDB82 = { + fileRef = F54AFECD06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE006B4703C014FDB82 = { + fileRef = F54AFEBE06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE106B4703C014FDB82 = { + fileRef = F54AFEBF06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE206B4703C014FDB82 = { + fileRef = F54AFECE06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE306B4703C014FDB82 = { + fileRef = F54AFECF06B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE406B4703C014FDB82 = { + fileRef = F54AFED006B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE506B4703C014FDB82 = { + fileRef = F54AFED106B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE606B4703C014FDB82 = { + fileRef = F54AFED206B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE706B4703C014FDB82 = { + fileRef = F54AFED306B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE806B4703C014FDB82 = { + fileRef = F54AFED406B4703C014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEE906B4710E014FDB82 = { + children = ( + F54AFEEA06B4710E014FDB82, + F54AFEEB06B4710E014FDB82, + F54AFEEC06B4710E014FDB82, + F54AFEED06B4710E014FDB82, + ); + isa = PBXGroup; + name = "OggFLAC++"; + refType = 4; + }; + F54AFEEA06B4710E014FDB82 = { + isa = PBXFileReference; + name = all.h; + path = "OggFLAC++/all.h"; + refType = 4; + }; + F54AFEEB06B4710E014FDB82 = { + isa = PBXFileReference; + name = decoder.h; + path = "OggFLAC++/decoder.h"; + refType = 4; + }; + F54AFEEC06B4710E014FDB82 = { + isa = PBXFileReference; + name = encoder.h; + path = "OggFLAC++/encoder.h"; + refType = 4; + }; + F54AFEED06B4710E014FDB82 = { + isa = PBXFileReference; + name = export.h; + path = "OggFLAC++/export.h"; + refType = 4; + }; + F54AFEEE06B4710F014FDB82 = { + children = ( + F54AFEEF06B4710F014FDB82, + F54AFEF006B4710F014FDB82, + F54AFEF106B4710F014FDB82, + F54AFEF206B4710F014FDB82, + F54AFEF306B4710F014FDB82, + F54AFEF406B4710F014FDB82, + ); + isa = PBXGroup; + name = "libOggFLAC++"; + refType = 4; + }; + F54AFEEF06B4710F014FDB82 = { + isa = PBXFileReference; + name = file_decoder.cpp; + path = "libOggFLAC++/file_decoder.cpp"; + refType = 4; + }; + F54AFEF006B4710F014FDB82 = { + isa = PBXFileReference; + name = file_encoder.cpp; + path = "libOggFLAC++/file_encoder.cpp"; + refType = 4; + }; + F54AFEF106B4710F014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_decoder.cpp; + path = "libOggFLAC++/seekable_stream_decoder.cpp"; + refType = 4; + }; + F54AFEF206B4710F014FDB82 = { + isa = PBXFileReference; + name = seekable_stream_encoder.cpp; + path = "libOggFLAC++/seekable_stream_encoder.cpp"; + refType = 4; + }; + F54AFEF306B4710F014FDB82 = { + isa = PBXFileReference; + name = stream_decoder.cpp; + path = "libOggFLAC++/stream_decoder.cpp"; + refType = 4; + }; + F54AFEF406B4710F014FDB82 = { + isa = PBXFileReference; + name = stream_encoder.cpp; + path = "libOggFLAC++/stream_encoder.cpp"; + refType = 4; + }; + F54AFEF506B4710F014FDB82 = { + children = ( + F54AFF4C06B4A163014FDB82, + F54AFF4D06B4A163014FDB82, + F54AFF4E06B4A163014FDB82, + F54AFF4F06B4A163014FDB82, + F54AFF5006B4A163014FDB82, + F54AFF5106B4A163014FDB82, + F54AFF5206B4A163014FDB82, + F54AFF5306B4A163014FDB82, + F54AFF5406B4A163014FDB82, + ); + isa = PBXGroup; + name = test_libOggFLAC; + refType = 4; + }; + F54AFEF606B4710F014FDB82 = { + children = ( + F54AFF5506B4A163014FDB82, + F54AFF5606B4A163014FDB82, + F54AFF5706B4A163014FDB82, + F54AFF5806B4A163014FDB82, + F54AFF5906B4A163014FDB82, + F54AFF5A06B4A163014FDB82, + F54AFF5B06B4A163014FDB82, + F54AFF5C06B4A163014FDB82, + F54AFF5D06B4A163014FDB82, + ); + isa = PBXGroup; + name = "test_libOggFLAC++"; + refType = 4; + }; + F54AFEF706B4710F014FDB82 = { + isa = PBXLibraryReference; + path = "libOggFLAC++.a"; + refType = 3; + }; + F54AFEF806B4710F014FDB82 = { + buildPhases = ( + F54AFEF906B4710F014FDB82, + F54AFEFE06B4710F014FDB82, + F54AFF0506B4710F014FDB82, + F54AFF0606B4710F014FDB82, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "/sw/include src/libOggFLAC++/include include"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = "libOggFLAC++.a"; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = "libOggFLAC++"; + productInstallPath = /usr/local/lib; + productName = "libOggFLAC++"; + productReference = F54AFEF706B4710F014FDB82; + shouldUseHeadermap = 0; + }; + F54AFEF906B4710F014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFEFA06B4710F014FDB82, + F54AFEFB06B4710F014FDB82, + F54AFEFC06B4710F014FDB82, + F54AFEFD06B4710F014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F54AFEFA06B4710F014FDB82 = { + fileRef = F54AFEEA06B4710E014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEFB06B4710F014FDB82 = { + fileRef = F54AFEEB06B4710E014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEFC06B4710F014FDB82 = { + fileRef = F54AFEEC06B4710E014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEFD06B4710F014FDB82 = { + fileRef = F54AFEED06B4710E014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFEFE06B4710F014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFEFF06B4710F014FDB82, + F54AFF0006B4710F014FDB82, + F54AFF0106B4710F014FDB82, + F54AFF0206B4710F014FDB82, + F54AFF0306B4710F014FDB82, + F54AFF0406B4710F014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F54AFEFF06B4710F014FDB82 = { + fileRef = F54AFEEF06B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0006B4710F014FDB82 = { + fileRef = F54AFEF006B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0106B4710F014FDB82 = { + fileRef = F54AFEF106B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0206B4710F014FDB82 = { + fileRef = F54AFEF206B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0306B4710F014FDB82 = { + fileRef = F54AFEF306B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0406B4710F014FDB82 = { + fileRef = F54AFEF406B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF0506B4710F014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F54AFF0606B4710F014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F54AFF3906B49FAA014FDB82 = { + isa = PBXExecutableFileReference; + path = test_libOggFLAC; + refType = 3; + }; + F54AFF3A06B49FAA014FDB82 = { + buildPhases = ( + F54AFF3B06B49FAA014FDB82, + F54AFF3C06B49FAA014FDB82, + F54AFF3D06B49FAA014FDB82, + F54AFF3E06B49FAA014FDB82, + ); + buildSettings = { + HEADER_SEARCH_PATHS = "/sw/include include"; + LIBRARY_SEARCH_PATHS = /sw/lib; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = "-logg"; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = test_libOggFLAC; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = test_libOggFLAC; + productInstallPath = /usr/local/bin; + productName = test_libOggFLAC; + productReference = F54AFF3906B49FAA014FDB82; + shouldUseHeadermap = 0; + }; + F54AFF3B06B49FAA014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFF5E06B4A163014FDB82, + F54AFF5F06B4A163014FDB82, + F54AFF6006B4A163014FDB82, + F54AFF6106B4A163014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F54AFF3C06B49FAA014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFF6206B4A163014FDB82, + F54AFF6306B4A163014FDB82, + F54AFF6406B4A163014FDB82, + F54AFF6506B4A163014FDB82, + F54AFF6606B4A163014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F54AFF3D06B49FAA014FDB82 = { + buildActionMask = 2147483647; + files = ( + F5A50B9606B5992501707A2A, + F5A50B9706B5992501707A2A, + F5A50B9806B5992501707A2A, + F5F3FDB606B6EABC01D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F54AFF3E06B49FAA014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F54AFF4606B4A0F8014FDB82 = { + isa = PBXExecutableFileReference; + path = "test_libOggFLAC++"; + refType = 3; + }; + F54AFF4706B4A0F8014FDB82 = { + buildPhases = ( + F54AFF4806B4A0F8014FDB82, + F54AFF4906B4A0F8014FDB82, + F54AFF4A06B4A0F8014FDB82, + F54AFF4B06B4A0F8014FDB82, + ); + buildSettings = { + HEADER_SEARCH_PATHS = "/sw/include include"; + LIBRARY_SEARCH_PATHS = /sw/lib; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = "-logg"; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = "test_libOggFLAC++"; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = "test_libOggFLAC++"; + productInstallPath = /usr/local/bin; + productName = "test_libOggFLAC++"; + productReference = F54AFF4606B4A0F8014FDB82; + shouldUseHeadermap = 0; + }; + F54AFF4806B4A0F8014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFF6706B4A163014FDB82, + F54AFF6806B4A163014FDB82, + F54AFF6906B4A163014FDB82, + F54AFF6A06B4A163014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F54AFF4906B4A0F8014FDB82 = { + buildActionMask = 2147483647; + files = ( + F54AFF6B06B4A163014FDB82, + F54AFF6C06B4A163014FDB82, + F54AFF6D06B4A163014FDB82, + F54AFF6E06B4A163014FDB82, + F54AFF6F06B4A163014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F54AFF4A06B4A0F8014FDB82 = { + buildActionMask = 2147483647; + files = ( + F5830B8506B59F610175F08C, + F5A50B9D06B599C901707A2A, + F5A50B9E06B599C901707A2A, + F5A50B9F06B599C901707A2A, + F5F3FDB706B6EAD201D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F54AFF4B06B4A0F8014FDB82 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F54AFF4C06B4A163014FDB82 = { + isa = PBXFileReference; + name = decoders.c; + path = test_libOggFLAC/decoders.c; + refType = 4; + }; + F54AFF4D06B4A163014FDB82 = { + isa = PBXFileReference; + name = decoders.h; + path = test_libOggFLAC/decoders.h; + refType = 4; + }; + F54AFF4E06B4A163014FDB82 = { + isa = PBXFileReference; + name = encoders.c; + path = test_libOggFLAC/encoders.c; + refType = 4; + }; + F54AFF4F06B4A163014FDB82 = { + isa = PBXFileReference; + name = encoders.h; + path = test_libOggFLAC/encoders.h; + refType = 4; + }; + F54AFF5006B4A163014FDB82 = { + isa = PBXFileReference; + name = file_utils.c; + path = test_libOggFLAC/file_utils.c; + refType = 4; + }; + F54AFF5106B4A163014FDB82 = { + isa = PBXFileReference; + name = file_utils.h; + path = test_libOggFLAC/file_utils.h; + refType = 4; + }; + F54AFF5206B4A163014FDB82 = { + isa = PBXFileReference; + name = main.c; + path = test_libOggFLAC/main.c; + refType = 4; + }; + F54AFF5306B4A163014FDB82 = { + isa = PBXFileReference; + name = metadata_utils.c; + path = test_libOggFLAC/metadata_utils.c; + refType = 4; + }; + F54AFF5406B4A163014FDB82 = { + isa = PBXFileReference; + name = metadata_utils.h; + path = test_libOggFLAC/metadata_utils.h; + refType = 4; + }; + F54AFF5506B4A163014FDB82 = { + isa = PBXFileReference; + name = decoders.cpp; + path = "test_libOggFLAC++/decoders.cpp"; + refType = 4; + }; + F54AFF5606B4A163014FDB82 = { + isa = PBXFileReference; + name = decoders.h; + path = "test_libOggFLAC++/decoders.h"; + refType = 4; + }; + F54AFF5706B4A163014FDB82 = { + isa = PBXFileReference; + name = encoders.cpp; + path = "test_libOggFLAC++/encoders.cpp"; + refType = 4; + }; + F54AFF5806B4A163014FDB82 = { + isa = PBXFileReference; + name = encoders.h; + path = "test_libOggFLAC++/encoders.h"; + refType = 4; + }; + F54AFF5906B4A163014FDB82 = { + isa = PBXFileReference; + name = file_utils.c; + path = "test_libOggFLAC++/file_utils.c"; + refType = 4; + }; + F54AFF5A06B4A163014FDB82 = { + isa = PBXFileReference; + name = file_utils.h; + path = "test_libOggFLAC++/file_utils.h"; + refType = 4; + }; + F54AFF5B06B4A163014FDB82 = { + isa = PBXFileReference; + name = main.cpp; + path = "test_libOggFLAC++/main.cpp"; + refType = 4; + }; + F54AFF5C06B4A163014FDB82 = { + isa = PBXFileReference; + name = metadata_utils.c; + path = "test_libOggFLAC++/metadata_utils.c"; + refType = 4; + }; + F54AFF5D06B4A163014FDB82 = { + isa = PBXFileReference; + name = metadata_utils.h; + path = "test_libOggFLAC++/metadata_utils.h"; + refType = 4; + }; + F54AFF5E06B4A163014FDB82 = { + fileRef = F54AFF4D06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF5F06B4A163014FDB82 = { + fileRef = F54AFF4F06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6006B4A163014FDB82 = { + fileRef = F54AFF5106B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6106B4A163014FDB82 = { + fileRef = F54AFF5406B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6206B4A163014FDB82 = { + fileRef = F54AFF4C06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6306B4A163014FDB82 = { + fileRef = F54AFF4E06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6406B4A163014FDB82 = { + fileRef = F54AFF5006B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6506B4A163014FDB82 = { + fileRef = F54AFF5206B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6606B4A163014FDB82 = { + fileRef = F54AFF5306B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6706B4A163014FDB82 = { + fileRef = F54AFF5606B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6806B4A163014FDB82 = { + fileRef = F54AFF5806B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6906B4A163014FDB82 = { + fileRef = F54AFF5A06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6A06B4A163014FDB82 = { + fileRef = F54AFF5D06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6B06B4A163014FDB82 = { + fileRef = F54AFF5506B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6C06B4A163014FDB82 = { + fileRef = F54AFF5706B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6D06B4A163014FDB82 = { + fileRef = F54AFF5906B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6E06B4A163014FDB82 = { + fileRef = F54AFF5B06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF6F06B4A163014FDB82 = { + fileRef = F54AFF5C06B4A163014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F54AFF7006B4A184014FDB82 = { + children = ( + F566F4AA06B4A2400107D11D, + F566F4AB06B4A2400107D11D, + ); + isa = PBXGroup; + name = getopt; + refType = 4; + }; + F566F4AA06B4A2400107D11D = { + isa = PBXFileReference; + name = getopt.c; + path = getopt/getopt.c; + refType = 4; + }; + F566F4AB06B4A2400107D11D = { + isa = PBXFileReference; + name = getopt1.c; + path = getopt/getopt1.c; + refType = 4; + }; + F566F4AC06B4A2400107D11D = { + fileRef = F566F4AA06B4A2400107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4AD06B4A2400107D11D = { + fileRef = F566F4AB06B4A2400107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4AE06B4A2B30107D11D = { + isa = PBXLibraryReference; + path = libgrabbag.a; + refType = 3; + }; + F566F4AF06B4A2B30107D11D = { + isa = PBXLibraryReference; + path = libreplaygain_analysis.a; + refType = 3; + }; + F566F4B006B4A2B30107D11D = { + buildPhases = ( + F566F4B106B4A2B30107D11D, + F566F4B206B4A2B30107D11D, + F566F4B306B4A2B30107D11D, + F566F4B406B4A2B30107D11D, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "src/share/grabbag/include include"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libgrabbag.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libgrabbag; + productInstallPath = /usr/local/lib; + productName = libgrabbag; + productReference = F566F4AE06B4A2B30107D11D; + shouldUseHeadermap = 0; + }; + F566F4B106B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4E406B4A4270107D11D, + F566F4E506B4A4270107D11D, + F566F4E606B4A4270107D11D, + F566F4E706B4A4270107D11D, + F566F4E806B4A4270107D11D, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F566F4B206B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4E906B4A4270107D11D, + F566F4EA06B4A4270107D11D, + F566F4EB06B4A4270107D11D, + F566F4EC06B4A4270107D11D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F566F4B306B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F566F4B406B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F566F4B506B4A2B30107D11D = { + buildPhases = ( + F566F4B606B4A2B30107D11D, + F566F4B706B4A2B30107D11D, + F566F4B806B4A2B30107D11D, + F566F4B906B4A2B30107D11D, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "src/share/replaygain_analysis/include include/share"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libreplaygain_analysis.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libreplaygain_analysis; + productInstallPath = /usr/local/lib; + productName = libreplaygain_analysis; + productReference = F566F4AF06B4A2B30107D11D; + shouldUseHeadermap = 0; + }; + F566F4B606B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4ED06B4A4270107D11D, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F566F4B706B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4EE06B4A4270107D11D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F566F4B806B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F566F4B906B4A2B30107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F566F4BA06B4A2C50107D11D = { + isa = PBXLibraryReference; + path = libreplaygain_synthesis.a; + refType = 3; + }; + F566F4BB06B4A2C50107D11D = { + buildPhases = ( + F566F4BC06B4A2C50107D11D, + F566F4BD06B4A2C50107D11D, + F566F4BE06B4A2C50107D11D, + F566F4BF06B4A2C50107D11D, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "src/share/replaygain_synthesis/include include include/share"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libreplaygain_synthesis.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libreplaygain_synthesis; + productInstallPath = /usr/local/lib; + productName = libreplaygain_synthesis; + productReference = F566F4BA06B4A2C50107D11D; + shouldUseHeadermap = 0; + }; + F566F4BC06B4A2C50107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4EF06B4A4270107D11D, + F566F4F006B4A4270107D11D, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F566F4BD06B4A2C50107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4F106B4A4270107D11D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F566F4BE06B4A2C50107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F566F4BF06B4A2C50107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F566F4C006B4A2F40107D11D = { + isa = PBXLibraryReference; + path = libutf8.a; + refType = 3; + }; + F566F4C106B4A2F40107D11D = { + buildPhases = ( + F566F4C206B4A2F40107D11D, + F566F4C306B4A2F40107D11D, + F566F4C406B4A2F40107D11D, + F566F4C506B4A2F40107D11D, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "/sw/include src/share/utf8/include include include/share"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libutf8.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libutf8; + productInstallPath = /usr/local/lib; + productName = libutf8; + productReference = F566F4C006B4A2F40107D11D; + shouldUseHeadermap = 0; + }; + F566F4C206B4A2F40107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4F206B4A4270107D11D, + F566F4F306B4A4270107D11D, + F566F4F406B4A4270107D11D, + F566F4F506B4A4270107D11D, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F566F4C306B4A2F40107D11D = { + buildActionMask = 2147483647; + files = ( + F566F4F606B4A4270107D11D, + F566F4F706B4A4270107D11D, + F566F4F806B4A4270107D11D, + F566F4F906B4A4270107D11D, + F566F4FA06B4A4270107D11D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F566F4C406B4A2F40107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F566F4C506B4A2F40107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F566F4C606B4A4270107D11D = { + children = ( + F566F4C706B4A4270107D11D, + F566F4C806B4A4270107D11D, + F566F4C906B4A4270107D11D, + F566F4CA06B4A4270107D11D, + ); + isa = PBXGroup; + path = grabbag; + refType = 4; + }; + F566F4C706B4A4270107D11D = { + isa = PBXFileReference; + path = cuesheet.h; + refType = 4; + }; + F566F4C806B4A4270107D11D = { + isa = PBXFileReference; + path = file.h; + refType = 4; + }; + F566F4C906B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain.h; + refType = 4; + }; + F566F4CA06B4A4270107D11D = { + isa = PBXFileReference; + path = seektable.h; + refType = 4; + }; + F566F4CB06B4A4270107D11D = { + isa = PBXFileReference; + path = grabbag.h; + refType = 4; + }; + F566F4CC06B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain_analysis.h; + refType = 4; + }; + F566F4CD06B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain_synthesis.h; + refType = 4; + }; + F566F4CE06B4A4270107D11D = { + isa = PBXFileReference; + path = utf8.h; + refType = 4; + }; + F566F4CF06B4A4270107D11D = { + children = ( + F566F4D006B4A4270107D11D, + F566F4D106B4A4270107D11D, + F566F4D206B4A4270107D11D, + F566F4D306B4A4270107D11D, + ); + isa = PBXGroup; + path = grabbag; + refType = 4; + }; + F566F4D006B4A4270107D11D = { + isa = PBXFileReference; + path = cuesheet.c; + refType = 4; + }; + F566F4D106B4A4270107D11D = { + isa = PBXFileReference; + path = file.c; + refType = 4; + }; + F566F4D206B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain.c; + refType = 4; + }; + F566F4D306B4A4270107D11D = { + isa = PBXFileReference; + path = seektable.c; + refType = 4; + }; + F566F4D406B4A4270107D11D = { + children = ( + F566F4D506B4A4270107D11D, + ); + isa = PBXGroup; + path = replaygain_analysis; + refType = 4; + }; + F566F4D506B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain_analysis.c; + refType = 4; + }; + F566F4D606B4A4270107D11D = { + children = ( + F566F4D706B4A4270107D11D, + F566F4DA06B4A4270107D11D, + ); + isa = PBXGroup; + path = replaygain_synthesis; + refType = 4; + }; + F566F4D706B4A4270107D11D = { + children = ( + F566F4D806B4A4270107D11D, + ); + isa = PBXGroup; + path = include; + refType = 4; + }; + F566F4D806B4A4270107D11D = { + children = ( + F566F4D906B4A4270107D11D, + ); + isa = PBXGroup; + path = private; + refType = 4; + }; + F566F4D906B4A4270107D11D = { + isa = PBXFileReference; + path = fast_float_math_hack.h; + refType = 4; + }; + F566F4DA06B4A4270107D11D = { + isa = PBXFileReference; + path = replaygain_synthesis.c; + refType = 4; + }; + F566F4DB06B4A4270107D11D = { + children = ( + F566F4DC06B4A4270107D11D, + F566F4DD06B4A4270107D11D, + F566F4DE06B4A4270107D11D, + F566F4DF06B4A4270107D11D, + F566F4E006B4A4270107D11D, + F566F4E106B4A4270107D11D, + F566F4E206B4A4270107D11D, + F566F4E306B4A4270107D11D, + ); + isa = PBXGroup; + path = utf8; + refType = 4; + }; + F566F4DC06B4A4270107D11D = { + isa = PBXFileReference; + path = charmaps.h; + refType = 4; + }; + F566F4DD06B4A4270107D11D = { + isa = PBXFileReference; + path = charset.c; + refType = 4; + }; + F566F4DE06B4A4270107D11D = { + isa = PBXFileReference; + path = charset.h; + refType = 4; + }; + F566F4DF06B4A4270107D11D = { + isa = PBXFileReference; + path = charset_test.c; + refType = 4; + }; + F566F4E006B4A4270107D11D = { + isa = PBXFileReference; + path = charsetmap.h; + refType = 4; + }; + F566F4E106B4A4270107D11D = { + isa = PBXFileReference; + path = iconvert.c; + refType = 4; + }; + F566F4E206B4A4270107D11D = { + isa = PBXFileReference; + path = makemap.c; + refType = 4; + }; + F566F4E306B4A4270107D11D = { + isa = PBXFileReference; + path = utf8.c; + refType = 4; + }; + F566F4E406B4A4270107D11D = { + fileRef = F566F4C706B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4E506B4A4270107D11D = { + fileRef = F566F4C806B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4E606B4A4270107D11D = { + fileRef = F566F4C906B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4E706B4A4270107D11D = { + fileRef = F566F4CA06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4E806B4A4270107D11D = { + fileRef = F566F4CB06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4E906B4A4270107D11D = { + fileRef = F566F4D006B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4EA06B4A4270107D11D = { + fileRef = F566F4D106B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4EB06B4A4270107D11D = { + fileRef = F566F4D206B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4EC06B4A4270107D11D = { + fileRef = F566F4D306B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4ED06B4A4270107D11D = { + fileRef = F566F4CC06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4EE06B4A4270107D11D = { + fileRef = F566F4D506B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4EF06B4A4270107D11D = { + fileRef = F566F4CD06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F006B4A4270107D11D = { + fileRef = F566F4D906B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F106B4A4270107D11D = { + fileRef = F566F4DA06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F206B4A4270107D11D = { + fileRef = F566F4CE06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F306B4A4270107D11D = { + fileRef = F566F4DC06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F406B4A4270107D11D = { + fileRef = F566F4DE06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F506B4A4270107D11D = { + fileRef = F566F4E006B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F606B4A4270107D11D = { + fileRef = F566F4DD06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F706B4A4270107D11D = { + fileRef = F566F4DF06B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F806B4A4270107D11D = { + fileRef = F566F4E106B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4F906B4A4270107D11D = { + fileRef = F566F4E206B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4FA06B4A4270107D11D = { + fileRef = F566F4E306B4A4270107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F566F4FB06B4B7DD0107D11D = { + isa = PBXExecutableFileReference; + path = test_cuesheet; + refType = 3; + }; + F566F4FC06B4B7DD0107D11D = { + buildPhases = ( + F566F4FD06B4B7DD0107D11D, + F566F4FE06B4B7DD0107D11D, + F566F4FF06B4B7DD0107D11D, + F566F50006B4B7DD0107D11D, + ); + buildSettings = { + HEADER_SEARCH_PATHS = include; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = test_cuesheet; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = test_cuesheet; + productInstallPath = /usr/local/bin; + productName = test_cuesheet; + productReference = F566F4FB06B4B7DD0107D11D; + shouldUseHeadermap = 0; + }; + F566F4FD06B4B7DD0107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F566F4FE06B4B7DD0107D11D = { + buildActionMask = 2147483647; + files = ( + F5A50BB406B59B3E01707A2A, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F566F4FF06B4B7DD0107D11D = { + buildActionMask = 2147483647; + files = ( + F5A50BAF06B59A8D01707A2A, + F5A50BB006B59A8D01707A2A, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F566F50006B4B7DD0107D11D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5830B7A06B59DF90175F08C = { + fileRef = F54AFE6406B46AC4014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F5830B7E06B59ECD0175F08C = { + fileRef = F566F4C006B4A2F40107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5830B8506B59F610175F08C = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E594B01972C6B01A8006D = { + buildStyles = ( + F59E594D01972C6B01A8006D, + F59E594E01972C6B01A8006D, + ); + isa = PBXProject; + mainGroup = F59E594C01972C6B01A8006D; + productRefGroup = F59E59C301972D3E01A8006D; + projectDirPath = ""; + targets = ( + F5F7D57006B6E75301AAAA86, + F59E59C501972D3E01A8006D, + F5CA9EC702D18601011525B7, + F54AFE6506B46AC4014FDB82, + F54AFEF806B4710F014FDB82, + F5D3C69302D18AAF015C5FF8, + F566F4B006B4A2B30107D11D, + F566F4B506B4A2B30107D11D, + F566F4BB06B4A2C50107D11D, + F566F4C106B4A2F40107D11D, + F59E5A0B0197308B01A8006D, + F5F561E6019B56E401A8006D, + F5F561F6019B58E101A8006D, + F5CA9ED002D18601011525B7, + F54AFF3A06B49FAA014FDB82, + F54AFF4706B4A0F8014FDB82, + F566F4FC06B4B7DD0107D11D, + F5F561F0019B58E101A8006D, + ); + }; + F59E594C01972C6B01A8006D = { + children = ( + F59E594F01972D3D01A8006D, + F59E59C301972D3E01A8006D, + ); + isa = PBXGroup; + refType = 4; + }; + F59E594D01972C6B01A8006D = { + buildRules = ( + ); + buildSettings = { + COPY_PHASE_STRIP = NO; + }; + isa = PBXBuildStyle; + name = Development; + }; + F59E594E01972C6B01A8006D = { + buildRules = ( + ); + buildSettings = { + COPY_PHASE_STRIP = YES; + }; + isa = PBXBuildStyle; + name = Deployment; + }; + F59E594F01972D3D01A8006D = { + children = ( + F59E595001972D3D01A8006D, + F59E595B01972D3D01A8006D, + ); + isa = PBXGroup; + name = Source; + refType = 4; + }; + F59E595001972D3D01A8006D = { + children = ( + F59E595101972D3D01A8006D, + F5CA9EC002D18601011525B7, + F54AFEA806B46FF0014FDB82, + F54AFEE906B4710E014FDB82, + F5D3C68D02D18AAF015C5FF8, + ); + isa = PBXGroup; + path = include; + refType = 4; + }; + F59E595101972D3D01A8006D = { + children = ( + F59E595201972D3D01A8006D, + F59E595301972D3D01A8006D, + F54AFE6A06B46CDB014FDB82, + F54AFE6B06B46CDB014FDB82, + F59E595401972D3D01A8006D, + F54AFE6C06B46CDB014FDB82, + F59E595501972D3D01A8006D, + F5CA9EBE02D18526011525B7, + F54AFE6D06B46CDB014FDB82, + F51C735C0199C3DF01A8006D, + F54AFE6E06B46CDB014FDB82, + F59E595801972D3D01A8006D, + F59E595901972D3D01A8006D, + ); + isa = PBXGroup; + path = FLAC; + refType = 4; + }; + F59E595201972D3D01A8006D = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F59E595301972D3D01A8006D = { + isa = PBXFileReference; + path = assert.h; + refType = 4; + }; + F59E595401972D3D01A8006D = { + isa = PBXFileReference; + path = file_decoder.h; + refType = 4; + }; + F59E595501972D3D01A8006D = { + isa = PBXFileReference; + path = format.h; + refType = 4; + }; + F59E595801972D3D01A8006D = { + isa = PBXFileReference; + path = stream_decoder.h; + refType = 4; + }; + F59E595901972D3D01A8006D = { + isa = PBXFileReference; + path = stream_encoder.h; + refType = 4; + }; + F59E595B01972D3D01A8006D = { + children = ( + F59E595C01972D3D01A8006D, + F59E596901972D3D01A8006D, + F5CA9EDA02D186C7011525B7, + F54AFEB106B46FF0014FDB82, + F54AFEEE06B4710F014FDB82, + F59E599901972D3D01A8006D, + F59E59B301972D3E01A8006D, + F59E59BC01972D3E01A8006D, + F5CA9EF202D1874F011525B7, + F54AFEF506B4710F014FDB82, + F54AFEF606B4710F014FDB82, + F5A50BB106B59B3D01707A2A, + F59E59B701972D3E01A8006D, + F5D3C68F02D18AAF015C5FF8, + ); + isa = PBXGroup; + path = src; + refType = 4; + }; + F59E595C01972D3D01A8006D = { + children = ( + F59E595D01972D3D01A8006D, + F59E595E01972D3D01A8006D, + F59E595F01972D3D01A8006D, + F59E596001972D3D01A8006D, + F59E596101972D3D01A8006D, + F59E596201972D3D01A8006D, + F54AFE8406B46EBF014FDB82, + F54AFE8506B46EBF014FDB82, + F59E596501972D3D01A8006D, + F54AFE8606B46EBF014FDB82, + F54AFE8706B46EBF014FDB82, + F54AFE8806B46EBF014FDB82, + F54AFE8906B46EBF014FDB82, + ); + isa = PBXGroup; + path = flac; + refType = 4; + }; + F59E595D01972D3D01A8006D = { + isa = PBXFileReference; + path = analyze.c; + refType = 4; + }; + F59E595E01972D3D01A8006D = { + isa = PBXFileReference; + path = analyze.h; + refType = 4; + }; + F59E595F01972D3D01A8006D = { + isa = PBXFileReference; + path = decode.c; + refType = 4; + }; + F59E596001972D3D01A8006D = { + isa = PBXFileReference; + path = decode.h; + refType = 4; + }; + F59E596101972D3D01A8006D = { + isa = PBXFileReference; + path = encode.c; + refType = 4; + }; + F59E596201972D3D01A8006D = { + isa = PBXFileReference; + path = encode.h; + refType = 4; + }; + F59E596501972D3D01A8006D = { + isa = PBXFileReference; + path = main.c; + refType = 4; + }; + F59E596901972D3D01A8006D = { + children = ( + F59E596A01972D3D01A8006D, + F59E596B01972D3D01A8006D, + F59E596C01972D3D01A8006D, + F59E596D01972D3D01A8006D, + F59E596E01972D3D01A8006D, + F54AFE7406B46DD3014FDB82, + F59E596F01972D3D01A8006D, + F59E597001972D3D01A8006D, + F59E597901972D3D01A8006D, + F59E598D01972D3D01A8006D, + F59E599101972D3D01A8006D, + F59E599201972D3D01A8006D, + F5CA9ED502D1865E011525B7, + F5CA9ED602D1865E011525B7, + F59E599401972D3D01A8006D, + F59E599501972D3D01A8006D, + F59E599601972D3D01A8006D, + F51C735F0199C42101A8006D, + F54AFE7506B46DD3014FDB82, + F5F7D56D06B6E75301AAAA86, + ); + isa = PBXGroup; + path = libFLAC; + refType = 4; + }; + F59E596A01972D3D01A8006D = { + isa = PBXFileReference; + path = bitbuffer.c; + refType = 4; + }; + F59E596B01972D3D01A8006D = { + isa = PBXFileReference; + path = bitmath.c; + refType = 4; + }; + F59E596C01972D3D01A8006D = { + isa = PBXFileReference; + path = cpu.c; + refType = 4; + }; + F59E596D01972D3D01A8006D = { + isa = PBXFileReference; + path = crc.c; + refType = 4; + }; + F59E596E01972D3D01A8006D = { + isa = PBXFileReference; + path = file_decoder.c; + refType = 4; + }; + F59E596F01972D3D01A8006D = { + isa = PBXFileReference; + path = fixed.c; + refType = 4; + }; + F59E597001972D3D01A8006D = { + isa = PBXFileReference; + path = format.c; + refType = 4; + }; + F59E597901972D3D01A8006D = { + children = ( + F59E597B01972D3D01A8006D, + F59E598701972D3D01A8006D, + ); + isa = PBXGroup; + path = include; + refType = 4; + }; + F59E597B01972D3D01A8006D = { + children = ( + F59E597C01972D3D01A8006D, + F59E597D01972D3D01A8006D, + F59E597E01972D3D01A8006D, + F59E597F01972D3D01A8006D, + F59E598001972D3D01A8006D, + F59E598101972D3D01A8006D, + F54AFE7906B46E73014FDB82, + F59E598201972D3D01A8006D, + F59E598401972D3D01A8006D, + F59E598501972D3D01A8006D, + F5CA9ED902D186C7011525B7, + F59E598601972D3D01A8006D, + ); + isa = PBXGroup; + path = private; + refType = 4; + }; + F59E597C01972D3D01A8006D = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F59E597D01972D3D01A8006D = { + isa = PBXFileReference; + path = bitbuffer.h; + refType = 4; + }; + F59E597E01972D3D01A8006D = { + isa = PBXFileReference; + path = bitmath.h; + refType = 4; + }; + F59E597F01972D3D01A8006D = { + isa = PBXFileReference; + path = cpu.h; + refType = 4; + }; + F59E598001972D3D01A8006D = { + isa = PBXFileReference; + path = crc.h; + refType = 4; + }; + F59E598101972D3D01A8006D = { + isa = PBXFileReference; + path = fixed.h; + refType = 4; + }; + F59E598201972D3D01A8006D = { + isa = PBXFileReference; + path = lpc.h; + refType = 4; + }; + F59E598401972D3D01A8006D = { + isa = PBXFileReference; + path = md5.h; + refType = 4; + }; + F59E598501972D3D01A8006D = { + isa = PBXFileReference; + path = memory.h; + refType = 4; + }; + F59E598601972D3D01A8006D = { + isa = PBXFileReference; + path = stream_encoder_framing.h; + refType = 4; + }; + F59E598701972D3D01A8006D = { + children = ( + F59E598801972D3D01A8006D, + F59E598901972D3D01A8006D, + F54AFE7A06B46E73014FDB82, + F51C735E0199C42101A8006D, + F54AFE7B06B46E73014FDB82, + F59E598B01972D3D01A8006D, + F59E598C01972D3D01A8006D, + ); + isa = PBXGroup; + path = protected; + refType = 4; + }; + F59E598801972D3D01A8006D = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F59E598901972D3D01A8006D = { + isa = PBXFileReference; + path = file_decoder.h; + refType = 4; + }; + F59E598B01972D3D01A8006D = { + isa = PBXFileReference; + path = stream_decoder.h; + refType = 4; + }; + F59E598C01972D3D01A8006D = { + isa = PBXFileReference; + path = stream_encoder.h; + refType = 4; + }; + F59E598D01972D3D01A8006D = { + isa = PBXFileReference; + path = lpc.c; + refType = 4; + }; + F59E599101972D3D01A8006D = { + isa = PBXFileReference; + path = md5.c; + refType = 4; + }; + F59E599201972D3D01A8006D = { + isa = PBXFileReference; + path = memory.c; + refType = 4; + }; + F59E599401972D3D01A8006D = { + isa = PBXFileReference; + path = stream_decoder.c; + refType = 4; + }; + F59E599501972D3D01A8006D = { + isa = PBXFileReference; + path = stream_encoder.c; + refType = 4; + }; + F59E599601972D3D01A8006D = { + isa = PBXFileReference; + path = stream_encoder_framing.c; + refType = 4; + }; + F59E599901972D3D01A8006D = { + children = ( + F59E599A01972D3D01A8006D, + F54AFE9006B46F13014FDB82, + F54AFE9106B46F13014FDB82, + F54AFE9206B46F13014FDB82, + F54AFE9306B46F13014FDB82, + F54AFE9406B46F13014FDB82, + F54AFE9506B46F13014FDB82, + F54AFE9606B46F13014FDB82, + F54AFE9706B46F13014FDB82, + F54AFE9806B46F13014FDB82, + F54AFE9906B46F13014FDB82, + F54AFE9A06B46F13014FDB82, + F54AFE9B06B46F13014FDB82, + ); + isa = PBXGroup; + path = metaflac; + refType = 4; + }; + F59E599A01972D3D01A8006D = { + isa = PBXFileReference; + path = main.c; + refType = 4; + }; + F59E59B301972D3E01A8006D = { + children = ( + F59E59B601972D3E01A8006D, + ); + isa = PBXGroup; + path = plugin_xmms; + refType = 4; + }; + F59E59B601972D3E01A8006D = { + isa = PBXFileReference; + path = plugin.c; + refType = 4; + }; + F59E59B701972D3E01A8006D = { + children = ( + F59E59B801972D3E01A8006D, + ); + isa = PBXGroup; + path = test_streams; + refType = 4; + }; + F59E59B801972D3E01A8006D = { + isa = PBXFileReference; + path = main.c; + refType = 4; + }; + F59E59BC01972D3E01A8006D = { + children = ( + F59E59BD01972D3E01A8006D, + F59E59BE01972D3E01A8006D, + F59E59BF01972D3E01A8006D, + F5CA9EE602D1874F011525B7, + F5CA9EE702D1874F011525B7, + F5CA9EE802D1874F011525B7, + F5CA9EE902D1874F011525B7, + F5CA9EEA02D1874F011525B7, + F5CA9EEB02D1874F011525B7, + F5CA9EEC02D1874F011525B7, + F5CA9EED02D1874F011525B7, + F5CA9EEE02D1874F011525B7, + F5CA9EEF02D1874F011525B7, + F5CA9EF002D1874F011525B7, + F5CA9EF102D1874F011525B7, + ); + isa = PBXGroup; + path = test_libFLAC; + refType = 4; + }; + F59E59BD01972D3E01A8006D = { + isa = PBXFileReference; + path = bitbuffer.c; + refType = 4; + }; + F59E59BE01972D3E01A8006D = { + isa = PBXFileReference; + path = bitbuffer.h; + refType = 4; + }; + F59E59BF01972D3E01A8006D = { + isa = PBXFileReference; + path = main.c; + refType = 4; + }; + F59E59C301972D3E01A8006D = { + children = ( + F5F7D56F06B6E75301AAAA86, + F59E59C401972D3E01A8006D, + F5CA9EC502D18601011525B7, + F54AFE6406B46AC4014FDB82, + F54AFEF706B4710F014FDB82, + F5D3C69202D18AAF015C5FF8, + F566F4AE06B4A2B30107D11D, + F566F4AF06B4A2B30107D11D, + F566F4BA06B4A2C50107D11D, + F566F4C006B4A2F40107D11D, + F59E5A0A0197308B01A8006D, + F5F561E5019B56E401A8006D, + F5F561EF019B58E101A8006D, + F5CA9EC602D18601011525B7, + F54AFF3906B49FAA014FDB82, + F54AFF4606B4A0F8014FDB82, + F566F4FB06B4B7DD0107D11D, + F5F561EE019B58E101A8006D, + ); + isa = PBXGroup; + name = Products; + refType = 4; + }; + F59E59C401972D3E01A8006D = { + isa = PBXLibraryReference; + path = libFLAC.a; + refType = 3; + }; + F59E59C501972D3E01A8006D = { + buildPhases = ( + F513F76501976EFF01A8006D, + F59E59C601972D3E01A8006D, + F59E59E701972D3E01A8006D, + F59E5A0501972D3E01A8006D, + F59E5A0601972D3E01A8006D, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "src/libFLAC/include include"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DVERSION=\\\\\\\"1.2.1\\\\\\\" -DHAVE_INTTYPES_H -DFLAC__CPU_PPC -DFLAC__USE_ALTIVEC -DFLAC__ALIGN_MALLOC_DATA"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libFLAC.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libFLAC; + productInstallPath = /usr/local/lib; + productName = libFLAC; + productReference = F59E59C401972D3E01A8006D; + shouldUseHeadermap = 0; + }; + F59E59C601972D3E01A8006D = { + buildActionMask = 2147483647; + files = ( + F59E59C701972D3E01A8006D, + F59E59C801972D3E01A8006D, + F54AFE6F06B46CDC014FDB82, + F54AFE7006B46CDC014FDB82, + F59E59C901972D3E01A8006D, + F54AFE7106B46CDC014FDB82, + F59E59CA01972D3E01A8006D, + F5CA9EBF02D18526011525B7, + F54AFE7206B46CDC014FDB82, + F51C735D0199C3DF01A8006D, + F54AFE7306B46CDC014FDB82, + F59E59CD01972D3E01A8006D, + F59E59CE01972D3E01A8006D, + F59E59D501972D3E01A8006D, + F59E59D601972D3E01A8006D, + F59E59D701972D3E01A8006D, + F59E59D801972D3E01A8006D, + F59E59D901972D3E01A8006D, + F59E59DA01972D3E01A8006D, + F59E59DB01972D3E01A8006D, + F59E59DC01972D3E01A8006D, + F59E59DD01972D3E01A8006D, + F59E59DE01972D3E01A8006D, + F59E59DF01972D3E01A8006D, + F59E59E001972D3E01A8006D, + F59E59E101972D3E01A8006D, + F59E59E201972D3E01A8006D, + F51C73600199C42101A8006D, + F5CA9EE002D186C7011525B7, + F54AFE7E06B46E73014FDB82, + F54AFE7F06B46E73014FDB82, + F54AFE8006B46E73014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F59E59C701972D3E01A8006D = { + fileRef = F59E595201972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59C801972D3E01A8006D = { + fileRef = F59E595301972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59C901972D3E01A8006D = { + fileRef = F59E595401972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59CA01972D3E01A8006D = { + fileRef = F59E595501972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59CD01972D3E01A8006D = { + fileRef = F59E595801972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59CE01972D3E01A8006D = { + fileRef = F59E595901972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59D501972D3E01A8006D = { + fileRef = F59E597C01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59D601972D3E01A8006D = { + fileRef = F59E597D01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59D701972D3E01A8006D = { + fileRef = F59E597E01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59D801972D3E01A8006D = { + fileRef = F59E597F01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59D901972D3E01A8006D = { + fileRef = F59E598001972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DA01972D3E01A8006D = { + fileRef = F59E598101972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DB01972D3E01A8006D = { + fileRef = F59E598201972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DC01972D3E01A8006D = { + fileRef = F59E598401972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DD01972D3E01A8006D = { + fileRef = F59E598501972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DE01972D3E01A8006D = { + fileRef = F59E598601972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59DF01972D3E01A8006D = { + fileRef = F59E598801972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59E001972D3E01A8006D = { + fileRef = F59E598901972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59E101972D3E01A8006D = { + fileRef = F59E598B01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59E201972D3E01A8006D = { + fileRef = F59E598C01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59E701972D3E01A8006D = { + buildActionMask = 2147483647; + files = ( + F59E59ED01972D3E01A8006D, + F59E59EE01972D3E01A8006D, + F59E59EF01972D3E01A8006D, + F59E59F001972D3E01A8006D, + F59E59F101972D3E01A8006D, + F59E59F201972D3E01A8006D, + F59E59F301972D3E01A8006D, + F59E59F401972D3E01A8006D, + F59E59F501972D3E01A8006D, + F59E59F601972D3E01A8006D, + F59E59F801972D3E01A8006D, + F59E59F901972D3E01A8006D, + F59E59FA01972D3E01A8006D, + F51C73610199C42101A8006D, + F5CA9ED702D1865E011525B7, + F5CA9ED802D1865E011525B7, + F54AFE7606B46DD3014FDB82, + F54AFE7706B46DD3014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F59E59ED01972D3E01A8006D = { + fileRef = F59E596A01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59EE01972D3E01A8006D = { + fileRef = F59E596B01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59EF01972D3E01A8006D = { + fileRef = F59E596C01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F001972D3E01A8006D = { + fileRef = F59E596D01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F101972D3E01A8006D = { + fileRef = F59E596E01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F201972D3E01A8006D = { + fileRef = F59E596F01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F301972D3E01A8006D = { + fileRef = F59E597001972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F401972D3E01A8006D = { + fileRef = F59E598D01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F501972D3E01A8006D = { + fileRef = F59E599101972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F601972D3E01A8006D = { + fileRef = F59E599201972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F801972D3E01A8006D = { + fileRef = F59E599401972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59F901972D3E01A8006D = { + fileRef = F59E599501972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E59FA01972D3E01A8006D = { + fileRef = F59E599601972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A0501972D3E01A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F59E5A0601972D3E01A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F59E5A0A0197308B01A8006D = { + isa = PBXExecutableFileReference; + path = flac; + refType = 3; + }; + F59E5A0B0197308B01A8006D = { + buildPhases = ( + F59E5A0C0197308B01A8006D, + F59E5A0D0197308B01A8006D, + F59E5A0E0197308B01A8006D, + F59E5A0F0197308B01A8006D, + ); + buildSettings = { + HEADER_SEARCH_PATHS = "/sw/include include"; + LIBRARY_SEARCH_PATHS = /sw/lib; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DVERSION=\\\\\\\"1.2.1\\\\\\\" -DHAVE_INTTYPES_H -DFLAC__HAS_OGG"; + OTHER_LDFLAGS = "-logg"; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = flac; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = flac; + productInstallPath = /usr/local/bin; + productName = flac; + productReference = F59E5A0A0197308B01A8006D; + shouldUseHeadermap = 0; + }; + F59E5A0C0197308B01A8006D = { + buildActionMask = 2147483647; + files = ( + F59E5A120197323601A8006D, + F59E5A140197323601A8006D, + F59E5A160197323601A8006D, + F54AFE8A06B46EBF014FDB82, + F54AFE8B06B46EBF014FDB82, + F54AFE8C06B46EBF014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F59E5A0D0197308B01A8006D = { + buildActionMask = 2147483647; + files = ( + F59E5A110197323601A8006D, + F59E5A130197323601A8006D, + F59E5A150197323601A8006D, + F59E5A190197323601A8006D, + F54AFE8D06B46EBF014FDB82, + F54AFE8E06B46EBF014FDB82, + F54AFE8F06B46EBF014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F59E5A0E0197308B01A8006D = { + buildActionMask = 2147483647; + files = ( + F5A50B3D06B5950501707A2A, + F5A50B3A06B594ED01707A2A, + F5A50B3B06B594ED01707A2A, + F5A50B3C06B594ED01707A2A, + F5A50B3E06B5952301707A2A, + F5830B7A06B59DF90175F08C, + F59E5A1D0197363A01A8006D, + F5F3FDB206B6E9AE01D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F59E5A0F0197308B01A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F59E5A110197323601A8006D = { + fileRef = F59E595D01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A120197323601A8006D = { + fileRef = F59E595E01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A130197323601A8006D = { + fileRef = F59E595F01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A140197323601A8006D = { + fileRef = F59E596001972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A150197323601A8006D = { + fileRef = F59E596101972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A160197323601A8006D = { + fileRef = F59E596201972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A190197323601A8006D = { + fileRef = F59E596501972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F59E5A1D0197363A01A8006D = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B3A06B594ED01707A2A = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B3B06B594ED01707A2A = { + fileRef = F566F4AF06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B3C06B594ED01707A2A = { + fileRef = F566F4BA06B4A2C50107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B3D06B5950501707A2A = { + fileRef = F5D3C69202D18AAF015C5FF8; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B3E06B5952301707A2A = { + fileRef = F566F4C006B4A2F40107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9606B5992501707A2A = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9706B5992501707A2A = { + fileRef = F54AFE6406B46AC4014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9806B5992501707A2A = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9D06B599C901707A2A = { + fileRef = F54AFEF706B4710F014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9E06B599C901707A2A = { + fileRef = F54AFE6406B46AC4014FDB82; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50B9F06B599C901707A2A = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50BAF06B59A8D01707A2A = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50BB006B59A8D01707A2A = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5A50BB106B59B3D01707A2A = { + children = ( + F5A50BB206B59B3D01707A2A, + ); + isa = PBXGroup; + path = test_grabbag; + refType = 4; + }; + F5A50BB206B59B3D01707A2A = { + children = ( + F5A50BB306B59B3D01707A2A, + ); + isa = PBXGroup; + path = cuesheet; + refType = 4; + }; + F5A50BB306B59B3D01707A2A = { + isa = PBXFileReference; + path = main.c; + refType = 4; + }; + F5A50BB406B59B3E01707A2A = { + fileRef = F5A50BB306B59B3D01707A2A; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EBE02D18526011525B7 = { + isa = PBXFileReference; + path = metadata.h; + refType = 4; + }; + F5CA9EBF02D18526011525B7 = { + fileRef = F5CA9EBE02D18526011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EC002D18601011525B7 = { + children = ( + F5CA9EC102D18601011525B7, + F5CA9EC202D18601011525B7, + F5CA9EC302D18601011525B7, + F54AFE7806B46E73014FDB82, + F5CA9EC402D18601011525B7, + ); + isa = PBXGroup; + path = "FLAC++"; + refType = 4; + }; + F5CA9EC102D18601011525B7 = { + isa = PBXFileReference; + path = all.h; + refType = 4; + }; + F5CA9EC202D18601011525B7 = { + isa = PBXFileReference; + path = decoder.h; + refType = 4; + }; + F5CA9EC302D18601011525B7 = { + isa = PBXFileReference; + path = encoder.h; + refType = 4; + }; + F5CA9EC402D18601011525B7 = { + isa = PBXFileReference; + path = metadata.h; + refType = 4; + }; + F5CA9EC502D18601011525B7 = { + isa = PBXLibraryReference; + path = "libFLAC++.a"; + refType = 3; + }; + F5CA9EC602D18601011525B7 = { + isa = PBXExecutableFileReference; + path = "test_libFLAC++"; + refType = 3; + }; + F5CA9EC702D18601011525B7 = { + buildPhases = ( + F5D3C68902D18932015C5FF8, + F5CA9EC802D18601011525B7, + F5CA9ECD02D18601011525B7, + F5CA9ECE02D18601011525B7, + F5CA9ECF02D18601011525B7, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = include; + INSTALL_PATH = ""; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = "libFLAC++.a"; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = "libFLAC++"; + productInstallPath = ""; + productName = "libFLAC++"; + productReference = F5CA9EC502D18601011525B7; + shouldUseHeadermap = 0; + }; + F5CA9EC802D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + F5CA9EC902D18601011525B7, + F5CA9ECA02D18601011525B7, + F5CA9ECB02D18601011525B7, + F5CA9ECC02D18601011525B7, + F54AFE8106B46E73014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5CA9EC902D18601011525B7 = { + fileRef = F5CA9EC102D18601011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ECA02D18601011525B7 = { + fileRef = F5CA9EC202D18601011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ECB02D18601011525B7 = { + fileRef = F5CA9EC302D18601011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ECC02D18601011525B7 = { + fileRef = F5CA9EC402D18601011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ECD02D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + F5CA9EE102D186C7011525B7, + F5CA9EE202D186C7011525B7, + F5CA9EE302D186C7011525B7, + F5CA9EE402D186C7011525B7, + F5CA9EE502D186C7011525B7, + F54AFE8206B46E73014FDB82, + F54AFE8306B46E73014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5CA9ECE02D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5CA9ECF02D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5CA9ED002D18601011525B7 = { + buildPhases = ( + F5CA9ED102D18601011525B7, + F5CA9ED202D18601011525B7, + F5CA9ED302D18601011525B7, + F5CA9ED402D18601011525B7, + ); + buildSettings = { + HEADER_SEARCH_PATHS = include; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = "test_libFLAC++"; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = "test_libFLAC++"; + productInstallPath = /usr/local/bin; + productName = "test_libFLAC++"; + productReference = F5CA9EC602D18601011525B7; + shouldUseHeadermap = 0; + }; + F5CA9ED102D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + F5CA9F0A02D1874F011525B7, + F5CA9F0B02D1874F011525B7, + F5CA9F0C02D1874F011525B7, + F5CA9F0D02D1874F011525B7, + F54AFEBC06B46FF0014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5CA9ED202D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + F5CA9F0E02D1874F011525B7, + F5CA9F0F02D1874F011525B7, + F5CA9F1002D1874F011525B7, + F5CA9F1102D1874F011525B7, + F5CA9F1202D1874F011525B7, + F5CA9F1302D1874F011525B7, + F5CA9F1402D1874F011525B7, + F54AFEBD06B46FF0014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5CA9ED302D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + F5F9157806B5911B01999A91, + F5D3C68C02D189F1015C5FF8, + F5D3C6B802D18D00015C5FF8, + F5F3FDB506B6EA9401D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5CA9ED402D18601011525B7 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5CA9ED502D1865E011525B7 = { + isa = PBXFileReference; + path = metadata_iterators.c; + refType = 4; + }; + F5CA9ED602D1865E011525B7 = { + isa = PBXFileReference; + path = metadata_object.c; + refType = 4; + }; + F5CA9ED702D1865E011525B7 = { + fileRef = F5CA9ED502D1865E011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ED802D1865E011525B7 = { + fileRef = F5CA9ED602D1865E011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9ED902D186C7011525B7 = { + isa = PBXFileReference; + path = metadata.h; + refType = 4; + }; + F5CA9EDA02D186C7011525B7 = { + children = ( + F5CA9EDB02D186C7011525B7, + F54AFE7C06B46E73014FDB82, + F5CA9EDC02D186C7011525B7, + F5CA9EDD02D186C7011525B7, + F54AFE7D06B46E73014FDB82, + F5CA9EDE02D186C7011525B7, + F5CA9EDF02D186C7011525B7, + ); + isa = PBXGroup; + path = "libFLAC++"; + refType = 4; + }; + F5CA9EDB02D186C7011525B7 = { + isa = PBXFileReference; + path = file_decoder.cpp; + refType = 4; + }; + F5CA9EDC02D186C7011525B7 = { + isa = PBXFileReference; + path = metadata.cpp; + refType = 4; + }; + F5CA9EDD02D186C7011525B7 = { + isa = PBXFileReference; + path = seekable_stream_decoder.cpp; + refType = 4; + }; + F5CA9EDE02D186C7011525B7 = { + isa = PBXFileReference; + path = stream_decoder.cpp; + refType = 4; + }; + F5CA9EDF02D186C7011525B7 = { + isa = PBXFileReference; + path = stream_encoder.cpp; + refType = 4; + }; + F5CA9EE002D186C7011525B7 = { + fileRef = F5CA9ED902D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE102D186C7011525B7 = { + fileRef = F5CA9EDB02D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE202D186C7011525B7 = { + fileRef = F5CA9EDC02D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE302D186C7011525B7 = { + fileRef = F5CA9EDD02D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE402D186C7011525B7 = { + fileRef = F5CA9EDE02D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE502D186C7011525B7 = { + fileRef = F5CA9EDF02D186C7011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EE602D1874F011525B7 = { + isa = PBXFileReference; + path = decoders.c; + refType = 4; + }; + F5CA9EE702D1874F011525B7 = { + isa = PBXFileReference; + path = decoders.h; + refType = 4; + }; + F5CA9EE802D1874F011525B7 = { + isa = PBXFileReference; + path = encoders.c; + refType = 4; + }; + F5CA9EE902D1874F011525B7 = { + isa = PBXFileReference; + path = encoders.h; + refType = 4; + }; + F5CA9EEA02D1874F011525B7 = { + isa = PBXFileReference; + path = file_utils.c; + refType = 4; + }; + F5CA9EEB02D1874F011525B7 = { + isa = PBXFileReference; + path = file_utils.h; + refType = 4; + }; + F5CA9EEC02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_manip.c; + refType = 4; + }; + F5CA9EED02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_object.c; + refType = 4; + }; + F5CA9EEE02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_utils.c; + refType = 4; + }; + F5CA9EEF02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_utils.h; + refType = 4; + }; + F5CA9EF002D1874F011525B7 = { + isa = PBXFileReference; + path = metadata.c; + refType = 4; + }; + F5CA9EF102D1874F011525B7 = { + isa = PBXFileReference; + path = metadata.h; + refType = 4; + }; + F5CA9EF202D1874F011525B7 = { + children = ( + F5CA9EF302D1874F011525B7, + F5CA9EF402D1874F011525B7, + F5CA9EF502D1874F011525B7, + F5CA9EF602D1874F011525B7, + F5CA9EF702D1874F011525B7, + F5CA9EF802D1874F011525B7, + F5CA9EF902D1874F011525B7, + F5CA9EFA02D1874F011525B7, + F5CA9EFB02D1874F011525B7, + F5CA9EFC02D1874F011525B7, + F5CA9EFD02D1874F011525B7, + F54AFEB206B46FF0014FDB82, + F54AFEB306B46FF0014FDB82, + ); + isa = PBXGroup; + path = "test_libFLAC++"; + refType = 4; + }; + F5CA9EF302D1874F011525B7 = { + isa = PBXFileReference; + path = decoders.cpp; + refType = 4; + }; + F5CA9EF402D1874F011525B7 = { + isa = PBXFileReference; + path = decoders.h; + refType = 4; + }; + F5CA9EF502D1874F011525B7 = { + isa = PBXFileReference; + path = encoders.cpp; + refType = 4; + }; + F5CA9EF602D1874F011525B7 = { + isa = PBXFileReference; + path = encoders.h; + refType = 4; + }; + F5CA9EF702D1874F011525B7 = { + isa = PBXFileReference; + path = file_utils.c; + refType = 4; + }; + F5CA9EF802D1874F011525B7 = { + isa = PBXFileReference; + path = file_utils.h; + refType = 4; + }; + F5CA9EF902D1874F011525B7 = { + isa = PBXFileReference; + path = main.cpp; + refType = 4; + }; + F5CA9EFA02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata.cpp; + refType = 4; + }; + F5CA9EFB02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata.h; + refType = 4; + }; + F5CA9EFC02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_manip.cpp; + refType = 4; + }; + F5CA9EFD02D1874F011525B7 = { + isa = PBXFileReference; + path = metadata_object.cpp; + refType = 4; + }; + F5CA9EFE02D1874F011525B7 = { + fileRef = F5CA9EE702D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9EFF02D1874F011525B7 = { + fileRef = F5CA9EE902D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0002D1874F011525B7 = { + fileRef = F5CA9EEB02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0102D1874F011525B7 = { + fileRef = F5CA9EEF02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0202D1874F011525B7 = { + fileRef = F5CA9EF102D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0302D1874F011525B7 = { + fileRef = F5CA9EE602D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0402D1874F011525B7 = { + fileRef = F5CA9EE802D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0502D1874F011525B7 = { + fileRef = F5CA9EEA02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0602D1874F011525B7 = { + fileRef = F5CA9EEC02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0702D1874F011525B7 = { + fileRef = F5CA9EED02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0802D1874F011525B7 = { + fileRef = F5CA9EEE02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0902D1874F011525B7 = { + fileRef = F5CA9EF002D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0A02D1874F011525B7 = { + fileRef = F5CA9EF402D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0B02D1874F011525B7 = { + fileRef = F5CA9EF602D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0C02D1874F011525B7 = { + fileRef = F5CA9EF802D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0D02D1874F011525B7 = { + fileRef = F5CA9EFB02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0E02D1874F011525B7 = { + fileRef = F5CA9EF302D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F0F02D1874F011525B7 = { + fileRef = F5CA9EF502D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F1002D1874F011525B7 = { + fileRef = F5CA9EF702D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F1102D1874F011525B7 = { + fileRef = F5CA9EF902D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F1202D1874F011525B7 = { + fileRef = F5CA9EFA02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F1302D1874F011525B7 = { + fileRef = F5CA9EFC02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5CA9F1402D1874F011525B7 = { + fileRef = F5CA9EFD02D1874F011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5D3C68902D18932015C5FF8 = { + buildActionMask = 2147483647; + files = ( + ); + generatedFileNames = ( + ); + isa = PBXShellScriptBuildPhase; + name = "Shell Script"; + neededFileNames = ( + ); + shellPath = /bin/sh; + shellScript = $SRCROOT/build/project_builder_prebuild_phase.sh; + }; + F5D3C68C02D189F1015C5FF8 = { + fileRef = F5CA9EC502D18601011525B7; + isa = PBXBuildFile; + settings = { + }; + }; + F5D3C68D02D18AAF015C5FF8 = { + children = ( + F5D3C68E02D18AAF015C5FF8, + F566F4C606B4A4270107D11D, + F566F4CB06B4A4270107D11D, + F566F4CC06B4A4270107D11D, + F566F4CD06B4A4270107D11D, + F566F4CE06B4A4270107D11D, + ); + isa = PBXGroup; + path = share; + refType = 4; + }; + F5D3C68E02D18AAF015C5FF8 = { + isa = PBXFileReference; + path = getopt.h; + refType = 4; + }; + F5D3C68F02D18AAF015C5FF8 = { + children = ( + F54AFF7006B4A184014FDB82, + F566F4CF06B4A4270107D11D, + F566F4D406B4A4270107D11D, + F566F4D606B4A4270107D11D, + F566F4DB06B4A4270107D11D, + ); + isa = PBXGroup; + path = share; + refType = 4; + }; + F5D3C69202D18AAF015C5FF8 = { + isa = PBXLibraryReference; + path = libgetopt.a; + refType = 3; + }; + F5D3C69302D18AAF015C5FF8 = { + buildPhases = ( + F5D3C69D02D18B5E015C5FF8, + F5D3C69402D18AAF015C5FF8, + F5D3C69602D18AAF015C5FF8, + F5D3C69902D18AAF015C5FF8, + F5D3C69A02D18AAF015C5FF8, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + HEADER_SEARCH_PATHS = "include include/share"; + LIBRARY_STYLE = STATIC; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = libgetopt.a; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = libgetopt; + productInstallPath = /usr/local/lib; + productName = libgetopt; + productReference = F5D3C69202D18AAF015C5FF8; + shouldUseHeadermap = 0; + }; + F5D3C69402D18AAF015C5FF8 = { + buildActionMask = 2147483647; + files = ( + F5D3C69502D18AAF015C5FF8, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5D3C69502D18AAF015C5FF8 = { + fileRef = F5D3C68E02D18AAF015C5FF8; + isa = PBXBuildFile; + settings = { + }; + }; + F5D3C69602D18AAF015C5FF8 = { + buildActionMask = 2147483647; + files = ( + F566F4AC06B4A2400107D11D, + F566F4AD06B4A2400107D11D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5D3C69902D18AAF015C5FF8 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5D3C69A02D18AAF015C5FF8 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5D3C69C02D18B1D015C5FF8 = { + fileRef = F5D3C69202D18AAF015C5FF8; + isa = PBXBuildFile; + settings = { + }; + }; + F5D3C69D02D18B5E015C5FF8 = { + buildActionMask = 2147483647; + files = ( + ); + generatedFileNames = ( + ); + isa = PBXShellScriptBuildPhase; + name = "Shell Script"; + neededFileNames = ( + ); + shellPath = /bin/sh; + shellScript = $SRCROOT/build/project_builder_prebuild_phase.sh; + }; + F5D3C6B802D18D00015C5FF8 = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB206B6E9AE01D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB306B6E9E701D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB406B6EA3E01D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB506B6EA9401D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB606B6EABC01D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F3FDB706B6EAD201D13CEE = { + fileRef = F5F7D56F06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561E5019B56E401A8006D = { + isa = PBXExecutableFileReference; + path = metaflac; + refType = 3; + }; + F5F561E6019B56E401A8006D = { + buildPhases = ( + F5F561E7019B56E401A8006D, + F5F561E8019B56E401A8006D, + F5F561E9019B56E401A8006D, + F5F561EA019B56E401A8006D, + ); + buildSettings = { + HEADER_SEARCH_PATHS = "/sw/include include"; + LIBRARY_SEARCH_PATHS = /sw/lib; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DVERSION=\\\\\\\"1.2.1\\\\\\\" -DHAVE_INTTYPES_H -DFLAC__HAS_OGG"; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = metaflac; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = metaflac; + productInstallPath = /usr/local/bin; + productName = metaflac; + productReference = F5F561E5019B56E401A8006D; + shouldUseHeadermap = 0; + }; + F5F561E7019B56E401A8006D = { + buildActionMask = 2147483647; + files = ( + F54AFE9C06B46F13014FDB82, + F54AFE9D06B46F13014FDB82, + F54AFE9E06B46F13014FDB82, + F54AFE9F06B46F13014FDB82, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5F561E8019B56E401A8006D = { + buildActionMask = 2147483647; + files = ( + F5F561EB019B573A01A8006D, + F54AFEA006B46F13014FDB82, + F54AFEA106B46F13014FDB82, + F54AFEA206B46F13014FDB82, + F54AFEA306B46F13014FDB82, + F54AFEA406B46F13014FDB82, + F54AFEA506B46F13014FDB82, + F54AFEA606B46F13014FDB82, + F54AFEA706B46F13014FDB82, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5F561E9019B56E401A8006D = { + buildActionMask = 2147483647; + files = ( + F5D3C69C02D18B1D015C5FF8, + F5F9157606B5907801999A91, + F5F9157906B5914D01999A91, + F5830B7E06B59ECD0175F08C, + F5F561ED019B579901A8006D, + F5F3FDB306B6E9E701D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5F561EA019B56E401A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5F561EB019B573A01A8006D = { + fileRef = F59E599A01972D3D01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561ED019B579901A8006D = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561EE019B58E101A8006D = { + isa = PBXExecutableFileReference; + path = test_streams; + refType = 3; + }; + F5F561EF019B58E101A8006D = { + isa = PBXExecutableFileReference; + path = test_libFLAC; + refType = 3; + }; + F5F561F0019B58E101A8006D = { + buildPhases = ( + F5F561F1019B58E101A8006D, + F5F561F2019B58E101A8006D, + F5F561F4019B58E101A8006D, + F5F561F5019B58E101A8006D, + ); + buildSettings = { + HEADER_SEARCH_PATHS = include; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = test_streams; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = test_streams; + productInstallPath = /usr/local/bin; + productName = test_streams; + productReference = F5F561EE019B58E101A8006D; + shouldUseHeadermap = 0; + }; + F5F561F1019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5F561F2019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + F5F561F3019B58E101A8006D, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5F561F3019B58E101A8006D = { + fileRef = F59E59B801972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561F4019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5F561F5019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5F561F6019B58E101A8006D = { + buildPhases = ( + F5F561F7019B58E101A8006D, + F5F561F9019B58E101A8006D, + F5F561FC019B58E101A8006D, + F5F561FE019B58E101A8006D, + ); + buildSettings = { + HEADER_SEARCH_PATHS = "src/libFLAC/include include"; + OPTIMIZATION_CFLAGS = "-O3"; + OTHER_CFLAGS = "-DHAVE_INTTYPES_H"; + OTHER_LDFLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = test_libFLAC; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXToolTarget; + name = test_libFLAC; + productInstallPath = /usr/local/bin; + productName = test_libFLAC; + productReference = F5F561EF019B58E101A8006D; + shouldUseHeadermap = 0; + }; + F5F561F7019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + F5F561F8019B58E101A8006D, + F5CA9EFE02D1874F011525B7, + F5CA9EFF02D1874F011525B7, + F5CA9F0002D1874F011525B7, + F5CA9F0102D1874F011525B7, + F5CA9F0202D1874F011525B7, + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5F561F8019B58E101A8006D = { + fileRef = F59E59BE01972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561F9019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + F5F561FA019B58E101A8006D, + F5F561FB019B58E101A8006D, + F5CA9F0302D1874F011525B7, + F5CA9F0402D1874F011525B7, + F5CA9F0502D1874F011525B7, + F5CA9F0602D1874F011525B7, + F5CA9F0702D1874F011525B7, + F5CA9F0802D1874F011525B7, + F5CA9F0902D1874F011525B7, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5F561FA019B58E101A8006D = { + fileRef = F59E59BD01972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561FB019B58E101A8006D = { + fileRef = F59E59BF01972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561FC019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + F5F9157706B590B901999A91, + F5F561FD019B58E101A8006D, + F5F3FDB406B6EA3E01D13CEE, + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5F561FD019B58E101A8006D = { + fileRef = F59E59C401972D3E01A8006D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F561FE019B58E101A8006D = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5F7D56D06B6E75301AAAA86 = { + children = ( + F5F7D56E06B6E75301AAAA86, + ); + isa = PBXGroup; + path = ppc; + refType = 4; + }; + F5F7D56E06B6E75301AAAA86 = { + isa = PBXFileReference; + path = lpc_asm.s; + refType = 4; + }; + F5F7D56F06B6E75301AAAA86 = { + isa = PBXLibraryReference; + path = "libFLAC-asm.a"; + refType = 3; + }; + F5F7D57006B6E75301AAAA86 = { + buildPhases = ( + F5F7D57106B6E75301AAAA86, + F5F7D57206B6E75301AAAA86, + F5F7D57406B6E75301AAAA86, + F5F7D57506B6E75301AAAA86, + ); + buildSettings = { + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + LIBRARY_STYLE = STATIC; + OTHER_CFLAGS = "-force_cpusubtype_ALL"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOL_FLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = "libFLAC-asm.a"; + REZ_EXECUTABLE = YES; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas"; + }; + dependencies = ( + ); + isa = PBXLibraryTarget; + name = "libFLAC-asm"; + productInstallPath = /usr/local/lib; + productName = "libFLAC-asm"; + productReference = F5F7D56F06B6E75301AAAA86; + shouldUseHeadermap = 0; + }; + F5F7D57106B6E75301AAAA86 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXHeadersBuildPhase; + name = Headers; + }; + F5F7D57206B6E75301AAAA86 = { + buildActionMask = 2147483647; + files = ( + F5F7D57306B6E75301AAAA86, + ); + isa = PBXSourcesBuildPhase; + name = Sources; + }; + F5F7D57306B6E75301AAAA86 = { + fileRef = F5F7D56E06B6E75301AAAA86; + isa = PBXBuildFile; + settings = { + }; + }; + F5F7D57406B6E75301AAAA86 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXFrameworksBuildPhase; + name = "Frameworks & Libraries"; + }; + F5F7D57506B6E75301AAAA86 = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXRezBuildPhase; + name = "ResourceManager Resources"; + }; + F5F9157606B5907801999A91 = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F9157706B590B901999A91 = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F9157806B5911B01999A91 = { + fileRef = F566F4AE06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + F5F9157906B5914D01999A91 = { + fileRef = F566F4AF06B4A2B30107D11D; + isa = PBXBuildFile; + settings = { + }; + }; + }; + rootObject = F59E594B01972C6B01A8006D; +} diff --git a/flac/include/FLAC++/Makefile.am b/flac/include/FLAC++/Makefile.am new file mode 100644 index 0000000..0961417 --- /dev/null +++ b/flac/include/FLAC++/Makefile.am @@ -0,0 +1,38 @@ +# libFLAC++ - Free Lossless Audio Codec library +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +flaccppincludedir = $(includedir)/FLAC++ + +flaccppinclude_HEADERS = \ + all.h \ + decoder.h \ + encoder.h \ + export.h \ + metadata.h diff --git a/flac/include/FLAC++/all.h b/flac/include/FLAC++/all.h new file mode 100644 index 0000000..514f2f6 --- /dev/null +++ b/flac/include/FLAC++/all.h @@ -0,0 +1,48 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLACPP__ALL_H +#define FLACPP__ALL_H + +#include "export.h" + +#include "encoder.h" +#include "decoder.h" +#include "metadata.h" + +/** \defgroup flacpp FLAC C++ API + * + * The FLAC C++ API is the interface to libFLAC++, a set of classes + * that encapsulate the encoders, decoders, and metadata interfaces + * in libFLAC. + */ + +#endif diff --git a/flac/include/FLAC++/decoder.h b/flac/include/FLAC++/decoder.h new file mode 100644 index 0000000..2aaccdf --- /dev/null +++ b/flac/include/FLAC++/decoder.h @@ -0,0 +1,245 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLACPP__DECODER_H +#define FLACPP__DECODER_H + +#include "export.h" + +#include +#include "FLAC/stream_decoder.h" + + +/** \file include/FLAC++/decoder.h + * + * \brief + * This module contains the classes which implement the various + * decoders. + * + * See the detailed documentation in the + * \link flacpp_decoder decoder \endlink module. + */ + +/** \defgroup flacpp_decoder FLAC++/decoder.h: decoder classes + * \ingroup flacpp + * + * \brief + * This module describes the decoder layers provided by libFLAC++. + * + * The libFLAC++ decoder classes are object wrappers around their + * counterparts in libFLAC. All decoding layers available in + * libFLAC are also provided here. The interface is very similar; + * make sure to read the \link flac_decoder libFLAC decoder module \endlink. + * + * There are only two significant differences here. First, instead of + * passing in C function pointers for callbacks, you inherit from the + * decoder class and provide implementations for the callbacks in your + * derived class; because of this there is no need for a 'client_data' + * property. + * + * Second, there are two stream decoder classes. FLAC::Decoder::Stream + * is used for the same cases that FLAC__stream_decoder_init_stream() / + * FLAC__stream_decoder_init_ogg_stream() are used, and FLAC::Decoder::File + * is used for the same cases that + * FLAC__stream_decoder_init_FILE() and FLAC__stream_decoder_init_file() / + * FLAC__stream_decoder_init_ogg_FILE() and FLAC__stream_decoder_init_ogg_file() + * are used. + */ + +namespace FLAC { + namespace Decoder { + + /** \ingroup flacpp_decoder + * \brief + * This class wraps the ::FLAC__StreamDecoder. If you are + * decoding from a file, FLAC::Decoder::File may be more + * convenient. + * + * The usage of this class is similar to FLAC__StreamDecoder, + * except instead of providing callbacks to + * FLAC__stream_decoder_init*_stream(), you will inherit from this + * class and override the virtual callback functions with your + * own implementations, then call init() or init_ogg(). The rest + * of the calls work the same as in the C layer. + * + * Only the read, write, and error callbacks are mandatory. The + * others are optional; this class provides default + * implementations that do nothing. In order for seeking to work + * you must overide seek_callback(), tell_callback(), + * length_callback(), and eof_callback(). + */ + class FLACPP_API Stream { + public: + /** This class is a wrapper around FLAC__StreamDecoderState. + */ + class FLACPP_API State { + public: + inline State(::FLAC__StreamDecoderState state): state_(state) { } + inline operator ::FLAC__StreamDecoderState() const { return state_; } + inline const char *as_cstring() const { return ::FLAC__StreamDecoderStateString[state_]; } + inline const char *resolved_as_cstring(const Stream &decoder) const { return ::FLAC__stream_decoder_get_resolved_state_string(decoder.decoder_); } + protected: + ::FLAC__StreamDecoderState state_; + }; + + Stream(); + virtual ~Stream(); + + //@{ + /** Call after construction to check the that the object was created + * successfully. If not, use get_state() to find out why not. + */ + virtual bool is_valid() const; + inline operator bool() const { return is_valid(); } ///< See is_valid() + //@} + + virtual bool set_ogg_serial_number(long value); ///< See FLAC__stream_decoder_set_ogg_serial_number() + virtual bool set_md5_checking(bool value); ///< See FLAC__stream_decoder_set_md5_checking() + virtual bool set_metadata_respond(::FLAC__MetadataType type); ///< See FLAC__stream_decoder_set_metadata_respond() + virtual bool set_metadata_respond_application(const FLAC__byte id[4]); ///< See FLAC__stream_decoder_set_metadata_respond_application() + virtual bool set_metadata_respond_all(); ///< See FLAC__stream_decoder_set_metadata_respond_all() + virtual bool set_metadata_ignore(::FLAC__MetadataType type); ///< See FLAC__stream_decoder_set_metadata_ignore() + virtual bool set_metadata_ignore_application(const FLAC__byte id[4]); ///< See FLAC__stream_decoder_set_metadata_ignore_application() + virtual bool set_metadata_ignore_all(); ///< See FLAC__stream_decoder_set_metadata_ignore_all() + + /* get_state() is not virtual since we want subclasses to be able to return their own state */ + State get_state() const; ///< See FLAC__stream_decoder_get_state() + virtual bool get_md5_checking() const; ///< See FLAC__stream_decoder_get_md5_checking() + virtual FLAC__uint64 get_total_samples() const; ///< See FLAC__stream_decoder_get_total_samples() + virtual unsigned get_channels() const; ///< See FLAC__stream_decoder_get_channels() + virtual ::FLAC__ChannelAssignment get_channel_assignment() const; ///< See FLAC__stream_decoder_get_channel_assignment() + virtual unsigned get_bits_per_sample() const; ///< See FLAC__stream_decoder_get_bits_per_sample() + virtual unsigned get_sample_rate() const; ///< See FLAC__stream_decoder_get_sample_rate() + virtual unsigned get_blocksize() const; ///< See FLAC__stream_decoder_get_blocksize() + virtual bool get_decode_position(FLAC__uint64 *position) const; ///< See FLAC__stream_decoder_get_decode_position() + + virtual ::FLAC__StreamDecoderInitStatus init(); ///< Seek FLAC__stream_decoder_init_stream() + virtual ::FLAC__StreamDecoderInitStatus init_ogg(); ///< Seek FLAC__stream_decoder_init_ogg_stream() + + virtual bool finish(); ///< See FLAC__stream_decoder_finish() + + virtual bool flush(); ///< See FLAC__stream_decoder_flush() + virtual bool reset(); ///< See FLAC__stream_decoder_reset() + + virtual bool process_single(); ///< See FLAC__stream_decoder_process_single() + virtual bool process_until_end_of_metadata(); ///< See FLAC__stream_decoder_process_until_end_of_metadata() + virtual bool process_until_end_of_stream(); ///< See FLAC__stream_decoder_process_until_end_of_stream() + virtual bool skip_single_frame(); ///< See FLAC__stream_decoder_skip_single_frame() + + virtual bool seek_absolute(FLAC__uint64 sample); ///< See FLAC__stream_decoder_seek_absolute() + protected: + /// see FLAC__StreamDecoderReadCallback + virtual ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes) = 0; + + /// see FLAC__StreamDecoderSeekCallback + virtual ::FLAC__StreamDecoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset); + + /// see FLAC__StreamDecoderTellCallback + virtual ::FLAC__StreamDecoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset); + + /// see FLAC__StreamDecoderLengthCallback + virtual ::FLAC__StreamDecoderLengthStatus length_callback(FLAC__uint64 *stream_length); + + /// see FLAC__StreamDecoderEofCallback + virtual bool eof_callback(); + + /// see FLAC__StreamDecoderWriteCallback + virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) = 0; + + /// see FLAC__StreamDecoderMetadataCallback + virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata); + + /// see FLAC__StreamDecoderErrorCallback + virtual void error_callback(::FLAC__StreamDecoderErrorStatus status) = 0; + +#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __GNUG__ && (__GNUG__ < 2 || (__GNUG__ == 2 && __GNUC_MINOR__ < 96))) || (defined __SUNPRO_CC) + // lame hack: some MSVC/GCC versions can't see a protected decoder_ from nested State::resolved_as_cstring() + friend State; +#endif + ::FLAC__StreamDecoder *decoder_; + + static ::FLAC__StreamDecoderReadStatus read_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); + static ::FLAC__StreamDecoderSeekStatus seek_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data); + static ::FLAC__StreamDecoderTellStatus tell_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data); + static ::FLAC__StreamDecoderLengthStatus length_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data); + static FLAC__bool eof_callback_(const ::FLAC__StreamDecoder *decoder, void *client_data); + static ::FLAC__StreamDecoderWriteStatus write_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); + static void metadata_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *client_data); + static void error_callback_(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data); + private: + // Private and undefined so you can't use them: + Stream(const Stream &); + void operator=(const Stream &); + }; + + /** \ingroup flacpp_decoder + * \brief + * This class wraps the ::FLAC__StreamDecoder. If you are + * not decoding from a file, you may need to use + * FLAC::Decoder::Stream. + * + * The usage of this class is similar to FLAC__StreamDecoder, + * except instead of providing callbacks to + * FLAC__stream_decoder_init*_FILE() or + * FLAC__stream_decoder_init*_file(), you will inherit from this + * class and override the virtual callback functions with your + * own implementations, then call init() or init_off(). The rest + * of the calls work the same as in the C layer. + * + * Only the write, and error callbacks from FLAC::Decoder::Stream + * are mandatory. The others are optional; this class provides + * full working implementations for all other callbacks and + * supports seeking. + */ + class FLACPP_API File: public Stream { + public: + File(); + virtual ~File(); + + virtual ::FLAC__StreamDecoderInitStatus init(FILE *file); ///< See FLAC__stream_decoder_init_FILE() + virtual ::FLAC__StreamDecoderInitStatus init(const char *filename); ///< See FLAC__stream_decoder_init_file() + virtual ::FLAC__StreamDecoderInitStatus init(const std::string &filename); ///< See FLAC__stream_decoder_init_file() + virtual ::FLAC__StreamDecoderInitStatus init_ogg(FILE *file); ///< See FLAC__stream_decoder_init_ogg_FILE() + virtual ::FLAC__StreamDecoderInitStatus init_ogg(const char *filename); ///< See FLAC__stream_decoder_init_ogg_file() + virtual ::FLAC__StreamDecoderInitStatus init_ogg(const std::string &filename); ///< See FLAC__stream_decoder_init_ogg_file() + protected: + // this is a dummy implementation to satisfy the pure virtual in Stream that is actually supplied internally by the C layer + virtual ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes); + private: + // Private and undefined so you can't use them: + File(const File &); + void operator=(const File &); + }; + + } +} + +#endif diff --git a/flac/include/FLAC++/encoder.h b/flac/include/FLAC++/encoder.h new file mode 100644 index 0000000..e26d0e6 --- /dev/null +++ b/flac/include/FLAC++/encoder.h @@ -0,0 +1,260 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLACPP__ENCODER_H +#define FLACPP__ENCODER_H + +#include "export.h" + +#include "FLAC/stream_encoder.h" +#include "decoder.h" +#include "metadata.h" + + +/** \file include/FLAC++/encoder.h + * + * \brief + * This module contains the classes which implement the various + * encoders. + * + * See the detailed documentation in the + * \link flacpp_encoder encoder \endlink module. + */ + +/** \defgroup flacpp_encoder FLAC++/encoder.h: encoder classes + * \ingroup flacpp + * + * \brief + * This module describes the encoder layers provided by libFLAC++. + * + * The libFLAC++ encoder classes are object wrappers around their + * counterparts in libFLAC. All encoding layers available in + * libFLAC are also provided here. The interface is very similar; + * make sure to read the \link flac_encoder libFLAC encoder module \endlink. + * + * There are only two significant differences here. First, instead of + * passing in C function pointers for callbacks, you inherit from the + * encoder class and provide implementations for the callbacks in your + * derived class; because of this there is no need for a 'client_data' + * property. + * + * Second, there are two stream encoder classes. FLAC::Encoder::Stream + * is used for the same cases that FLAC__stream_encoder_init_stream() / + * FLAC__stream_encoder_init_ogg_stream() are used, and FLAC::Encoder::File + * is used for the same cases that + * FLAC__stream_encoder_init_FILE() and FLAC__stream_encoder_init_file() / + * FLAC__stream_encoder_init_ogg_FILE() and FLAC__stream_encoder_init_ogg_file() + * are used. + */ + +namespace FLAC { + namespace Encoder { + + /** \ingroup flacpp_encoder + * \brief + * This class wraps the ::FLAC__StreamEncoder. If you are + * encoding to a file, FLAC::Encoder::File may be more + * convenient. + * + * The usage of this class is similar to FLAC__StreamEncoder, + * except instead of providing callbacks to + * FLAC__stream_encoder_init*_stream(), you will inherit from this + * class and override the virtual callback functions with your + * own implementations, then call init() or init_ogg(). The rest of + * the calls work the same as in the C layer. + * + * Only the write callback is mandatory. The others are + * optional; this class provides default implementations that do + * nothing. In order for some STREAMINFO and SEEKTABLE data to + * be written properly, you must overide seek_callback() and + * tell_callback(); see FLAC__stream_encoder_init_stream() as to + * why. + */ + class FLACPP_API Stream { + public: + /** This class is a wrapper around FLAC__StreamEncoderState. + */ + class FLACPP_API State { + public: + inline State(::FLAC__StreamEncoderState state): state_(state) { } + inline operator ::FLAC__StreamEncoderState() const { return state_; } + inline const char *as_cstring() const { return ::FLAC__StreamEncoderStateString[state_]; } + inline const char *resolved_as_cstring(const Stream &encoder) const { return ::FLAC__stream_encoder_get_resolved_state_string(encoder.encoder_); } + protected: + ::FLAC__StreamEncoderState state_; + }; + + Stream(); + virtual ~Stream(); + + //@{ + /** Call after construction to check the that the object was created + * successfully. If not, use get_state() to find out why not. + * + */ + virtual bool is_valid() const; + inline operator bool() const { return is_valid(); } ///< See is_valid() + //@} + + virtual bool set_ogg_serial_number(long value); ///< See FLAC__stream_encoder_set_ogg_serial_number() + virtual bool set_verify(bool value); ///< See FLAC__stream_encoder_set_verify() + virtual bool set_streamable_subset(bool value); ///< See FLAC__stream_encoder_set_streamable_subset() + virtual bool set_channels(unsigned value); ///< See FLAC__stream_encoder_set_channels() + virtual bool set_bits_per_sample(unsigned value); ///< See FLAC__stream_encoder_set_bits_per_sample() + virtual bool set_sample_rate(unsigned value); ///< See FLAC__stream_encoder_set_sample_rate() + virtual bool set_compression_level(unsigned value); ///< See FLAC__stream_encoder_set_compression_level() + virtual bool set_blocksize(unsigned value); ///< See FLAC__stream_encoder_set_blocksize() + virtual bool set_do_mid_side_stereo(bool value); ///< See FLAC__stream_encoder_set_do_mid_side_stereo() + virtual bool set_loose_mid_side_stereo(bool value); ///< See FLAC__stream_encoder_set_loose_mid_side_stereo() + virtual bool set_apodization(const char *specification); ///< See FLAC__stream_encoder_set_apodization() + virtual bool set_max_lpc_order(unsigned value); ///< See FLAC__stream_encoder_set_max_lpc_order() + virtual bool set_qlp_coeff_precision(unsigned value); ///< See FLAC__stream_encoder_set_qlp_coeff_precision() + virtual bool set_do_qlp_coeff_prec_search(bool value); ///< See FLAC__stream_encoder_set_do_qlp_coeff_prec_search() + virtual bool set_do_escape_coding(bool value); ///< See FLAC__stream_encoder_set_do_escape_coding() + virtual bool set_do_exhaustive_model_search(bool value); ///< See FLAC__stream_encoder_set_do_exhaustive_model_search() + virtual bool set_min_residual_partition_order(unsigned value); ///< See FLAC__stream_encoder_set_min_residual_partition_order() + virtual bool set_max_residual_partition_order(unsigned value); ///< See FLAC__stream_encoder_set_max_residual_partition_order() + virtual bool set_rice_parameter_search_dist(unsigned value); ///< See FLAC__stream_encoder_set_rice_parameter_search_dist() + virtual bool set_total_samples_estimate(FLAC__uint64 value); ///< See FLAC__stream_encoder_set_total_samples_estimate() + virtual bool set_metadata(::FLAC__StreamMetadata **metadata, unsigned num_blocks); ///< See FLAC__stream_encoder_set_metadata() + virtual bool set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks); ///< See FLAC__stream_encoder_set_metadata() + + /* get_state() is not virtual since we want subclasses to be able to return their own state */ + State get_state() const; ///< See FLAC__stream_encoder_get_state() + virtual Decoder::Stream::State get_verify_decoder_state() const; ///< See FLAC__stream_encoder_get_verify_decoder_state() + virtual void get_verify_decoder_error_stats(FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got); ///< See FLAC__stream_encoder_get_verify_decoder_error_stats() + virtual bool get_verify() const; ///< See FLAC__stream_encoder_get_verify() + virtual bool get_streamable_subset() const; ///< See FLAC__stream_encoder_get_streamable_subset() + virtual bool get_do_mid_side_stereo() const; ///< See FLAC__stream_encoder_get_do_mid_side_stereo() + virtual bool get_loose_mid_side_stereo() const; ///< See FLAC__stream_encoder_get_loose_mid_side_stereo() + virtual unsigned get_channels() const; ///< See FLAC__stream_encoder_get_channels() + virtual unsigned get_bits_per_sample() const; ///< See FLAC__stream_encoder_get_bits_per_sample() + virtual unsigned get_sample_rate() const; ///< See FLAC__stream_encoder_get_sample_rate() + virtual unsigned get_blocksize() const; ///< See FLAC__stream_encoder_get_blocksize() + virtual unsigned get_max_lpc_order() const; ///< See FLAC__stream_encoder_get_max_lpc_order() + virtual unsigned get_qlp_coeff_precision() const; ///< See FLAC__stream_encoder_get_qlp_coeff_precision() + virtual bool get_do_qlp_coeff_prec_search() const; ///< See FLAC__stream_encoder_get_do_qlp_coeff_prec_search() + virtual bool get_do_escape_coding() const; ///< See FLAC__stream_encoder_get_do_escape_coding() + virtual bool get_do_exhaustive_model_search() const; ///< See FLAC__stream_encoder_get_do_exhaustive_model_search() + virtual unsigned get_min_residual_partition_order() const; ///< See FLAC__stream_encoder_get_min_residual_partition_order() + virtual unsigned get_max_residual_partition_order() const; ///< See FLAC__stream_encoder_get_max_residual_partition_order() + virtual unsigned get_rice_parameter_search_dist() const; ///< See FLAC__stream_encoder_get_rice_parameter_search_dist() + virtual FLAC__uint64 get_total_samples_estimate() const; ///< See FLAC__stream_encoder_get_total_samples_estimate() + + virtual ::FLAC__StreamEncoderInitStatus init(); ///< See FLAC__stream_encoder_init_stream() + virtual ::FLAC__StreamEncoderInitStatus init_ogg(); ///< See FLAC__stream_encoder_init_ogg_stream() + + virtual bool finish(); ///< See FLAC__stream_encoder_finish() + + virtual bool process(const FLAC__int32 * const buffer[], unsigned samples); ///< See FLAC__stream_encoder_process() + virtual bool process_interleaved(const FLAC__int32 buffer[], unsigned samples); ///< See FLAC__stream_encoder_process_interleaved() + protected: + /// See FLAC__StreamEncoderReadCallback + virtual ::FLAC__StreamEncoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes); + + /// See FLAC__StreamEncoderWriteCallback + virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame) = 0; + + /// See FLAC__StreamEncoderSeekCallback + virtual ::FLAC__StreamEncoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset); + + /// See FLAC__StreamEncoderTellCallback + virtual ::FLAC__StreamEncoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset); + + /// See FLAC__StreamEncoderMetadataCallback + virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata); + +#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __GNUG__ && (__GNUG__ < 2 || (__GNUG__ == 2 && __GNUC_MINOR__ < 96))) || (defined __SUNPRO_CC) + // lame hack: some MSVC/GCC versions can't see a protected encoder_ from nested State::resolved_as_cstring() + friend State; +#endif + ::FLAC__StreamEncoder *encoder_; + + static ::FLAC__StreamEncoderReadStatus read_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data); + static ::FLAC__StreamEncoderWriteStatus write_callback_(const ::FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data); + static ::FLAC__StreamEncoderSeekStatus seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data); + static ::FLAC__StreamEncoderTellStatus tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data); + static void metadata_callback_(const ::FLAC__StreamEncoder *encoder, const ::FLAC__StreamMetadata *metadata, void *client_data); + private: + // Private and undefined so you can't use them: + Stream(const Stream &); + void operator=(const Stream &); + }; + + /** \ingroup flacpp_encoder + * \brief + * This class wraps the ::FLAC__StreamEncoder. If you are + * not encoding to a file, you may need to use + * FLAC::Encoder::Stream. + * + * The usage of this class is similar to FLAC__StreamEncoder, + * except instead of providing callbacks to + * FLAC__stream_encoder_init*_FILE() or + * FLAC__stream_encoder_init*_file(), you will inherit from this + * class and override the virtual callback functions with your + * own implementations, then call init() or init_ogg(). The rest + * of the calls work the same as in the C layer. + * + * There are no mandatory callbacks; all the callbacks from + * FLAC::Encoder::Stream are implemented here fully and support + * full post-encode STREAMINFO and SEEKTABLE updating. There is + * only an optional progress callback which you may override to + * get periodic reports on the progress of the encode. + */ + class FLACPP_API File: public Stream { + public: + File(); + virtual ~File(); + + virtual ::FLAC__StreamEncoderInitStatus init(FILE *file); ///< See FLAC__stream_encoder_init_FILE() + virtual ::FLAC__StreamEncoderInitStatus init(const char *filename); ///< See FLAC__stream_encoder_init_file() + virtual ::FLAC__StreamEncoderInitStatus init(const std::string &filename); ///< See FLAC__stream_encoder_init_file() + virtual ::FLAC__StreamEncoderInitStatus init_ogg(FILE *file); ///< See FLAC__stream_encoder_init_ogg_FILE() + virtual ::FLAC__StreamEncoderInitStatus init_ogg(const char *filename); ///< See FLAC__stream_encoder_init_ogg_file() + virtual ::FLAC__StreamEncoderInitStatus init_ogg(const std::string &filename); ///< See FLAC__stream_encoder_init_ogg_file() + protected: + /// See FLAC__StreamEncoderProgressCallback + virtual void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate); + + /// This is a dummy implementation to satisfy the pure virtual in Stream that is actually supplied internally by the C layer + virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame); + private: + static void progress_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data); + + // Private and undefined so you can't use them: + File(const Stream &); + void operator=(const Stream &); + }; + + } +} + +#endif diff --git a/flac/include/FLAC++/export.h b/flac/include/FLAC++/export.h new file mode 100644 index 0000000..e8364f2 --- /dev/null +++ b/flac/include/FLAC++/export.h @@ -0,0 +1,80 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLACPP__EXPORT_H +#define FLACPP__EXPORT_H + +/** \file include/FLAC++/export.h + * + * \brief + * This module contains #defines and symbols for exporting function + * calls, and providing version information and compiled-in features. + * + * See the \link flacpp_export export \endlink module. + */ + +/** \defgroup flacpp_export FLAC++/export.h: export symbols + * \ingroup flacpp + * + * \brief + * This module contains #defines and symbols for exporting function + * calls, and providing version information and compiled-in features. + * + * If you are compiling with MSVC and will link to the static library + * (libFLAC++.lib) you should define FLAC__NO_DLL in your project to + * make sure the symbols are exported properly. + * + * \{ + */ + +#if defined(FLAC__NO_DLL) || !defined(_MSC_VER) +#define FLACPP_API + +#else + +#ifdef FLACPP_API_EXPORTS +#define FLACPP_API _declspec(dllexport) +#else +#define FLACPP_API _declspec(dllimport) + +#endif +#endif + +/* These #defines will mirror the libtool-based library version number, see + * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning + */ +#define FLACPP_API_VERSION_CURRENT 8 +#define FLACPP_API_VERSION_REVISION 0 +#define FLACPP_API_VERSION_AGE 2 + +/* \} */ + +#endif diff --git a/flac/include/FLAC++/metadata.h b/flac/include/FLAC++/metadata.h new file mode 100644 index 0000000..060ebf5 --- /dev/null +++ b/flac/include/FLAC++/metadata.h @@ -0,0 +1,1156 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLACPP__METADATA_H +#define FLACPP__METADATA_H + +#include "export.h" + +#include "FLAC/metadata.h" + +// =============================================================== +// +// Full documentation for the metadata interface can be found +// in the C layer in include/FLAC/metadata.h +// +// =============================================================== + +/** \file include/FLAC++/metadata.h + * + * \brief + * This module provides classes for creating and manipulating FLAC + * metadata blocks in memory, and three progressively more powerful + * interfaces for traversing and editing metadata in FLAC files. + * + * See the detailed documentation for each interface in the + * \link flacpp_metadata metadata \endlink module. + */ + +/** \defgroup flacpp_metadata FLAC++/metadata.h: metadata interfaces + * \ingroup flacpp + * + * \brief + * This module provides classes for creating and manipulating FLAC + * metadata blocks in memory, and three progressively more powerful + * interfaces for traversing and editing metadata in FLAC files. + * + * The behavior closely mimics the C layer interface; be sure to read + * the detailed description of the + * \link flac_metadata C metadata module \endlink. Note that like the + * C layer, currently only the Chain interface (level 2) supports Ogg + * FLAC files, and it is read-only i.e. no writing back changed + * metadata to file. + */ + + +namespace FLAC { + namespace Metadata { + + // ============================================================ + // + // Metadata objects + // + // ============================================================ + + /** \defgroup flacpp_metadata_object FLAC++/metadata.h: metadata object classes + * \ingroup flacpp_metadata + * + * This module contains classes representing FLAC metadata + * blocks in memory. + * + * The behavior closely mimics the C layer interface; be + * sure to read the detailed description of the + * \link flac_metadata_object C metadata object module \endlink. + * + * Any time a metadata object is constructed or assigned, you + * should check is_valid() to make sure the underlying + * ::FLAC__StreamMetadata object was able to be created. + * + * \warning + * When the get_*() methods of any metadata object method + * return you a const pointer, DO NOT disobey and write into it. + * Always use the set_*() methods. + * + * \{ + */ + + /** Base class for all metadata block types. + * See the \link flacpp_metadata_object overview \endlink for more. + */ + class FLACPP_API Prototype { + protected: + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + Prototype(const Prototype &); + Prototype(const ::FLAC__StreamMetadata &); + Prototype(const ::FLAC__StreamMetadata *); + //@} + + /** Constructs an object with copy control. When \a copy + * is \c true, behaves identically to + * FLAC::Metadata::Prototype::Prototype(const ::FLAC__StreamMetadata *object). + * When \a copy is \c false, the instance takes ownership of + * the pointer and the ::FLAC__StreamMetadata object will + * be freed by the destructor. + * + * \assert + * \code object != NULL \endcode + */ + Prototype(::FLAC__StreamMetadata *object, bool copy); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + Prototype &operator=(const Prototype &); + Prototype &operator=(const ::FLAC__StreamMetadata &); + Prototype &operator=(const ::FLAC__StreamMetadata *); + //@} + + /** Assigns an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + Prototype &assign_object(::FLAC__StreamMetadata *object, bool copy); + + /** Deletes the underlying ::FLAC__StreamMetadata object. + */ + virtual void clear(); + + ::FLAC__StreamMetadata *object_; + public: + /** Deletes the underlying ::FLAC__StreamMetadata object. + */ + virtual ~Prototype(); + + //@{ + /** Check for equality, performing a deep compare by following pointers. + */ + inline bool operator==(const Prototype &) const; + inline bool operator==(const ::FLAC__StreamMetadata &) const; + inline bool operator==(const ::FLAC__StreamMetadata *) const; + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const Prototype &) const; + inline bool operator!=(const ::FLAC__StreamMetadata &) const; + inline bool operator!=(const ::FLAC__StreamMetadata *) const; + //@} + + friend class SimpleIterator; + friend class Iterator; + + /** Returns \c true if the object was correctly constructed + * (i.e. the underlying ::FLAC__StreamMetadata object was + * properly allocated), else \c false. + */ + inline bool is_valid() const; + + /** Returns \c true if this block is the last block in a + * stream, else \c false. + * + * \assert + * \code is_valid() \endcode + */ + bool get_is_last() const; + + /** Returns the type of the block. + * + * \assert + * \code is_valid() \endcode + */ + ::FLAC__MetadataType get_type() const; + + /** Returns the stream length of the metadata block. + * + * \note + * The length does not include the metadata block header, + * per spec. + * + * \assert + * \code is_valid() \endcode + */ + unsigned get_length() const; + + /** Sets the "is_last" flag for the block. When using the iterators + * it is not necessary to set this flag; they will do it for you. + * + * \assert + * \code is_valid() \endcode + */ + void set_is_last(bool); + + /** Returns a pointer to the underlying ::FLAC__StreamMetadata + * object. This can be useful for plugging any holes between + * the C++ and C interfaces. + * + * \assert + * \code is_valid() \endcode + */ + inline operator const ::FLAC__StreamMetadata *() const; + private: + /** Private and undefined so you can't use it. */ + Prototype(); + + // These are used only by Iterator + bool is_reference_; + inline void set_reference(bool x) { is_reference_ = x; } + }; + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + + inline bool Prototype::operator==(const Prototype &object) const + { return (bool)::FLAC__metadata_object_is_equal(object_, object.object_); } + + inline bool Prototype::operator==(const ::FLAC__StreamMetadata &object) const + { return (bool)::FLAC__metadata_object_is_equal(object_, &object); } + + inline bool Prototype::operator==(const ::FLAC__StreamMetadata *object) const + { return (bool)::FLAC__metadata_object_is_equal(object_, object); } + +#ifdef _MSC_VER +// @@@ how to re-enable? the following doesn't work +// #pragma warning ( enable : 4800 ) +#endif + + inline bool Prototype::operator!=(const Prototype &object) const + { return !operator==(object); } + + inline bool Prototype::operator!=(const ::FLAC__StreamMetadata &object) const + { return !operator==(object); } + + inline bool Prototype::operator!=(const ::FLAC__StreamMetadata *object) const + { return !operator==(object); } + + inline bool Prototype::is_valid() const + { return 0 != object_; } + + inline Prototype::operator const ::FLAC__StreamMetadata *() const + { return object_; } + + /** Create a deep copy of an object and return it. */ + FLACPP_API Prototype *clone(const Prototype *); + + + /** STREAMINFO metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API StreamInfo : public Prototype { + public: + StreamInfo(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline StreamInfo(const StreamInfo &object): Prototype(object) { } + inline StreamInfo(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline StreamInfo(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline StreamInfo(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~StreamInfo(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline StreamInfo &operator=(const StreamInfo &object) { Prototype::operator=(object); return *this; } + inline StreamInfo &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline StreamInfo &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline StreamInfo &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const StreamInfo &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const StreamInfo &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + //@{ + /** See format specification. */ + unsigned get_min_blocksize() const; + unsigned get_max_blocksize() const; + unsigned get_min_framesize() const; + unsigned get_max_framesize() const; + unsigned get_sample_rate() const; + unsigned get_channels() const; + unsigned get_bits_per_sample() const; + FLAC__uint64 get_total_samples() const; + const FLAC__byte *get_md5sum() const; + + void set_min_blocksize(unsigned value); + void set_max_blocksize(unsigned value); + void set_min_framesize(unsigned value); + void set_max_framesize(unsigned value); + void set_sample_rate(unsigned value); + void set_channels(unsigned value); + void set_bits_per_sample(unsigned value); + void set_total_samples(FLAC__uint64 value); + void set_md5sum(const FLAC__byte value[16]); + //@} + }; + + /** PADDING metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API Padding : public Prototype { + public: + Padding(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline Padding(const Padding &object): Prototype(object) { } + inline Padding(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline Padding(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline Padding(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~Padding(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline Padding &operator=(const Padding &object) { Prototype::operator=(object); return *this; } + inline Padding &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline Padding &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline Padding &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const Padding &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const Padding &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + void set_length(unsigned length); + }; + + /** APPLICATION metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API Application : public Prototype { + public: + Application(); + // + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline Application(const Application &object): Prototype(object) { } + inline Application(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline Application(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline Application(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~Application(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline Application &operator=(const Application &object) { Prototype::operator=(object); return *this; } + inline Application &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline Application &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline Application &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const Application &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const Application &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + const FLAC__byte *get_id() const; + const FLAC__byte *get_data() const; + + void set_id(const FLAC__byte value[4]); + //! This form always copies \a data + bool set_data(const FLAC__byte *data, unsigned length); + bool set_data(FLAC__byte *data, unsigned length, bool copy); + }; + + /** SEEKTABLE metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API SeekTable : public Prototype { + public: + SeekTable(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline SeekTable(const SeekTable &object): Prototype(object) { } + inline SeekTable(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline SeekTable(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline SeekTable(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~SeekTable(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline SeekTable &operator=(const SeekTable &object) { Prototype::operator=(object); return *this; } + inline SeekTable &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline SeekTable &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline SeekTable &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const SeekTable &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const SeekTable &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + unsigned get_num_points() const; + ::FLAC__StreamMetadata_SeekPoint get_point(unsigned index) const; + + //! See FLAC__metadata_object_seektable_set_point() + void set_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point); + + //! See FLAC__metadata_object_seektable_insert_point() + bool insert_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point); + + //! See FLAC__metadata_object_seektable_delete_point() + bool delete_point(unsigned index); + + //! See FLAC__metadata_object_seektable_is_legal() + bool is_legal() const; + }; + + /** VORBIS_COMMENT metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API VorbisComment : public Prototype { + public: + /** Convenience class for encapsulating Vorbis comment + * entries. An entry is a vendor string or a comment + * field. In the case of a vendor string, the field + * name is undefined; only the field value is relevant. + * + * A \a field as used in the methods refers to an + * entire 'NAME=VALUE' string; for convenience the + * string is NUL-terminated. A length field is + * required in the unlikely event that the value + * contains contain embedded NULs. + * + * A \a field_name is what is on the left side of the + * first '=' in the \a field. By definition it is ASCII + * and so is NUL-terminated and does not require a + * length to describe it. \a field_name is undefined + * for a vendor string entry. + * + * A \a field_value is what is on the right side of the + * first '=' in the \a field. By definition, this may + * contain embedded NULs and so a \a field_value_length + * is required to describe it. However in practice, + * embedded NULs are not known to be used, so it is + * generally safe to treat field values as NUL- + * terminated UTF-8 strings. + * + * Always check is_valid() after the constructor or operator= + * to make sure memory was properly allocated and that the + * Entry conforms to the Vorbis comment specification. + */ + class FLACPP_API Entry { + public: + Entry(); + + Entry(const char *field, unsigned field_length); + Entry(const char *field); // assumes \a field is NUL-terminated + + Entry(const char *field_name, const char *field_value, unsigned field_value_length); + Entry(const char *field_name, const char *field_value); // assumes \a field_value is NUL-terminated + + Entry(const Entry &entry); + + Entry &operator=(const Entry &entry); + + virtual ~Entry(); + + virtual bool is_valid() const; ///< Returns \c true iff object was properly constructed. + + unsigned get_field_length() const; + unsigned get_field_name_length() const; + unsigned get_field_value_length() const; + + ::FLAC__StreamMetadata_VorbisComment_Entry get_entry() const; + const char *get_field() const; + const char *get_field_name() const; + const char *get_field_value() const; + + bool set_field(const char *field, unsigned field_length); + bool set_field(const char *field); // assumes \a field is NUL-terminated + bool set_field_name(const char *field_name); + bool set_field_value(const char *field_value, unsigned field_value_length); + bool set_field_value(const char *field_value); // assumes \a field_value is NUL-terminated + protected: + bool is_valid_; + ::FLAC__StreamMetadata_VorbisComment_Entry entry_; + char *field_name_; + unsigned field_name_length_; + char *field_value_; + unsigned field_value_length_; + private: + void zero(); + void clear(); + void clear_entry(); + void clear_field_name(); + void clear_field_value(); + void construct(const char *field, unsigned field_length); + void construct(const char *field); // assumes \a field is NUL-terminated + void construct(const char *field_name, const char *field_value, unsigned field_value_length); + void construct(const char *field_name, const char *field_value); // assumes \a field_value is NUL-terminated + void compose_field(); + void parse_field(); + }; + + VorbisComment(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline VorbisComment(const VorbisComment &object): Prototype(object) { } + inline VorbisComment(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline VorbisComment(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline VorbisComment(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~VorbisComment(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline VorbisComment &operator=(const VorbisComment &object) { Prototype::operator=(object); return *this; } + inline VorbisComment &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline VorbisComment &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline VorbisComment &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const VorbisComment &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const VorbisComment &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + unsigned get_num_comments() const; + const FLAC__byte *get_vendor_string() const; // NUL-terminated UTF-8 string + Entry get_comment(unsigned index) const; + + //! See FLAC__metadata_object_vorbiscomment_set_vendor_string() + bool set_vendor_string(const FLAC__byte *string); // NUL-terminated UTF-8 string + + //! See FLAC__metadata_object_vorbiscomment_set_comment() + bool set_comment(unsigned index, const Entry &entry); + + //! See FLAC__metadata_object_vorbiscomment_insert_comment() + bool insert_comment(unsigned index, const Entry &entry); + + //! See FLAC__metadata_object_vorbiscomment_append_comment() + bool append_comment(const Entry &entry); + + //! See FLAC__metadata_object_vorbiscomment_delete_comment() + bool delete_comment(unsigned index); + }; + + /** CUESHEET metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API CueSheet : public Prototype { + public: + /** Convenience class for encapsulating a cue sheet + * track. + * + * Always check is_valid() after the constructor or operator= + * to make sure memory was properly allocated. + */ + class FLACPP_API Track { + protected: + ::FLAC__StreamMetadata_CueSheet_Track *object_; + public: + Track(); + Track(const ::FLAC__StreamMetadata_CueSheet_Track *track); + Track(const Track &track); + Track &operator=(const Track &track); + + virtual ~Track(); + + virtual bool is_valid() const; ///< Returns \c true iff object was properly constructed. + + + inline FLAC__uint64 get_offset() const { return object_->offset; } + inline FLAC__byte get_number() const { return object_->number; } + inline const char *get_isrc() const { return object_->isrc; } + inline unsigned get_type() const { return object_->type; } + inline bool get_pre_emphasis() const { return object_->pre_emphasis; } + + inline FLAC__byte get_num_indices() const { return object_->num_indices; } + ::FLAC__StreamMetadata_CueSheet_Index get_index(unsigned i) const; + + inline const ::FLAC__StreamMetadata_CueSheet_Track *get_track() const { return object_; } + + inline void set_offset(FLAC__uint64 value) { object_->offset = value; } + inline void set_number(FLAC__byte value) { object_->number = value; } + void set_isrc(const char value[12]); + void set_type(unsigned value); + inline void set_pre_emphasis(bool value) { object_->pre_emphasis = value? 1 : 0; } + + void set_index(unsigned i, const ::FLAC__StreamMetadata_CueSheet_Index &index); + //@@@ It's awkward but to insert/delete index points + //@@@ you must use the routines in the CueSheet class. + }; + + CueSheet(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline CueSheet(const CueSheet &object): Prototype(object) { } + inline CueSheet(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline CueSheet(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline CueSheet(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~CueSheet(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline CueSheet &operator=(const CueSheet &object) { Prototype::operator=(object); return *this; } + inline CueSheet &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline CueSheet &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline CueSheet &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const CueSheet &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const CueSheet &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + const char *get_media_catalog_number() const; + FLAC__uint64 get_lead_in() const; + bool get_is_cd() const; + + unsigned get_num_tracks() const; + Track get_track(unsigned i) const; + + void set_media_catalog_number(const char value[128]); + void set_lead_in(FLAC__uint64 value); + void set_is_cd(bool value); + + void set_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index); + + //! See FLAC__metadata_object_cuesheet_track_insert_index() + bool insert_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index); + + //! See FLAC__metadata_object_cuesheet_track_delete_index() + bool delete_index(unsigned track_num, unsigned index_num); + + //! See FLAC__metadata_object_cuesheet_set_track() + bool set_track(unsigned i, const Track &track); + + //! See FLAC__metadata_object_cuesheet_insert_track() + bool insert_track(unsigned i, const Track &track); + + //! See FLAC__metadata_object_cuesheet_delete_track() + bool delete_track(unsigned i); + + //! See FLAC__metadata_object_cuesheet_is_legal() + bool is_legal(bool check_cd_da_subset = false, const char **violation = 0) const; + + //! See FLAC__metadata_object_cuesheet_calculate_cddb_id() + FLAC__uint32 calculate_cddb_id() const; + }; + + /** PICTURE metadata block. + * See the \link flacpp_metadata_object overview \endlink for more, + * and the format specification. + */ + class FLACPP_API Picture : public Prototype { + public: + Picture(); + + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline Picture(const Picture &object): Prototype(object) { } + inline Picture(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline Picture(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline Picture(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~Picture(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline Picture &operator=(const Picture &object) { Prototype::operator=(object); return *this; } + inline Picture &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline Picture &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline Picture &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const Picture &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const Picture &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + ::FLAC__StreamMetadata_Picture_Type get_type() const; + const char *get_mime_type() const; // NUL-terminated printable ASCII string + const FLAC__byte *get_description() const; // NUL-terminated UTF-8 string + FLAC__uint32 get_width() const; + FLAC__uint32 get_height() const; + FLAC__uint32 get_depth() const; + FLAC__uint32 get_colors() const; ///< a return value of \c 0 means true-color, i.e. 2^depth colors + FLAC__uint32 get_data_length() const; + const FLAC__byte *get_data() const; + + void set_type(::FLAC__StreamMetadata_Picture_Type type); + + //! See FLAC__metadata_object_picture_set_mime_type() + bool set_mime_type(const char *string); // NUL-terminated printable ASCII string + + //! See FLAC__metadata_object_picture_set_description() + bool set_description(const FLAC__byte *string); // NUL-terminated UTF-8 string + + void set_width(FLAC__uint32 value) const; + void set_height(FLAC__uint32 value) const; + void set_depth(FLAC__uint32 value) const; + void set_colors(FLAC__uint32 value) const; ///< a value of \c 0 means true-color, i.e. 2^depth colors + + //! See FLAC__metadata_object_picture_set_data() + bool set_data(const FLAC__byte *data, FLAC__uint32 data_length); + }; + + /** Opaque metadata block for storing unknown types. + * This should not be used unless you know what you are doing; + * it is currently used only internally to support forward + * compatibility of metadata blocks. + * See the \link flacpp_metadata_object overview \endlink for more, + */ + class FLACPP_API Unknown : public Prototype { + public: + Unknown(); + // + //@{ + /** Constructs a copy of the given object. This form + * always performs a deep copy. + */ + inline Unknown(const Unknown &object): Prototype(object) { } + inline Unknown(const ::FLAC__StreamMetadata &object): Prototype(object) { } + inline Unknown(const ::FLAC__StreamMetadata *object): Prototype(object) { } + //@} + + /** Constructs an object with copy control. See + * Prototype(::FLAC__StreamMetadata *object, bool copy). + */ + inline Unknown(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { } + + ~Unknown(); + + //@{ + /** Assign from another object. Always performs a deep copy. */ + inline Unknown &operator=(const Unknown &object) { Prototype::operator=(object); return *this; } + inline Unknown &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; } + inline Unknown &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; } + //@} + + /** Assigns an object with copy control. See + * Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy). + */ + inline Unknown &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; } + + //@{ + /** Check for equality, performing a deep compare by following pointers. */ + inline bool operator==(const Unknown &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); } + inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); } + //@} + + //@{ + /** Check for inequality, performing a deep compare by following pointers. */ + inline bool operator!=(const Unknown &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); } + inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); } + //@} + + const FLAC__byte *get_data() const; + + //! This form always copies \a data + bool set_data(const FLAC__byte *data, unsigned length); + bool set_data(FLAC__byte *data, unsigned length, bool copy); + }; + + /* \} */ + + + /** \defgroup flacpp_metadata_level0 FLAC++/metadata.h: metadata level 0 interface + * \ingroup flacpp_metadata + * + * \brief + * Level 0 metadata iterators. + * + * See the \link flac_metadata_level0 C layer equivalent \endlink + * for more. + * + * \{ + */ + + FLACPP_API bool get_streaminfo(const char *filename, StreamInfo &streaminfo); ///< See FLAC__metadata_get_streaminfo(). + + FLACPP_API bool get_tags(const char *filename, VorbisComment *&tags); ///< See FLAC__metadata_get_tags(). + FLACPP_API bool get_tags(const char *filename, VorbisComment &tags); ///< See FLAC__metadata_get_tags(). + + FLACPP_API bool get_cuesheet(const char *filename, CueSheet *&cuesheet); ///< See FLAC__metadata_get_cuesheet(). + FLACPP_API bool get_cuesheet(const char *filename, CueSheet &cuesheet); ///< See FLAC__metadata_get_cuesheet(). + + FLACPP_API bool get_picture(const char *filename, Picture *&picture, ::FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors); ///< See FLAC__metadata_get_picture(). + FLACPP_API bool get_picture(const char *filename, Picture &picture, ::FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors); ///< See FLAC__metadata_get_picture(). + + /* \} */ + + + /** \defgroup flacpp_metadata_level1 FLAC++/metadata.h: metadata level 1 interface + * \ingroup flacpp_metadata + * + * \brief + * Level 1 metadata iterator. + * + * The flow through the iterator in the C++ layer is similar + * to the C layer: + * - Create a SimpleIterator instance + * - Check SimpleIterator::is_valid() + * - Call SimpleIterator::init() and check the return + * - Traverse and/or edit. Edits are written to file + * immediately. + * - Destroy the SimpleIterator instance + * + * The ownership of pointers in the C++ layer follows that in + * the C layer, i.e. + * - The objects returned by get_block() are yours to + * modify, but changes are not reflected in the FLAC file + * until you call set_block(). The objects are also + * yours to delete; they are not automatically deleted + * when passed to set_block() or insert_block_after(). + * + * See the \link flac_metadata_level1 C layer equivalent \endlink + * for more. + * + * \{ + */ + + /** This class is a wrapper around the FLAC__metadata_simple_iterator + * structures and methods; see the + * \link flacpp_metadata_level1 usage guide \endlink and + * ::FLAC__Metadata_SimpleIterator. + */ + class FLACPP_API SimpleIterator { + public: + /** This class is a wrapper around FLAC__Metadata_SimpleIteratorStatus. + */ + class FLACPP_API Status { + public: + inline Status(::FLAC__Metadata_SimpleIteratorStatus status): status_(status) { } + inline operator ::FLAC__Metadata_SimpleIteratorStatus() const { return status_; } + inline const char *as_cstring() const { return ::FLAC__Metadata_SimpleIteratorStatusString[status_]; } + protected: + ::FLAC__Metadata_SimpleIteratorStatus status_; + }; + + SimpleIterator(); + virtual ~SimpleIterator(); + + bool is_valid() const; ///< Returns \c true iff object was properly constructed. + + bool init(const char *filename, bool read_only, bool preserve_file_stats); ///< See FLAC__metadata_simple_iterator_init(). + + Status status(); ///< See FLAC__metadata_simple_iterator_status(). + bool is_writable() const; ///< See FLAC__metadata_simple_iterator_is_writable(). + + bool next(); ///< See FLAC__metadata_simple_iterator_next(). + bool prev(); ///< See FLAC__metadata_simple_iterator_prev(). + bool is_last() const; ///< See FLAC__metadata_simple_iterator_is_last(). + + off_t get_block_offset() const; ///< See FLAC__metadata_simple_iterator_get_block_offset(). + ::FLAC__MetadataType get_block_type() const; ///< See FLAC__metadata_simple_iterator_get_block_type(). + unsigned get_block_length() const; ///< See FLAC__metadata_simple_iterator_get_block_length(). + bool get_application_id(FLAC__byte *id); ///< See FLAC__metadata_simple_iterator_get_application_id(). + Prototype *get_block(); ///< See FLAC__metadata_simple_iterator_get_block(). + bool set_block(Prototype *block, bool use_padding = true); ///< See FLAC__metadata_simple_iterator_set_block(). + bool insert_block_after(Prototype *block, bool use_padding = true); ///< See FLAC__metadata_simple_iterator_insert_block_after(). + bool delete_block(bool use_padding = true); ///< See FLAC__metadata_simple_iterator_delete_block(). + + protected: + ::FLAC__Metadata_SimpleIterator *iterator_; + void clear(); + }; + + /* \} */ + + + /** \defgroup flacpp_metadata_level2 FLAC++/metadata.h: metadata level 2 interface + * \ingroup flacpp_metadata + * + * \brief + * Level 2 metadata iterator. + * + * The flow through the iterator in the C++ layer is similar + * to the C layer: + * - Create a Chain instance + * - Check Chain::is_valid() + * - Call Chain::read() and check the return + * - Traverse and/or edit with an Iterator or with + * Chain::merge_padding() or Chain::sort_padding() + * - Write changes back to FLAC file with Chain::write() + * - Destroy the Chain instance + * + * The ownership of pointers in the C++ layer is slightly + * different than in the C layer, i.e. + * - The objects returned by Iterator::get_block() are NOT + * owned by the iterator and should be deleted by the + * caller when finished, BUT, when you modify the block, + * it will directly edit what's in the chain and you do + * not need to call Iterator::set_block(). However the + * changes will not be reflected in the FLAC file until + * the chain is written with Chain::write(). + * - When you pass an object to Iterator::set_block(), + * Iterator::insert_block_before(), or + * Iterator::insert_block_after(), the iterator takes + * ownership of the block and it will be deleted by the + * chain. + * + * See the \link flac_metadata_level2 C layer equivalent \endlink + * for more. + * + * \{ + */ + + /** This class is a wrapper around the FLAC__metadata_chain + * structures and methods; see the + * \link flacpp_metadata_level2 usage guide \endlink and + * ::FLAC__Metadata_Chain. + */ + class FLACPP_API Chain { + public: + /** This class is a wrapper around FLAC__Metadata_ChainStatus. + */ + class FLACPP_API Status { + public: + inline Status(::FLAC__Metadata_ChainStatus status): status_(status) { } + inline operator ::FLAC__Metadata_ChainStatus() const { return status_; } + inline const char *as_cstring() const { return ::FLAC__Metadata_ChainStatusString[status_]; } + protected: + ::FLAC__Metadata_ChainStatus status_; + }; + + Chain(); + virtual ~Chain(); + + friend class Iterator; + + bool is_valid() const; ///< Returns \c true iff object was properly constructed. + + Status status(); ///< See FLAC__metadata_chain_status(). + + bool read(const char *filename, bool is_ogg = false); ///< See FLAC__metadata_chain_read(), FLAC__metadata_chain_read_ogg(). + bool read(FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, bool is_ogg = false); ///< See FLAC__metadata_chain_read_with_callbacks(), FLAC__metadata_chain_read_ogg_with_callbacks(). + + bool check_if_tempfile_needed(bool use_padding); ///< See FLAC__metadata_chain_check_if_tempfile_needed(). + + bool write(bool use_padding = true, bool preserve_file_stats = false); ///< See FLAC__metadata_chain_write(). + bool write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks); ///< See FLAC__metadata_chain_write_with_callbacks(). + bool write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, ::FLAC__IOHandle temp_handle, ::FLAC__IOCallbacks temp_callbacks); ///< See FLAC__metadata_chain_write_with_callbacks_and_tempfile(). + + void merge_padding(); ///< See FLAC__metadata_chain_merge_padding(). + void sort_padding(); ///< See FLAC__metadata_chain_sort_padding(). + + protected: + ::FLAC__Metadata_Chain *chain_; + virtual void clear(); + }; + + /** This class is a wrapper around the FLAC__metadata_iterator + * structures and methods; see the + * \link flacpp_metadata_level2 usage guide \endlink and + * ::FLAC__Metadata_Iterator. + */ + class FLACPP_API Iterator { + public: + Iterator(); + virtual ~Iterator(); + + bool is_valid() const; ///< Returns \c true iff object was properly constructed. + + + void init(Chain &chain); ///< See FLAC__metadata_iterator_init(). + + bool next(); ///< See FLAC__metadata_iterator_next(). + bool prev(); ///< See FLAC__metadata_iterator_prev(). + + ::FLAC__MetadataType get_block_type() const; ///< See FLAC__metadata_iterator_get_block_type(). + Prototype *get_block(); ///< See FLAC__metadata_iterator_get_block(). + bool set_block(Prototype *block); ///< See FLAC__metadata_iterator_set_block(). + bool delete_block(bool replace_with_padding); ///< See FLAC__metadata_iterator_delete_block(). + bool insert_block_before(Prototype *block); ///< See FLAC__metadata_iterator_insert_block_before(). + bool insert_block_after(Prototype *block); ///< See FLAC__metadata_iterator_insert_block_after(). + + protected: + ::FLAC__Metadata_Iterator *iterator_; + virtual void clear(); + }; + + /* \} */ + + } +} + +#endif diff --git a/flac/include/FLAC/Makefile.am b/flac/include/FLAC/Makefile.am new file mode 100644 index 0000000..c1710a2 --- /dev/null +++ b/flac/include/FLAC/Makefile.am @@ -0,0 +1,42 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +flaccincludedir = $(includedir)/FLAC + +flaccinclude_HEADERS = \ + all.h \ + assert.h \ + callback.h \ + export.h \ + format.h \ + metadata.h \ + ordinals.h \ + stream_decoder.h \ + stream_encoder.h diff --git a/flac/include/FLAC/all.h b/flac/include/FLAC/all.h new file mode 100644 index 0000000..c69cf84 --- /dev/null +++ b/flac/include/FLAC/all.h @@ -0,0 +1,370 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__ALL_H +#define FLAC__ALL_H + +#include "export.h" + +#include "assert.h" +#include "callback.h" +#include "format.h" +#include "metadata.h" +#include "ordinals.h" +#include "stream_decoder.h" +#include "stream_encoder.h" + +/** \mainpage + * + * \section intro Introduction + * + * This is the documentation for the FLAC C and C++ APIs. It is + * highly interconnected; this introduction should give you a top + * level idea of the structure and how to find the information you + * need. As a prerequisite you should have at least a basic + * knowledge of the FLAC format, documented + * here. + * + * \section c_api FLAC C API + * + * The FLAC C API is the interface to libFLAC, a set of structures + * describing the components of FLAC streams, and functions for + * encoding and decoding streams, as well as manipulating FLAC + * metadata in files. The public include files will be installed + * in your include area (for example /usr/include/FLAC/...). + * + * By writing a little code and linking against libFLAC, it is + * relatively easy to add FLAC support to another program. The + * library is licensed under Xiph's BSD license. + * Complete source code of libFLAC as well as the command-line + * encoder and plugins is available and is a useful source of + * examples. + * + * Aside from encoders and decoders, libFLAC provides a powerful + * metadata interface for manipulating metadata in FLAC files. It + * allows the user to add, delete, and modify FLAC metadata blocks + * and it can automatically take advantage of PADDING blocks to avoid + * rewriting the entire FLAC file when changing the size of the + * metadata. + * + * libFLAC usually only requires the standard C library and C math + * library. In particular, threading is not used so there is no + * dependency on a thread library. However, libFLAC does not use + * global variables and should be thread-safe. + * + * libFLAC also supports encoding to and decoding from Ogg FLAC. + * However the metadata editing interfaces currently have limited + * read-only support for Ogg FLAC files. + * + * \section cpp_api FLAC C++ API + * + * The FLAC C++ API is a set of classes that encapsulate the + * structures and functions in libFLAC. They provide slightly more + * functionality with respect to metadata but are otherwise + * equivalent. For the most part, they share the same usage as + * their counterparts in libFLAC, and the FLAC C API documentation + * can be used as a supplement. The public include files + * for the C++ API will be installed in your include area (for + * example /usr/include/FLAC++/...). + * + * libFLAC++ is also licensed under + * Xiph's BSD license. + * + * \section getting_started Getting Started + * + * A good starting point for learning the API is to browse through + * the modules. Modules are logical + * groupings of related functions or classes, which correspond roughly + * to header files or sections of header files. Each module includes a + * detailed description of the general usage of its functions or + * classes. + * + * From there you can go on to look at the documentation of + * individual functions. You can see different views of the individual + * functions through the links in top bar across this page. + * + * If you prefer a more hands-on approach, you can jump right to some + * example code. + * + * \section porting_guide Porting Guide + * + * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink + * has been introduced which gives detailed instructions on how to + * port your code to newer versions of FLAC. + * + * \section embedded_developers Embedded Developers + * + * libFLAC has grown larger over time as more functionality has been + * included, but much of it may be unnecessary for a particular embedded + * implementation. Unused parts may be pruned by some simple editing of + * src/libFLAC/Makefile.am. In general, the decoders, encoders, and + * metadata interface are all independent from each other. + * + * It is easiest to just describe the dependencies: + * + * - All modules depend on the \link flac_format Format \endlink module. + * - The decoders and encoders depend on the bitbuffer. + * - The decoder is independent of the encoder. The encoder uses the + * decoder because of the verify feature, but this can be removed if + * not needed. + * - Parts of the metadata interface require the stream decoder (but not + * the encoder). + * - Ogg support is selectable through the compile time macro + * \c FLAC__HAS_OGG. + * + * For example, if your application only requires the stream decoder, no + * encoder, and no metadata interface, you can remove the stream encoder + * and the metadata interface, which will greatly reduce the size of the + * library. + * + * Also, there are several places in the libFLAC code with comments marked + * with "OPT:" where a #define can be changed to enable code that might be + * faster on a specific platform. Experimenting with these can yield faster + * binaries. + */ + +/** \defgroup porting Porting Guide for New Versions + * + * This module describes differences in the library interfaces from + * version to version. It assists in the porting of code that uses + * the libraries to newer versions of FLAC. + * + * One simple facility for making porting easier that has been added + * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each + * library's includes (e.g. \c include/FLAC/export.h). The + * \c #defines mirror the libraries' + * libtool version numbers, + * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT, + * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE. + * These can be used to support multiple versions of an API during the + * transition phase, e.g. + * + * \code + * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7 + * legacy code + * #else + * new code + * #endif + * \endcode + * + * The the source will work for multiple versions and the legacy code can + * easily be removed when the transition is complete. + * + * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in + * include/FLAC/export.h), which can be used to determine whether or not + * the library has been compiled with support for Ogg FLAC. This is + * simpler than trying to call an Ogg init function and catching the + * error. + */ + +/** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3 + * \ingroup porting + * + * \brief + * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3. + * + * The main change between the APIs in 1.1.2 and 1.1.3 is that they have + * been simplified. First, libOggFLAC has been merged into libFLAC and + * libOggFLAC++ has been merged into libFLAC++. Second, both the three + * decoding layers and three encoding layers have been merged into a + * single stream decoder and stream encoder. That is, the functionality + * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged + * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and + * FLAC__FileEncoder into FLAC__StreamEncoder. Only the + * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means + * is there is now a single API that can be used to encode or decode + * streams to/from native FLAC or Ogg FLAC and the single API can work + * on both seekable and non-seekable streams. + * + * Instead of creating an encoder or decoder of a certain layer, now the + * client will always create a FLAC__StreamEncoder or + * FLAC__StreamDecoder. The old layers are now differentiated by the + * initialization function. For example, for the decoder, + * FLAC__stream_decoder_init() has been replaced by + * FLAC__stream_decoder_init_stream(). This init function takes + * callbacks for the I/O, and the seeking callbacks are optional. This + * allows the client to use the same object for seekable and + * non-seekable streams. For decoding a FLAC file directly, the client + * can use FLAC__stream_decoder_init_file() and pass just a filename + * and fewer callbacks; most of the other callbacks are supplied + * internally. For situations where fopen()ing by filename is not + * possible (e.g. Unicode filenames on Windows) the client can instead + * open the file itself and supply the FILE* to + * FLAC__stream_decoder_init_FILE(). The init functions now returns a + * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState. + * Since the callbacks and client data are now passed to the init + * function, the FLAC__stream_decoder_set_*_callback() functions and + * FLAC__stream_decoder_set_client_data() are no longer needed. The + * rest of the calls to the decoder are the same as before. + * + * There are counterpart init functions for Ogg FLAC, e.g. + * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls + * and callbacks are the same as for native FLAC. + * + * As an example, in FLAC 1.1.2 a seekable stream decoder would have + * been set up like so: + * + * \code + * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new(); + * if(decoder == NULL) do_something; + * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true); + * [... other settings ...] + * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback); + * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback); + * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback); + * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback); + * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback); + * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback); + * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback); + * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback); + * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data); + * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something; + * \endcode + * + * In FLAC 1.1.3 it is like this: + * + * \code + * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new(); + * if(decoder == NULL) do_something; + * FLAC__stream_decoder_set_md5_checking(decoder, true); + * [... other settings ...] + * if(FLAC__stream_decoder_init_stream( + * decoder, + * my_read_callback, + * my_seek_callback, // or NULL + * my_tell_callback, // or NULL + * my_length_callback, // or NULL + * my_eof_callback, // or NULL + * my_write_callback, + * my_metadata_callback, // or NULL + * my_error_callback, + * my_client_data + * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; + * \endcode + * + * or you could do; + * + * \code + * [...] + * FILE *file = fopen("somefile.flac","rb"); + * if(file == NULL) do_somthing; + * if(FLAC__stream_decoder_init_FILE( + * decoder, + * file, + * my_write_callback, + * my_metadata_callback, // or NULL + * my_error_callback, + * my_client_data + * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; + * \endcode + * + * or just: + * + * \code + * [...] + * if(FLAC__stream_decoder_init_file( + * decoder, + * "somefile.flac", + * my_write_callback, + * my_metadata_callback, // or NULL + * my_error_callback, + * my_client_data + * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; + * \endcode + * + * Another small change to the decoder is in how it handles unparseable + * streams. Before, when the decoder found an unparseable stream + * (reserved for when the decoder encounters a stream from a future + * encoder that it can't parse), it changed the state to + * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead + * drops sync and calls the error callback with a new error code + * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is + * more robust. If your error callback does not discriminate on the the + * error state, your code does not need to be changed. + * + * The encoder now has a new setting: + * FLAC__stream_encoder_set_apodization(). This is for setting the + * method used to window the data before LPC analysis. You only need to + * add a call to this function if the default is not suitable. There + * are also two new convenience functions that may be useful: + * FLAC__metadata_object_cuesheet_calculate_cddb_id() and + * FLAC__metadata_get_cuesheet(). + * + * The \a bytes parameter to FLAC__StreamDecoderReadCallback, + * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback + * is now \c size_t instead of \c unsigned. + */ + +/** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4 + * \ingroup porting + * + * \brief + * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4. + * + * There were no changes to any of the interfaces from 1.1.3 to 1.1.4. + * There was a slight change in the implementation of + * FLAC__stream_encoder_set_metadata(); the function now makes a copy + * of the \a metadata array of pointers so the client no longer needs + * to maintain it after the call. The objects themselves that are + * pointed to by the array are still not copied though and must be + * maintained until the call to FLAC__stream_encoder_finish(). + */ + +/** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0 + * \ingroup porting + * + * \brief + * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0. + * + * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0. + * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added. + * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added. + * + * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN + * has changed to reflect the conversion of one of the reserved bits + * into active use. It used to be \c 2 and now is \c 1. However the + * FLAC frame header length has not changed, so to skip the proper + * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN + + * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN + */ + +/** \defgroup flac FLAC C API + * + * The FLAC C API is the interface to libFLAC, a set of structures + * describing the components of FLAC streams, and functions for + * encoding and decoding streams, as well as manipulating FLAC + * metadata in files. + * + * You should start with the format components as all other modules + * are dependent on it. + */ + +#endif diff --git a/flac/include/FLAC/assert.h b/flac/include/FLAC/assert.h new file mode 100644 index 0000000..2991417 --- /dev/null +++ b/flac/include/FLAC/assert.h @@ -0,0 +1,45 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__ASSERT_H +#define FLAC__ASSERT_H + +/* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */ +#ifdef DEBUG +#include +#define FLAC__ASSERT(x) assert(x) +#define FLAC__ASSERT_DECLARATION(x) x +#else +#define FLAC__ASSERT(x) +#define FLAC__ASSERT_DECLARATION(x) +#endif + +#endif diff --git a/flac/include/FLAC/callback.h b/flac/include/FLAC/callback.h new file mode 100644 index 0000000..7960637 --- /dev/null +++ b/flac/include/FLAC/callback.h @@ -0,0 +1,184 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__CALLBACK_H +#define FLAC__CALLBACK_H + +#include "ordinals.h" +#include /* for size_t */ + +/** \file include/FLAC/callback.h + * + * \brief + * This module defines the structures for describing I/O callbacks + * to the other FLAC interfaces. + * + * See the detailed documentation for callbacks in the + * \link flac_callbacks callbacks \endlink module. + */ + +/** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures + * \ingroup flac + * + * \brief + * This module defines the structures for describing I/O callbacks + * to the other FLAC interfaces. + * + * The purpose of the I/O callback functions is to create a common way + * for the metadata interfaces to handle I/O. + * + * Originally the metadata interfaces required filenames as the way of + * specifying FLAC files to operate on. This is problematic in some + * environments so there is an additional option to specify a set of + * callbacks for doing I/O on the FLAC file, instead of the filename. + * + * In addition to the callbacks, a FLAC__IOHandle type is defined as an + * opaque structure for a data source. + * + * The callback function prototypes are similar (but not identical) to the + * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use + * stdio streams to implement the callbacks, you can pass fread, fwrite, and + * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or + * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle + * is required. \warning You generally CANNOT directly use fseek or ftell + * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems + * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with + * large files. You will have to find an equivalent function (e.g. ftello), + * or write a wrapper. The same is true for feof() since this is usually + * implemented as a macro, not as a function whose address can be taken. + * + * \{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the opaque handle type used by the callbacks. Typically + * this is a \c FILE* or address of a file descriptor. + */ +typedef void* FLAC__IOHandle; + +/** Signature for the read callback. + * The signature and semantics match POSIX fread() implementations + * and can generally be used interchangeably. + * + * \param ptr The address of the read buffer. + * \param size The size of the records to be read. + * \param nmemb The number of records to be read. + * \param handle The handle to the data source. + * \retval size_t + * The number of records read. + */ +typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle); + +/** Signature for the write callback. + * The signature and semantics match POSIX fwrite() implementations + * and can generally be used interchangeably. + * + * \param ptr The address of the write buffer. + * \param size The size of the records to be written. + * \param nmemb The number of records to be written. + * \param handle The handle to the data source. + * \retval size_t + * The number of records written. + */ +typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle); + +/** Signature for the seek callback. + * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT + * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long' + * and 32-bits wide. + * + * \param handle The handle to the data source. + * \param offset The new position, relative to \a whence + * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END + * \retval int + * \c 0 on success, \c -1 on error. + */ +typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence); + +/** Signature for the tell callback. + * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT + * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long' + * and 32-bits wide. + * + * \param handle The handle to the data source. + * \retval FLAC__int64 + * The current position on success, \c -1 on error. + */ +typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle); + +/** Signature for the EOF callback. + * The signature and semantics mostly match POSIX feof() but WATCHOUT: + * on many systems, feof() is a macro, so in this case a wrapper function + * must be provided instead. + * + * \param handle The handle to the data source. + * \retval int + * \c 0 if not at end of file, nonzero if at end of file. + */ +typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle); + +/** Signature for the close callback. + * The signature and semantics match POSIX fclose() implementations + * and can generally be used interchangeably. + * + * \param handle The handle to the data source. + * \retval int + * \c 0 on success, \c EOF on error. + */ +typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle); + +/** A structure for holding a set of callbacks. + * Each FLAC interface that requires a FLAC__IOCallbacks structure will + * describe which of the callbacks are required. The ones that are not + * required may be set to NULL. + * + * If the seek requirement for an interface is optional, you can signify that + * a data sorce is not seekable by setting the \a seek field to \c NULL. + */ +typedef struct { + FLAC__IOCallback_Read read; + FLAC__IOCallback_Write write; + FLAC__IOCallback_Seek seek; + FLAC__IOCallback_Tell tell; + FLAC__IOCallback_Eof eof; + FLAC__IOCallback_Close close; +} FLAC__IOCallbacks; + +/* \} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/FLAC/export.h b/flac/include/FLAC/export.h new file mode 100644 index 0000000..b7a4ce7 --- /dev/null +++ b/flac/include/FLAC/export.h @@ -0,0 +1,91 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__EXPORT_H +#define FLAC__EXPORT_H + +/** \file include/FLAC/export.h + * + * \brief + * This module contains #defines and symbols for exporting function + * calls, and providing version information and compiled-in features. + * + * See the \link flac_export export \endlink module. + */ + +/** \defgroup flac_export FLAC/export.h: export symbols + * \ingroup flac + * + * \brief + * This module contains #defines and symbols for exporting function + * calls, and providing version information and compiled-in features. + * + * If you are compiling with MSVC and will link to the static library + * (libFLAC.lib) you should define FLAC__NO_DLL in your project to + * make sure the symbols are exported properly. + * + * \{ + */ + +#if defined(FLAC__NO_DLL) || !defined(_MSC_VER) +#define FLAC_API + +#else + +#ifdef FLAC_API_EXPORTS +#define FLAC_API _declspec(dllexport) +#else +#define FLAC_API _declspec(dllimport) + +#endif +#endif + +/** These #defines will mirror the libtool-based library version number, see + * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning + */ +#define FLAC_API_VERSION_CURRENT 10 +#define FLAC_API_VERSION_REVISION 0 /**< see above */ +#define FLAC_API_VERSION_AGE 2 /**< see above */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */ +extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC; + +#ifdef __cplusplus +} +#endif + +/* \} */ + +#endif diff --git a/flac/include/FLAC/format.h b/flac/include/FLAC/format.h new file mode 100644 index 0000000..013972d --- /dev/null +++ b/flac/include/FLAC/format.h @@ -0,0 +1,1022 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__FORMAT_H +#define FLAC__FORMAT_H + +#include "export.h" +#include "ordinals.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file include/FLAC/format.h + * + * \brief + * This module contains structure definitions for the representation + * of FLAC format components in memory. These are the basic + * structures used by the rest of the interfaces. + * + * See the detailed documentation in the + * \link flac_format format \endlink module. + */ + +/** \defgroup flac_format FLAC/format.h: format components + * \ingroup flac + * + * \brief + * This module contains structure definitions for the representation + * of FLAC format components in memory. These are the basic + * structures used by the rest of the interfaces. + * + * First, you should be familiar with the + * FLAC format. Many of the values here + * follow directly from the specification. As a user of libFLAC, the + * interesting parts really are the structures that describe the frame + * header and metadata blocks. + * + * The format structures here are very primitive, designed to store + * information in an efficient way. Reading information from the + * structures is easy but creating or modifying them directly is + * more complex. For the most part, as a user of a library, editing + * is not necessary; however, for metadata blocks it is, so there are + * convenience functions provided in the \link flac_metadata metadata + * module \endlink to simplify the manipulation of metadata blocks. + * + * \note + * It's not the best convention, but symbols ending in _LEN are in bits + * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of + * global variables because they are usually used when declaring byte + * arrays and some compilers require compile-time knowledge of array + * sizes when declared on the stack. + * + * \{ + */ + + +/* + Most of the values described in this file are defined by the FLAC + format specification. There is nothing to tune here. +*/ + +/** The largest legal metadata type code. */ +#define FLAC__MAX_METADATA_TYPE_CODE (126u) + +/** The minimum block size, in samples, permitted by the format. */ +#define FLAC__MIN_BLOCK_SIZE (16u) + +/** The maximum block size, in samples, permitted by the format. */ +#define FLAC__MAX_BLOCK_SIZE (65535u) + +/** The maximum block size, in samples, permitted by the FLAC subset for + * sample rates up to 48kHz. */ +#define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u) + +/** The maximum number of channels permitted by the format. */ +#define FLAC__MAX_CHANNELS (8u) + +/** The minimum sample resolution permitted by the format. */ +#define FLAC__MIN_BITS_PER_SAMPLE (4u) + +/** The maximum sample resolution permitted by the format. */ +#define FLAC__MAX_BITS_PER_SAMPLE (32u) + +/** The maximum sample resolution permitted by libFLAC. + * + * \warning + * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However, + * the reference encoder/decoder is currently limited to 24 bits because + * of prevalent 32-bit math, so make sure and use this value when + * appropriate. + */ +#define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u) + +/** The maximum sample rate permitted by the format. The value is + * ((2 ^ 16) - 1) * 10; see FLAC format + * as to why. + */ +#define FLAC__MAX_SAMPLE_RATE (655350u) + +/** The maximum LPC order permitted by the format. */ +#define FLAC__MAX_LPC_ORDER (32u) + +/** The maximum LPC order permitted by the FLAC subset for sample rates + * up to 48kHz. */ +#define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u) + +/** The minimum quantized linear predictor coefficient precision + * permitted by the format. + */ +#define FLAC__MIN_QLP_COEFF_PRECISION (5u) + +/** The maximum quantized linear predictor coefficient precision + * permitted by the format. + */ +#define FLAC__MAX_QLP_COEFF_PRECISION (15u) + +/** The maximum order of the fixed predictors permitted by the format. */ +#define FLAC__MAX_FIXED_ORDER (4u) + +/** The maximum Rice partition order permitted by the format. */ +#define FLAC__MAX_RICE_PARTITION_ORDER (15u) + +/** The maximum Rice partition order permitted by the FLAC Subset. */ +#define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u) + +/** The version string of the release, stamped onto the libraries and binaries. + * + * \note + * This does not correspond to the shared library version number, which + * is used to determine binary compatibility. + */ +extern FLAC_API const char *FLAC__VERSION_STRING; + +/** The vendor string inserted by the encoder into the VORBIS_COMMENT block. + * This is a NUL-terminated ASCII string; when inserted into the + * VORBIS_COMMENT the trailing null is stripped. + */ +extern FLAC_API const char *FLAC__VENDOR_STRING; + +/** The byte string representation of the beginning of a FLAC stream. */ +extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */ + +/** The 32-bit integer big-endian representation of the beginning of + * a FLAC stream. + */ +extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */ + +/** The length of the FLAC signature in bits. */ +extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */ + +/** The length of the FLAC signature in bytes. */ +#define FLAC__STREAM_SYNC_LENGTH (4u) + + +/***************************************************************************** + * + * Subframe structures + * + *****************************************************************************/ + +/*****************************************************************************/ + +/** An enumeration of the available entropy coding methods. */ +typedef enum { + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0, + /**< Residual is coded by partitioning into contexts, each with it's own + * 4-bit Rice parameter. */ + + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1 + /**< Residual is coded by partitioning into contexts, each with it's own + * 5-bit Rice parameter. */ +} FLAC__EntropyCodingMethodType; + +/** Maps a FLAC__EntropyCodingMethodType to a C string. + * + * Using a FLAC__EntropyCodingMethodType as the index to this array will + * give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[]; + + +/** Contents of a Rice partitioned residual + */ +typedef struct { + + unsigned *parameters; + /**< The Rice parameters for each context. */ + + unsigned *raw_bits; + /**< Widths for escape-coded partitions. Will be non-zero for escaped + * partitions and zero for unescaped partitions. + */ + + unsigned capacity_by_order; + /**< The capacity of the \a parameters and \a raw_bits arrays + * specified as an order, i.e. the number of array elements + * allocated is 2 ^ \a capacity_by_order. + */ +} FLAC__EntropyCodingMethod_PartitionedRiceContents; + +/** Header for a Rice partitioned residual. (c.f. format specification) + */ +typedef struct { + + unsigned order; + /**< The partition order, i.e. # of contexts = 2 ^ \a order. */ + + const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents; + /**< The context's Rice parameters and/or raw bits. */ + +} FLAC__EntropyCodingMethod_PartitionedRice; + +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */ +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */ + +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; +/**< == (1<format specification) + */ +typedef struct { + FLAC__EntropyCodingMethodType type; + union { + FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice; + } data; +} FLAC__EntropyCodingMethod; + +extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */ + +/*****************************************************************************/ + +/** An enumeration of the available subframe types. */ +typedef enum { + FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */ + FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */ + FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */ + FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */ +} FLAC__SubframeType; + +/** Maps a FLAC__SubframeType to a C string. + * + * Using a FLAC__SubframeType as the index to this array will + * give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__SubframeTypeString[]; + + +/** CONSTANT subframe. (c.f. format specification) + */ +typedef struct { + FLAC__int32 value; /**< The constant signal value. */ +} FLAC__Subframe_Constant; + + +/** VERBATIM subframe. (c.f. format specification) + */ +typedef struct { + const FLAC__int32 *data; /**< A pointer to verbatim signal. */ +} FLAC__Subframe_Verbatim; + + +/** FIXED subframe. (c.f. format specification) + */ +typedef struct { + FLAC__EntropyCodingMethod entropy_coding_method; + /**< The residual coding method. */ + + unsigned order; + /**< The polynomial order. */ + + FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER]; + /**< Warmup samples to prime the predictor, length == order. */ + + const FLAC__int32 *residual; + /**< The residual signal, length == (blocksize minus order) samples. */ +} FLAC__Subframe_Fixed; + + +/** LPC subframe. (c.f. format specification) + */ +typedef struct { + FLAC__EntropyCodingMethod entropy_coding_method; + /**< The residual coding method. */ + + unsigned order; + /**< The FIR order. */ + + unsigned qlp_coeff_precision; + /**< Quantized FIR filter coefficient precision in bits. */ + + int quantization_level; + /**< The qlp coeff shift needed. */ + + FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; + /**< FIR filter coefficients. */ + + FLAC__int32 warmup[FLAC__MAX_LPC_ORDER]; + /**< Warmup samples to prime the predictor, length == order. */ + + const FLAC__int32 *residual; + /**< The residual signal, length == (blocksize minus order) samples. */ +} FLAC__Subframe_LPC; + +extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */ + + +/** FLAC subframe structure. (c.f. format specification) + */ +typedef struct { + FLAC__SubframeType type; + union { + FLAC__Subframe_Constant constant; + FLAC__Subframe_Fixed fixed; + FLAC__Subframe_LPC lpc; + FLAC__Subframe_Verbatim verbatim; + } data; + unsigned wasted_bits; +} FLAC__Subframe; + +/** == 1 (bit) + * + * This used to be a zero-padding bit (hence the name + * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a + * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1 + * to mean something else. + */ +extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN; +extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */ +extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */ + +extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */ +extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */ +extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */ +extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */ + +/*****************************************************************************/ + + +/***************************************************************************** + * + * Frame structures + * + *****************************************************************************/ + +/** An enumeration of the available channel assignments. */ +typedef enum { + FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */ + FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */ + FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */ + FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */ +} FLAC__ChannelAssignment; + +/** Maps a FLAC__ChannelAssignment to a C string. + * + * Using a FLAC__ChannelAssignment as the index to this array will + * give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__ChannelAssignmentString[]; + +/** An enumeration of the possible frame numbering methods. */ +typedef enum { + FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */ + FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */ +} FLAC__FrameNumberType; + +/** Maps a FLAC__FrameNumberType to a C string. + * + * Using a FLAC__FrameNumberType as the index to this array will + * give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__FrameNumberTypeString[]; + + +/** FLAC frame header structure. (c.f. format specification) + */ +typedef struct { + unsigned blocksize; + /**< The number of samples per subframe. */ + + unsigned sample_rate; + /**< The sample rate in Hz. */ + + unsigned channels; + /**< The number of channels (== number of subframes). */ + + FLAC__ChannelAssignment channel_assignment; + /**< The channel assignment for the frame. */ + + unsigned bits_per_sample; + /**< The sample resolution. */ + + FLAC__FrameNumberType number_type; + /**< The numbering scheme used for the frame. As a convenience, the + * decoder will always convert a frame number to a sample number because + * the rules are complex. */ + + union { + FLAC__uint32 frame_number; + FLAC__uint64 sample_number; + } number; + /**< The frame number or sample number of first sample in frame; + * use the \a number_type value to determine which to use. */ + + FLAC__uint8 crc; + /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0) + * of the raw frame header bytes, meaning everything before the CRC byte + * including the sync code. + */ +} FLAC__FrameHeader; + +extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */ +extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */ + + +/** FLAC frame footer structure. (c.f. format specification) + */ +typedef struct { + FLAC__uint16 crc; + /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with + * 0) of the bytes before the crc, back to and including the frame header + * sync code. + */ +} FLAC__FrameFooter; + +extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */ + + +/** FLAC frame structure. (c.f. format specification) + */ +typedef struct { + FLAC__FrameHeader header; + FLAC__Subframe subframes[FLAC__MAX_CHANNELS]; + FLAC__FrameFooter footer; +} FLAC__Frame; + +/*****************************************************************************/ + + +/***************************************************************************** + * + * Meta-data structures + * + *****************************************************************************/ + +/** An enumeration of the available metadata block types. */ +typedef enum { + + FLAC__METADATA_TYPE_STREAMINFO = 0, + /**< STREAMINFO block */ + + FLAC__METADATA_TYPE_PADDING = 1, + /**< PADDING block */ + + FLAC__METADATA_TYPE_APPLICATION = 2, + /**< APPLICATION block */ + + FLAC__METADATA_TYPE_SEEKTABLE = 3, + /**< SEEKTABLE block */ + + FLAC__METADATA_TYPE_VORBIS_COMMENT = 4, + /**< VORBISCOMMENT block (a.k.a. FLAC tags) */ + + FLAC__METADATA_TYPE_CUESHEET = 5, + /**< CUESHEET block */ + + FLAC__METADATA_TYPE_PICTURE = 6, + /**< PICTURE block */ + + FLAC__METADATA_TYPE_UNDEFINED = 7 + /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */ + +} FLAC__MetadataType; + +/** Maps a FLAC__MetadataType to a C string. + * + * Using a FLAC__MetadataType as the index to this array will + * give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__MetadataTypeString[]; + + +/** FLAC STREAMINFO structure. (c.f. format specification) + */ +typedef struct { + unsigned min_blocksize, max_blocksize; + unsigned min_framesize, max_framesize; + unsigned sample_rate; + unsigned channels; + unsigned bits_per_sample; + FLAC__uint64 total_samples; + FLAC__byte md5sum[16]; +} FLAC__StreamMetadata_StreamInfo; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */ + +/** The total stream length of the STREAMINFO block in bytes. */ +#define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u) + +/** FLAC PADDING structure. (c.f. format specification) + */ +typedef struct { + int dummy; + /**< Conceptually this is an empty struct since we don't store the + * padding bytes. Empty structs are not allowed by some C compilers, + * hence the dummy. + */ +} FLAC__StreamMetadata_Padding; + + +/** FLAC APPLICATION structure. (c.f. format specification) + */ +typedef struct { + FLAC__byte id[4]; + FLAC__byte *data; +} FLAC__StreamMetadata_Application; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */ + +/** SeekPoint structure used in SEEKTABLE blocks. (c.f. format specification) + */ +typedef struct { + FLAC__uint64 sample_number; + /**< The sample number of the target frame. */ + + FLAC__uint64 stream_offset; + /**< The offset, in bytes, of the target frame with respect to + * beginning of the first frame. */ + + unsigned frame_samples; + /**< The number of samples in the target frame. */ +} FLAC__StreamMetadata_SeekPoint; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */ + +/** The total stream length of a seek point in bytes. */ +#define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u) + +/** The value used in the \a sample_number field of + * FLAC__StreamMetadataSeekPoint used to indicate a placeholder + * point (== 0xffffffffffffffff). + */ +extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + + +/** FLAC SEEKTABLE structure. (c.f. format specification) + * + * \note From the format specification: + * - The seek points must be sorted by ascending sample number. + * - Each seek point's sample number must be the first sample of the + * target frame. + * - Each seek point's sample number must be unique within the table. + * - Existence of a SEEKTABLE block implies a correct setting of + * total_samples in the stream_info block. + * - Behavior is undefined when more than one SEEKTABLE block is + * present in a stream. + */ +typedef struct { + unsigned num_points; + FLAC__StreamMetadata_SeekPoint *points; +} FLAC__StreamMetadata_SeekTable; + + +/** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. format specification) + * + * For convenience, the APIs maintain a trailing NUL character at the end of + * \a entry which is not counted toward \a length, i.e. + * \code strlen(entry) == length \endcode + */ +typedef struct { + FLAC__uint32 length; + FLAC__byte *entry; +} FLAC__StreamMetadata_VorbisComment_Entry; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */ + + +/** FLAC VORBIS_COMMENT structure. (c.f. format specification) + */ +typedef struct { + FLAC__StreamMetadata_VorbisComment_Entry vendor_string; + FLAC__uint32 num_comments; + FLAC__StreamMetadata_VorbisComment_Entry *comments; +} FLAC__StreamMetadata_VorbisComment; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */ + + +/** FLAC CUESHEET track index structure. (See the + * format specification for + * the full description of each field.) + */ +typedef struct { + FLAC__uint64 offset; + /**< Offset in samples, relative to the track offset, of the index + * point. + */ + + FLAC__byte number; + /**< The index point number. */ +} FLAC__StreamMetadata_CueSheet_Index; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */ + + +/** FLAC CUESHEET track structure. (See the + * format specification for + * the full description of each field.) + */ +typedef struct { + FLAC__uint64 offset; + /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */ + + FLAC__byte number; + /**< The track number. */ + + char isrc[13]; + /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */ + + unsigned type:1; + /**< The track type: 0 for audio, 1 for non-audio. */ + + unsigned pre_emphasis:1; + /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */ + + FLAC__byte num_indices; + /**< The number of track index points. */ + + FLAC__StreamMetadata_CueSheet_Index *indices; + /**< NULL if num_indices == 0, else pointer to array of index points. */ + +} FLAC__StreamMetadata_CueSheet_Track; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */ + + +/** FLAC CUESHEET structure. (See the + * format specification + * for the full description of each field.) + */ +typedef struct { + char media_catalog_number[129]; + /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In + * general, the media catalog number may be 0 to 128 bytes long; any + * unused characters should be right-padded with NUL characters. + */ + + FLAC__uint64 lead_in; + /**< The number of lead-in samples. */ + + FLAC__bool is_cd; + /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */ + + unsigned num_tracks; + /**< The number of tracks. */ + + FLAC__StreamMetadata_CueSheet_Track *tracks; + /**< NULL if num_tracks == 0, else pointer to array of tracks. */ + +} FLAC__StreamMetadata_CueSheet; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */ + + +/** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */ +typedef enum { + FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */ + FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */ + FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */ + FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */ + FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */ + FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */ + FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */ + FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */ + FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */ + FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */ + FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */ + FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */ + FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */ + FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */ + FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */ + FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */ + FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */ + FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */ + FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */ + FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */ + FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */ + FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED +} FLAC__StreamMetadata_Picture_Type; + +/** Maps a FLAC__StreamMetadata_Picture_Type to a C string. + * + * Using a FLAC__StreamMetadata_Picture_Type as the index to this array + * will give the string equivalent. The contents should not be + * modified. + */ +extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[]; + +/** FLAC PICTURE structure. (See the + * format specification + * for the full description of each field.) + */ +typedef struct { + FLAC__StreamMetadata_Picture_Type type; + /**< The kind of picture stored. */ + + char *mime_type; + /**< Picture data's MIME type, in ASCII printable characters + * 0x20-0x7e, NUL terminated. For best compatibility with players, + * use picture data of MIME type \c image/jpeg or \c image/png. A + * MIME type of '-->' is also allowed, in which case the picture + * data should be a complete URL. In file storage, the MIME type is + * stored as a 32-bit length followed by the ASCII string with no NUL + * terminator, but is converted to a plain C string in this structure + * for convenience. + */ + + FLAC__byte *description; + /**< Picture's description in UTF-8, NUL terminated. In file storage, + * the description is stored as a 32-bit length followed by the UTF-8 + * string with no NUL terminator, but is converted to a plain C string + * in this structure for convenience. + */ + + FLAC__uint32 width; + /**< Picture's width in pixels. */ + + FLAC__uint32 height; + /**< Picture's height in pixels. */ + + FLAC__uint32 depth; + /**< Picture's color depth in bits-per-pixel. */ + + FLAC__uint32 colors; + /**< For indexed palettes (like GIF), picture's number of colors (the + * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth). + */ + + FLAC__uint32 data_length; + /**< Length of binary picture data in bytes. */ + + FLAC__byte *data; + /**< Binary picture data. */ + +} FLAC__StreamMetadata_Picture; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */ + + +/** Structure that is used when a metadata block of unknown type is loaded. + * The contents are opaque. The structure is used only internally to + * correctly handle unknown metadata. + */ +typedef struct { + FLAC__byte *data; +} FLAC__StreamMetadata_Unknown; + + +/** FLAC metadata block structure. (c.f. format specification) + */ +typedef struct { + FLAC__MetadataType type; + /**< The type of the metadata block; used determine which member of the + * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED + * then \a data.unknown must be used. */ + + FLAC__bool is_last; + /**< \c true if this metadata block is the last, else \a false */ + + unsigned length; + /**< Length, in bytes, of the block data as it appears in the stream. */ + + union { + FLAC__StreamMetadata_StreamInfo stream_info; + FLAC__StreamMetadata_Padding padding; + FLAC__StreamMetadata_Application application; + FLAC__StreamMetadata_SeekTable seek_table; + FLAC__StreamMetadata_VorbisComment vorbis_comment; + FLAC__StreamMetadata_CueSheet cue_sheet; + FLAC__StreamMetadata_Picture picture; + FLAC__StreamMetadata_Unknown unknown; + } data; + /**< Polymorphic block data; use the \a type value to determine which + * to use. */ +} FLAC__StreamMetadata; + +extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */ +extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */ + +/** The total stream length of a metadata block header in bytes. */ +#define FLAC__STREAM_METADATA_HEADER_LENGTH (4u) + +/*****************************************************************************/ + + +/***************************************************************************** + * + * Utility functions + * + *****************************************************************************/ + +/** Tests that a sample rate is valid for FLAC. + * + * \param sample_rate The sample rate to test for compliance. + * \retval FLAC__bool + * \c true if the given sample rate conforms to the specification, else + * \c false. + */ +FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate); + +/** Tests that a blocksize at the given sample rate is valid for the FLAC + * subset. + * + * \param blocksize The blocksize to test for compliance. + * \param sample_rate The sample rate is needed, since the valid subset + * blocksize depends on the sample rate. + * \retval FLAC__bool + * \c true if the given blocksize conforms to the specification for the + * subset at the given sample rate, else \c false. + */ +FLAC_API FLAC__bool FLAC__format_blocksize_is_subset(unsigned blocksize, unsigned sample_rate); + +/** Tests that a sample rate is valid for the FLAC subset. The subset rules + * for valid sample rates are slightly more complex since the rate has to + * be expressible completely in the frame header. + * + * \param sample_rate The sample rate to test for compliance. + * \retval FLAC__bool + * \c true if the given sample rate conforms to the specification for the + * subset, else \c false. + */ +FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate); + +/** Check a Vorbis comment entry name to see if it conforms to the Vorbis + * comment specification. + * + * Vorbis comment names must be composed only of characters from + * [0x20-0x3C,0x3E-0x7D]. + * + * \param name A NUL-terminated string to be checked. + * \assert + * \code name != NULL \endcode + * \retval FLAC__bool + * \c false if entry name is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name); + +/** Check a Vorbis comment entry value to see if it conforms to the Vorbis + * comment specification. + * + * Vorbis comment values must be valid UTF-8 sequences. + * + * \param value A string to be checked. + * \param length A the length of \a value in bytes. May be + * \c (unsigned)(-1) to indicate that \a value is a plain + * UTF-8 NUL-terminated string. + * \assert + * \code value != NULL \endcode + * \retval FLAC__bool + * \c false if entry name is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length); + +/** Check a Vorbis comment entry to see if it conforms to the Vorbis + * comment specification. + * + * Vorbis comment entries must be of the form 'name=value', and 'name' and + * 'value' must be legal according to + * FLAC__format_vorbiscomment_entry_name_is_legal() and + * FLAC__format_vorbiscomment_entry_value_is_legal() respectively. + * + * \param entry An entry to be checked. + * \param length The length of \a entry in bytes. + * \assert + * \code value != NULL \endcode + * \retval FLAC__bool + * \c false if entry name is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length); + +/** Check a seek table to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * seek table. + * + * \param seek_table A pointer to a seek table to be checked. + * \assert + * \code seek_table != NULL \endcode + * \retval FLAC__bool + * \c false if seek table is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table); + +/** Sort a seek table's seek points according to the format specification. + * This includes a "unique-ification" step to remove duplicates, i.e. + * seek points with identical \a sample_number values. Duplicate seek + * points are converted into placeholder points and sorted to the end of + * the table. + * + * \param seek_table A pointer to a seek table to be sorted. + * \assert + * \code seek_table != NULL \endcode + * \retval unsigned + * The number of duplicate seek points converted into placeholders. + */ +FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table); + +/** Check a cue sheet to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * cue sheet. + * + * \param cue_sheet A pointer to an existing cue sheet to be checked. + * \param check_cd_da_subset If \c true, check CUESHEET against more + * stringent requirements for a CD-DA (audio) disc. + * \param violation Address of a pointer to a string. If there is a + * violation, a pointer to a string explanation of the + * violation will be returned here. \a violation may be + * \c NULL if you don't need the returned string. Do not + * free the returned string; it will always point to static + * data. + * \assert + * \code cue_sheet != NULL \endcode + * \retval FLAC__bool + * \c false if cue sheet is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation); + +/** Check picture data to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * PICTURE block. + * + * \param picture A pointer to existing picture data to be checked. + * \param violation Address of a pointer to a string. If there is a + * violation, a pointer to a string explanation of the + * violation will be returned here. \a violation may be + * \c NULL if you don't need the returned string. Do not + * free the returned string; it will always point to static + * data. + * \assert + * \code picture != NULL \endcode + * \retval FLAC__bool + * \c false if picture data is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation); + +/* \} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/FLAC/metadata.h b/flac/include/FLAC/metadata.h new file mode 100644 index 0000000..c38a97d --- /dev/null +++ b/flac/include/FLAC/metadata.h @@ -0,0 +1,2181 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__METADATA_H +#define FLAC__METADATA_H + +#include /* for off_t */ +#include "export.h" +#include "callback.h" +#include "format.h" + +/* -------------------------------------------------------------------- + (For an example of how all these routines are used, see the source + code for the unit tests in src/test_libFLAC/metadata_*.c, or + metaflac in src/metaflac/) + ------------------------------------------------------------------*/ + +/** \file include/FLAC/metadata.h + * + * \brief + * This module provides functions for creating and manipulating FLAC + * metadata blocks in memory, and three progressively more powerful + * interfaces for traversing and editing metadata in FLAC files. + * + * See the detailed documentation for each interface in the + * \link flac_metadata metadata \endlink module. + */ + +/** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces + * \ingroup flac + * + * \brief + * This module provides functions for creating and manipulating FLAC + * metadata blocks in memory, and three progressively more powerful + * interfaces for traversing and editing metadata in native FLAC files. + * Note that currently only the Chain interface (level 2) supports Ogg + * FLAC files, and it is read-only i.e. no writing back changed + * metadata to file. + * + * There are three metadata interfaces of increasing complexity: + * + * Level 0: + * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and + * PICTURE blocks. + * + * Level 1: + * Read-write access to all metadata blocks. This level is write- + * efficient in most cases (more on this below), and uses less memory + * than level 2. + * + * Level 2: + * Read-write access to all metadata blocks. This level is write- + * efficient in all cases, but uses more memory since all metadata for + * the whole file is read into memory and manipulated before writing + * out again. + * + * What do we mean by efficient? Since FLAC metadata appears at the + * beginning of the file, when writing metadata back to a FLAC file + * it is possible to grow or shrink the metadata such that the entire + * file must be rewritten. However, if the size remains the same during + * changes or PADDING blocks are utilized, only the metadata needs to be + * overwritten, which is much faster. + * + * Efficient means the whole file is rewritten at most one time, and only + * when necessary. Level 1 is not efficient only in the case that you + * cause more than one metadata block to grow or shrink beyond what can + * be accomodated by padding. In this case you should probably use level + * 2, which allows you to edit all the metadata for a file in memory and + * write it out all at once. + * + * All levels know how to skip over and not disturb an ID3v2 tag at the + * front of the file. + * + * All levels access files via their filenames. In addition, level 2 + * has additional alternative read and write functions that take an I/O + * handle and callbacks, for situations where access by filename is not + * possible. + * + * In addition to the three interfaces, this module defines functions for + * creating and manipulating various metadata objects in memory. As we see + * from the Format module, FLAC metadata blocks in memory are very primitive + * structures for storing information in an efficient way. Reading + * information from the structures is easy but creating or modifying them + * directly is more complex. The metadata object routines here facilitate + * this by taking care of the consistency and memory management drudgery. + * + * Unless you will be using the level 1 or 2 interfaces to modify existing + * metadata however, you will not probably not need these. + * + * From a dependency standpoint, none of the encoders or decoders require + * the metadata module. This is so that embedded users can strip out the + * metadata module from libFLAC to reduce the size and complexity. + */ + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface + * \ingroup flac_metadata + * + * \brief + * The level 0 interface consists of individual routines to read the + * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring + * only a filename. + * + * They try to skip any ID3v2 tag at the head of the file. + * + * \{ + */ + +/** Read the STREAMINFO metadata block of the given FLAC file. This function + * will try to skip any ID3v2 tag at the head of the file. + * + * \param filename The path to the FLAC file to read. + * \param streaminfo A pointer to space for the STREAMINFO block. Since + * FLAC__StreamMetadata is a simple structure with no + * memory allocation involved, you pass the address of + * an existing structure. It need not be initialized. + * \assert + * \code filename != NULL \endcode + * \code streaminfo != NULL \endcode + * \retval FLAC__bool + * \c true if a valid STREAMINFO block was read from \a filename. Returns + * \c false if there was a memory allocation error, a file decoder error, + * or the file contained no STREAMINFO block. (A memory allocation error + * is possible because this function must set up a file decoder.) + */ +FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo); + +/** Read the VORBIS_COMMENT metadata block of the given FLAC file. This + * function will try to skip any ID3v2 tag at the head of the file. + * + * \param filename The path to the FLAC file to read. + * \param tags The address where the returned pointer will be + * stored. The \a tags object must be deleted by + * the caller using FLAC__metadata_object_delete(). + * \assert + * \code filename != NULL \endcode + * \code tags != NULL \endcode + * \retval FLAC__bool + * \c true if a valid VORBIS_COMMENT block was read from \a filename, + * and \a *tags will be set to the address of the metadata structure. + * Returns \c false if there was a memory allocation error, a file + * decoder error, or the file contained no VORBIS_COMMENT block, and + * \a *tags will be set to \c NULL. + */ +FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags); + +/** Read the CUESHEET metadata block of the given FLAC file. This + * function will try to skip any ID3v2 tag at the head of the file. + * + * \param filename The path to the FLAC file to read. + * \param cuesheet The address where the returned pointer will be + * stored. The \a cuesheet object must be deleted by + * the caller using FLAC__metadata_object_delete(). + * \assert + * \code filename != NULL \endcode + * \code cuesheet != NULL \endcode + * \retval FLAC__bool + * \c true if a valid CUESHEET block was read from \a filename, + * and \a *cuesheet will be set to the address of the metadata + * structure. Returns \c false if there was a memory allocation + * error, a file decoder error, or the file contained no CUESHEET + * block, and \a *cuesheet will be set to \c NULL. + */ +FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet); + +/** Read a PICTURE metadata block of the given FLAC file. This + * function will try to skip any ID3v2 tag at the head of the file. + * Since there can be more than one PICTURE block in a file, this + * function takes a number of parameters that act as constraints to + * the search. The PICTURE block with the largest area matching all + * the constraints will be returned, or \a *picture will be set to + * \c NULL if there was no such block. + * + * \param filename The path to the FLAC file to read. + * \param picture The address where the returned pointer will be + * stored. The \a picture object must be deleted by + * the caller using FLAC__metadata_object_delete(). + * \param type The desired picture type. Use \c -1 to mean + * "any type". + * \param mime_type The desired MIME type, e.g. "image/jpeg". The + * string will be matched exactly. Use \c NULL to + * mean "any MIME type". + * \param description The desired description. The string will be + * matched exactly. Use \c NULL to mean "any + * description". + * \param max_width The maximum width in pixels desired. Use + * \c (unsigned)(-1) to mean "any width". + * \param max_height The maximum height in pixels desired. Use + * \c (unsigned)(-1) to mean "any height". + * \param max_depth The maximum color depth in bits-per-pixel desired. + * Use \c (unsigned)(-1) to mean "any depth". + * \param max_colors The maximum number of colors desired. Use + * \c (unsigned)(-1) to mean "any number of colors". + * \assert + * \code filename != NULL \endcode + * \code picture != NULL \endcode + * \retval FLAC__bool + * \c true if a valid PICTURE block was read from \a filename, + * and \a *picture will be set to the address of the metadata + * structure. Returns \c false if there was a memory allocation + * error, a file decoder error, or the file contained no PICTURE + * block, and \a *picture will be set to \c NULL. + */ +FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors); + +/* \} */ + + +/** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface + * \ingroup flac_metadata + * + * \brief + * The level 1 interface provides read-write access to FLAC file metadata and + * operates directly on the FLAC file. + * + * The general usage of this interface is: + * + * - Create an iterator using FLAC__metadata_simple_iterator_new() + * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check + * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to + * see if the file is writable, or only read access is allowed. + * - Use FLAC__metadata_simple_iterator_next() and + * FLAC__metadata_simple_iterator_prev() to traverse the blocks. + * This is does not read the actual blocks themselves. + * FLAC__metadata_simple_iterator_next() is relatively fast. + * FLAC__metadata_simple_iterator_prev() is slower since it needs to search + * forward from the front of the file. + * - Use FLAC__metadata_simple_iterator_get_block_type() or + * FLAC__metadata_simple_iterator_get_block() to access the actual data at + * the current iterator position. The returned object is yours to modify + * and free. + * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block + * back. You must have write permission to the original file. Make sure to + * read the whole comment to FLAC__metadata_simple_iterator_set_block() + * below. + * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks. + * Use the object creation functions from + * \link flac_metadata_object here \endlink to generate new objects. + * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block + * currently referred to by the iterator, or replace it with padding. + * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when + * finished. + * + * \note + * The FLAC file remains open the whole time between + * FLAC__metadata_simple_iterator_init() and + * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering + * the file during this time. + * + * \note + * Do not modify the \a is_last, \a length, or \a type fields of returned + * FLAC__StreamMetadata objects. These are managed automatically. + * + * \note + * If any of the modification functions + * (FLAC__metadata_simple_iterator_set_block(), + * FLAC__metadata_simple_iterator_delete_block(), + * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false, + * you should delete the iterator as it may no longer be valid. + * + * \{ + */ + +struct FLAC__Metadata_SimpleIterator; +/** The opaque structure definition for the level 1 iterator type. + * See the + * \link flac_metadata_level1 metadata level 1 module \endlink + * for a detailed description. + */ +typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator; + +/** Status type for FLAC__Metadata_SimpleIterator. + * + * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status(). + */ +typedef enum { + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0, + /**< The iterator is in the normal OK state */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, + /**< The data passed into a function violated the function's usage criteria */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE, + /**< The iterator could not open the target file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE, + /**< The iterator could not find the FLAC signature at the start of the file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE, + /**< The iterator tried to write to a file that was not writable */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA, + /**< The iterator encountered input that does not conform to the FLAC metadata specification */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR, + /**< The iterator encountered an error while reading the FLAC file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, + /**< The iterator encountered an error while seeking in the FLAC file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR, + /**< The iterator encountered an error while writing the FLAC file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR, + /**< The iterator encountered an error renaming the FLAC file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR, + /**< The iterator encountered an error removing the temporary file */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR, + /**< Memory allocation failed */ + + FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR + /**< The caller violated an assertion or an unexpected error occurred */ + +} FLAC__Metadata_SimpleIteratorStatus; + +/** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string. + * + * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[]; + + +/** Create a new iterator instance. + * + * \retval FLAC__Metadata_SimpleIterator* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void); + +/** Free an iterator instance. Deletes the object pointed to by \a iterator. + * + * \param iterator A pointer to an existing iterator. + * \assert + * \code iterator != NULL \endcode + */ +FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator); + +/** Get the current status of the iterator. Call this after a function + * returns \c false to get the reason for the error. Also resets the status + * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK. + * + * \param iterator A pointer to an existing iterator. + * \assert + * \code iterator != NULL \endcode + * \retval FLAC__Metadata_SimpleIteratorStatus + * The current status of the iterator. + */ +FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator); + +/** Initialize the iterator to point to the first metadata block in the + * given FLAC file. + * + * \param iterator A pointer to an existing iterator. + * \param filename The path to the FLAC file. + * \param read_only If \c true, the FLAC file will be opened + * in read-only mode; if \c false, the FLAC + * file will be opened for edit even if no + * edits are performed. + * \param preserve_file_stats If \c true, the owner and modification + * time will be preserved even if the FLAC + * file is written to. + * \assert + * \code iterator != NULL \endcode + * \code filename != NULL \endcode + * \retval FLAC__bool + * \c false if a memory allocation error occurs, the file can't be + * opened, or another error occurs, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats); + +/** Returns \c true if the FLAC file is writable. If \c false, calls to + * FLAC__metadata_simple_iterator_set_block() and + * FLAC__metadata_simple_iterator_insert_block_after() will fail. + * + * \param iterator A pointer to an existing iterator. + * \assert + * \code iterator != NULL \endcode + * \retval FLAC__bool + * See above. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator); + +/** Moves the iterator forward one metadata block, returning \c false if + * already at the end. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__bool + * \c false if already at the last metadata block of the chain, else + * \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator); + +/** Moves the iterator backward one metadata block, returning \c false if + * already at the beginning. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__bool + * \c false if already at the first metadata block of the chain, else + * \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator); + +/** Returns a flag telling if the current metadata block is the last. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__bool + * \c true if the current metadata block is the last in the file, + * else \c false. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator); + +/** Get the offset of the metadata block at the current position. This + * avoids reading the actual block data which can save time for large + * blocks. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval off_t + * The offset of the metadata block at the current iterator position. + * This is the byte offset relative to the beginning of the file of + * the current metadata block's header. + */ +FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator); + +/** Get the type of the metadata block at the current position. This + * avoids reading the actual block data which can save time for large + * blocks. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__MetadataType + * The type of the metadata block at the current iterator position. + */ +FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator); + +/** Get the length of the metadata block at the current position. This + * avoids reading the actual block data which can save time for large + * blocks. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval unsigned + * The length of the metadata block at the current iterator position. + * The is same length as that in the + * metadata block header, + * i.e. the length of the metadata body that follows the header. + */ +FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator); + +/** Get the application ID of the \c APPLICATION block at the current + * position. This avoids reading the actual block data which can save + * time for large blocks. + * + * \param iterator A pointer to an existing initialized iterator. + * \param id A pointer to a buffer of at least \c 4 bytes where + * the ID will be stored. + * \assert + * \code iterator != NULL \endcode + * \code id != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__bool + * \c true if the ID was successfully read, else \c false, in which + * case you should check FLAC__metadata_simple_iterator_status() to + * find out why. If the status is + * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the + * current metadata block is not an \c APPLICATION block. Otherwise + * if the status is + * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or + * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error + * occurred and the iterator can no longer be used. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id); + +/** Get the metadata block at the current position. You can modify the + * block but must use FLAC__metadata_simple_iterator_set_block() to + * write it back to the FLAC file. + * + * You must call FLAC__metadata_object_delete() on the returned object + * when you are finished with it. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__StreamMetadata* + * The current metadata block, or \c NULL if there was a memory + * allocation error. + */ +FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator); + +/** Write a block back to the FLAC file. This function tries to be + * as efficient as possible; how the block is actually written is + * shown by the following: + * + * Existing block is a STREAMINFO block and the new block is a + * STREAMINFO block: the new block is written in place. Make sure + * you know what you're doing when changing the values of a + * STREAMINFO block. + * + * Existing block is a STREAMINFO block and the new block is a + * not a STREAMINFO block: this is an error since the first block + * must be a STREAMINFO block. Returns \c false without altering the + * file. + * + * Existing block is not a STREAMINFO block and the new block is a + * STREAMINFO block: this is an error since there may be only one + * STREAMINFO block. Returns \c false without altering the file. + * + * Existing block and new block are the same length: the existing + * block will be replaced by the new block, written in place. + * + * Existing block is longer than new block: if use_padding is \c true, + * the existing block will be overwritten in place with the new + * block followed by a PADDING block, if possible, to make the total + * size the same as the existing block. Remember that a padding + * block requires at least four bytes so if the difference in size + * between the new block and existing block is less than that, the + * entire file will have to be rewritten, using the new block's + * exact size. If use_padding is \c false, the entire file will be + * rewritten, replacing the existing block by the new block. + * + * Existing block is shorter than new block: if use_padding is \c true, + * the function will try and expand the new block into the following + * PADDING block, if it exists and doing so won't shrink the PADDING + * block to less than 4 bytes. If there is no following PADDING + * block, or it will shrink to less than 4 bytes, or use_padding is + * \c false, the entire file is rewritten, replacing the existing block + * with the new block. Note that in this case any following PADDING + * block is preserved as is. + * + * After writing the block, the iterator will remain in the same + * place, i.e. pointing to the new block. + * + * \param iterator A pointer to an existing initialized iterator. + * \param block The block to set. + * \param use_padding See above. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \code block != NULL \endcode + * \retval FLAC__bool + * \c true if successful, else \c false. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding); + +/** This is similar to FLAC__metadata_simple_iterator_set_block() + * except that instead of writing over an existing block, it appends + * a block after the existing block. \a use_padding is again used to + * tell the function to try an expand into following padding in an + * attempt to avoid rewriting the entire file. + * + * This function will fail and return \c false if given a STREAMINFO + * block. + * + * After writing the block, the iterator will be pointing to the + * new block. + * + * \param iterator A pointer to an existing initialized iterator. + * \param block The block to set. + * \param use_padding See above. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \code block != NULL \endcode + * \retval FLAC__bool + * \c true if successful, else \c false. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding); + +/** Deletes the block at the current position. This will cause the + * entire FLAC file to be rewritten, unless \a use_padding is \c true, + * in which case the block will be replaced by an equal-sized PADDING + * block. The iterator will be left pointing to the block before the + * one just deleted. + * + * You may not delete the STREAMINFO block. + * + * \param iterator A pointer to an existing initialized iterator. + * \param use_padding See above. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_simple_iterator_init() + * \retval FLAC__bool + * \c true if successful, else \c false. + */ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding); + +/* \} */ + + +/** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface + * \ingroup flac_metadata + * + * \brief + * The level 2 interface provides read-write access to FLAC file metadata; + * all metadata is read into memory, operated on in memory, and then written + * to file, which is more efficient than level 1 when editing multiple blocks. + * + * Currently Ogg FLAC is supported for read only, via + * FLAC__metadata_chain_read_ogg() but a subsequent + * FLAC__metadata_chain_write() will fail. + * + * The general usage of this interface is: + * + * - Create a new chain using FLAC__metadata_chain_new(). A chain is a + * linked list of FLAC metadata blocks. + * - Read all metadata into the the chain from a FLAC file using + * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and + * check the status. + * - Optionally, consolidate the padding using + * FLAC__metadata_chain_merge_padding() or + * FLAC__metadata_chain_sort_padding(). + * - Create a new iterator using FLAC__metadata_iterator_new() + * - Initialize the iterator to point to the first element in the chain + * using FLAC__metadata_iterator_init() + * - Traverse the chain using FLAC__metadata_iterator_next and + * FLAC__metadata_iterator_prev(). + * - Get a block for reading or modification using + * FLAC__metadata_iterator_get_block(). The pointer to the object + * inside the chain is returned, so the block is yours to modify. + * Changes will be reflected in the FLAC file when you write the + * chain. You can also add and delete blocks (see functions below). + * - When done, write out the chain using FLAC__metadata_chain_write(). + * Make sure to read the whole comment to the function below. + * - Delete the chain using FLAC__metadata_chain_delete(). + * + * \note + * Even though the FLAC file is not open while the chain is being + * manipulated, you must not alter the file externally during + * this time. The chain assumes the FLAC file will not change + * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg() + * and FLAC__metadata_chain_write(). + * + * \note + * Do not modify the is_last, length, or type fields of returned + * FLAC__StreamMetadata objects. These are managed automatically. + * + * \note + * The metadata objects returned by FLAC__metadata_iterator_get_block() + * are owned by the chain; do not FLAC__metadata_object_delete() them. + * In the same way, blocks passed to FLAC__metadata_iterator_set_block() + * become owned by the chain and they will be deleted when the chain is + * deleted. + * + * \{ + */ + +struct FLAC__Metadata_Chain; +/** The opaque structure definition for the level 2 chain type. + */ +typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain; + +struct FLAC__Metadata_Iterator; +/** The opaque structure definition for the level 2 iterator type. + */ +typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator; + +typedef enum { + FLAC__METADATA_CHAIN_STATUS_OK = 0, + /**< The chain is in the normal OK state */ + + FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT, + /**< The data passed into a function violated the function's usage criteria */ + + FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE, + /**< The chain could not open the target file */ + + FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE, + /**< The chain could not find the FLAC signature at the start of the file */ + + FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE, + /**< The chain tried to write to a file that was not writable */ + + FLAC__METADATA_CHAIN_STATUS_BAD_METADATA, + /**< The chain encountered input that does not conform to the FLAC metadata specification */ + + FLAC__METADATA_CHAIN_STATUS_READ_ERROR, + /**< The chain encountered an error while reading the FLAC file */ + + FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR, + /**< The chain encountered an error while seeking in the FLAC file */ + + FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR, + /**< The chain encountered an error while writing the FLAC file */ + + FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR, + /**< The chain encountered an error renaming the FLAC file */ + + FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR, + /**< The chain encountered an error removing the temporary file */ + + FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR, + /**< Memory allocation failed */ + + FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR, + /**< The caller violated an assertion or an unexpected error occurred */ + + FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS, + /**< One or more of the required callbacks was NULL */ + + FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH, + /**< FLAC__metadata_chain_write() was called on a chain read by + * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), + * or + * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile() + * was called on a chain read by + * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). + * Matching read/write methods must always be used. */ + + FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL + /**< FLAC__metadata_chain_write_with_callbacks() was called when the + * chain write requires a tempfile; use + * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead. + * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was + * called when the chain write does not require a tempfile; use + * FLAC__metadata_chain_write_with_callbacks() instead. + * Always check FLAC__metadata_chain_check_if_tempfile_needed() + * before writing via callbacks. */ + +} FLAC__Metadata_ChainStatus; + +/** Maps a FLAC__Metadata_ChainStatus to a C string. + * + * Using a FLAC__Metadata_ChainStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[]; + +/*********** FLAC__Metadata_Chain ***********/ + +/** Create a new chain instance. + * + * \retval FLAC__Metadata_Chain* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void); + +/** Free a chain instance. Deletes the object pointed to by \a chain. + * + * \param chain A pointer to an existing chain. + * \assert + * \code chain != NULL \endcode + */ +FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain); + +/** Get the current status of the chain. Call this after a function + * returns \c false to get the reason for the error. Also resets the + * status to FLAC__METADATA_CHAIN_STATUS_OK. + * + * \param chain A pointer to an existing chain. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__Metadata_ChainStatus + * The current status of the chain. + */ +FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain); + +/** Read all metadata from a FLAC file into the chain. + * + * \param chain A pointer to an existing chain. + * \param filename The path to the FLAC file to read. + * \assert + * \code chain != NULL \endcode + * \code filename != NULL \endcode + * \retval FLAC__bool + * \c true if a valid list of metadata blocks was read from + * \a filename, else \c false. On failure, check the status with + * FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename); + +/** Read all metadata from an Ogg FLAC file into the chain. + * + * \note Ogg FLAC metadata data writing is not supported yet and + * FLAC__metadata_chain_write() will fail. + * + * \param chain A pointer to an existing chain. + * \param filename The path to the Ogg FLAC file to read. + * \assert + * \code chain != NULL \endcode + * \code filename != NULL \endcode + * \retval FLAC__bool + * \c true if a valid list of metadata blocks was read from + * \a filename, else \c false. On failure, check the status with + * FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename); + +/** Read all metadata from a FLAC stream into the chain via I/O callbacks. + * + * The \a handle need only be open for reading, but must be seekable. + * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" + * for Windows). + * + * \param chain A pointer to an existing chain. + * \param handle The I/O handle of the FLAC stream to read. The + * handle will NOT be closed after the metadata is read; + * that is the duty of the caller. + * \param callbacks + * A set of callbacks to use for I/O. The mandatory + * callbacks are \a read, \a seek, and \a tell. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if a valid list of metadata blocks was read from + * \a handle, else \c false. On failure, check the status with + * FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); + +/** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks. + * + * The \a handle need only be open for reading, but must be seekable. + * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" + * for Windows). + * + * \note Ogg FLAC metadata data writing is not supported yet and + * FLAC__metadata_chain_write() will fail. + * + * \param chain A pointer to an existing chain. + * \param handle The I/O handle of the Ogg FLAC stream to read. The + * handle will NOT be closed after the metadata is read; + * that is the duty of the caller. + * \param callbacks + * A set of callbacks to use for I/O. The mandatory + * callbacks are \a read, \a seek, and \a tell. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if a valid list of metadata blocks was read from + * \a handle, else \c false. On failure, check the status with + * FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); + +/** Checks if writing the given chain would require the use of a + * temporary file, or if it could be written in place. + * + * Under certain conditions, padding can be utilized so that writing + * edited metadata back to the FLAC file does not require rewriting the + * entire file. If rewriting is required, then a temporary workfile is + * required. When writing metadata using callbacks, you must check + * this function to know whether to call + * FLAC__metadata_chain_write_with_callbacks() or + * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When + * writing with FLAC__metadata_chain_write(), the temporary file is + * handled internally. + * + * \param chain A pointer to an existing chain. + * \param use_padding + * Whether or not padding will be allowed to be used + * during the write. The value of \a use_padding given + * here must match the value later passed to + * FLAC__metadata_chain_write_with_callbacks() or + * FLAC__metadata_chain_write_with_callbacks_with_tempfile(). + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if writing the current chain would require a tempfile, or + * \c false if metadata can be written in place. + */ +FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding); + +/** Write all metadata out to the FLAC file. This function tries to be as + * efficient as possible; how the metadata is actually written is shown by + * the following: + * + * If the current chain is the same size as the existing metadata, the new + * data is written in place. + * + * If the current chain is longer than the existing metadata, and + * \a use_padding is \c true, and the last block is a PADDING block of + * sufficient length, the function will truncate the final padding block + * so that the overall size of the metadata is the same as the existing + * metadata, and then just rewrite the metadata. Otherwise, if not all of + * the above conditions are met, the entire FLAC file must be rewritten. + * If you want to use padding this way it is a good idea to call + * FLAC__metadata_chain_sort_padding() first so that you have the maximum + * amount of padding to work with, unless you need to preserve ordering + * of the PADDING blocks for some reason. + * + * If the current chain is shorter than the existing metadata, and + * \a use_padding is \c true, and the final block is a PADDING block, the padding + * is extended to make the overall size the same as the existing data. If + * \a use_padding is \c true and the last block is not a PADDING block, a new + * PADDING block is added to the end of the new data to make it the same + * size as the existing data (if possible, see the note to + * FLAC__metadata_simple_iterator_set_block() about the four byte limit) + * and the new data is written in place. If none of the above apply or + * \a use_padding is \c false, the entire FLAC file is rewritten. + * + * If \a preserve_file_stats is \c true, the owner and modification time will + * be preserved even if the FLAC file is written. + * + * For this write function to be used, the chain must have been read with + * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not + * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(). + * + * \param chain A pointer to an existing chain. + * \param use_padding See above. + * \param preserve_file_stats See above. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if the write succeeded, else \c false. On failure, + * check the status with FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats); + +/** Write all metadata out to a FLAC stream via callbacks. + * + * (See FLAC__metadata_chain_write() for the details on how padding is + * used to write metadata in place if possible.) + * + * The \a handle must be open for updating and be seekable. The + * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b" + * for Windows). + * + * For this write function to be used, the chain must have been read with + * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), + * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). + * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned + * \c false. + * + * \param chain A pointer to an existing chain. + * \param use_padding See FLAC__metadata_chain_write() + * \param handle The I/O handle of the FLAC stream to write. The + * handle will NOT be closed after the metadata is + * written; that is the duty of the caller. + * \param callbacks A set of callbacks to use for I/O. The mandatory + * callbacks are \a write and \a seek. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if the write succeeded, else \c false. On failure, + * check the status with FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); + +/** Write all metadata out to a FLAC stream via callbacks. + * + * (See FLAC__metadata_chain_write() for the details on how padding is + * used to write metadata in place if possible.) + * + * This version of the write-with-callbacks function must be used when + * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In + * this function, you must supply an I/O handle corresponding to the + * FLAC file to edit, and a temporary handle to which the new FLAC + * file will be written. It is the caller's job to move this temporary + * FLAC file on top of the original FLAC file to complete the metadata + * edit. + * + * The \a handle must be open for reading and be seekable. The + * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" + * for Windows). + * + * The \a temp_handle must be open for writing. The + * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb" + * for Windows). It should be an empty stream, or at least positioned + * at the start-of-file (in which case it is the caller's duty to + * truncate it on return). + * + * For this write function to be used, the chain must have been read with + * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), + * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). + * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned + * \c true. + * + * \param chain A pointer to an existing chain. + * \param use_padding See FLAC__metadata_chain_write() + * \param handle The I/O handle of the original FLAC stream to read. + * The handle will NOT be closed after the metadata is + * written; that is the duty of the caller. + * \param callbacks A set of callbacks to use for I/O on \a handle. + * The mandatory callbacks are \a read, \a seek, and + * \a eof. + * \param temp_handle The I/O handle of the FLAC stream to write. The + * handle will NOT be closed after the metadata is + * written; that is the duty of the caller. + * \param temp_callbacks + * A set of callbacks to use for I/O on temp_handle. + * The only mandatory callback is \a write. + * \assert + * \code chain != NULL \endcode + * \retval FLAC__bool + * \c true if the write succeeded, else \c false. On failure, + * check the status with FLAC__metadata_chain_status(). + */ +FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks); + +/** Merge adjacent PADDING blocks into a single block. + * + * \note This function does not write to the FLAC file, it only + * modifies the chain. + * + * \warning Any iterator on the current chain will become invalid after this + * call. You should delete the iterator and get a new one. + * + * \param chain A pointer to an existing chain. + * \assert + * \code chain != NULL \endcode + */ +FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain); + +/** This function will move all PADDING blocks to the end on the metadata, + * then merge them into a single block. + * + * \note This function does not write to the FLAC file, it only + * modifies the chain. + * + * \warning Any iterator on the current chain will become invalid after this + * call. You should delete the iterator and get a new one. + * + * \param chain A pointer to an existing chain. + * \assert + * \code chain != NULL \endcode + */ +FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain); + + +/*********** FLAC__Metadata_Iterator ***********/ + +/** Create a new iterator instance. + * + * \retval FLAC__Metadata_Iterator* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void); + +/** Free an iterator instance. Deletes the object pointed to by \a iterator. + * + * \param iterator A pointer to an existing iterator. + * \assert + * \code iterator != NULL \endcode + */ +FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator); + +/** Initialize the iterator to point to the first metadata block in the + * given chain. + * + * \param iterator A pointer to an existing iterator. + * \param chain A pointer to an existing and initialized (read) chain. + * \assert + * \code iterator != NULL \endcode + * \code chain != NULL \endcode + */ +FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain); + +/** Moves the iterator forward one metadata block, returning \c false if + * already at the end. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__bool + * \c false if already at the last metadata block of the chain, else + * \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator); + +/** Moves the iterator backward one metadata block, returning \c false if + * already at the beginning. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__bool + * \c false if already at the first metadata block of the chain, else + * \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator); + +/** Get the type of the metadata block at the current position. + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__MetadataType + * The type of the metadata block at the current iterator position. + */ +FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator); + +/** Get the metadata block at the current position. You can modify + * the block in place but must write the chain before the changes + * are reflected to the FLAC file. You do not need to call + * FLAC__metadata_iterator_set_block() to reflect the changes; + * the pointer returned by FLAC__metadata_iterator_get_block() + * points directly into the chain. + * + * \warning + * Do not call FLAC__metadata_object_delete() on the returned object; + * to delete a block use FLAC__metadata_iterator_delete_block(). + * + * \param iterator A pointer to an existing initialized iterator. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__StreamMetadata* + * The current metadata block. + */ +FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator); + +/** Set the metadata block at the current position, replacing the existing + * block. The new block passed in becomes owned by the chain and it will be + * deleted when the chain is deleted. + * + * \param iterator A pointer to an existing initialized iterator. + * \param block A pointer to a metadata block. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \code block != NULL \endcode + * \retval FLAC__bool + * \c false if the conditions in the above description are not met, or + * a memory allocation error occurs, otherwise \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); + +/** Removes the current block from the chain. If \a replace_with_padding is + * \c true, the block will instead be replaced with a padding block of equal + * size. You can not delete the STREAMINFO block. The iterator will be + * left pointing to the block before the one just "deleted", even if + * \a replace_with_padding is \c true. + * + * \param iterator A pointer to an existing initialized iterator. + * \param replace_with_padding See above. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__bool + * \c false if the conditions in the above description are not met, + * otherwise \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding); + +/** Insert a new block before the current block. You cannot insert a block + * before the first STREAMINFO block. You cannot insert a STREAMINFO block + * as there can be only one, the one that already exists at the head when you + * read in a chain. The chain takes ownership of the new block and it will be + * deleted when the chain is deleted. The iterator will be left pointing to + * the new block. + * + * \param iterator A pointer to an existing initialized iterator. + * \param block A pointer to a metadata block to insert. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__bool + * \c false if the conditions in the above description are not met, or + * a memory allocation error occurs, otherwise \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); + +/** Insert a new block after the current block. You cannot insert a STREAMINFO + * block as there can be only one, the one that already exists at the head when + * you read in a chain. The chain takes ownership of the new block and it will + * be deleted when the chain is deleted. The iterator will be left pointing to + * the new block. + * + * \param iterator A pointer to an existing initialized iterator. + * \param block A pointer to a metadata block to insert. + * \assert + * \code iterator != NULL \endcode + * \a iterator has been successfully initialized with + * FLAC__metadata_iterator_init() + * \retval FLAC__bool + * \c false if the conditions in the above description are not met, or + * a memory allocation error occurs, otherwise \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); + +/* \} */ + + +/** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods + * \ingroup flac_metadata + * + * \brief + * This module contains methods for manipulating FLAC metadata objects. + * + * Since many are variable length we have to be careful about the memory + * management. We decree that all pointers to data in the object are + * owned by the object and memory-managed by the object. + * + * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete() + * functions to create all instances. When using the + * FLAC__metadata_object_set_*() functions to set pointers to data, set + * \a copy to \c true to have the function make it's own copy of the data, or + * to \c false to give the object ownership of your data. In the latter case + * your pointer must be freeable by free() and will be free()d when the object + * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as + * the data pointer to a FLAC__metadata_object_set_*() function as long as + * the length argument is 0 and the \a copy argument is \c false. + * + * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function + * will return \c NULL in the case of a memory allocation error, otherwise a new + * object. The FLAC__metadata_object_set_*() functions return \c false in the + * case of a memory allocation error. + * + * We don't have the convenience of C++ here, so note that the library relies + * on you to keep the types straight. In other words, if you pass, for + * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to + * FLAC__metadata_object_application_set_data(), you will get an assertion + * failure. + * + * For convenience the FLAC__metadata_object_vorbiscomment_*() functions + * maintain a trailing NUL on each Vorbis comment entry. This is not counted + * toward the length or stored in the stream, but it can make working with plain + * comments (those that don't contain embedded-NULs in the value) easier. + * Entries passed into these functions have trailing NULs added if missing, and + * returned entries are guaranteed to have a trailing NUL. + * + * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis + * comment entry/name/value will first validate that it complies with the Vorbis + * comment specification and return false if it does not. + * + * There is no need to recalculate the length field on metadata blocks you + * have modified. They will be calculated automatically before they are + * written back to a file. + * + * \{ + */ + + +/** Create a new metadata object instance of the given type. + * + * The object will be "empty"; i.e. values and data pointers will be \c 0, + * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have + * the vendor string set (but zero comments). + * + * Do not pass in a value greater than or equal to + * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're + * doing. + * + * \param type Type of object to create + * \retval FLAC__StreamMetadata* + * \c NULL if there was an error allocating memory or the type code is + * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance. + */ +FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type); + +/** Create a copy of an existing metadata object. + * + * The copy is a "deep" copy, i.e. dynamically allocated data within the + * object is also copied. The caller takes ownership of the new block and + * is responsible for freeing it with FLAC__metadata_object_delete(). + * + * \param object Pointer to object to copy. + * \assert + * \code object != NULL \endcode + * \retval FLAC__StreamMetadata* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object); + +/** Free a metadata object. Deletes the object pointed to by \a object. + * + * The delete is a "deep" delete, i.e. dynamically allocated data within the + * object is also deleted. + * + * \param object A pointer to an existing object. + * \assert + * \code object != NULL \endcode + */ +FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object); + +/** Compares two metadata objects. + * + * The compare is "deep", i.e. dynamically allocated data within the + * object is also compared. + * + * \param block1 A pointer to an existing object. + * \param block2 A pointer to an existing object. + * \assert + * \code block1 != NULL \endcode + * \code block2 != NULL \endcode + * \retval FLAC__bool + * \c true if objects are identical, else \c false. + */ +FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2); + +/** Sets the application data of an APPLICATION block. + * + * If \a copy is \c true, a copy of the data is stored; otherwise, the object + * takes ownership of the pointer. The existing data will be freed if this + * function is successful, otherwise the original data will remain if \a copy + * is \c true and malloc() fails. + * + * \note It is safe to pass a const pointer to \a data if \a copy is \c true. + * + * \param object A pointer to an existing APPLICATION object. + * \param data A pointer to the data to set. + * \param length The length of \a data in bytes. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode + * \code (data != NULL && length > 0) || + * (data == NULL && length == 0 && copy == false) \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy); + +/** Resize the seekpoint array. + * + * If the size shrinks, elements will truncated; if it grows, new placeholder + * points will be added to the end. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param new_num_points The desired length of the array; may be \c 0. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) || + * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation error, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points); + +/** Set a seekpoint in a seektable. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param point_num Index into seekpoint array to set. + * \param point The point to set. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code object->data.seek_table.num_points > point_num \endcode + */ +FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point); + +/** Insert a seekpoint into a seektable. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param point_num Index into seekpoint array to set. + * \param point The point to set. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code object->data.seek_table.num_points >= point_num \endcode + * \retval FLAC__bool + * \c false if memory allocation error, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point); + +/** Delete a seekpoint from a seektable. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param point_num Index into seekpoint array to set. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code object->data.seek_table.num_points > point_num \endcode + * \retval FLAC__bool + * \c false if memory allocation error, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num); + +/** Check a seektable to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * seektable. + * + * \param object A pointer to an existing SEEKTABLE object. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \retval FLAC__bool + * \c false if seek table is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object); + +/** Append a number of placeholder points to the end of a seek table. + * + * \note + * As with the other ..._seektable_template_... functions, you should + * call FLAC__metadata_object_seektable_template_sort() when finished + * to make the seek table legal. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param num The number of placeholder points to append. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num); + +/** Append a specific seek point template to the end of a seek table. + * + * \note + * As with the other ..._seektable_template_... functions, you should + * call FLAC__metadata_object_seektable_template_sort() when finished + * to make the seek table legal. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param sample_number The sample number of the seek point template. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number); + +/** Append specific seek point templates to the end of a seek table. + * + * \note + * As with the other ..._seektable_template_... functions, you should + * call FLAC__metadata_object_seektable_template_sort() when finished + * to make the seek table legal. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param sample_numbers An array of sample numbers for the seek points. + * \param num The number of seek point templates to append. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num); + +/** Append a set of evenly-spaced seek point templates to the end of a + * seek table. + * + * \note + * As with the other ..._seektable_template_... functions, you should + * call FLAC__metadata_object_seektable_template_sort() when finished + * to make the seek table legal. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param num The number of placeholder points to append. + * \param total_samples The total number of samples to be encoded; + * the seekpoints will be spaced approximately + * \a total_samples / \a num samples apart. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code total_samples > 0 \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples); + +/** Append a set of evenly-spaced seek point templates to the end of a + * seek table. + * + * \note + * As with the other ..._seektable_template_... functions, you should + * call FLAC__metadata_object_seektable_template_sort() when finished + * to make the seek table legal. + * + * \param object A pointer to an existing SEEKTABLE object. + * \param samples The number of samples apart to space the placeholder + * points. The first point will be at sample \c 0, the + * second at sample \a samples, then 2*\a samples, and + * so on. As long as \a samples and \a total_samples + * are greater than \c 0, there will always be at least + * one seekpoint at sample \c 0. + * \param total_samples The total number of samples to be encoded; + * the seekpoints will be spaced + * \a samples samples apart. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \code samples > 0 \endcode + * \code total_samples > 0 \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples); + +/** Sort a seek table's seek points according to the format specification, + * removing duplicates. + * + * \param object A pointer to a seek table to be sorted. + * \param compact If \c false, behaves like FLAC__format_seektable_sort(). + * If \c true, duplicates are deleted and the seek table is + * shrunk appropriately; the number of placeholder points + * present in the seek table will be the same after the call + * as before. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact); + +/** Sets the vendor string in a VORBIS_COMMENT block. + * + * For convenience, a trailing NUL is added to the entry if it doesn't have + * one already. + * + * If \a copy is \c true, a copy of the entry is stored; otherwise, the object + * takes ownership of the \c entry.entry pointer. + * + * \note If this function returns \c false, the caller still owns the + * pointer. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param entry The entry to set the vendor string to. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code (entry.entry != NULL && entry.length > 0) || + * (entry.entry == NULL && entry.length == 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); + +/** Resize the comment array. + * + * If the size shrinks, elements will truncated; if it grows, new empty + * fields will be added to the end. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param new_num_comments The desired length of the array; may be \c 0. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) || + * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments); + +/** Sets a comment in a VORBIS_COMMENT block. + * + * For convenience, a trailing NUL is added to the entry if it doesn't have + * one already. + * + * If \a copy is \c true, a copy of the entry is stored; otherwise, the object + * takes ownership of the \c entry.entry pointer. + * + * \note If this function returns \c false, the caller still owns the + * pointer. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param comment_num Index into comment array to set. + * \param entry The entry to set the comment to. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code comment_num < object->data.vorbis_comment.num_comments \endcode + * \code (entry.entry != NULL && entry.length > 0) || + * (entry.entry == NULL && entry.length == 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); + +/** Insert a comment in a VORBIS_COMMENT block at the given index. + * + * For convenience, a trailing NUL is added to the entry if it doesn't have + * one already. + * + * If \a copy is \c true, a copy of the entry is stored; otherwise, the object + * takes ownership of the \c entry.entry pointer. + * + * \note If this function returns \c false, the caller still owns the + * pointer. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param comment_num The index at which to insert the comment. The comments + * at and after \a comment_num move right one position. + * To append a comment to the end, set \a comment_num to + * \c object->data.vorbis_comment.num_comments . + * \param entry The comment to insert. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code object->data.vorbis_comment.num_comments >= comment_num \endcode + * \code (entry.entry != NULL && entry.length > 0) || + * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); + +/** Appends a comment to a VORBIS_COMMENT block. + * + * For convenience, a trailing NUL is added to the entry if it doesn't have + * one already. + * + * If \a copy is \c true, a copy of the entry is stored; otherwise, the object + * takes ownership of the \c entry.entry pointer. + * + * \note If this function returns \c false, the caller still owns the + * pointer. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param entry The comment to insert. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code (entry.entry != NULL && entry.length > 0) || + * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); + +/** Replaces comments in a VORBIS_COMMENT block with a new one. + * + * For convenience, a trailing NUL is added to the entry if it doesn't have + * one already. + * + * Depending on the the value of \a all, either all or just the first comment + * whose field name(s) match the given entry's name will be replaced by the + * given entry. If no comments match, \a entry will simply be appended. + * + * If \a copy is \c true, a copy of the entry is stored; otherwise, the object + * takes ownership of the \c entry.entry pointer. + * + * \note If this function returns \c false, the caller still owns the + * pointer. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param entry The comment to insert. + * \param all If \c true, all comments whose field name matches + * \a entry's field name will be removed, and \a entry will + * be inserted at the position of the first matching + * comment. If \c false, only the first comment whose + * field name matches \a entry's field name will be + * replaced with \a entry. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code (entry.entry != NULL && entry.length > 0) || + * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy); + +/** Delete a comment in a VORBIS_COMMENT block at the given index. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param comment_num The index of the comment to delete. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code object->data.vorbis_comment.num_comments > comment_num \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num); + +/** Creates a Vorbis comment entry from NUL-terminated name and value strings. + * + * On return, the filled-in \a entry->entry pointer will point to malloc()ed + * memory and shall be owned by the caller. For convenience the entry will + * have a terminating NUL. + * + * \param entry A pointer to a Vorbis comment entry. The entry's + * \c entry pointer should not point to allocated + * memory as it will be overwritten. + * \param field_name The field name in ASCII, \c NUL terminated. + * \param field_value The field value in UTF-8, \c NUL terminated. + * \assert + * \code entry != NULL \endcode + * \code field_name != NULL \endcode + * \code field_value != NULL \endcode + * \retval FLAC__bool + * \c false if malloc() fails, or if \a field_name or \a field_value does + * not comply with the Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value); + +/** Splits a Vorbis comment entry into NUL-terminated name and value strings. + * + * The returned pointers to name and value will be allocated by malloc() + * and shall be owned by the caller. + * + * \param entry An existing Vorbis comment entry. + * \param field_name The address of where the returned pointer to the + * field name will be stored. + * \param field_value The address of where the returned pointer to the + * field value will be stored. + * \assert + * \code (entry.entry != NULL && entry.length > 0) \endcode + * \code memchr(entry.entry, '=', entry.length) != NULL \endcode + * \code field_name != NULL \endcode + * \code field_value != NULL \endcode + * \retval FLAC__bool + * \c false if memory allocation fails or \a entry does not comply with the + * Vorbis comment specification, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value); + +/** Check if the given Vorbis comment entry's field name matches the given + * field name. + * + * \param entry An existing Vorbis comment entry. + * \param field_name The field name to check. + * \param field_name_length The length of \a field_name, not including the + * terminating \c NUL. + * \assert + * \code (entry.entry != NULL && entry.length > 0) \endcode + * \retval FLAC__bool + * \c true if the field names match, else \c false + */ +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length); + +/** Find a Vorbis comment with the given field name. + * + * The search begins at entry number \a offset; use an offset of 0 to + * search from the beginning of the comment array. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param offset The offset into the comment array from where to start + * the search. + * \param field_name The field name of the comment to find. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \code field_name != NULL \endcode + * \retval int + * The offset in the comment array of the first comment whose field + * name matches \a field_name, or \c -1 if no match was found. + */ +FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name); + +/** Remove first Vorbis comment matching the given field name. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param field_name The field name of comment to delete. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \retval int + * \c -1 for memory allocation error, \c 0 for no matching entries, + * \c 1 for one matching entry deleted. + */ +FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name); + +/** Remove all Vorbis comments matching the given field name. + * + * \param object A pointer to an existing VORBIS_COMMENT object. + * \param field_name The field name of comments to delete. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode + * \retval int + * \c -1 for memory allocation error, \c 0 for no matching entries, + * else the number of matching entries deleted. + */ +FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name); + +/** Create a new CUESHEET track instance. + * + * The object will be "empty"; i.e. values and data pointers will be \c 0. + * + * \retval FLAC__StreamMetadata_CueSheet_Track* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void); + +/** Create a copy of an existing CUESHEET track object. + * + * The copy is a "deep" copy, i.e. dynamically allocated data within the + * object is also copied. The caller takes ownership of the new object and + * is responsible for freeing it with + * FLAC__metadata_object_cuesheet_track_delete(). + * + * \param object Pointer to object to copy. + * \assert + * \code object != NULL \endcode + * \retval FLAC__StreamMetadata_CueSheet_Track* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object); + +/** Delete a CUESHEET track object + * + * \param object A pointer to an existing CUESHEET track object. + * \assert + * \code object != NULL \endcode + */ +FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object); + +/** Resize a track's index point array. + * + * If the size shrinks, elements will truncated; if it grows, new blank + * indices will be added to the end. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index of the track to modify. NOTE: this is not + * necessarily the same as the track's \a number field. + * \param new_num_indices The desired length of the array; may be \c 0. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks > track_num \endcode + * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) || + * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation error, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices); + +/** Insert an index point in a CUESHEET track at the given index. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index of the track to modify. NOTE: this is not + * necessarily the same as the track's \a number field. + * \param index_num The index into the track's index array at which to + * insert the index point. NOTE: this is not necessarily + * the same as the index point's \a number field. The + * indices at and after \a index_num move right one + * position. To append an index point to the end, set + * \a index_num to + * \c object->data.cue_sheet.tracks[track_num].num_indices . + * \param index The index point to insert. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks > track_num \endcode + * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index); + +/** Insert a blank index point in a CUESHEET track at the given index. + * + * A blank index point is one in which all field values are zero. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index of the track to modify. NOTE: this is not + * necessarily the same as the track's \a number field. + * \param index_num The index into the track's index array at which to + * insert the index point. NOTE: this is not necessarily + * the same as the index point's \a number field. The + * indices at and after \a index_num move right one + * position. To append an index point to the end, set + * \a index_num to + * \c object->data.cue_sheet.tracks[track_num].num_indices . + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks > track_num \endcode + * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num); + +/** Delete an index point in a CUESHEET track at the given index. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index into the track array of the track to + * modify. NOTE: this is not necessarily the same + * as the track's \a number field. + * \param index_num The index into the track's index array of the index + * to delete. NOTE: this is not necessarily the same + * as the index's \a number field. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks > track_num \endcode + * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num); + +/** Resize the track array. + * + * If the size shrinks, elements will truncated; if it grows, new blank + * tracks will be added to the end. + * + * \param object A pointer to an existing CUESHEET object. + * \param new_num_tracks The desired length of the array; may be \c 0. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) || + * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode + * \retval FLAC__bool + * \c false if memory allocation error, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks); + +/** Sets a track in a CUESHEET block. + * + * If \a copy is \c true, a copy of the track is stored; otherwise, the object + * takes ownership of the \a track pointer. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num Index into track array to set. NOTE: this is not + * necessarily the same as the track's \a number field. + * \param track The track to set the track to. You may safely pass in + * a const pointer if \a copy is \c true. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code track_num < object->data.cue_sheet.num_tracks \endcode + * \code (track->indices != NULL && track->num_indices > 0) || + * (track->indices == NULL && track->num_indices == 0) + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy); + +/** Insert a track in a CUESHEET block at the given index. + * + * If \a copy is \c true, a copy of the track is stored; otherwise, the object + * takes ownership of the \a track pointer. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index at which to insert the track. NOTE: this + * is not necessarily the same as the track's \a number + * field. The tracks at and after \a track_num move right + * one position. To append a track to the end, set + * \a track_num to \c object->data.cue_sheet.num_tracks . + * \param track The track to insert. You may safely pass in a const + * pointer if \a copy is \c true. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks >= track_num \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy); + +/** Insert a blank track in a CUESHEET block at the given index. + * + * A blank track is one in which all field values are zero. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index at which to insert the track. NOTE: this + * is not necessarily the same as the track's \a number + * field. The tracks at and after \a track_num move right + * one position. To append a track to the end, set + * \a track_num to \c object->data.cue_sheet.num_tracks . + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks >= track_num \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num); + +/** Delete a track in a CUESHEET block at the given index. + * + * \param object A pointer to an existing CUESHEET object. + * \param track_num The index into the track array of the track to + * delete. NOTE: this is not necessarily the same + * as the track's \a number field. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \code object->data.cue_sheet.num_tracks > track_num \endcode + * \retval FLAC__bool + * \c false if realloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num); + +/** Check a cue sheet to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * cue sheet. + * + * \param object A pointer to an existing CUESHEET object. + * \param check_cd_da_subset If \c true, check CUESHEET against more + * stringent requirements for a CD-DA (audio) disc. + * \param violation Address of a pointer to a string. If there is a + * violation, a pointer to a string explanation of the + * violation will be returned here. \a violation may be + * \c NULL if you don't need the returned string. Do not + * free the returned string; it will always point to static + * data. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \retval FLAC__bool + * \c false if cue sheet is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation); + +/** Calculate and return the CDDB/freedb ID for a cue sheet. The function + * assumes the cue sheet corresponds to a CD; the result is undefined + * if the cuesheet's is_cd bit is not set. + * + * \param object A pointer to an existing CUESHEET object. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode + * \retval FLAC__uint32 + * The unsigned integer representation of the CDDB/freedb ID + */ +FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object); + +/** Sets the MIME type of a PICTURE block. + * + * If \a copy is \c true, a copy of the string is stored; otherwise, the object + * takes ownership of the pointer. The existing string will be freed if this + * function is successful, otherwise the original string will remain if \a copy + * is \c true and malloc() fails. + * + * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true. + * + * \param object A pointer to an existing PICTURE object. + * \param mime_type A pointer to the MIME type string. The string must be + * ASCII characters 0x20-0x7e, NUL-terminated. No validation + * is done. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode + * \code (mime_type != NULL) \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy); + +/** Sets the description of a PICTURE block. + * + * If \a copy is \c true, a copy of the string is stored; otherwise, the object + * takes ownership of the pointer. The existing string will be freed if this + * function is successful, otherwise the original string will remain if \a copy + * is \c true and malloc() fails. + * + * \note It is safe to pass a const pointer to \a description if \a copy is \c true. + * + * \param object A pointer to an existing PICTURE object. + * \param description A pointer to the description string. The string must be + * valid UTF-8, NUL-terminated. No validation is done. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode + * \code (description != NULL) \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy); + +/** Sets the picture data of a PICTURE block. + * + * If \a copy is \c true, a copy of the data is stored; otherwise, the object + * takes ownership of the pointer. Also sets the \a data_length field of the + * metadata object to what is passed in as the \a length parameter. The + * existing data will be freed if this function is successful, otherwise the + * original data and data_length will remain if \a copy is \c true and + * malloc() fails. + * + * \note It is safe to pass a const pointer to \a data if \a copy is \c true. + * + * \param object A pointer to an existing PICTURE object. + * \param data A pointer to the data to set. + * \param length The length of \a data in bytes. + * \param copy See above. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode + * \code (data != NULL && length > 0) || + * (data == NULL && length == 0 && copy == false) \endcode + * \retval FLAC__bool + * \c false if \a copy is \c true and malloc() fails, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy); + +/** Check a PICTURE block to see if it conforms to the FLAC specification. + * See the format specification for limits on the contents of the + * PICTURE block. + * + * \param object A pointer to existing PICTURE block to be checked. + * \param violation Address of a pointer to a string. If there is a + * violation, a pointer to a string explanation of the + * violation will be returned here. \a violation may be + * \c NULL if you don't need the returned string. Do not + * free the returned string; it will always point to static + * data. + * \assert + * \code object != NULL \endcode + * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode + * \retval FLAC__bool + * \c false if PICTURE block is illegal, else \c true. + */ +FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation); + +/* \} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/FLAC/ordinals.h b/flac/include/FLAC/ordinals.h new file mode 100644 index 0000000..277442b --- /dev/null +++ b/flac/include/FLAC/ordinals.h @@ -0,0 +1,80 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__ORDINALS_H +#define FLAC__ORDINALS_H + +#if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__)) +#include +#endif + +typedef signed char FLAC__int8; +typedef unsigned char FLAC__uint8; + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef __int16 FLAC__int16; +typedef __int32 FLAC__int32; +typedef __int64 FLAC__int64; +typedef unsigned __int16 FLAC__uint16; +typedef unsigned __int32 FLAC__uint32; +typedef unsigned __int64 FLAC__uint64; +#elif defined(__EMX__) +typedef short FLAC__int16; +typedef long FLAC__int32; +typedef long long FLAC__int64; +typedef unsigned short FLAC__uint16; +typedef unsigned long FLAC__uint32; +typedef unsigned long long FLAC__uint64; +#else +typedef int16_t FLAC__int16; +typedef int32_t FLAC__int32; +typedef int64_t FLAC__int64; +typedef uint16_t FLAC__uint16; +typedef uint32_t FLAC__uint32; +typedef uint64_t FLAC__uint64; +#endif + +typedef int FLAC__bool; + +typedef FLAC__uint8 FLAC__byte; + +#ifdef true +#undef true +#endif +#ifdef false +#undef false +#endif +#ifndef __cplusplus +#define true 1 +#define false 0 +#endif + +#endif diff --git a/flac/include/FLAC/stream_decoder.h b/flac/include/FLAC/stream_decoder.h new file mode 100644 index 0000000..58b072c --- /dev/null +++ b/flac/include/FLAC/stream_decoder.h @@ -0,0 +1,1559 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__STREAM_DECODER_H +#define FLAC__STREAM_DECODER_H + +#include /* for FILE */ +#include "export.h" +#include "format.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \file include/FLAC/stream_decoder.h + * + * \brief + * This module contains the functions which implement the stream + * decoder. + * + * See the detailed documentation in the + * \link flac_stream_decoder stream decoder \endlink module. + */ + +/** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces + * \ingroup flac + * + * \brief + * This module describes the decoder layers provided by libFLAC. + * + * The stream decoder can be used to decode complete streams either from + * the client via callbacks, or directly from a file, depending on how + * it is initialized. When decoding via callbacks, the client provides + * callbacks for reading FLAC data and writing decoded samples, and + * handling metadata and errors. If the client also supplies seek-related + * callback, the decoder function for sample-accurate seeking within the + * FLAC input is also available. When decoding from a file, the client + * needs only supply a filename or open \c FILE* and write/metadata/error + * callbacks; the rest of the callbacks are supplied internally. For more + * info see the \link flac_stream_decoder stream decoder \endlink module. + */ + +/** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface + * \ingroup flac_decoder + * + * \brief + * This module contains the functions which implement the stream + * decoder. + * + * The stream decoder can decode native FLAC, and optionally Ogg FLAC + * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files. + * + * The basic usage of this decoder is as follows: + * - The program creates an instance of a decoder using + * FLAC__stream_decoder_new(). + * - The program overrides the default settings using + * FLAC__stream_decoder_set_*() functions. + * - The program initializes the instance to validate the settings and + * prepare for decoding using + * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE() + * or FLAC__stream_decoder_init_file() for native FLAC, + * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE() + * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC + * - The program calls the FLAC__stream_decoder_process_*() functions + * to decode data, which subsequently calls the callbacks. + * - The program finishes the decoding with FLAC__stream_decoder_finish(), + * which flushes the input and output and resets the decoder to the + * uninitialized state. + * - The instance may be used again or deleted with + * FLAC__stream_decoder_delete(). + * + * In more detail, the program will create a new instance by calling + * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*() + * functions to override the default decoder options, and call + * one of the FLAC__stream_decoder_init_*() functions. + * + * There are three initialization functions for native FLAC, one for + * setting up the decoder to decode FLAC data from the client via + * callbacks, and two for decoding directly from a FLAC file. + * + * For decoding via callbacks, use FLAC__stream_decoder_init_stream(). + * You must also supply several callbacks for handling I/O. Some (like + * seeking) are optional, depending on the capabilities of the input. + * + * For decoding directly from a file, use FLAC__stream_decoder_init_FILE() + * or FLAC__stream_decoder_init_file(). Then you must only supply an open + * \c FILE* or filename and fewer callbacks; the decoder will handle + * the other callbacks internally. + * + * There are three similarly-named init functions for decoding from Ogg + * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the + * library has been built with Ogg support. + * + * Once the decoder is initialized, your program will call one of several + * functions to start the decoding process: + * + * - FLAC__stream_decoder_process_single() - Tells the decoder to process at + * most one metadata block or audio frame and return, calling either the + * metadata callback or write callback, respectively, once. If the decoder + * loses sync it will return with only the error callback being called. + * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder + * to process the stream from the current location and stop upon reaching + * the first audio frame. The client will get one metadata, write, or error + * callback per metadata block, audio frame, or sync error, respectively. + * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder + * to process the stream from the current location until the read callback + * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or + * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata, + * write, or error callback per metadata block, audio frame, or sync error, + * respectively. + * + * When the decoder has finished decoding (normally or through an abort), + * the instance is finished by calling FLAC__stream_decoder_finish(), which + * ensures the decoder is in the correct state and frees memory. Then the + * instance may be deleted with FLAC__stream_decoder_delete() or initialized + * again to decode another stream. + * + * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method. + * At any point after the stream decoder has been initialized, the client can + * call this function to seek to an exact sample within the stream. + * Subsequently, the first time the write callback is called it will be + * passed a (possibly partial) block starting at that sample. + * + * If the client cannot seek via the callback interface provided, but still + * has another way of seeking, it can flush the decoder using + * FLAC__stream_decoder_flush() and start feeding data from the new position + * through the read callback. + * + * The stream decoder also provides MD5 signature checking. If this is + * turned on before initialization, FLAC__stream_decoder_finish() will + * report when the decoded MD5 signature does not match the one stored + * in the STREAMINFO block. MD5 checking is automatically turned off + * (until the next FLAC__stream_decoder_reset()) if there is no signature + * in the STREAMINFO block or when a seek is attempted. + * + * The FLAC__stream_decoder_set_metadata_*() functions deserve special + * attention. By default, the decoder only calls the metadata_callback for + * the STREAMINFO block. These functions allow you to tell the decoder + * explicitly which blocks to parse and return via the metadata_callback + * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(), + * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(), + * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify + * which blocks to return. Remember that metadata blocks can potentially + * be big (for example, cover art) so filtering out the ones you don't + * use can reduce the memory requirements of the decoder. Also note the + * special forms FLAC__stream_decoder_set_metadata_respond_application(id) + * and FLAC__stream_decoder_set_metadata_ignore_application(id) for + * filtering APPLICATION blocks based on the application ID. + * + * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but + * they still can legally be filtered from the metadata_callback. + * + * \note + * The "set" functions may only be called when the decoder is in the + * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after + * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but + * before FLAC__stream_decoder_init_*(). If this is the case they will + * return \c true, otherwise \c false. + * + * \note + * FLAC__stream_decoder_finish() resets all settings to the constructor + * defaults, including the callbacks. + * + * \{ + */ + + +/** State values for a FLAC__StreamDecoder + * + * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state(). + */ +typedef enum { + + FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0, + /**< The decoder is ready to search for metadata. */ + + FLAC__STREAM_DECODER_READ_METADATA, + /**< The decoder is ready to or is in the process of reading metadata. */ + + FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC, + /**< The decoder is ready to or is in the process of searching for the + * frame sync code. + */ + + FLAC__STREAM_DECODER_READ_FRAME, + /**< The decoder is ready to or is in the process of reading a frame. */ + + FLAC__STREAM_DECODER_END_OF_STREAM, + /**< The decoder has reached the end of the stream. */ + + FLAC__STREAM_DECODER_OGG_ERROR, + /**< An error occurred in the underlying Ogg layer. */ + + FLAC__STREAM_DECODER_SEEK_ERROR, + /**< An error occurred while seeking. The decoder must be flushed + * with FLAC__stream_decoder_flush() or reset with + * FLAC__stream_decoder_reset() before decoding can continue. + */ + + FLAC__STREAM_DECODER_ABORTED, + /**< The decoder was aborted by the read callback. */ + + FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR, + /**< An error occurred allocating memory. The decoder is in an invalid + * state and can no longer be used. + */ + + FLAC__STREAM_DECODER_UNINITIALIZED + /**< The decoder is in the uninitialized state; one of the + * FLAC__stream_decoder_init_*() functions must be called before samples + * can be processed. + */ + +} FLAC__StreamDecoderState; + +/** Maps a FLAC__StreamDecoderState to a C string. + * + * Using a FLAC__StreamDecoderState as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderStateString[]; + + +/** Possible return values for the FLAC__stream_decoder_init_*() functions. + */ +typedef enum { + + FLAC__STREAM_DECODER_INIT_STATUS_OK = 0, + /**< Initialization was successful. */ + + FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER, + /**< The library was not compiled with support for the given container + * format. + */ + + FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS, + /**< A required callback was not supplied. */ + + FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR, + /**< An error occurred allocating memory. */ + + FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE, + /**< fopen() failed in FLAC__stream_decoder_init_file() or + * FLAC__stream_decoder_init_ogg_file(). */ + + FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED + /**< FLAC__stream_decoder_init_*() was called when the decoder was + * already initialized, usually because + * FLAC__stream_decoder_finish() was not called. + */ + +} FLAC__StreamDecoderInitStatus; + +/** Maps a FLAC__StreamDecoderInitStatus to a C string. + * + * Using a FLAC__StreamDecoderInitStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[]; + + +/** Return values for the FLAC__StreamDecoder read callback. + */ +typedef enum { + + FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, + /**< The read was OK and decoding can continue. */ + + FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM, + /**< The read was attempted while at the end of the stream. Note that + * the client must only return this value when the read callback was + * called when already at the end of the stream. Otherwise, if the read + * itself moves to the end of the stream, the client should still return + * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on + * the next read callback it should return + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count + * of \c 0. + */ + + FLAC__STREAM_DECODER_READ_STATUS_ABORT + /**< An unrecoverable error occurred. The decoder will return from the process call. */ + +} FLAC__StreamDecoderReadStatus; + +/** Maps a FLAC__StreamDecoderReadStatus to a C string. + * + * Using a FLAC__StreamDecoderReadStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[]; + + +/** Return values for the FLAC__StreamDecoder seek callback. + */ +typedef enum { + + FLAC__STREAM_DECODER_SEEK_STATUS_OK, + /**< The seek was OK and decoding can continue. */ + + FLAC__STREAM_DECODER_SEEK_STATUS_ERROR, + /**< An unrecoverable error occurred. The decoder will return from the process call. */ + + FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED + /**< Client does not support seeking. */ + +} FLAC__StreamDecoderSeekStatus; + +/** Maps a FLAC__StreamDecoderSeekStatus to a C string. + * + * Using a FLAC__StreamDecoderSeekStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[]; + + +/** Return values for the FLAC__StreamDecoder tell callback. + */ +typedef enum { + + FLAC__STREAM_DECODER_TELL_STATUS_OK, + /**< The tell was OK and decoding can continue. */ + + FLAC__STREAM_DECODER_TELL_STATUS_ERROR, + /**< An unrecoverable error occurred. The decoder will return from the process call. */ + + FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED + /**< Client does not support telling the position. */ + +} FLAC__StreamDecoderTellStatus; + +/** Maps a FLAC__StreamDecoderTellStatus to a C string. + * + * Using a FLAC__StreamDecoderTellStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[]; + + +/** Return values for the FLAC__StreamDecoder length callback. + */ +typedef enum { + + FLAC__STREAM_DECODER_LENGTH_STATUS_OK, + /**< The length call was OK and decoding can continue. */ + + FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR, + /**< An unrecoverable error occurred. The decoder will return from the process call. */ + + FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED + /**< Client does not support reporting the length. */ + +} FLAC__StreamDecoderLengthStatus; + +/** Maps a FLAC__StreamDecoderLengthStatus to a C string. + * + * Using a FLAC__StreamDecoderLengthStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[]; + + +/** Return values for the FLAC__StreamDecoder write callback. + */ +typedef enum { + + FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE, + /**< The write was OK and decoding can continue. */ + + FLAC__STREAM_DECODER_WRITE_STATUS_ABORT + /**< An unrecoverable error occurred. The decoder will return from the process call. */ + +} FLAC__StreamDecoderWriteStatus; + +/** Maps a FLAC__StreamDecoderWriteStatus to a C string. + * + * Using a FLAC__StreamDecoderWriteStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[]; + + +/** Possible values passed back to the FLAC__StreamDecoder error callback. + * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch- + * all. The rest could be caused by bad sync (false synchronization on + * data that is not the start of a frame) or corrupted data. The error + * itself is the decoder's best guess at what happened assuming a correct + * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER + * could be caused by a correct sync on the start of a frame, but some + * data in the frame header was corrupted. Or it could be the result of + * syncing on a point the stream that looked like the starting of a frame + * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM + * could be because the decoder encountered a valid frame made by a future + * version of the encoder which it cannot parse, or because of a false + * sync making it appear as though an encountered frame was generated by + * a future encoder. + */ +typedef enum { + + FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, + /**< An error in the stream caused the decoder to lose synchronization. */ + + FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, + /**< The decoder encountered a corrupted frame header. */ + + FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH, + /**< The frame's data did not match the CRC in the footer. */ + + FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM + /**< The decoder encountered reserved fields in use in the stream. */ + +} FLAC__StreamDecoderErrorStatus; + +/** Maps a FLAC__StreamDecoderErrorStatus to a C string. + * + * Using a FLAC__StreamDecoderErrorStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[]; + + +/*********************************************************************** + * + * class FLAC__StreamDecoder + * + ***********************************************************************/ + +struct FLAC__StreamDecoderProtected; +struct FLAC__StreamDecoderPrivate; +/** The opaque structure definition for the stream decoder type. + * See the \link flac_stream_decoder stream decoder module \endlink + * for a detailed description. + */ +typedef struct { + struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */ + struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */ +} FLAC__StreamDecoder; + +/** Signature for the read callback. + * + * A function pointer matching this signature must be passed to + * FLAC__stream_decoder_init*_stream(). The supplied function will be + * called when the decoder needs more input data. The address of the + * buffer to be filled is supplied, along with the number of bytes the + * buffer can hold. The callback may choose to supply less data and + * modify the byte count but must be careful not to overflow the buffer. + * The callback then returns a status code chosen from + * FLAC__StreamDecoderReadStatus. + * + * Here is an example of a read callback for stdio streams: + * \code + * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * if(*bytes > 0) { + * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file); + * if(ferror(file)) + * return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + * else if(*bytes == 0) + * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + * else + * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + * } + * else + * return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + * } + * \endcode + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param buffer A pointer to a location for the callee to store + * data to be decoded. + * \param bytes A pointer to the size of the buffer. On entry + * to the callback, it contains the maximum number + * of bytes that may be stored in \a buffer. The + * callee must set it to the actual number of bytes + * stored (0 in case of error or end-of-stream) before + * returning. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__StreamDecoderReadStatus + * The callee's return status. Note that the callback should return + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if + * zero bytes were read and there is no more data to be read. + */ +typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); + +/** Signature for the seek callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_decoder_init*_stream(). The supplied function will be + * called when the decoder needs to seek the input stream. The decoder + * will pass the absolute byte offset to seek to, 0 meaning the + * beginning of the stream. + * + * Here is an example of a seek callback for stdio streams: + * \code + * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * if(file == stdin) + * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; + * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0) + * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + * else + * return FLAC__STREAM_DECODER_SEEK_STATUS_OK; + * } + * \endcode + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param absolute_byte_offset The offset from the beginning of the stream + * to seek to. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__StreamDecoderSeekStatus + * The callee's return status. + */ +typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data); + +/** Signature for the tell callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_decoder_init*_stream(). The supplied function will be + * called when the decoder wants to know the current position of the + * stream. The callback should return the byte offset from the + * beginning of the stream. + * + * Here is an example of a tell callback for stdio streams: + * \code + * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * off_t pos; + * if(file == stdin) + * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; + * else if((pos = ftello(file)) < 0) + * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + * else { + * *absolute_byte_offset = (FLAC__uint64)pos; + * return FLAC__STREAM_DECODER_TELL_STATUS_OK; + * } + * } + * \endcode + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param absolute_byte_offset A pointer to storage for the current offset + * from the beginning of the stream. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__StreamDecoderTellStatus + * The callee's return status. + */ +typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data); + +/** Signature for the length callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_decoder_init*_stream(). The supplied function will be + * called when the decoder wants to know the total length of the stream + * in bytes. + * + * Here is an example of a length callback for stdio streams: + * \code + * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * struct stat filestats; + * + * if(file == stdin) + * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; + * else if(fstat(fileno(file), &filestats) != 0) + * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + * else { + * *stream_length = (FLAC__uint64)filestats.st_size; + * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; + * } + * } + * \endcode + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param stream_length A pointer to storage for the length of the stream + * in bytes. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__StreamDecoderLengthStatus + * The callee's return status. + */ +typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data); + +/** Signature for the EOF callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_decoder_init*_stream(). The supplied function will be + * called when the decoder needs to know if the end of the stream has + * been reached. + * + * Here is an example of a EOF callback for stdio streams: + * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data) + * \code + * { + * FILE *file = ((MyClientData*)client_data)->file; + * return feof(file)? true : false; + * } + * \endcode + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__bool + * \c true if the currently at the end of the stream, else \c false. + */ +typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data); + +/** Signature for the write callback. + * + * A function pointer matching this signature must be passed to one of + * the FLAC__stream_decoder_init_*() functions. + * The supplied function will be called when the decoder has decoded a + * single audio frame. The decoder will pass the frame metadata as well + * as an array of pointers (one for each channel) pointing to the + * decoded audio. + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param frame The description of the decoded frame. See + * FLAC__Frame. + * \param buffer An array of pointers to decoded channels of data. + * Each pointer will point to an array of signed + * samples of length \a frame->header.blocksize. + * Channels will be ordered according to the FLAC + * specification; see the documentation for the + * frame header. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + * \retval FLAC__StreamDecoderWriteStatus + * The callee's return status. + */ +typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); + +/** Signature for the metadata callback. + * + * A function pointer matching this signature must be passed to one of + * the FLAC__stream_decoder_init_*() functions. + * The supplied function will be called when the decoder has decoded a + * metadata block. In a valid FLAC file there will always be one + * \c STREAMINFO block, followed by zero or more other metadata blocks. + * These will be supplied by the decoder in the same order as they + * appear in the stream and always before the first audio frame (i.e. + * write callback). The metadata block that is passed in must not be + * modified, and it doesn't live beyond the callback, so you should make + * a copy of it with FLAC__metadata_object_clone() if you will need it + * elsewhere. Since metadata blocks can potentially be large, by + * default the decoder only calls the metadata callback for the + * \c STREAMINFO block; you can instruct the decoder to pass or filter + * other blocks with FLAC__stream_decoder_set_metadata_*() calls. + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param metadata The decoded metadata block. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + */ +typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); + +/** Signature for the error callback. + * + * A function pointer matching this signature must be passed to one of + * the FLAC__stream_decoder_init_*() functions. + * The supplied function will be called whenever an error occurs during + * decoding. + * + * \note In general, FLAC__StreamDecoder functions which change the + * state should not be called on the \a decoder while in the callback. + * + * \param decoder The decoder instance calling the callback. + * \param status The error encountered by the decoder. + * \param client_data The callee's client data set through + * FLAC__stream_decoder_init_*(). + */ +typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + + +/*********************************************************************** + * + * Class constructor/destructor + * + ***********************************************************************/ + +/** Create a new stream decoder instance. The instance is created with + * default settings; see the individual FLAC__stream_decoder_set_*() + * functions for each setting's default. + * + * \retval FLAC__StreamDecoder* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void); + +/** Free a decoder instance. Deletes the object pointed to by \a decoder. + * + * \param decoder A pointer to an existing decoder. + * \assert + * \code decoder != NULL \endcode + */ +FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder); + + +/*********************************************************************** + * + * Public class method prototypes + * + ***********************************************************************/ + +/** Set the serial number for the FLAC stream within the Ogg container. + * The default behavior is to use the serial number of the first Ogg + * page. Setting a serial number here will explicitly specify which + * stream is to be decoded. + * + * \note + * This does not need to be set for native FLAC decoding. + * + * \default \c use serial number of first page + * \param decoder A decoder instance to set. + * \param serial_number See above. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number); + +/** Set the "MD5 signature checking" flag. If \c true, the decoder will + * compute the MD5 signature of the unencoded audio data while decoding + * and compare it to the signature from the STREAMINFO block, if it + * exists, during FLAC__stream_decoder_finish(). + * + * MD5 signature checking will be turned off (until the next + * FLAC__stream_decoder_reset()) if there is no signature in the + * STREAMINFO block or when a seek is attempted. + * + * Clients that do not use the MD5 check should leave this off to speed + * up decoding. + * + * \default \c false + * \param decoder A decoder instance to set. + * \param value Flag value (see above). + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value); + +/** Direct the decoder to pass on all metadata blocks of type \a type. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \param type See above. + * \assert + * \code decoder != NULL \endcode + * \a type is valid + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type); + +/** Direct the decoder to pass on all APPLICATION metadata blocks of the + * given \a id. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \param id See above. + * \assert + * \code decoder != NULL \endcode + * \code id != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]); + +/** Direct the decoder to pass on all metadata blocks of any type. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder); + +/** Direct the decoder to filter out all metadata blocks of type \a type. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \param type See above. + * \assert + * \code decoder != NULL \endcode + * \a type is valid + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type); + +/** Direct the decoder to filter out all APPLICATION metadata blocks of + * the given \a id. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \param id See above. + * \assert + * \code decoder != NULL \endcode + * \code id != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]); + +/** Direct the decoder to filter out all metadata blocks of any type. + * + * \default By default, only the \c STREAMINFO block is returned via the + * metadata callback. + * \param decoder A decoder instance to set. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if the decoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder); + +/** Get the current decoder state. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__StreamDecoderState + * The current decoder state. + */ +FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder); + +/** Get the current decoder state as a C string. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval const char * + * The decoder state as a C string. Do not modify the contents. + */ +FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder); + +/** Get the "MD5 signature checking" flag. + * This is the value of the setting, not whether or not the decoder is + * currently checking the MD5 (remember, it can be turned off automatically + * by a seek). When the decoder is reset the flag will be restored to the + * value returned by this function. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * See above. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder); + +/** Get the total number of samples in the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the \c STREAMINFO block. A value of \c 0 means "unknown". + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval unsigned + * See above. + */ +FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder); + +/** Get the current number of channels in the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the most recently decoded frame header. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval unsigned + * See above. + */ +FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder); + +/** Get the current channel assignment in the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the most recently decoded frame header. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__ChannelAssignment + * See above. + */ +FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder); + +/** Get the current sample resolution in the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the most recently decoded frame header. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval unsigned + * See above. + */ +FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder); + +/** Get the current sample rate in Hz of the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the most recently decoded frame header. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval unsigned + * See above. + */ +FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder); + +/** Get the current blocksize of the stream being decoded. + * Will only be valid after decoding has started and will contain the + * value from the most recently decoded frame header. + * + * \param decoder A decoder instance to query. + * \assert + * \code decoder != NULL \endcode + * \retval unsigned + * See above. + */ +FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder); + +/** Returns the decoder's current read position within the stream. + * The position is the byte offset from the start of the stream. + * Bytes before this position have been fully decoded. Note that + * there may still be undecoded bytes in the decoder's read FIFO. + * The returned position is correct even after a seek. + * + * \warning This function currently only works for native FLAC, + * not Ogg FLAC streams. + * + * \param decoder A decoder instance to query. + * \param position Address at which to return the desired position. + * \assert + * \code decoder != NULL \endcode + * \code position != NULL \endcode + * \retval FLAC__bool + * \c true if successful, \c false if the stream is not native FLAC, + * or there was an error from the 'tell' callback or it returned + * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position); + +/** Initialize the decoder instance to decode native FLAC streams. + * + * This flavor of initialization sets up the decoder to decode from a + * native FLAC stream. I/O is performed via callbacks to the client. + * For decoding from a plain file via filename or open FILE*, + * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE() + * provide a simpler interface. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \param decoder An uninitialized decoder instance. + * \param read_callback See FLAC__StreamDecoderReadCallback. This + * pointer must not be \c NULL. + * \param seek_callback See FLAC__StreamDecoderSeekCallback. This + * pointer may be \c NULL if seeking is not + * supported. If \a seek_callback is not \c NULL then a + * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied. + * Alternatively, a dummy seek callback that just + * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param tell_callback See FLAC__StreamDecoderTellCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a tell_callback must also be supplied. + * Alternatively, a dummy tell callback that just + * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param length_callback See FLAC__StreamDecoderLengthCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a length_callback must also be supplied. + * Alternatively, a dummy length callback that just + * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param eof_callback See FLAC__StreamDecoderEofCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a eof_callback must also be supplied. + * Alternatively, a dummy length callback that just + * returns \c false + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream( + FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderReadCallback read_callback, + FLAC__StreamDecoderSeekCallback seek_callback, + FLAC__StreamDecoderTellCallback tell_callback, + FLAC__StreamDecoderLengthCallback length_callback, + FLAC__StreamDecoderEofCallback eof_callback, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Initialize the decoder instance to decode Ogg FLAC streams. + * + * This flavor of initialization sets up the decoder to decode from a + * FLAC stream in an Ogg container. I/O is performed via callbacks to the + * client. For decoding from a plain file via filename or open FILE*, + * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE() + * provide a simpler interface. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \note Support for Ogg FLAC in the library is optional. If this + * library has been built without support for Ogg FLAC, this function + * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. + * + * \param decoder An uninitialized decoder instance. + * \param read_callback See FLAC__StreamDecoderReadCallback. This + * pointer must not be \c NULL. + * \param seek_callback See FLAC__StreamDecoderSeekCallback. This + * pointer may be \c NULL if seeking is not + * supported. If \a seek_callback is not \c NULL then a + * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied. + * Alternatively, a dummy seek callback that just + * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param tell_callback See FLAC__StreamDecoderTellCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a tell_callback must also be supplied. + * Alternatively, a dummy tell callback that just + * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param length_callback See FLAC__StreamDecoderLengthCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a length_callback must also be supplied. + * Alternatively, a dummy length callback that just + * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param eof_callback See FLAC__StreamDecoderEofCallback. This + * pointer may be \c NULL if not supported by the client. If + * \a seek_callback is not \c NULL then a + * \a eof_callback must also be supplied. + * Alternatively, a dummy length callback that just + * returns \c false + * may also be supplied, all though this is slightly + * less efficient for the decoder. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream( + FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderReadCallback read_callback, + FLAC__StreamDecoderSeekCallback seek_callback, + FLAC__StreamDecoderTellCallback tell_callback, + FLAC__StreamDecoderLengthCallback length_callback, + FLAC__StreamDecoderEofCallback eof_callback, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Initialize the decoder instance to decode native FLAC files. + * + * This flavor of initialization sets up the decoder to decode from a + * plain native FLAC file. For non-stdio streams, you must use + * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \param decoder An uninitialized decoder instance. + * \param file An open FLAC file. The file should have been + * opened with mode \c "rb" and rewound. The file + * becomes owned by the decoder and should not be + * manipulated by the client while decoding. + * Unless \a file is \c stdin, it will be closed + * when FLAC__stream_decoder_finish() is called. + * Note however that seeking will not work when + * decoding from \c stdout since it is not seekable. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \code file != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE( + FLAC__StreamDecoder *decoder, + FILE *file, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Initialize the decoder instance to decode Ogg FLAC files. + * + * This flavor of initialization sets up the decoder to decode from a + * plain Ogg FLAC file. For non-stdio streams, you must use + * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \note Support for Ogg FLAC in the library is optional. If this + * library has been built without support for Ogg FLAC, this function + * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. + * + * \param decoder An uninitialized decoder instance. + * \param file An open FLAC file. The file should have been + * opened with mode \c "rb" and rewound. The file + * becomes owned by the decoder and should not be + * manipulated by the client while decoding. + * Unless \a file is \c stdin, it will be closed + * when FLAC__stream_decoder_finish() is called. + * Note however that seeking will not work when + * decoding from \c stdout since it is not seekable. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \code file != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE( + FLAC__StreamDecoder *decoder, + FILE *file, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Initialize the decoder instance to decode native FLAC files. + * + * This flavor of initialization sets up the decoder to decode from a plain + * native FLAC file. If POSIX fopen() semantics are not sufficient, (for + * example, with Unicode filenames on Windows), you must use + * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream() + * and provide callbacks for the I/O. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \param decoder An uninitialized decoder instance. + * \param filename The name of the file to decode from. The file will + * be opened with fopen(). Use \c NULL to decode from + * \c stdin. Note that \c stdin is not seekable. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file( + FLAC__StreamDecoder *decoder, + const char *filename, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Initialize the decoder instance to decode Ogg FLAC files. + * + * This flavor of initialization sets up the decoder to decode from a plain + * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for + * example, with Unicode filenames on Windows), you must use + * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream() + * and provide callbacks for the I/O. + * + * This function should be called after FLAC__stream_decoder_new() and + * FLAC__stream_decoder_set_*() but before any of the + * FLAC__stream_decoder_process_*() functions. Will set and return the + * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA + * if initialization succeeded. + * + * \note Support for Ogg FLAC in the library is optional. If this + * library has been built without support for Ogg FLAC, this function + * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. + * + * \param decoder An uninitialized decoder instance. + * \param filename The name of the file to decode from. The file will + * be opened with fopen(). Use \c NULL to decode from + * \c stdin. Note that \c stdin is not seekable. + * \param write_callback See FLAC__StreamDecoderWriteCallback. This + * pointer must not be \c NULL. + * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This + * pointer may be \c NULL if the callback is not + * desired. + * \param error_callback See FLAC__StreamDecoderErrorCallback. This + * pointer must not be \c NULL. + * \param client_data This value will be supplied to callbacks in their + * \a client_data argument. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__StreamDecoderInitStatus + * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; + * see FLAC__StreamDecoderInitStatus for the meanings of other return values. + */ +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file( + FLAC__StreamDecoder *decoder, + const char *filename, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +); + +/** Finish the decoding process. + * Flushes the decoding buffer, releases resources, resets the decoder + * settings to their defaults, and returns the decoder state to + * FLAC__STREAM_DECODER_UNINITIALIZED. + * + * In the event of a prematurely-terminated decode, it is not strictly + * necessary to call this immediately before FLAC__stream_decoder_delete() + * but it is good practice to match every FLAC__stream_decoder_init_*() + * with a FLAC__stream_decoder_finish(). + * + * \param decoder An uninitialized decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if MD5 checking is on AND a STREAMINFO block was available + * AND the MD5 signature in the STREAMINFO block was non-zero AND the + * signature does not match the one computed by the decoder; else + * \c true. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder); + +/** Flush the stream input. + * The decoder's input buffer will be cleared and the state set to + * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn + * off MD5 checking. + * + * \param decoder A decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c true if successful, else \c false if a memory allocation + * error occurs (in which case the state will be set to + * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder); + +/** Reset the decoding process. + * The decoder's input buffer will be cleared and the state set to + * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to + * FLAC__stream_decoder_finish() except that the settings are + * preserved; there is no need to call FLAC__stream_decoder_init_*() + * before decoding again. MD5 checking will be restored to its original + * setting. + * + * If the decoder is seekable, or was initialized with + * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(), + * the decoder will also attempt to seek to the beginning of the file. + * If this rewind fails, this function will return \c false. It follows + * that FLAC__stream_decoder_reset() cannot be used when decoding from + * \c stdin. + * + * If the decoder was initialized with FLAC__stream_encoder_init*_stream() + * and is not seekable (i.e. no seek callback was provided or the seek + * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it + * is the duty of the client to start feeding data from the beginning of + * the stream on the next FLAC__stream_decoder_process() or + * FLAC__stream_decoder_process_interleaved() call. + * + * \param decoder A decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c true if successful, else \c false if a memory allocation occurs + * (in which case the state will be set to + * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error + * occurs (the state will be unchanged). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder); + +/** Decode one metadata block or audio frame. + * This version instructs the decoder to decode a either a single metadata + * block or a single frame and stop, unless the callbacks return a fatal + * error or the read callback returns + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. + * + * As the decoder needs more input it will call the read callback. + * Depending on what was decoded, the metadata or write callback will be + * called with the decoded metadata block or audio frame. + * + * Unless there is a fatal read error or end of stream, this function + * will return once one whole frame is decoded. In other words, if the + * stream is not synchronized or points to a corrupt frame header, the + * decoder will continue to try and resync until it gets to a valid + * frame, then decode one frame, then return. If the decoder points to + * a frame whose frame CRC in the frame footer does not match the + * computed frame CRC, this function will issue a + * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the + * error callback, and return, having decoded one complete, although + * corrupt, frame. (Such corrupted frames are sent as silence of the + * correct length to the write callback.) + * + * \param decoder An initialized decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if any fatal read, write, or memory allocation error + * occurred (meaning decoding must stop), else \c true; for more + * information about the decoder, check the decoder state with + * FLAC__stream_decoder_get_state(). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder); + +/** Decode until the end of the metadata. + * This version instructs the decoder to decode from the current position + * and continue until all the metadata has been read, or until the + * callbacks return a fatal error or the read callback returns + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. + * + * As the decoder needs more input it will call the read callback. + * As each metadata block is decoded, the metadata callback will be called + * with the decoded metadata. + * + * \param decoder An initialized decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if any fatal read, write, or memory allocation error + * occurred (meaning decoding must stop), else \c true; for more + * information about the decoder, check the decoder state with + * FLAC__stream_decoder_get_state(). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder); + +/** Decode until the end of the stream. + * This version instructs the decoder to decode from the current position + * and continue until the end of stream (the read callback returns + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the + * callbacks return a fatal error. + * + * As the decoder needs more input it will call the read callback. + * As each metadata block and frame is decoded, the metadata or write + * callback will be called with the decoded metadata or frame. + * + * \param decoder An initialized decoder instance. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if any fatal read, write, or memory allocation error + * occurred (meaning decoding must stop), else \c true; for more + * information about the decoder, check the decoder state with + * FLAC__stream_decoder_get_state(). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder); + +/** Skip one audio frame. + * This version instructs the decoder to 'skip' a single frame and stop, + * unless the callbacks return a fatal error or the read callback returns + * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. + * + * The decoding flow is the same as what occurs when + * FLAC__stream_decoder_process_single() is called to process an audio + * frame, except that this function does not decode the parsed data into + * PCM or call the write callback. The integrity of the frame is still + * checked the same way as in the other process functions. + * + * This function will return once one whole frame is skipped, in the + * same way that FLAC__stream_decoder_process_single() will return once + * one whole frame is decoded. + * + * This function can be used in more quickly determining FLAC frame + * boundaries when decoding of the actual data is not needed, for + * example when an application is separating a FLAC stream into frames + * for editing or storing in a container. To do this, the application + * can use FLAC__stream_decoder_skip_single_frame() to quickly advance + * to the next frame, then use + * FLAC__stream_decoder_get_decode_position() to find the new frame + * boundary. + * + * This function should only be called when the stream has advanced + * past all the metadata, otherwise it will return \c false. + * + * \param decoder An initialized decoder instance not in a metadata + * state. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c false if any fatal read, write, or memory allocation error + * occurred (meaning decoding must stop), or if the decoder + * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or + * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more + * information about the decoder, check the decoder state with + * FLAC__stream_decoder_get_state(). + */ +FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder); + +/** Flush the input and seek to an absolute sample. + * Decoding will resume at the given sample. Note that because of + * this, the next write callback may contain a partial block. The + * client must support seeking the input or this function will fail + * and return \c false. Furthermore, if the decoder state is + * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed + * with FLAC__stream_decoder_flush() or reset with + * FLAC__stream_decoder_reset() before decoding can continue. + * + * \param decoder A decoder instance. + * \param sample The target sample number to seek to. + * \assert + * \code decoder != NULL \endcode + * \retval FLAC__bool + * \c true if successful, else \c false. + */ +FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample); + +/* \} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/FLAC/stream_encoder.h b/flac/include/FLAC/stream_encoder.h new file mode 100644 index 0000000..acc295e --- /dev/null +++ b/flac/include/FLAC/stream_encoder.h @@ -0,0 +1,1768 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__STREAM_ENCODER_H +#define FLAC__STREAM_ENCODER_H + +#include /* for FILE */ +#include "export.h" +#include "format.h" +#include "stream_decoder.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \file include/FLAC/stream_encoder.h + * + * \brief + * This module contains the functions which implement the stream + * encoder. + * + * See the detailed documentation in the + * \link flac_stream_encoder stream encoder \endlink module. + */ + +/** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces + * \ingroup flac + * + * \brief + * This module describes the encoder layers provided by libFLAC. + * + * The stream encoder can be used to encode complete streams either to the + * client via callbacks, or directly to a file, depending on how it is + * initialized. When encoding via callbacks, the client provides a write + * callback which will be called whenever FLAC data is ready to be written. + * If the client also supplies a seek callback, the encoder will also + * automatically handle the writing back of metadata discovered while + * encoding, like stream info, seek points offsets, etc. When encoding to + * a file, the client needs only supply a filename or open \c FILE* and an + * optional progress callback for periodic notification of progress; the + * write and seek callbacks are supplied internally. For more info see the + * \link flac_stream_encoder stream encoder \endlink module. + */ + +/** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface + * \ingroup flac_encoder + * + * \brief + * This module contains the functions which implement the stream + * encoder. + * + * The stream encoder can encode to native FLAC, and optionally Ogg FLAC + * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files. + * + * The basic usage of this encoder is as follows: + * - The program creates an instance of an encoder using + * FLAC__stream_encoder_new(). + * - The program overrides the default settings using + * FLAC__stream_encoder_set_*() functions. At a minimum, the following + * functions should be called: + * - FLAC__stream_encoder_set_channels() + * - FLAC__stream_encoder_set_bits_per_sample() + * - FLAC__stream_encoder_set_sample_rate() + * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC) + * - FLAC__stream_encoder_set_total_samples_estimate() (if known) + * - If the application wants to control the compression level or set its own + * metadata, then the following should also be called: + * - FLAC__stream_encoder_set_compression_level() + * - FLAC__stream_encoder_set_verify() + * - FLAC__stream_encoder_set_metadata() + * - The rest of the set functions should only be called if the client needs + * exact control over how the audio is compressed; thorough understanding + * of the FLAC format is necessary to achieve good results. + * - The program initializes the instance to validate the settings and + * prepare for encoding using + * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE() + * or FLAC__stream_encoder_init_file() for native FLAC + * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE() + * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC + * - The program calls FLAC__stream_encoder_process() or + * FLAC__stream_encoder_process_interleaved() to encode data, which + * subsequently calls the callbacks when there is encoder data ready + * to be written. + * - The program finishes the encoding with FLAC__stream_encoder_finish(), + * which causes the encoder to encode any data still in its input pipe, + * update the metadata with the final encoding statistics if output + * seeking is possible, and finally reset the encoder to the + * uninitialized state. + * - The instance may be used again or deleted with + * FLAC__stream_encoder_delete(). + * + * In more detail, the stream encoder functions similarly to the + * \link flac_stream_decoder stream decoder \endlink, but has fewer + * callbacks and more options. Typically the client will create a new + * instance by calling FLAC__stream_encoder_new(), then set the necessary + * parameters with FLAC__stream_encoder_set_*(), and initialize it by + * calling one of the FLAC__stream_encoder_init_*() functions. + * + * Unlike the decoders, the stream encoder has many options that can + * affect the speed and compression ratio. When setting these parameters + * you should have some basic knowledge of the format (see the + * user-level documentation + * or the formal description). The + * FLAC__stream_encoder_set_*() functions themselves do not validate the + * values as many are interdependent. The FLAC__stream_encoder_init_*() + * functions will do this, so make sure to pay attention to the state + * returned by FLAC__stream_encoder_init_*() to make sure that it is + * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set + * before FLAC__stream_encoder_init_*() will take on the defaults from + * the constructor. + * + * There are three initialization functions for native FLAC, one for + * setting up the encoder to encode FLAC data to the client via + * callbacks, and two for encoding directly to a file. + * + * For encoding via callbacks, use FLAC__stream_encoder_init_stream(). + * You must also supply a write callback which will be called anytime + * there is raw encoded data to write. If the client can seek the output + * it is best to also supply seek and tell callbacks, as this allows the + * encoder to go back after encoding is finished to write back + * information that was collected while encoding, like seek point offsets, + * frame sizes, etc. + * + * For encoding directly to a file, use FLAC__stream_encoder_init_FILE() + * or FLAC__stream_encoder_init_file(). Then you must only supply a + * filename or open \c FILE*; the encoder will handle all the callbacks + * internally. You may also supply a progress callback for periodic + * notification of the encoding progress. + * + * There are three similarly-named init functions for encoding to Ogg + * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the + * library has been built with Ogg support. + * + * The call to FLAC__stream_encoder_init_*() currently will also immediately + * call the write callback several times, once with the \c fLaC signature, + * and once for each encoded metadata block. Note that for Ogg FLAC + * encoding you will usually get at least twice the number of callbacks than + * with native FLAC, one for the Ogg page header and one for the page body. + * + * After initializing the instance, the client may feed audio data to the + * encoder in one of two ways: + * + * - Channel separate, through FLAC__stream_encoder_process() - The client + * will pass an array of pointers to buffers, one for each channel, to + * the encoder, each of the same length. The samples need not be + * block-aligned, but each channel should have the same number of samples. + * - Channel interleaved, through + * FLAC__stream_encoder_process_interleaved() - The client will pass a single + * pointer to data that is channel-interleaved (i.e. channel0_sample0, + * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...). + * Again, the samples need not be block-aligned but they must be + * sample-aligned, i.e. the first value should be channel0_sample0 and + * the last value channelN_sampleM. + * + * Note that for either process call, each sample in the buffers should be a + * signed integer, right-justified to the resolution set by + * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution + * is 16 bits per sample, the samples should all be in the range [-32768,32767]. + * + * When the client is finished encoding data, it calls + * FLAC__stream_encoder_finish(), which causes the encoder to encode any + * data still in its input pipe, and call the metadata callback with the + * final encoding statistics. Then the instance may be deleted with + * FLAC__stream_encoder_delete() or initialized again to encode another + * stream. + * + * For programs that write their own metadata, but that do not know the + * actual metadata until after encoding, it is advantageous to instruct + * the encoder to write a PADDING block of the correct size, so that + * instead of rewriting the whole stream after encoding, the program can + * just overwrite the PADDING block. If only the maximum size of the + * metadata is known, the program can write a slightly larger padding + * block, then split it after encoding. + * + * Make sure you understand how lengths are calculated. All FLAC metadata + * blocks have a 4 byte header which contains the type and length. This + * length does not include the 4 bytes of the header. See the format page + * for the specification of metadata blocks and their lengths. + * + * \note + * If you are writing the FLAC data to a file via callbacks, make sure it + * is open for update (e.g. mode "w+" for stdio streams). This is because + * after the first encoding pass, the encoder will try to seek back to the + * beginning of the stream, to the STREAMINFO block, to write some data + * there. (If using FLAC__stream_encoder_init*_file() or + * FLAC__stream_encoder_init*_FILE(), the file is managed internally.) + * + * \note + * The "set" functions may only be called when the encoder is in the + * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after + * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but + * before FLAC__stream_encoder_init_*(). If this is the case they will + * return \c true, otherwise \c false. + * + * \note + * FLAC__stream_encoder_finish() resets all settings to the constructor + * defaults. + * + * \{ + */ + + +/** State values for a FLAC__StreamEncoder. + * + * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state(). + * + * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK + * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and + * must be deleted with FLAC__stream_encoder_delete(). + */ +typedef enum { + + FLAC__STREAM_ENCODER_OK = 0, + /**< The encoder is in the normal OK state and samples can be processed. */ + + FLAC__STREAM_ENCODER_UNINITIALIZED, + /**< The encoder is in the uninitialized state; one of the + * FLAC__stream_encoder_init_*() functions must be called before samples + * can be processed. + */ + + FLAC__STREAM_ENCODER_OGG_ERROR, + /**< An error occurred in the underlying Ogg layer. */ + + FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR, + /**< An error occurred in the underlying verify stream decoder; + * check FLAC__stream_encoder_get_verify_decoder_state(). + */ + + FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA, + /**< The verify decoder detected a mismatch between the original + * audio signal and the decoded audio signal. + */ + + FLAC__STREAM_ENCODER_CLIENT_ERROR, + /**< One of the callbacks returned a fatal error. */ + + FLAC__STREAM_ENCODER_IO_ERROR, + /**< An I/O error occurred while opening/reading/writing a file. + * Check \c errno. + */ + + FLAC__STREAM_ENCODER_FRAMING_ERROR, + /**< An error occurred while writing the stream; usually, the + * write_callback returned an error. + */ + + FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR + /**< Memory allocation failed. */ + +} FLAC__StreamEncoderState; + +/** Maps a FLAC__StreamEncoderState to a C string. + * + * Using a FLAC__StreamEncoderState as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderStateString[]; + + +/** Possible return values for the FLAC__stream_encoder_init_*() functions. + */ +typedef enum { + + FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0, + /**< Initialization was successful. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR, + /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER, + /**< The library was not compiled with support for the given container + * format. + */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS, + /**< A required callback was not supplied. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS, + /**< The encoder has an invalid setting for number of channels. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE, + /**< The encoder has an invalid setting for bits-per-sample. + * FLAC supports 4-32 bps but the reference encoder currently supports + * only up to 24 bps. + */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE, + /**< The encoder has an invalid setting for the input sample rate. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE, + /**< The encoder has an invalid setting for the block size. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER, + /**< The encoder has an invalid setting for the maximum LPC order. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION, + /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER, + /**< The specified block size is less than the maximum LPC order. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE, + /**< The encoder is bound to the Subset but other settings violate it. */ + + FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA, + /**< The metadata input to the encoder is invalid, in one of the following ways: + * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0 + * - One of the metadata blocks contains an undefined type + * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal() + * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal() + * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block + */ + + FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED + /**< FLAC__stream_encoder_init_*() was called when the encoder was + * already initialized, usually because + * FLAC__stream_encoder_finish() was not called. + */ + +} FLAC__StreamEncoderInitStatus; + +/** Maps a FLAC__StreamEncoderInitStatus to a C string. + * + * Using a FLAC__StreamEncoderInitStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[]; + + +/** Return values for the FLAC__StreamEncoder read callback. + */ +typedef enum { + + FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE, + /**< The read was OK and decoding can continue. */ + + FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM, + /**< The read was attempted at the end of the stream. */ + + FLAC__STREAM_ENCODER_READ_STATUS_ABORT, + /**< An unrecoverable error occurred. */ + + FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED + /**< Client does not support reading back from the output. */ + +} FLAC__StreamEncoderReadStatus; + +/** Maps a FLAC__StreamEncoderReadStatus to a C string. + * + * Using a FLAC__StreamEncoderReadStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[]; + + +/** Return values for the FLAC__StreamEncoder write callback. + */ +typedef enum { + + FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0, + /**< The write was OK and encoding can continue. */ + + FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR + /**< An unrecoverable error occurred. The encoder will return from the process call. */ + +} FLAC__StreamEncoderWriteStatus; + +/** Maps a FLAC__StreamEncoderWriteStatus to a C string. + * + * Using a FLAC__StreamEncoderWriteStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[]; + + +/** Return values for the FLAC__StreamEncoder seek callback. + */ +typedef enum { + + FLAC__STREAM_ENCODER_SEEK_STATUS_OK, + /**< The seek was OK and encoding can continue. */ + + FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR, + /**< An unrecoverable error occurred. */ + + FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED + /**< Client does not support seeking. */ + +} FLAC__StreamEncoderSeekStatus; + +/** Maps a FLAC__StreamEncoderSeekStatus to a C string. + * + * Using a FLAC__StreamEncoderSeekStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[]; + + +/** Return values for the FLAC__StreamEncoder tell callback. + */ +typedef enum { + + FLAC__STREAM_ENCODER_TELL_STATUS_OK, + /**< The tell was OK and encoding can continue. */ + + FLAC__STREAM_ENCODER_TELL_STATUS_ERROR, + /**< An unrecoverable error occurred. */ + + FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED + /**< Client does not support seeking. */ + +} FLAC__StreamEncoderTellStatus; + +/** Maps a FLAC__StreamEncoderTellStatus to a C string. + * + * Using a FLAC__StreamEncoderTellStatus as the index to this array + * will give the string equivalent. The contents should not be modified. + */ +extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[]; + + +/*********************************************************************** + * + * class FLAC__StreamEncoder + * + ***********************************************************************/ + +struct FLAC__StreamEncoderProtected; +struct FLAC__StreamEncoderPrivate; +/** The opaque structure definition for the stream encoder type. + * See the \link flac_stream_encoder stream encoder module \endlink + * for a detailed description. + */ +typedef struct { + struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */ + struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */ +} FLAC__StreamEncoder; + +/** Signature for the read callback. + * + * A function pointer matching this signature must be passed to + * FLAC__stream_encoder_init_ogg_stream() if seeking is supported. + * The supplied function will be called when the encoder needs to read back + * encoded data. This happens during the metadata callback, when the encoder + * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered + * while encoding. The address of the buffer to be filled is supplied, along + * with the number of bytes the buffer can hold. The callback may choose to + * supply less data and modify the byte count but must be careful not to + * overflow the buffer. The callback then returns a status code chosen from + * FLAC__StreamEncoderReadStatus. + * + * Here is an example of a read callback for stdio streams: + * \code + * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * if(*bytes > 0) { + * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file); + * if(ferror(file)) + * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; + * else if(*bytes == 0) + * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM; + * else + * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE; + * } + * else + * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; + * } + * \endcode + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param buffer A pointer to a location for the callee to store + * data to be encoded. + * \param bytes A pointer to the size of the buffer. On entry + * to the callback, it contains the maximum number + * of bytes that may be stored in \a buffer. The + * callee must set it to the actual number of bytes + * stored (0 in case of error or end-of-stream) before + * returning. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_set_client_data(). + * \retval FLAC__StreamEncoderReadStatus + * The callee's return status. + */ +typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data); + +/** Signature for the write callback. + * + * A function pointer matching this signature must be passed to + * FLAC__stream_encoder_init*_stream(). The supplied function will be called + * by the encoder anytime there is raw encoded data ready to write. It may + * include metadata mixed with encoded audio frames and the data is not + * guaranteed to be aligned on frame or metadata block boundaries. + * + * The only duty of the callback is to write out the \a bytes worth of data + * in \a buffer to the current position in the output stream. The arguments + * \a samples and \a current_frame are purely informational. If \a samples + * is greater than \c 0, then \a current_frame will hold the current frame + * number that is being written; otherwise it indicates that the write + * callback is being called to write metadata. + * + * \note + * Unlike when writing to native FLAC, when writing to Ogg FLAC the + * write callback will be called twice when writing each audio + * frame; once for the page header, and once for the page body. + * When writing the page header, the \a samples argument to the + * write callback will be \c 0. + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param buffer An array of encoded data of length \a bytes. + * \param bytes The byte length of \a buffer. + * \param samples The number of samples encoded by \a buffer. + * \c 0 has a special meaning; see above. + * \param current_frame The number of the current frame being encoded. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_init_*(). + * \retval FLAC__StreamEncoderWriteStatus + * The callee's return status. + */ +typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data); + +/** Signature for the seek callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_encoder_init*_stream(). The supplied function will be called + * when the encoder needs to seek the output stream. The encoder will pass + * the absolute byte offset to seek to, 0 meaning the beginning of the stream. + * + * Here is an example of a seek callback for stdio streams: + * \code + * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * if(file == stdin) + * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED; + * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0) + * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; + * else + * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK; + * } + * \endcode + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param absolute_byte_offset The offset from the beginning of the stream + * to seek to. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_init_*(). + * \retval FLAC__StreamEncoderSeekStatus + * The callee's return status. + */ +typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data); + +/** Signature for the tell callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_encoder_init*_stream(). The supplied function will be called + * when the encoder needs to know the current position of the output stream. + * + * \warning + * The callback must return the true current byte offset of the output to + * which the encoder is writing. If you are buffering the output, make + * sure and take this into account. If you are writing directly to a + * FILE* from your write callback, ftell() is sufficient. If you are + * writing directly to a file descriptor from your write callback, you + * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to + * these points to rewrite metadata after encoding. + * + * Here is an example of a tell callback for stdio streams: + * \code + * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) + * { + * FILE *file = ((MyClientData*)client_data)->file; + * off_t pos; + * if(file == stdin) + * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED; + * else if((pos = ftello(file)) < 0) + * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR; + * else { + * *absolute_byte_offset = (FLAC__uint64)pos; + * return FLAC__STREAM_ENCODER_TELL_STATUS_OK; + * } + * } + * \endcode + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param absolute_byte_offset The address at which to store the current + * position of the output. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_init_*(). + * \retval FLAC__StreamEncoderTellStatus + * The callee's return status. + */ +typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data); + +/** Signature for the metadata callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_encoder_init*_stream(). The supplied function will be called + * once at the end of encoding with the populated STREAMINFO structure. This + * is so the client can seek back to the beginning of the file and write the + * STREAMINFO block with the correct statistics after encoding (like + * minimum/maximum frame size and total samples). + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param metadata The final populated STREAMINFO block. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_init_*(). + */ +typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data); + +/** Signature for the progress callback. + * + * A function pointer matching this signature may be passed to + * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE(). + * The supplied function will be called when the encoder has finished + * writing a frame. The \c total_frames_estimate argument to the + * callback will be based on the value from + * FLAC__stream_encoder_set_total_samples_estimate(). + * + * \note In general, FLAC__StreamEncoder functions which change the + * state should not be called on the \a encoder while in the callback. + * + * \param encoder The encoder instance calling the callback. + * \param bytes_written Bytes written so far. + * \param samples_written Samples written so far. + * \param frames_written Frames written so far. + * \param total_frames_estimate The estimate of the total number of + * frames to be written. + * \param client_data The callee's client data set through + * FLAC__stream_encoder_init_*(). + */ +typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data); + + +/*********************************************************************** + * + * Class constructor/destructor + * + ***********************************************************************/ + +/** Create a new stream encoder instance. The instance is created with + * default settings; see the individual FLAC__stream_encoder_set_*() + * functions for each setting's default. + * + * \retval FLAC__StreamEncoder* + * \c NULL if there was an error allocating memory, else the new instance. + */ +FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void); + +/** Free an encoder instance. Deletes the object pointed to by \a encoder. + * + * \param encoder A pointer to an existing encoder. + * \assert + * \code encoder != NULL \endcode + */ +FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder); + + +/*********************************************************************** + * + * Public class method prototypes + * + ***********************************************************************/ + +/** Set the serial number for the FLAC stream to use in the Ogg container. + * + * \note + * This does not need to be set for native FLAC encoding. + * + * \note + * It is recommended to set a serial number explicitly as the default of '0' + * may collide with other streams. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param serial_number See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number); + +/** Set the "verify" flag. If \c true, the encoder will verify it's own + * encoded output by feeding it through an internal decoder and comparing + * the original signal against the decoded signal. If a mismatch occurs, + * the process call will return \c false. Note that this will slow the + * encoding process by the extra time required for decoding and comparison. + * + * \default \c false + * \param encoder An encoder instance to set. + * \param value Flag value (see above). + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value); + +/** Set the Subset flag. If \c true, + * the encoder will comply with the Subset and will check the + * settings during FLAC__stream_encoder_init_*() to see if all settings + * comply. If \c false, the settings may take advantage of the full + * range that the format allows. + * + * Make sure you know what it entails before setting this to \c false. + * + * \default \c true + * \param encoder An encoder instance to set. + * \param value Flag value (see above). + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value); + +/** Set the number of channels to be encoded. + * + * \default \c 2 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set the sample resolution of the input to be encoded. + * + * \warning + * Do not feed the encoder data that is wider than the value you + * set here or you will generate an invalid stream. + * + * \default \c 16 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set the sample rate (in Hz) of the input to be encoded. + * + * \default \c 44100 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set the compression level + * + * The compression level is roughly proportional to the amount of effort + * the encoder expends to compress the file. A higher level usually + * means more computation but higher compression. The default level is + * suitable for most applications. + * + * Currently the levels range from \c 0 (fastest, least compression) to + * \c 8 (slowest, most compression). A value larger than \c 8 will be + * treated as \c 8. + * + * This function automatically calls the following other \c _set_ + * functions with appropriate values, so the client does not need to + * unless it specifically wants to override them: + * - FLAC__stream_encoder_set_do_mid_side_stereo() + * - FLAC__stream_encoder_set_loose_mid_side_stereo() + * - FLAC__stream_encoder_set_apodization() + * - FLAC__stream_encoder_set_max_lpc_order() + * - FLAC__stream_encoder_set_qlp_coeff_precision() + * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search() + * - FLAC__stream_encoder_set_do_escape_coding() + * - FLAC__stream_encoder_set_do_exhaustive_model_search() + * - FLAC__stream_encoder_set_min_residual_partition_order() + * - FLAC__stream_encoder_set_max_residual_partition_order() + * - FLAC__stream_encoder_set_rice_parameter_search_dist() + * + * The actual values set for each level are: + * + * + * + * + * + * + * + * + * + * + * + * + *
      level + * do mid-side stereo + * loose mid-side stereo + * apodization + * max lpc order + * qlp coeff precision + * qlp coeff prec search + * escape coding + * exhaustive model search + * min residual partition order + * max residual partition order + * rice parameter search dist + *
      0 false false tukey(0.5) 0 0 false false false 0 3 0
      1 true true tukey(0.5) 0 0 false false false 0 3 0
      2 true false tukey(0.5) 0 0 false false false 0 3 0
      3 false false tukey(0.5) 6 0 false false false 0 4 0
      4 true true tukey(0.5) 8 0 false false false 0 4 0
      5 true false tukey(0.5) 8 0 false false false 0 5 0
      6 true false tukey(0.5) 8 0 false false false 0 6 0
      7 true false tukey(0.5) 8 0 false false true 0 6 0
      8 true false tukey(0.5) 12 0 false false true 0 6 0
      + * + * \default \c 5 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set the blocksize to use while encoding. + * + * The number of samples to use per frame. Use \c 0 to let the encoder + * estimate a blocksize; this is usually best. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set to \c true to enable mid-side encoding on stereo input. The + * number of channels must be 2 for this to have any effect. Set to + * \c false to use only independent channel coding. + * + * \default \c false + * \param encoder An encoder instance to set. + * \param value Flag value (see above). + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value); + +/** Set to \c true to enable adaptive switching between mid-side and + * left-right encoding on stereo input. Set to \c false to use + * exhaustive searching. Setting this to \c true requires + * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to + * \c true in order to have any effect. + * + * \default \c false + * \param encoder An encoder instance to set. + * \param value Flag value (see above). + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value); + +/** Sets the apodization function(s) the encoder will use when windowing + * audio data for LPC analysis. + * + * The \a specification is a plain ASCII string which specifies exactly + * which functions to use. There may be more than one (up to 32), + * separated by \c ';' characters. Some functions take one or more + * comma-separated arguments in parentheses. + * + * The available functions are \c bartlett, \c bartlett_hann, + * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop, + * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall, + * \c rectangle, \c triangle, \c tukey(P), \c welch. + * + * For \c gauss(STDDEV), STDDEV specifies the standard deviation + * (0blocksize / (2 ^ order). + * + * Set both min and max values to \c 0 to force a single context, + * whose Rice parameter is based on the residual signal variance. + * Otherwise, set a min and max order, and the encoder will search + * all orders, using the mean of each context for its Rice parameter, + * and use the best. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set the maximum partition order to search when coding the residual. + * This is used in tandem with + * FLAC__stream_encoder_set_min_residual_partition_order(). + * + * The partition order determines the context size in the residual. + * The context size will be approximately blocksize / (2 ^ order). + * + * Set both min and max values to \c 0 to force a single context, + * whose Rice parameter is based on the residual signal variance. + * Otherwise, set a min and max order, and the encoder will search + * all orders, using the mean of each context for its Rice parameter, + * and use the best. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value); + +/** Deprecated. Setting this value has no effect. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value); + +/** Set an estimate of the total samples that will be encoded. + * This is merely an estimate and may be set to \c 0 if unknown. + * This value will be written to the STREAMINFO block before encoding, + * and can remove the need for the caller to rewrite the value later + * if the value is known before encoding. + * + * \default \c 0 + * \param encoder An encoder instance to set. + * \param value See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value); + +/** Set the metadata blocks to be emitted to the stream before encoding. + * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an + * array of pointers to metadata blocks. The array is non-const since + * the encoder may need to change the \a is_last flag inside them, and + * in some cases update seek point offsets. Otherwise, the encoder will + * not modify or free the blocks. It is up to the caller to free the + * metadata blocks after encoding finishes. + * + * \note + * The encoder stores only copies of the pointers in the \a metadata array; + * the metadata blocks themselves must survive at least until after + * FLAC__stream_encoder_finish() returns. Do not free the blocks until then. + * + * \note + * The STREAMINFO block is always written and no STREAMINFO block may + * occur in the supplied array. + * + * \note + * By default the encoder does not create a SEEKTABLE. If one is supplied + * in the \a metadata array, but the client has specified that it does not + * support seeking, then the SEEKTABLE will be written verbatim. However + * by itself this is not very useful as the client will not know the stream + * offsets for the seekpoints ahead of time. In order to get a proper + * seektable the client must support seeking. See next note. + * + * \note + * SEEKTABLE blocks are handled specially. Since you will not know + * the values for the seek point stream offsets, you should pass in + * a SEEKTABLE 'template', that is, a SEEKTABLE object with the + * required sample numbers (or placeholder points), with \c 0 for the + * \a frame_samples and \a stream_offset fields for each point. If the + * client has specified that it supports seeking by providing a seek + * callback to FLAC__stream_encoder_init_stream() or both seek AND read + * callback to FLAC__stream_encoder_init_ogg_stream() (or by using + * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()), + * then while it is encoding the encoder will fill the stream offsets in + * for you and when encoding is finished, it will seek back and write the + * real values into the SEEKTABLE block in the stream. There are helper + * routines for manipulating seektable template blocks; see metadata.h: + * FLAC__metadata_object_seektable_template_*(). If the client does + * not support seeking, the SEEKTABLE will have inaccurate offsets which + * will slow down or remove the ability to seek in the FLAC stream. + * + * \note + * The encoder instance \b will modify the first \c SEEKTABLE block + * as it transforms the template to a valid seektable while encoding, + * but it is still up to the caller to free all metadata blocks after + * encoding. + * + * \note + * A VORBIS_COMMENT block may be supplied. The vendor string in it + * will be ignored. libFLAC will use it's own vendor string. libFLAC + * will not modify the passed-in VORBIS_COMMENT's vendor string, it + * will simply write it's own into the stream. If no VORBIS_COMMENT + * block is present in the \a metadata array, libFLAC will write an + * empty one, containing only the vendor string. + * + * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be + * the second metadata block of the stream. The encoder already supplies + * the STREAMINFO block automatically. If \a metadata does not contain a + * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if + * \a metadata does contain a VORBIS_COMMENT block and it is not the + * first, the init function will reorder \a metadata by moving the + * VORBIS_COMMENT block to the front; the relative ordering of the other + * blocks will remain as they were. + * + * \note The Ogg FLAC mapping limits the number of metadata blocks per + * stream to \c 65535. If \a num_blocks exceeds this the function will + * return \c false. + * + * \default \c NULL, 0 + * \param encoder An encoder instance to set. + * \param metadata See above. + * \param num_blocks See above. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * \c false if the encoder is already initialized, else \c true. + * \c false if the encoder is already initialized, or if + * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks); + +/** Get the current encoder state. + * + * \param encoder An encoder instance to query. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__StreamEncoderState + * The current encoder state. + */ +FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder); + +/** Get the state of the verify stream decoder. + * Useful when the stream encoder state is + * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. + * + * \param encoder An encoder instance to query. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__StreamDecoderState + * The verify stream decoder state. + */ +FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder); + +/** Get the current encoder state as a C string. + * This version automatically resolves + * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the + * verify decoder's state. + * + * \param encoder A encoder instance to query. + * \assert + * \code encoder != NULL \endcode + * \retval const char * + * The encoder state as a C string. Do not modify the contents. + */ +FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder); + +/** Get relevant values about the nature of a verify decoder error. + * Useful when the stream encoder state is + * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should + * be addresses in which the stats will be returned, or NULL if value + * is not desired. + * + * \param encoder An encoder instance to query. + * \param absolute_sample The absolute sample number of the mismatch. + * \param frame_number The number of the frame in which the mismatch occurred. + * \param channel The channel in which the mismatch occurred. + * \param sample The number of the sample (relative to the frame) in + * which the mismatch occurred. + * \param expected The expected value for the sample in question. + * \param got The actual value returned by the decoder. + * \assert + * \code encoder != NULL \endcode + */ +FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got); + +/** Get the "verify" flag. + * + * \param encoder An encoder instance to query. + * \assert + * \code encoder != NULL \endcode + * \retval FLAC__bool + * See FLAC__stream_encoder_set_verify(). + */ +FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder); + +/** Get the frame header. + * + * \param encoder An initialized encoder instance in the OK state. + * \param buffer An array of pointers to each channel's signal. + * \param samples The number of samples in one channel. + * \assert + * \code encoder != NULL \endcode + * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode + * \retval FLAC__bool + * \c true if successful, else \c false; in this case, check the + * encoder state with FLAC__stream_encoder_get_state() to see what + * went wrong. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples); + +/** Submit data for encoding. + * This version allows you to supply the input data where the channels + * are interleaved into a single array (i.e. channel0_sample0, + * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...). + * The samples need not be block-aligned but they must be + * sample-aligned, i.e. the first value should be channel0_sample0 + * and the last value channelN_sampleM. Each sample should be a signed + * integer, right-justified to the resolution set by + * FLAC__stream_encoder_set_bits_per_sample(). For example, if the + * resolution is 16 bits per sample, the samples should all be in the + * range [-32768,32767]. + * + * For applications where channel order is important, channels must + * follow the order as described in the + * frame header. + * + * \param encoder An initialized encoder instance in the OK state. + * \param buffer An array of channel-interleaved data (see above). + * \param samples The number of samples in one channel, the same as for + * FLAC__stream_encoder_process(). For example, if + * encoding two channels, \c 1000 \a samples corresponds + * to a \a buffer of 2000 values. + * \assert + * \code encoder != NULL \endcode + * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode + * \retval FLAC__bool + * \c true if successful, else \c false; in this case, check the + * encoder state with FLAC__stream_encoder_get_state() to see what + * went wrong. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples); + +/* \} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/Makefile.am b/flac/include/Makefile.am new file mode 100644 index 0000000..f6b7ece --- /dev/null +++ b/flac/include/Makefile.am @@ -0,0 +1,22 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +if FLaC__WITH_CPPLIBS +CPPLIBS_DIRS = FLAC++ +endif + +SUBDIRS = FLAC $(CPPLIBS_DIRS) share test_libs_common diff --git a/flac/include/share/Makefile.am b/flac/include/share/Makefile.am new file mode 100644 index 0000000..aaa68c2 --- /dev/null +++ b/flac/include/share/Makefile.am @@ -0,0 +1,13 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = grabbag + +EXTRA_DIST = \ + alloc.h \ + getopt.h \ + grabbag.h \ + replaygain_analysis.h \ + replaygain_synthesis.h \ + utf8.h diff --git a/flac/include/share/alloc.h b/flac/include/share/alloc.h new file mode 100644 index 0000000..43215fd --- /dev/null +++ b/flac/include/share/alloc.h @@ -0,0 +1,212 @@ +/* alloc - Convenience routines for safely allocating memory + * Copyright (C) 2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__SHARE__ALLOC_H +#define FLAC__SHARE__ALLOC_H + +#if HAVE_CONFIG_H +# include +#endif + +/* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early + * before #including this file, otherwise SIZE_MAX might not be defined + */ + +#include /* for SIZE_MAX */ +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__ +#include /* for SIZE_MAX in case limits.h didn't get it */ +#endif +#include /* for size_t, malloc(), etc */ + +#ifndef SIZE_MAX +# ifndef SIZE_T_MAX +# ifdef _MSC_VER +# define SIZE_T_MAX UINT_MAX +# else +# error +# endif +# endif +# define SIZE_MAX SIZE_T_MAX +#endif + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +/* avoid malloc()ing 0 bytes, see: + * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003 +*/ +static FLaC__INLINE void *safe_malloc_(size_t size) +{ + /* malloc(0) is undefined; FLAC src convention is to always allocate */ + if(!size) + size++; + return malloc(size); +} + +static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size) +{ + if(!nmemb || !size) + return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */ + return calloc(nmemb, size); +} + +/*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */ + +static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2) +{ + size2 += size1; + if(size2 < size1) + return 0; + return safe_malloc_(size2); +} + +static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3) +{ + size2 += size1; + if(size2 < size1) + return 0; + size3 += size2; + if(size3 < size2) + return 0; + return safe_malloc_(size3); +} + +static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4) +{ + size2 += size1; + if(size2 < size1) + return 0; + size3 += size2; + if(size3 < size2) + return 0; + size4 += size3; + if(size4 < size3) + return 0; + return safe_malloc_(size4); +} + +static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2) +#if 0 +needs support for cases where sizeof(size_t) != 4 +{ + /* could be faster #ifdef'ing off SIZEOF_SIZE_T */ + if(sizeof(size_t) == 4) { + if ((double)size1 * (double)size2 < 4294967296.0) + return malloc(size1*size2); + } + return 0; +} +#else +/* better? */ +{ + if(!size1 || !size2) + return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */ + if(size1 > SIZE_MAX / size2) + return 0; + return malloc(size1*size2); +} +#endif + +static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3) +{ + if(!size1 || !size2 || !size3) + return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */ + if(size1 > SIZE_MAX / size2) + return 0; + size1 *= size2; + if(size1 > SIZE_MAX / size3) + return 0; + return malloc(size1*size3); +} + +/* size1*size2 + size3 */ +static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3) +{ + if(!size1 || !size2) + return safe_malloc_(size3); + if(size1 > SIZE_MAX / size2) + return 0; + return safe_malloc_add_2op_(size1*size2, size3); +} + +/* size1 * (size2 + size3) */ +static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3) +{ + if(!size1 || (!size2 && !size3)) + return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */ + size2 += size3; + if(size2 < size3) + return 0; + return safe_malloc_mul_2op_(size1, size2); +} + +static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2) +{ + size2 += size1; + if(size2 < size1) + return 0; + return realloc(ptr, size2); +} + +static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3) +{ + size2 += size1; + if(size2 < size1) + return 0; + size3 += size2; + if(size3 < size2) + return 0; + return realloc(ptr, size3); +} + +static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4) +{ + size2 += size1; + if(size2 < size1) + return 0; + size3 += size2; + if(size3 < size2) + return 0; + size4 += size3; + if(size4 < size3) + return 0; + return realloc(ptr, size4); +} + +static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2) +{ + if(!size1 || !size2) + return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */ + if(size1 > SIZE_MAX / size2) + return 0; + return realloc(ptr, size1*size2); +} + +/* size1 * (size2 + size3) */ +static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3) +{ + if(!size1 || (!size2 && !size3)) + return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */ + size2 += size3; + if(size2 < size3) + return 0; + return safe_realloc_mul_2op_(ptr, size1, size2); +} + +#endif diff --git a/flac/include/share/getopt.h b/flac/include/share/getopt.h new file mode 100644 index 0000000..2d901c6 --- /dev/null +++ b/flac/include/share/getopt.h @@ -0,0 +1,184 @@ +/* + NOTE: + I cannot get the vanilla getopt code to work (i.e. compile only what + is needed and not duplicate symbols found in the standard library) + on all the platforms that FLAC supports. In particular the gating + of code with the ELIDE_CODE #define is not accurate enough on systems + that are POSIX but not glibc. If someone has a patch that works on + GNU/Linux, Darwin, AND Solaris please submit it on the project page: + http://sourceforge.net/projects/flac + + In the meantime I have munged the global symbols and removed gates + around code, while at the same time trying to touch the original as + little as possible. +*/ +/* Declarations for getopt. + Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifndef SHARE__GETOPT_H +#define SHARE__GETOPT_H + +/*[JEC] was:#ifndef __need_getopt*/ +/*[JEC] was:# define _GETOPT_H 1*/ +/*[JEC] was:#endif*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `share__getopt' to the caller. + When `share__getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *share__optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `share__getopt'. + + On entry to `share__getopt', zero means this is the first call; initialize. + + When `share__getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `share__optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int share__optind; + +/* Callers store zero here to inhibit the error message `share__getopt' prints + for unrecognized options. */ + +extern int share__opterr; + +/* Set to an option character which was unrecognized. */ + +extern int share__optopt; + +/*[JEC] was:#ifndef __need_getopt */ +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to share__getopt_long or share__getopt_long_only is a vector + of `struct share__option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + share__no_argument (or 0) if the option does not take an argument, + share__required_argument (or 1) if the option requires an argument, + share__optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `share__optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `share__getopt' + returns the contents of the `val' field. */ + +struct share__option +{ +# if defined __STDC__ && __STDC__ + const char *name; +# else + char *name; +# endif + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct share__option'. */ + +# define share__no_argument 0 +# define share__required_argument 1 +# define share__optional_argument 2 +/*[JEC] was:#endif*/ /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `share__optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `share__optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `share__getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `share__getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `share__getopt'. */ + +/*[JEC] was:#if defined __STDC__ && __STDC__*/ +/*[JEC] was:# ifdef __GNU_LIBRARY__*/ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int share__getopt (int argc, char *const *argv, const char *shortopts); +/*[JEC] was:# else*/ /* not __GNU_LIBRARY__ */ +/*[JEC] was:extern int getopt ();*/ +/*[JEC] was:# endif*/ /* __GNU_LIBRARY__ */ + +/*[JEC] was:# ifndef __need_getopt*/ +extern int share__getopt_long (int argc, char *const *argv, const char *shortopts, + const struct share__option *longopts, int *longind); +extern int share__getopt_long_only (int argc, char *const *argv, + const char *shortopts, + const struct share__option *longopts, int *longind); + +/* Internal only. Users should not call this directly. */ +extern int share___getopt_internal (int argc, char *const *argv, + const char *shortopts, + const struct share__option *longopts, int *longind, + int long_only); +/*[JEC] was:# endif*/ +/*[JEC] was:#else*/ /* not __STDC__ */ +/*[JEC] was:extern int getopt ();*/ +/*[JEC] was:# ifndef __need_getopt*/ +/*[JEC] was:extern int getopt_long ();*/ +/*[JEC] was:extern int getopt_long_only ();*/ + +/*[JEC] was:extern int _getopt_internal ();*/ +/*[JEC] was:# endif*/ +/*[JEC] was:#endif*/ /* __STDC__ */ + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +/*[JEC] was:#undef __need_getopt*/ + +#endif /* getopt.h */ diff --git a/flac/include/share/grabbag.h b/flac/include/share/grabbag.h new file mode 100644 index 0000000..52e6a55 --- /dev/null +++ b/flac/include/share/grabbag.h @@ -0,0 +1,29 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef SHARE__GRABBAG_H +#define SHARE__GRABBAG_H + +/* These can't be included by themselves, only from within grabbag.h */ +#include "grabbag/cuesheet.h" +#include "grabbag/file.h" +#include "grabbag/picture.h" +#include "grabbag/replaygain.h" +#include "grabbag/seektable.h" + +#endif diff --git a/flac/include/share/grabbag/Makefile.am b/flac/include/share/grabbag/Makefile.am new file mode 100644 index 0000000..a2e45de --- /dev/null +++ b/flac/include/share/grabbag/Makefile.am @@ -0,0 +1,10 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +EXTRA_DIST = \ + cuesheet.h \ + file.h \ + picture.h \ + replaygain.h \ + seektable.h diff --git a/flac/include/share/grabbag/cuesheet.h b/flac/include/share/grabbag/cuesheet.h new file mode 100644 index 0000000..55a347b --- /dev/null +++ b/flac/include/share/grabbag/cuesheet.h @@ -0,0 +1,42 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ + +#ifndef GRABBAG__CUESHEET_H +#define GRABBAG__CUESHEET_H + +#include +#include "FLAC/metadata.h" + +#ifdef __cplusplus +extern "C" { +#endif + +unsigned grabbag__cuesheet_msf_to_frame(unsigned minutes, unsigned seconds, unsigned frames); +void grabbag__cuesheet_frame_to_msf(unsigned frame, unsigned *minutes, unsigned *seconds, unsigned *frames); + +FLAC__StreamMetadata *grabbag__cuesheet_parse(FILE *file, const char **error_message, unsigned *last_line_read, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset); + +void grabbag__cuesheet_emit(FILE *file, const FLAC__StreamMetadata *cuesheet, const char *file_reference); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/share/grabbag/file.h b/flac/include/share/grabbag/file.h new file mode 100644 index 0000000..666d222 --- /dev/null +++ b/flac/include/share/grabbag/file.h @@ -0,0 +1,63 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Convenience routines for manipulating files */ + +/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ + +#ifndef GRABAG__FILE_H +#define GRABAG__FILE_H + +/* needed because of off_t */ +#if HAVE_CONFIG_H +# include +#endif + +#include /* for off_t */ +#include /* for FILE */ +#include "FLAC/ordinals.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void grabbag__file_copy_metadata(const char *srcpath, const char *destpath); +off_t grabbag__file_get_filesize(const char *srcpath); +const char *grabbag__file_get_basename(const char *srcpath); + +/* read_only == false means "make file writable by user" + * read_only == true means "make file read-only for everyone" + */ +FLAC__bool grabbag__file_change_stats(const char *filename, FLAC__bool read_only); + +/* returns true iff stat() succeeds for both files and they have the same device and inode. */ +/* on windows, uses GetFileInformationByHandle() to compare */ +FLAC__bool grabbag__file_are_same(const char *f1, const char *f2); + +/* attempts to make writable before unlinking */ +FLAC__bool grabbag__file_remove_file(const char *filename); + +/* these will forcibly set stdin/stdout to binary mode (for OSes that require it) */ +FILE *grabbag__file_get_binary_stdin(void); +FILE *grabbag__file_get_binary_stdout(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/share/grabbag/picture.h b/flac/include/share/grabbag/picture.h new file mode 100644 index 0000000..15596e7 --- /dev/null +++ b/flac/include/share/grabbag/picture.h @@ -0,0 +1,46 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ + +#ifndef GRABBAG__PICTURE_H +#define GRABBAG__PICTURE_H + +#include "FLAC/metadata.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* spec should be of the form "[TYPE]|MIME_TYPE|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE", e.g. + * "|image/jpeg|||cover.jpg" + * "4|image/jpeg||300x300x24|backcover.jpg" + * "|image/png|description|300x300x24/71|cover.png" + * "-->|image/gif||300x300x24/71|http://blah.blah.blah/cover.gif" + * + * empty type means default to FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER + * empty resolution spec means to get from the file (cannot get used with "-->" linked images) + * spec and error_message must not be NULL + */ +FLAC__StreamMetadata *grabbag__picture_parse_specification(const char *spec, const char **error_message); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/share/grabbag/replaygain.h b/flac/include/share/grabbag/replaygain.h new file mode 100644 index 0000000..16d22bc --- /dev/null +++ b/flac/include/share/grabbag/replaygain.h @@ -0,0 +1,72 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * This wraps the replaygain_analysis lib, which is LGPL. This wrapper + * allows analysis of different input resolutions by automatically + * scaling the input signal + */ + +/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ + +#ifndef GRABBAG__REPLAYGAIN_H +#define GRABBAG__REPLAYGAIN_H + +#include "FLAC/metadata.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED; + +extern const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS; /* = "REPLAYGAIN_REFERENCE_LOUDNESS" */ +extern const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN; /* = "REPLAYGAIN_TRACK_GAIN" */ +extern const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK; /* = "REPLAYGAIN_TRACK_PEAK" */ +extern const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN; /* = "REPLAYGAIN_ALBUM_GAIN" */ +extern const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK; /* = "REPLAYGAIN_ALBUM_PEAK" */ + +FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency); + +FLAC__bool grabbag__replaygain_init(unsigned sample_frequency); + +/* 'bps' must be valid for FLAC, i.e. >=4 and <= 32 */ +FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples); + +void grabbag__replaygain_get_album(float *gain, float *peak); +void grabbag__replaygain_get_title(float *gain, float *peak); + +/* These three functions return an error string on error, or NULL if successful */ +const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak); +const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak); +const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block); +const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak); +const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak); +const char *grabbag__replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak, FLAC__bool preserve_modtime); +const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime); +const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime); +const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime); + +FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak); +double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/share/grabbag/seektable.h b/flac/include/share/grabbag/seektable.h new file mode 100644 index 0000000..8bb452d --- /dev/null +++ b/flac/include/share/grabbag/seektable.h @@ -0,0 +1,38 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Convenience routines for working with seek tables */ + +/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ + +#ifndef GRABAG__SEEKTABLE_H +#define GRABAG__SEEKTABLE_H + +#include "FLAC/format.h" + +#ifdef __cplusplus +extern "C" { +#endif + +FLAC__bool grabbag__seektable_convert_specification_to_template(const char *spec, FLAC__bool only_explicit_placeholders, FLAC__uint64 total_samples_to_encode, unsigned sample_rate, FLAC__StreamMetadata *seektable_template, FLAC__bool *spec_has_real_points); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/flac/include/share/replaygain_analysis.h b/flac/include/share/replaygain_analysis.h new file mode 100644 index 0000000..ad146d3 --- /dev/null +++ b/flac/include/share/replaygain_analysis.h @@ -0,0 +1,59 @@ +/* + * ReplayGainAnalysis - analyzes input samples and give the recommended dB change + * Copyright (C) 2001 David Robinson and Glen Sawyer + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * concept and filter values by David Robinson (David@Robinson.org) + * -- blame him if you think the idea is flawed + * coding by Glen Sawyer (glensawyer@hotmail.com) 442 N 700 E, Provo, UT 84606 USA + * -- blame him if you think this runs too slowly, or the coding is otherwise flawed + * minor cosmetic tweaks to integrate with FLAC by Josh Coalson + * + * For an explanation of the concepts and the basic algorithms involved, go to: + * http://www.replaygain.org/ + */ + +#ifndef GAIN_ANALYSIS_H +#define GAIN_ANALYSIS_H + +#include + +#define GAIN_NOT_ENOUGH_SAMPLES -24601 +#define GAIN_ANALYSIS_ERROR 0 +#define GAIN_ANALYSIS_OK 1 + +#define INIT_GAIN_ANALYSIS_ERROR 0 +#define INIT_GAIN_ANALYSIS_OK 1 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef float Float_t; /* Type used for filtering */ + +extern Float_t ReplayGainReferenceLoudness; /* in dB SPL, currently == 89.0 */ + +int InitGainAnalysis ( long samplefreq ); +int AnalyzeSamples ( const Float_t* left_samples, const Float_t* right_samples, size_t num_samples, int num_channels ); +int ResetSampleFrequency ( long samplefreq ); +Float_t GetTitleGain ( void ); +Float_t GetAlbumGain ( void ); + +#ifdef __cplusplus +} +#endif + +#endif /* GAIN_ANALYSIS_H */ diff --git a/flac/include/share/replaygain_synthesis.h b/flac/include/share/replaygain_synthesis.h new file mode 100644 index 0000000..9cf39c0 --- /dev/null +++ b/flac/include/share/replaygain_synthesis.h @@ -0,0 +1,51 @@ +/* replaygain_synthesis - Routines for applying ReplayGain to a signal + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__SHARE__REPLAYGAIN_SYNTHESIS_H +#define FLAC__SHARE__REPLAYGAIN_SYNTHESIS_H + +#include /* for size_t */ +#include "FLAC/ordinals.h" + +#define FLAC_SHARE__MAX_SUPPORTED_CHANNELS 2 + +typedef enum { + NOISE_SHAPING_NONE = 0, + NOISE_SHAPING_LOW = 1, + NOISE_SHAPING_MEDIUM = 2, + NOISE_SHAPING_HIGH = 3 +} NoiseShaping; + +typedef struct { + const float* FilterCoeff; + FLAC__uint64 Mask; + double Add; + float Dither; + float ErrorHistory [FLAC_SHARE__MAX_SUPPORTED_CHANNELS] [16]; /* 16th order Noise shaping */ + float DitherHistory [FLAC_SHARE__MAX_SUPPORTED_CHANNELS] [16]; + int LastRandomNumber [FLAC_SHARE__MAX_SUPPORTED_CHANNELS]; + unsigned LastHistoryIndex; + NoiseShaping ShapingType; +} DitherContext; + +void FLAC__replaygain_synthesis__init_dither_context(DitherContext *dither, int bits, int shapingtype); + +/* scale = (float) pow(10., (double)replaygain * 0.05); */ +size_t FLAC__replaygain_synthesis__apply_gain(FLAC__byte *data_out, FLAC__bool little_endian_data_out, FLAC__bool unsigned_data_out, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, const unsigned source_bps, const unsigned target_bps, const double scale, const FLAC__bool hard_limit, FLAC__bool do_dithering, DitherContext *dither_context); + +#endif diff --git a/flac/include/share/utf8.h b/flac/include/share/utf8.h new file mode 100644 index 0000000..5b292e2 --- /dev/null +++ b/flac/include/share/utf8.h @@ -0,0 +1,25 @@ +#ifndef SHARE__UTF8_H +#define SHARE__UTF8_H + +/* + * Convert a string between UTF-8 and the locale's charset. + * Invalid bytes are replaced by '#', and characters that are + * not available in the target encoding are replaced by '?'. + * + * If the locale's charset is not set explicitly then it is + * obtained using nl_langinfo(CODESET), where available, the + * environment variable CHARSET, or assumed to be US-ASCII. + * + * Return value of conversion functions: + * + * -1 : memory allocation failed + * 0 : data was converted exactly + * 1 : valid data was converted approximately (using '?') + * 2 : input was invalid (but still converted, using '#') + * 3 : unknown encoding (but still converted, using '?') + */ + +int utf8_encode(const char *from, char **to); +int utf8_decode(const char *from, char **to); + +#endif diff --git a/flac/include/test_libs_common/Makefile.am b/flac/include/test_libs_common/Makefile.am new file mode 100644 index 0000000..fad1227 --- /dev/null +++ b/flac/include/test_libs_common/Makefile.am @@ -0,0 +1,7 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +EXTRA_DIST = \ + file_utils_flac.h \ + metadata_utils.h diff --git a/flac/include/test_libs_common/file_utils_flac.h b/flac/include/test_libs_common/file_utils_flac.h new file mode 100644 index 0000000..d7f4b25 --- /dev/null +++ b/flac/include/test_libs_common/file_utils_flac.h @@ -0,0 +1,34 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_FILE_UTILS_H +#define FLAC__TEST_LIBFLAC_FILE_UTILS_H + +/* needed because of off_t */ +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/format.h" +#include /* for off_t */ + +extern const long file_utils__ogg_serial_number; + +FLAC__bool file_utils__generate_flacfile(FLAC__bool is_ogg, const char *output_filename, off_t *output_filesize, unsigned length, const FLAC__StreamMetadata *streaminfo, FLAC__StreamMetadata **metadata, unsigned num_metadata); + +#endif diff --git a/flac/include/test_libs_common/metadata_utils.h b/flac/include/test_libs_common/metadata_utils.h new file mode 100644 index 0000000..c9a3107 --- /dev/null +++ b/flac/include/test_libs_common/metadata_utils.h @@ -0,0 +1,70 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBS_COMMON_METADATA_UTILS_H +#define FLAC__TEST_LIBS_COMMON_METADATA_UTILS_H + +/* + * These are not tests, just utility functions used by the metadata tests + */ + +#include "FLAC/format.h" + +FLAC__bool mutils__compare_block_data_streaminfo(const FLAC__StreamMetadata_StreamInfo *block, const FLAC__StreamMetadata_StreamInfo *blockcopy); + +FLAC__bool mutils__compare_block_data_padding(const FLAC__StreamMetadata_Padding *block, const FLAC__StreamMetadata_Padding *blockcopy, unsigned block_length); + +FLAC__bool mutils__compare_block_data_application(const FLAC__StreamMetadata_Application *block, const FLAC__StreamMetadata_Application *blockcopy, unsigned block_length); + +FLAC__bool mutils__compare_block_data_seektable(const FLAC__StreamMetadata_SeekTable *block, const FLAC__StreamMetadata_SeekTable *blockcopy); + +FLAC__bool mutils__compare_block_data_vorbiscomment(const FLAC__StreamMetadata_VorbisComment *block, const FLAC__StreamMetadata_VorbisComment *blockcopy); + +FLAC__bool mutils__compare_block_data_cuesheet(const FLAC__StreamMetadata_CueSheet *block, const FLAC__StreamMetadata_CueSheet *blockcopy); + +FLAC__bool mutils__compare_block_data_picture(const FLAC__StreamMetadata_Picture *block, const FLAC__StreamMetadata_Picture *blockcopy); + +FLAC__bool mutils__compare_block_data_unknown(const FLAC__StreamMetadata_Unknown *block, const FLAC__StreamMetadata_Unknown *blockcopy, unsigned block_length); + +FLAC__bool mutils__compare_block(const FLAC__StreamMetadata *block, const FLAC__StreamMetadata *blockcopy); + +void mutils__init_metadata_blocks( + FLAC__StreamMetadata *streaminfo, + FLAC__StreamMetadata *padding, + FLAC__StreamMetadata *seektable, + FLAC__StreamMetadata *application1, + FLAC__StreamMetadata *application2, + FLAC__StreamMetadata *vorbiscomment, + FLAC__StreamMetadata *cuesheet, + FLAC__StreamMetadata *picture, + FLAC__StreamMetadata *unknown +); + +void mutils__free_metadata_blocks( + FLAC__StreamMetadata *streaminfo, + FLAC__StreamMetadata *padding, + FLAC__StreamMetadata *seektable, + FLAC__StreamMetadata *application1, + FLAC__StreamMetadata *application2, + FLAC__StreamMetadata *vorbiscomment, + FLAC__StreamMetadata *cuesheet, + FLAC__StreamMetadata *picture, + FLAC__StreamMetadata *unknown +); + +#endif diff --git a/flac/m4/Makefile.am b/flac/m4/Makefile.am new file mode 100644 index 0000000..81ad52e --- /dev/null +++ b/flac/m4/Makefile.am @@ -0,0 +1,20 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + ogg.m4 \ + xmms.m4 diff --git a/flac/m4/ogg.m4 b/flac/m4/ogg.m4 new file mode 100644 index 0000000..e964a8c --- /dev/null +++ b/flac/m4/ogg.m4 @@ -0,0 +1,102 @@ +# Configure paths for libogg +# Jack Moffitt 10-21-2000 +# Shamelessly stolen from Owen Taylor and Manish Singh + +dnl XIPH_PATH_OGG([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libogg, and define OGG_CFLAGS and OGG_LIBS +dnl +AC_DEFUN([XIPH_PATH_OGG], +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(ogg,[ --with-ogg=PFX Prefix where libogg is installed (optional)], ogg_prefix="$withval", ogg_prefix="") +AC_ARG_WITH(ogg-libraries,[ --with-ogg-libraries=DIR Directory where libogg library is installed (optional)], ogg_libraries="$withval", ogg_libraries="") +AC_ARG_WITH(ogg-includes,[ --with-ogg-includes=DIR Directory where libogg header files are installed (optional)], ogg_includes="$withval", ogg_includes="") +AC_ARG_ENABLE(oggtest, [ --disable-oggtest Do not try to compile and run a test Ogg program],, enable_oggtest=yes) + + if test "x$ogg_libraries" != "x" ; then + OGG_LIBS="-L$ogg_libraries" + elif test "x$ogg_prefix" != "x" ; then + OGG_LIBS="-L$ogg_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + OGG_LIBS="-L$prefix/lib" + fi + + OGG_LIBS="$OGG_LIBS -logg" + + if test "x$ogg_includes" != "x" ; then + OGG_CFLAGS="-I$ogg_includes" + elif test "x$ogg_prefix" != "x" ; then + OGG_CFLAGS="-I$ogg_prefix/include" + elif test "x$prefix" != "xNONE"; then + OGG_CFLAGS="-I$prefix/include" + fi + + AC_MSG_CHECKING(for Ogg) + no_ogg="" + + + if test "x$enable_oggtest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $OGG_CFLAGS" + LIBS="$LIBS $OGG_LIBS" +dnl +dnl Now check if the installed Ogg is sufficiently new. +dnl + rm -f conf.oggtest + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.oggtest"); + return 0; +} + +],, no_ogg=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + + if test "x$no_ogg" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.oggtest ; then + : + else + echo "*** Could not run Ogg test program, checking why..." + CFLAGS="$CFLAGS $OGG_CFLAGS" + LIBS="$LIBS $OGG_LIBS" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding Ogg or finding the wrong" + echo "*** version of Ogg. If it is not finding Ogg, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means Ogg was incorrectly installed" + echo "*** or that you have moved Ogg since it was installed." ]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + OGG_CFLAGS="" + OGG_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(OGG_CFLAGS) + AC_SUBST(OGG_LIBS) + rm -f conf.oggtest +]) diff --git a/flac/m4/xmms.m4 b/flac/m4/xmms.m4 new file mode 100644 index 0000000..62d31a8 --- /dev/null +++ b/flac/m4/xmms.m4 @@ -0,0 +1,148 @@ +# CFLAGS and library paths for XMMS +# written 15 December 1999 by Ben Gertzfield + +dnl Usage: +dnl AM_PATH_XMMS([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]]) +dnl +dnl Example: +dnl AM_PATH_XMMS(0.9.5.1, , AC_MSG_ERROR([*** XMMS >= 0.9.5.1 not installed - please install first ***])) +dnl +dnl Defines XMMS_CFLAGS, XMMS_LIBS, XMMS_DATA_DIR, XMMS_PLUGIN_DIR, +dnl XMMS_VISUALIZATION_PLUGIN_DIR, XMMS_INPUT_PLUGIN_DIR, +dnl XMMS_OUTPUT_PLUGIN_DIR, XMMS_GENERAL_PLUGIN_DIR, XMMS_EFFECT_PLUGIN_DIR, +dnl and XMMS_VERSION for your plugin pleasure. +dnl + +dnl XMMS_TEST_VERSION(AVAILABLE-VERSION, NEEDED-VERSION [, ACTION-IF-OKAY [, ACTION-IF-NOT-OKAY]]) +AC_DEFUN([XMMS_TEST_VERSION], [ + +# Determine which version number is greater. Prints 2 to stdout if +# the second number is greater, 1 if the first number is greater, +# 0 if the numbers are equal. + +# Written 15 December 1999 by Ben Gertzfield +# Revised 15 December 1999 by Jim Monty + + AC_PROG_AWK + xmms_got_version=[` $AWK ' \ +BEGIN { \ + print vercmp(ARGV[1], ARGV[2]); \ +} \ + \ +function vercmp(ver1, ver2, ver1arr, ver2arr, \ + ver1len, ver2len, \ + ver1int, ver2int, len, i, p) { \ + \ + ver1len = split(ver1, ver1arr, /\./); \ + ver2len = split(ver2, ver2arr, /\./); \ + \ + len = ver1len > ver2len ? ver1len : ver2len; \ + \ + for (i = 1; i <= len; i++) { \ + p = 1000 ^ (len - i); \ + ver1int += ver1arr[i] * p; \ + ver2int += ver2arr[i] * p; \ + } \ + \ + if (ver1int < ver2int) \ + return 2; \ + else if (ver1int > ver2int) \ + return 1; \ + else \ + return 0; \ +}' $1 $2`] + + if test $xmms_got_version -eq 2; then # failure + ifelse([$4], , :, $4) + else # success! + ifelse([$3], , :, $3) + fi +]) + +AC_DEFUN([AM_PATH_XMMS], +[ +AC_ARG_WITH(xmms-prefix,[ --with-xmms-prefix=PFX Prefix where XMMS is installed (optional)], + xmms_config_prefix="$withval", xmms_config_prefix="") +AC_ARG_WITH(xmms-exec-prefix,[ --with-xmms-exec-prefix=PFX Exec prefix where XMMS is installed (optional)], + xmms_config_exec_prefix="$withval", xmms_config_exec_prefix="") + +if test x$xmms_config_exec_prefix != x; then + xmms_config_args="$xmms_config_args --exec-prefix=$xmms_config_exec_prefix" + if test x${XMMS_CONFIG+set} != xset; then + XMMS_CONFIG=$xmms_config_exec_prefix/bin/xmms-config + fi +fi + +if test x$xmms_config_prefix != x; then + xmms_config_args="$xmms_config_args --prefix=$xmms_config_prefix" + if test x${XMMS_CONFIG+set} != xset; then + XMMS_CONFIG=$xmms_config_prefix/bin/xmms-config + fi +fi + +AC_PATH_PROG(XMMS_CONFIG, xmms-config, no) +min_xmms_version=ifelse([$1], ,0.9.5.1, $1) + +if test "$XMMS_CONFIG" = "no"; then + no_xmms=yes +else + XMMS_CFLAGS=`$XMMS_CONFIG $xmms_config_args --cflags` + XMMS_LIBS=`$XMMS_CONFIG $xmms_config_args --libs` + XMMS_VERSION=`$XMMS_CONFIG $xmms_config_args --version` + XMMS_DATA_DIR=`$XMMS_CONFIG $xmms_config_args --data-dir` + XMMS_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args --plugin-dir` + XMMS_VISUALIZATION_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args \ + --visualization-plugin-dir` + XMMS_INPUT_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args --input-plugin-dir` + XMMS_OUTPUT_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args --output-plugin-dir` + XMMS_EFFECT_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args --effect-plugin-dir` + XMMS_GENERAL_PLUGIN_DIR=`$XMMS_CONFIG $xmms_config_args --general-plugin-dir` + + XMMS_TEST_VERSION($XMMS_VERSION, $min_xmms_version, ,no_xmms=version) +fi + +AC_MSG_CHECKING(for XMMS - version >= $min_xmms_version) + +if test "x$no_xmms" = x; then + AC_MSG_RESULT(yes) + ifelse([$2], , :, [$2]) +else + AC_MSG_RESULT(no) + + if test "$XMMS_CONFIG" = "no" ; then + echo "*** The xmms-config script installed by XMMS could not be found." + echo "*** If XMMS was installed in PREFIX, make sure PREFIX/bin is in" + echo "*** your path, or set the XMMS_CONFIG environment variable to the" + echo "*** full path to xmms-config." + else + if test "$no_xmms" = "version"; then + echo "*** An old version of XMMS, $XMMS_VERSION, was found." + echo "*** You need a version of XMMS newer than $min_xmms_version." + echo "*** The latest version of XMMS is always available from" + echo "*** http://www.xmms.org/" + echo "***" + + echo "*** If you have already installed a sufficiently new version, this error" + echo "*** probably means that the wrong copy of the xmms-config shell script is" + echo "*** being found. The easiest way to fix this is to remove the old version" + echo "*** of XMMS, but you can also set the XMMS_CONFIG environment to point to the" + echo "*** correct copy of xmms-config. (In this case, you will have to" + echo "*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf" + echo "*** so that the correct libraries are found at run-time)" + fi + fi + XMMS_CFLAGS="" + XMMS_LIBS="" + ifelse([$3], , :, [$3]) +fi +AC_SUBST(XMMS_CFLAGS) +AC_SUBST(XMMS_LIBS) +AC_SUBST(XMMS_VERSION) +AC_SUBST(XMMS_DATA_DIR) +AC_SUBST(XMMS_PLUGIN_DIR) +AC_SUBST(XMMS_VISUALIZATION_PLUGIN_DIR) +AC_SUBST(XMMS_INPUT_PLUGIN_DIR) +AC_SUBST(XMMS_OUTPUT_PLUGIN_DIR) +AC_SUBST(XMMS_GENERAL_PLUGIN_DIR) +AC_SUBST(XMMS_EFFECT_PLUGIN_DIR) +]) diff --git a/flac/man/Makefile.am b/flac/man/Makefile.am new file mode 100644 index 0000000..895617e --- /dev/null +++ b/flac/man/Makefile.am @@ -0,0 +1,35 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +if FLaC__HAS_DOCBOOK_TO_MAN +flac.1: flac.sgml + docbook-to-man $? > $@ || (docbook2man $? && mv FLAC.1 $@) + +metaflac.1: metaflac.sgml + docbook-to-man $? > $@ || (docbook2man $? && mv METAFLAC.1 $@) +else +flac.1: + echo "*** Warning: docbook-to-man not found; man pages will not be built." + touch $@ + +metaflac.1: + touch $@ +endif + +man_MANS = flac.1 metaflac.1 + +EXTRA_DIST = $(man_MANS) flac.sgml metaflac.sgml diff --git a/flac/man/flac.1 b/flac/man/flac.1 new file mode 100644 index 0000000..dbcafd0 --- /dev/null +++ b/flac/man/flac.1 @@ -0,0 +1,331 @@ +.\" This manpage has been automatically generated by docbook2man +.\" from a DocBook document. This tool can be found at: +.\" +.\" Please send any bug reports, improvements, comments, patches, +.\" etc. to Steve Cheng . +.TH "FLAC" "1" "14 September 2007" "" "" + +.SH NAME +flac \- Free Lossless Audio Codec +.SH SYNOPSIS + +\fBflac\fR [ \fB\fIOPTIONS\fB\fR ] [ \fB\fIinfile.wav\fB\fR | \fB\fIinfile.aiff\fB\fR | \fB\fIinfile.raw\fB\fR | \fB\fIinfile.flac\fB\fR | \fB\fIinfile.oga\fB\fR | \fB\fIinfile.ogg\fB\fR | \fB-\fR\fI ...\fR ] + + +\fBflac\fR [ \fB-d\fR | \fB--decode\fR | \fB-t\fR | \fB--test\fR | \fB-a\fR | \fB--analyze\fR ] [ \fB\fIOPTIONS\fB\fR ] [ \fB\fIinfile.flac\fB\fR | \fB\fIinfile.oga\fB\fR | \fB\fIinfile.ogg\fB\fR | \fB-\fR\fI ...\fR ] + +.SH "DESCRIPTION" +.PP +\fBflac\fR is a command-line tool for encoding, decoding, testing and analyzing FLAC streams. +.SH "OPTIONS" +.PP +A summary of options is included below. For a complete +description, see the HTML documentation. +.SS "GENERAL OPTIONS" +.TP +\fB-v, --version\fR +Show the flac version number +.TP +\fB-h, --help \fR +Show basic usage and a list of all options +.TP +\fB-H, --explain \fR +Show detailed explanation of usage and all options +.TP +\fB-d, --decode \fR +Decode (the default behavior is to encode) +.TP +\fB-t, --test \fR +Test a flac encoded file (same as -d except no decoded file is written) +.TP +\fB-a, --analyze \fR +Analyze a FLAC encoded file (same as -d except an analysis file is written) +.TP +\fB-c, --stdout \fR +Write output to stdout +.TP +\fB-s, --silent \fR +Silent mode (do not write runtime encode/decode statistics to stderr) +.TP +\fB--totally-silent \fR +Do not print anything of any kind, including warnings or errors. The exit code will be the only way to determine successful completion. +.TP +\fB--no-utf8-convert \fR +Do not convert tags from local charset to UTF-8. This is useful for scripts, and setting tags in situations where the locale is wrong. This option must appear before any tag options! +.TP +\fB-w, --warnings-as-errors \fR +Treat all warnings as errors (which cause flac to terminate with a non-zero exit code). +.TP +\fB-f, --force \fR +Force overwriting of output files. By default, flac warns that the output file already exists and continues to the next file. +.TP +\fB-o \fIfilename\fB, --output-name=\fIfilename\fB\fR +Force the output file name (usually flac just changes the extension). May only be used when encoding a single file. May not be used in conjunction with --output-prefix. +.TP +\fB--output-prefix=\fIstring\fB\fR +Prefix each output file name with the given string. This can be useful for encoding or decoding files to a different directory. Make sure if your string is a path name that it ends with a trailing `/' (slash). +.TP +\fB--delete-input-file \fR +Automatically delete the input file after a successful encode or decode. If there was an error (including a verify error) the input file is left intact. +.TP +\fB--keep-foreign-metadata \fR +If encoding, save WAVE or AIFF non-audio chunks in FLAC metadata. If decoding, restore any saved non-audio chunks from FLAC metadata when writing the decoded file. Foreign metadata cannot be transcoded, e.g. WAVE chunks saved in a FLAC file cannot be restored when decoding to AIFF. Input and output must be regular files (not stdin or stdout). +.TP +\fB--skip={\fI#\fB|\fImm:ss.ss\fB}\fR +Skip over the first number of samples of the input. This works for both encoding and decoding, but not testing. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second. +.TP +\fB--until={\fI#\fB|[\fI+\fB|\fI-\fB]\fImm:ss.ss\fB}\fR +Stop at the given sample number for each input file. This works for both encoding and decoding, but not testing. The given sample number is not included in the decoded output. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second. If a `+' (plus) sign is at the beginning, the --until point is relative to the --skip point. If a `-' (minus) sign is at the beginning, the --until point is relative to end of the audio. +.TP +\fB--ogg\fR +When encoding, generate Ogg FLAC output instead of native FLAC. Ogg FLAC streams are FLAC streams wrapped in an Ogg transport layer. The resulting file should have an '.oga' extension and will still be decodable by flac. + +When decoding, force the input to be treated as Ogg FLAC. This is useful when piping input from stdin or when the filename does not end in '.oga' or '.ogg'. +.TP +\fB--serial-number=\fI#\fB\fR +When used with --ogg, specifies the serial number to use for the first Ogg FLAC stream, which is then incremented for each additional stream. When encoding and no serial number is given, flac uses a random number for the first stream, then increments it for each additional stream. When decoding and no number is given, flac uses the serial number of the first page. +.SS "ANALYSIS OPTIONS" +.TP +\fB--residual-text \fR +Includes the residual signal in the analysis file. This will make the file very big, much larger than even the decoded file. +.TP +\fB--residual-gnuplot \fR +Generates a gnuplot file for every subframe; each file will contain the residual distribution of the subframe. This will create a lot of files. +.SS "DECODING OPTIONS" +.TP +\fB--cue=[\fI#.#\fB][-[\fI#.#\fB]]\fR +Set the beginning and ending cuepoints to decode. The optional first #.# is the track and index point at which decoding will start; the default is the beginning of the stream. The optional second #.# is the track and index point at which decoding will end; the default is the end of the stream. If the cuepoint does not exist, the closest one before it (for the start point) or after it (for the end point) will be used. If those don't exist, the start of the stream (for the start point) or end of the stream (for the end point) will be used. The cuepoints are merely translated into sample numbers then used as --skip and --until. A CD track can always be cued by, for example, --cue=9.1-10.1 for track 9, even if the CD has no 10th track. +.TP +\fB-F, --decode-through-errors \fR +By default flac stops decoding with an error and removes the partially decoded file if it encounters a bitstream error. With -F, errors are still printed but flac will continue decoding to completion. Note that errors may cause the decoded audio to be missing some samples or have silent sections. +.SS "ENCODING OPTIONS" +.TP +\fB-V, --verify\fR +Verify a correct encoding by decoding the output in parallel and comparing to the original +.TP +\fB--lax\fR +Allow encoder to generate non-Subset files. The resulting FLAC file may not be streamable or might have trouble being played in all players (especially hardware devices), so you should only use this option in combination with custom encoding options meant for archival. +.TP +\fB--replay-gain\fR +Calculate ReplayGain values and store them as FLAC tags, similar to vorbisgain. Title gains/peaks will be computed for each input file, and an album gain/peak will be computed for all files. All input files must have the same resolution, sample rate, and number of channels. Only mono and stereo files are allowed, and the sample rate must be one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1, or 48 kHz. Also note that this option may leave a few extra bytes in a PADDING block as the exact size of the tags is not known until all files are processed. Note that this option cannot be used when encoding to standard output (stdout). +.TP +\fB--cuesheet=\fIfilename\fB\fR +Import the given cuesheet file and store it in a CUESHEET metadata block. This option may only be used when encoding a single file. A seekpoint will be added for each index point in the cuesheet to the SEEKTABLE unless --no-cued-seekpoints is specified. +.TP +\fB--picture={\fIFILENAME\fB|\fISPECIFICATION\fB}\fR +Import a picture and store it in a PICTURE metadata block. More than one --picture command can be specified. Either a filename for the picture file or a more complete specification form can be used. The SPECIFICATION is a string whose parts are separated by | (pipe) characters. Some parts may be left empty to invoke default values. FILENAME is just shorthand for "||||FILENAME". The format of SPECIFICATION is + +[TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE + +TYPE is optional; it is a number from one of: + +0: Other + +1: 32x32 pixels 'file icon' (PNG only) + +2: Other file icon + +3: Cover (front) + +4: Cover (back) + +5: Leaflet page + +6: Media (e.g. label side of CD) + +7: Lead artist/lead performer/soloist + +8: Artist/performer + +9: Conductor + +10: Band/Orchestra + +11: Composer + +12: Lyricist/text writer + +13: Recording Location + +14: During recording + +15: During performance + +16: Movie/video screen capture + +17: A bright coloured fish + +18: Illustration + +19: Band/artist logotype + +20: Publisher/Studio logotype + +The default is 3 (front cover). There may only be one picture each of type 1 and 2 in a file. + +MIME-TYPE is optional; if left blank, it will be detected from the file. For best compatibility with players, use pictures with MIME type image/jpeg or image/png. The MIME type can also be --> to mean that FILE is actually a URL to an image, though this use is discouraged. + +DESCRIPTION is optional; the default is an empty string. + +The next part specfies the resolution and color information. If the MIME-TYPE is image/jpeg, image/png, or image/gif, you can usually leave this empty and they can be detected from the file. Otherwise, you must specify the width in pixels, height in pixels, and color depth in bits-per-pixel. If the image has indexed colors you should also specify the number of colors used. When manually specified, it is not checked against the file for accuracy. + +FILE is the path to the picture file to be imported, or the URL if MIME type is --> + +For example, "|image/jpeg|||../cover.jpg" will embed the JPEG file at ../cover.jpg, defaulting to type 3 (front cover) and an empty description. The resolution and color info will be retrieved from the file itself. + +The specification "4|-->|CD|320x300x24/173|http://blah.blah/backcover.tiff" will embed the given URL, with type 4 (back cover), description "CD", and a manually specified resolution of 320x300, 24 bits-per-pixel, and 173 colors. The file at the URL will not be fetched; the URL itself is stored in the PICTURE metadata block. +.TP +\fB--sector-align\fR +Align encoding of multiple CD format files on sector boundaries. See the HTML documentation for more information. +.TP +\fB-S {\fI#\fB|\fIX\fB|\fI#x\fB|\fI#s\fB}, --seekpoint={\fI#\fB|\fIX\fB|\fI#x\fB|\fI#s\fB}\fR +Include a point or points in a SEEKTABLE. Using #, a seek point at that sample number is added. Using X, a placeholder point is added at the end of a the table. Using #x, # evenly spaced seek points will be added, the first being at sample 0. Using #s, a seekpoint will be added every # seconds (# does not have to be a whole number; it can be, for example, 9.5, meaning a seekpoint every 9.5 seconds). You may use many -S options; the resulting SEEKTABLE will be the unique-ified union of all such values. With no -S options, flac defaults to '-S 10s'. Use --no-seektable for no SEEKTABLE. Note: '-S #x' and '-S #s' will not work if the encoder can't determine the input size before starting. Note: if you use '-S #' and # is >= samples in the input, there will be either no seek point entered (if the input size is determinable before encoding starts) or a placeholder point (if input size is not determinable). +.TP +\fB-P \fI#\fB, --padding=\fI#\fB\fR +Tell the encoder to write a PADDING metadata block of the given length (in bytes) after the STREAMINFO block. This is useful if you plan to tag the file later with an APPLICATION block; instead of having to rewrite the entire file later just to insert your block, you can write directly over the PADDING block. Note that the total length of the PADDING block will be 4 bytes longer than the length given because of the 4 metadata block header bytes. You can force no PADDING block at all to be written with --no-padding. The encoder writes a PADDING block of 8192 bytes by default (or 65536 bytes if the input audio stream is more that 20 minutes long). +.TP +\fB-T \fIFIELD=VALUE\fB, --tag=\fIFIELD=VALUE\fB\fR +Add a FLAC tag. The comment must adhere to the Vorbis comment spec; i.e. the FIELD must contain only legal characters, terminated by an 'equals' sign. Make sure to quote the comment if necessary. This option may appear more than once to add several comments. NOTE: all tags will be added to all encoded files. +.TP +\fB--tag-from-file=\fIFIELD=FILENAME\fB\fR +Like --tag, except FILENAME is a file whose contents will be read verbatim to set the tag value. The contents will be converted to UTF-8 from the local charset. This can be used to store a cuesheet in a tag (e.g. --tag-from-file="CUESHEET=image.cue"). Do not try to store binary data in tag fields! Use APPLICATION blocks for that. +.TP +\fB-b \fI#\fB, --blocksize=\fI#\fB\fR +Specify the block size in samples. Subset streams must use one of 192, 576, 1152, 2304, 4608, 256, 512, 1024, 2048, 4096 (and 8192 or 16384 if the sample rate is >48kHz). +.TP +\fB-m, --mid-side\fR +Try mid-side coding for each frame (stereo input only) +.TP +\fB-M, --adaptive-mid-side\fR +Adaptive mid-side coding for all frames (stereo input only) +.TP +\fB-0\&..-8, --compression-level-0\&..--compression-level-8\fR +Fastest compression..highest compression (default is -5). These are synonyms for other options: +.RS +.TP +\fB-0, --compression-level-0\fR +Synonymous with -l 0 -b 1152 -r 3 +.TP +\fB-1, --compression-level-1\fR +Synonymous with -l 0 -b 1152 -M -r 3 +.TP +\fB-2, --compression-level-2\fR +Synonymous with -l 0 -b 1152 -m -r 3 +.TP +\fB-3, --compression-level-3\fR +Synonymous with -l 6 -b 4096 -r 4 +.TP +\fB-4, --compression-level-4\fR +Synonymous with -l 8 -b 4096 -M -r 4 +.TP +\fB-5, --compression-level-5\fR +Synonymous with -l 8 -b 4096 -m -r 5 +.TP +\fB-6, --compression-level-6\fR +Synonymous with -l 8 -b 4096 -m -r 6 +.TP +\fB-7, --compression-level-7\fR +Synonymous with -l 8 -b 4096 -m -e -r 6 +.TP +\fB-8, --compression-level-8\fR +Synonymous with -l 12 -b 4096 -m -e -r 6 +.RE +.TP +\fB--fast\fR +Fastest compression. Currently synonymous with -0. +.TP +\fB--best\fR +Highest compression. Currently synonymous with -8. +.TP +\fB-e, --exhaustive-model-search\fR +Do exhaustive model search (expensive!) +.TP +\fB-A \fIfunction\fB, --apodization=\fIfunction\fB\fR +Window audio data with given the apodization function. The functions are: bartlett, bartlett_hann, blackman, blackman_harris_4term_92db, connes, flattop, gauss(STDDEV), hamming, hann, kaiser_bessel, nuttall, rectangle, triangle, tukey(P), welch. + +For gauss(STDDEV), STDDEV is the standard deviation (0 let encoder decide (min is 5, default is 0) +.TP +\fB-r [\fI#\fB,]\fI#\fB, --rice-partition-order=[\fI#\fB,]\fI#\fB\fR +Set the [min,]max residual partition order (0..16). min defaults to 0 if unspecified. Default is -r 5. +.SS "FORMAT OPTIONS" +.TP +\fB--endian={\fIbig\fB|\fIlittle\fB}\fR +Set the byte order for samples +.TP +\fB--channels=\fI#\fB\fR +Set number of channels. +.TP +\fB--bps=\fI#\fB\fR +Set bits per sample. +.TP +\fB--sample-rate=\fI#\fB\fR +Set sample rate (in Hz). +.TP +\fB--sign={\fIsigned\fB|\fIunsigned\fB}\fR +Set the sign of samples (the default is signed). +.TP +\fB--input-size=\fI#\fB\fR +Specify the size of the raw input in bytes. If you are encoding raw samples from stdin, you must set this option in order to be able to use --skip, --until, --cue-sheet, or other options that need to know the size of the input beforehand. If the size given is greater than what is found in the input stream, the encoder will complain about an unexpected end-of-file. If the size given is less, samples will be truncated. +.TP +\fB--force-aiff-format\fR +Force the decoder to output AIFF format. This option is not needed if the output filename (as set by -o) ends with \fI\&.aiff\fR\&. Also, this option has no effect when encoding since input AIFF is auto-detected. +.TP +\fB--force-raw-format\fR +Force input (when encoding) or output (when decoding) to be treated as raw samples (even if filename ends in \fI\&.wav\fR). +.SS "NEGATIVE OPTIONS" +.TP +\fB--no-adaptive-mid-side\fR +.TP +\fB--no-decode-through-errors\fR +.TP +\fB--no-delete-input-file\fR +.TP +\fB--no-exhaustive-model-search\fR +.TP +\fB--no-lax\fR +.TP +\fB--no-mid-side\fR +.TP +\fB--no-ogg\fR +.TP +\fB--no-padding\fR +.TP +\fB--no-qlp-coeff-precision-search\fR +.TP +\fB--no-residual-gnuplot\fR +.TP +\fB--no-residual-text\fR +.TP +\fB--no-sector-align\fR +.TP +\fB--no-seektable\fR +.TP +\fB--no-silent\fR +.TP +\fB--no-verify\fR +.TP +\fB--no-warnings-as-errors\fR +These flags can be used to invert the sense of the corresponding normal option. +.SH "SEE ALSO" +.PP +metaflac(1). +.PP +The programs are documented fully by HTML format documentation, available in \fI/usr/share/doc/flac/html\fR on Debian GNU/Linux systems. +.SH "AUTHOR" +.PP +This manual page was written by Matt Zimmerman for the Debian GNU/Linux system (but may be used by others). diff --git a/flac/man/flac.sgml b/flac/man/flac.sgml new file mode 100644 index 0000000..497848f --- /dev/null +++ b/flac/man/flac.sgml @@ -0,0 +1,754 @@ + + Matt"> + Zimmerman"> + + Nov 4, 2006"> + + 1"> + mdz@debian.org"> + + FLAC"> + + + Debian GNU/Linux"> + GNU"> +]> + + + +
      + &dhemail; +
      + + &dhfirstname; + &dhsurname; + + + 2002,2003,2004,2005 + &dhusername; + + &dhdate; +
      + + &dhucpackage; + + &dhsection; + + + &dhpackage; + + Free Lossless Audio Codec + + + + flac + OPTIONS + + infile.wav + infile.rf64 + infile.aiff + infile.raw + infile.flac + infile.oga + infile.ogg + - + + + + flac + + -d --decode + -t --test + -a --analyze + + OPTIONS + + infile.flac + infile.oga + infile.ogg + - + + + + + DESCRIPTION + + flac is a command-line tool for encoding, decoding, testing and analyzing FLAC streams. + + + + OPTIONS + + A summary of options is included below. For a complete + description, see the HTML documentation. + + + General Options + + + + , + + Show the flac version number + + + + + , + + + Show basic usage and a list of all options + + + + + , + + + Show detailed explanation of usage and all options + + + + + , + + + Decode (the default behavior is to encode) + + + + + , + + + Test a flac encoded file (same as -d except no decoded file is written) + + + + + , + + + Analyze a FLAC encoded file (same as -d except an analysis file is written) + + + + + , + + + Write output to stdout + + + + + , + + + Silent mode (do not write runtime encode/decode statistics to stderr) + + + + + + + + Do not print anything of any kind, including warnings or errors. The exit code will be the only way to determine successful completion. + + + + + + + + Do not convert tags from local charset to UTF-8. This is useful for scripts, and setting tags in situations where the locale is wrong. This option must appear before any tag options! + + + + + , + + + Treat all warnings as errors (which cause flac to terminate with a non-zero exit code). + + + + + , + + + Force overwriting of output files. By default, flac warns that the output file already exists and continues to the next file. + + + + + filename, =filename + + Force the output file name (usually flac just changes the extension). May only be used when encoding a single file. May not be used in conjunction with --output-prefix. + + + + + =string + + Prefix each output file name with the given string. This can be useful for encoding or decoding files to a different directory. Make sure if your string is a path name that it ends with a trailing `/' (slash). + + + + + + + + Automatically delete the input file after a successful encode or decode. If there was an error (including a verify error) the input file is left intact. + + + + + + + + Output files have their timestamps/permissions set to match those of their inputs (this is default). Use --no-preserve-modtime to make output files have the current time and default permissions. + + + + + + + + If encoding, save WAVE, RF64, or AIFF non-audio chunks in FLAC metadata. If decoding, restore any saved non-audio chunks from FLAC metadata when writing the decoded file. Foreign metadata cannot be transcoded, e.g. WAVE chunks saved in a FLAC file cannot be restored when decoding to AIFF. Input and output must be regular files (not stdin or stdout). + + + + + ={#|mm:ss.ss} + + Skip over the first number of samples of the input. This works for both encoding and decoding, but not testing. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second. + + + + + ={#|[+|-]mm:ss.ss} + + Stop at the given sample number for each input file. This works for both encoding and decoding, but not testing. The given sample number is not included in the decoded output. The alternative form mm:ss.ss can be used to specify minutes, seconds, and fractions of a second. If a `+' (plus) sign is at the beginning, the --until point is relative to the --skip point. If a `-' (minus) sign is at the beginning, the --until point is relative to end of the audio. + + + + + + + + When encoding, generate Ogg FLAC output instead of native FLAC. Ogg FLAC streams are FLAC streams wrapped in an Ogg transport layer. The resulting file should have an '.oga' extension and will still be decodable by flac. + When decoding, force the input to be treated as Ogg FLAC. This is useful when piping input from stdin or when the filename does not end in '.oga' or '.ogg'. + + + + + =# + + + When used with --ogg, specifies the serial number to use for the first Ogg FLAC stream, which is then incremented for each additional stream. When encoding and no serial number is given, flac uses a random number for the first stream, then increments it for each additional stream. When decoding and no number is given, flac uses the serial number of the first page. + + + + + + + + Analysis Options + + + + + + + Includes the residual signal in the analysis file. This will make the file very big, much larger than even the decoded file. + + + + + + + + Generates a gnuplot file for every subframe; each file will contain the residual distribution of the subframe. This will create a lot of files. + + + + + + + + Decoding Options + + + + + + Set the beginning and ending cuepoints to decode. The optional first #.# is the track and index point at which decoding will start; the default is the beginning of the stream. The optional second #.# is the track and index point at which decoding will end; the default is the end of the stream. If the cuepoint does not exist, the closest one before it (for the start point) or after it (for the end point) will be used. If those don't exist, the start of the stream (for the start point) or end of the stream (for the end point) will be used. The cuepoints are merely translated into sample numbers then used as --skip and --until. A CD track can always be cued by, for example, --cue=9.1-10.1 for track 9, even if the CD has no 10th track. + + + + + , + + + By default flac stops decoding with an error and removes the partially decoded file if it encounters a bitstream error. With -F, errors are still printed but flac will continue decoding to completion. Note that errors may cause the decoded audio to be missing some samples or have silent sections. + + + + + + + + Encoding Options + + + + , + + + Verify a correct encoding by decoding the output in parallel and comparing to the original + + + + + + + + Allow encoder to generate non-Subset files. The resulting FLAC file may not be streamable or might have trouble being played in all players (especially hardware devices), so you should only use this option in combination with custom encoding options meant for archival. + + + + + + + + Calculate ReplayGain values and store them as FLAC tags, similar to vorbisgain. Title gains/peaks will be computed for each input file, and an album gain/peak will be computed for all files. All input files must have the same resolution, sample rate, and number of channels. Only mono and stereo files are allowed, and the sample rate must be one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1, or 48 kHz. Also note that this option may leave a few extra bytes in a PADDING block as the exact size of the tags is not known until all files are processed. Note that this option cannot be used when encoding to standard output (stdout). + + + + + =filename + + + Import the given cuesheet file and store it in a CUESHEET metadata block. This option may only be used when encoding a single file. A seekpoint will be added for each index point in the cuesheet to the SEEKTABLE unless --no-cued-seekpoints is specified. + + + + + ={FILENAME|SPECIFICATION} + + + Import a picture and store it in a PICTURE metadata block. More than one --picture command can be specified. Either a filename for the picture file or a more complete specification form can be used. The SPECIFICATION is a string whose parts are separated by | (pipe) characters. Some parts may be left empty to invoke default values. FILENAME is just shorthand for "||||FILENAME". The format of SPECIFICATION is + [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE + TYPE is optional; it is a number from one of: + 0: Other + 1: 32x32 pixels 'file icon' (PNG only) + 2: Other file icon + 3: Cover (front) + 4: Cover (back) + 5: Leaflet page + 6: Media (e.g. label side of CD) + 7: Lead artist/lead performer/soloist + 8: Artist/performer + 9: Conductor + 10: Band/Orchestra + 11: Composer + 12: Lyricist/text writer + 13: Recording Location + 14: During recording + 15: During performance + 16: Movie/video screen capture + 17: A bright coloured fish + 18: Illustration + 19: Band/artist logotype + 20: Publisher/Studio logotype + The default is 3 (front cover). There may only be one picture each of type 1 and 2 in a file. + + MIME-TYPE is optional; if left blank, it will be detected from the file. For best compatibility with players, use pictures with MIME type image/jpeg or image/png. The MIME type can also be --> to mean that FILE is actually a URL to an image, though this use is discouraged. + + DESCRIPTION is optional; the default is an empty string. + + The next part specfies the resolution and color information. If the MIME-TYPE is image/jpeg, image/png, or image/gif, you can usually leave this empty and they can be detected from the file. Otherwise, you must specify the width in pixels, height in pixels, and color depth in bits-per-pixel. If the image has indexed colors you should also specify the number of colors used. When manually specified, it is not checked against the file for accuracy. + + FILE is the path to the picture file to be imported, or the URL if MIME type is --> + + For example, "|image/jpeg|||../cover.jpg" will embed the JPEG file at ../cover.jpg, defaulting to type 3 (front cover) and an empty description. The resolution and color info will be retrieved from the file itself. + + The specification "4|-->|CD|320x300x24/173|http://blah.blah/backcover.tiff" will embed the given URL, with type 4 (back cover), description "CD", and a manually specified resolution of 320x300, 24 bits-per-pixel, and 173 colors. The file at the URL will not be fetched; the URL itself is stored in the PICTURE metadata block. + + + + + + + + Align encoding of multiple CD format files on sector boundaries. See the HTML documentation for more information. This option is DEPRECATED and may not exist in future versions of flac. + + + + + {#|X|#x|#s}, ={#|X|#x|#s} + + + Include a point or points in a SEEKTABLE. Using #, a seek point at that sample number is added. Using X, a placeholder point is added at the end of a the table. Using #x, # evenly spaced seek points will be added, the first being at sample 0. Using #s, a seekpoint will be added every # seconds (# does not have to be a whole number; it can be, for example, 9.5, meaning a seekpoint every 9.5 seconds). You may use many -S options; the resulting SEEKTABLE will be the unique-ified union of all such values. With no -S options, flac defaults to '-S 10s'. Use --no-seektable for no SEEKTABLE. Note: '-S #x' and '-S #s' will not work if the encoder can't determine the input size before starting. Note: if you use '-S #' and # is >= samples in the input, there will be either no seek point entered (if the input size is determinable before encoding starts) or a placeholder point (if input size is not determinable). + + + + + #, =# + + + Tell the encoder to write a PADDING metadata block of the given length (in bytes) after the STREAMINFO block. This is useful if you plan to tag the file later with an APPLICATION block; instead of having to rewrite the entire file later just to insert your block, you can write directly over the PADDING block. Note that the total length of the PADDING block will be 4 bytes longer than the length given because of the 4 metadata block header bytes. You can force no PADDING block at all to be written with --no-padding. The encoder writes a PADDING block of 8192 bytes by default (or 65536 bytes if the input audio stream is more that 20 minutes long). + + + + + FIELD=VALUE, =FIELD=VALUE + + + Add a FLAC tag. The comment must adhere to the Vorbis comment spec; i.e. the FIELD must contain only legal characters, terminated by an 'equals' sign. Make sure to quote the comment if necessary. This option may appear more than once to add several comments. NOTE: all tags will be added to all encoded files. + + + + + =FIELD=FILENAME + + + Like --tag, except FILENAME is a file whose contents will be read verbatim to set the tag value. The contents will be converted to UTF-8 from the local charset. This can be used to store a cuesheet in a tag (e.g. --tag-from-file="CUESHEET=image.cue"). Do not try to store binary data in tag fields! Use APPLICATION blocks for that. + + + + + #, =# + + + Specify the block size in samples. Subset streams must use one of 192, 576, 1152, 2304, 4608, 256, 512, 1024, 2048, 4096 (and 8192 or 16384 if the sample rate is >48kHz). + + + + + , + + + Try mid-side coding for each frame (stereo input only) + + + + + , + + + Adaptive mid-side coding for all frames (stereo input only) + + + + + .., .. + + + Fastest compression..highest compression (default is -5). These are synonyms for other options: + + + + , + + + Synonymous with -l 0 -b 1152 -r 3 + + + + + , + + + Synonymous with -l 0 -b 1152 -M -r 3 + + + + + , + + + Synonymous with -l 0 -b 1152 -m -r 3 + + + + + , + + + Synonymous with -l 6 -b 4096 -r 4 + + + + + , + + + Synonymous with -l 8 -b 4096 -M -r 4 + + + + + , + + + Synonymous with -l 8 -b 4096 -m -r 5 + + + + + , + + + Synonymous with -l 8 -b 4096 -m -r 6 + + + + + , + + + Synonymous with -l 8 -b 4096 -m -e -r 6 + + + + + , + + + Synonymous with -l 12 -b 4096 -m -e -r 6 + + + + + + + + + + + + + Fastest compression. Currently synonymous with -0. + + + + + + + + Highest compression. Currently synonymous with -8. + + + + + , + + + Do exhaustive model search (expensive!) + + + + + function, =function + + + Window audio data with given the apodization function. The functions are: bartlett, bartlett_hann, blackman, blackman_harris_4term_92db, connes, flattop, gauss(STDDEV), hamming, hann, kaiser_bessel, nuttall, rectangle, triangle, tukey(P), welch. + For gauss(STDDEV), STDDEV is the standard deviation (0<STDDEV<=0.5). + For tukey(P), P specifies the fraction of the window that is tapered (0<=P<=1; P=0 corresponds to "rectangle" and P=1 corresponds to "hann"). + More than one -A option (up to 32) may be used. Any function that is specified erroneously is silently dropped. The encoder chooses suitable defaults in the absence of any -A options; any -A option specified replaces the default(s). + When more than one function is specified, then for every subframe the encoder will try each of them separately and choose the window that results in the smallest compressed subframe. Multiple functions can greatly increase the encoding time. + + + + + #, =# + + + Specifies the maximum LPC order. This number must be <= 32. For Subset streams, it must be <=12 if the sample rate is <=48kHz. If 0, the encoder will not attempt generic linear prediction, and use only fixed predictors. Using fixed predictors is faster but usually results in files being 5-10% larger. + + + + + , + + + Do exhaustive search of LP coefficient quantization (expensive!). Overrides -q; does nothing if using -l 0 + + + + + #, =# + + + Precision of the quantized linear-predictor coefficients, 0 => let encoder decide (min is 5, default is 0) + + + + + [#,]#, =[#,]# + + + Set the [min,]max residual partition order (0..16). min defaults to 0 if unspecified. Default is -r 5. + + + + + + + + Format Options + + + + ={big|little} + + + Set the byte order for samples + + + + + =# + + + Set number of channels. + + + + + =# + + + Set bits per sample. + + + + + =# + + + Set sample rate (in Hz). + + + + + ={signed|unsigned} + + + Set the sign of samples (the default is signed). + + + + + =# + + + Specify the size of the raw input in bytes. If you are encoding raw samples from stdin, you must set this option in order to be able to use --skip, --until, --cue-sheet, or other options that need to know the size of the input beforehand. If the size given is greater than what is found in the input stream, the encoder will complain about an unexpected end-of-file. If the size given is less, samples will be truncated. + + + + + + + + Force input (when encoding) or output (when decoding) to be treated as raw samples (even if filename ends in .wav). + + + + + + + + Force the decoder to output AIFF format. This option is not needed if the output filename (as set by -o) ends with .aif or .aiff. Also, this option has no effect when encoding since input AIFF is auto-detected. + + + + + + + + Force the decoder to output RF64 format. This option is not needed if the output filename (as set by -o) ends with .rf64. Also, this option has no effect when encoding since input RF64 is auto-detected. + + + + + + + + Force the decoder to output Wave64 format. This option is not needed if the output filename (as set by -o) ends with .w64. Also, this option has no effect when encoding since input Wave64 is auto-detected. + + + + + + + + Negative Options + + + + + + + + + + + + + + + + + + + + + + + These flags can be used to invert the sense of the corresponding normal option. + + + + + + + + + SEE ALSO + + metaflac(1). + + The programs are documented fully by HTML format documentation, available in /usr/share/doc/flac/html on &debian; systems. + + + AUTHOR + + This manual page was written by &dhusername; &dhemail; for the &debian; system (but may be used by others). + + + + +
      + + diff --git a/flac/man/metaflac.1 b/flac/man/metaflac.1 new file mode 100644 index 0000000..f9d3835 --- /dev/null +++ b/flac/man/metaflac.1 @@ -0,0 +1,299 @@ +.\" This manpage has been automatically generated by docbook2man +.\" from a DocBook document. This tool can be found at: +.\" +.\" Please send any bug reports, improvements, comments, patches, +.\" etc. to Steve Cheng . +.TH "METAFLAC" "1" "14 September 2007" "" "" + +.SH NAME +metaflac \- program to list, add, remove, or edit metadata in one or more FLAC files. +.SH SYNOPSIS + +\fBmetaflac\fR [ \fB\fIoptions\fB\fR ] [ \fB\fIoperations\fB\fR ] \fB\fIFLACfile\fB\fR\fI ...\fR + +.SH "DESCRIPTION" +.PP +Use \fBmetaflac\fR to list, add, remove, or edit +metadata in one or more FLAC files. You may perform one major operation, +or many shorthand operations at a time. +.SH "OPTIONS" +.TP +\fB--preserve-modtime\fR +Preserve the original modification time in spite of edits. +.TP +\fB--with-filename\fR +Prefix each output line with the FLAC file name (the default if +more than one FLAC file is specified). +.TP +\fB--no-filename\fR +Do not prefix each output line with the FLAC file name (the default +if only one FLAC file is specified). +.TP +\fB--no-utf8-convert\fR +Do not convert tags from UTF-8 to local charset, or vice versa. This is +useful for scripts, and setting tags in situations where the locale is wrong. +.TP +\fB--dont-use-padding\fR +By default metaflac tries to use padding where possible to avoid +rewriting the entire file if the metadata size changes. Use this +option to tell metaflac to not take advantage of padding this way. +.SH "SHORTHAND OPERATIONS" +.TP +\fB--show-md5sum\fR +Show the MD5 signature from the STREAMINFO block. +.TP +\fB--show-min-blocksize\fR +Show the minimum block size from the STREAMINFO block. +.TP +\fB--show-max-blocksize\fR +Show the maximum block size from the STREAMINFO block. +.TP +\fB--show-min-framesize\fR +Show the minimum frame size from the STREAMINFO block. +.TP +\fB--show-max-framesize\fR +Show the maximum frame size from the STREAMINFO block. +.TP +\fB--show-sample-rate\fR +Show the sample rate from the STREAMINFO block. +.TP +\fB--show-channels\fR +Show the number of channels from the STREAMINFO block. +.TP +\fB--show-bps\fR +Show the # of bits per sample from the STREAMINFO block. +.TP +\fB--show-total-samples\fR +Show the total # of samples from the STREAMINFO block. +.TP +\fB--show-vendor-tag\fR +Show the vendor string from the VORBIS_COMMENT block. +.TP +\fB--show-tag=name\fR +Show all tags where the the field name matches 'name'. +.TP +\fB--remove-tag=name\fR +Remove all tags whose field name is 'name'. +.TP +\fB--remove-first-tag=name\fR +Remove first tag whose field name is 'name'. +.TP +\fB--remove-all-tags\fR +Remove all tags, leaving only the vendor string. +.TP +\fB--set-tag=field\fR +Add a tag. The field must comply with the +Vorbis comment spec, of the form "NAME=VALUE". If there is +currently no tag block, one will be created. +.TP +\fB--set-tag-from-file=field\fR +Like --set-tag, except the VALUE is a filename whose +contents will be read verbatim to set the tag value. +Unless --no-utf8-convert is specified, the contents will be +converted to UTF-8 from the local charset. This can be used +to store a cuesheet in a tag (e.g. +--set-tag-from-file="CUESHEET=image.cue"). Do not try to +store binary data in tag fields! Use APPLICATION blocks for +that. +.TP +\fB--import-tags-from=file\fR +Import tags from a file. Use '-' for stdin. Each +line should be of the form NAME=VALUE. Multi-line comments +are currently not supported. Specify --remove-all-tags and/or +--no-utf8-convert before --import-tags-from if necessary. If +FILE is '-' (stdin), only one FLAC file may be specified. +.TP +\fB--export-tags-to=file\fR +Export tags to a file. Use '-' for stdout. Each +line will be of the form NAME=VALUE. Specify +--no-utf8-convert if necessary. +.TP +\fB--import-cuesheet-from=file\fR +Import a cuesheet from a file. Use '-' for stdin. Only one +FLAC file may be specified. A seekpoint will be added for each +index point in the cuesheet to the SEEKTABLE unless +--no-cued-seekpoints is specified. +.TP +\fB--export-cuesheet-to=file\fR +Export CUESHEET block to a cuesheet file, suitable for use by +CD authoring software. Use '-' for stdout. Only one FLAC file +may be specified on the command line. +.TP +\fB--import-picture-from={\fIFILENAME\fB|\fISPECIFICATION\fB}\fR +Import a picture and store it in a PICTURE metadata block. More than one --import-picture-from command can be specified. Either a filename for the picture file or a more complete specification form can be used. The SPECIFICATION is a string whose parts are separated by | (pipe) characters. Some parts may be left empty to invoke default values. FILENAME is just shorthand for "||||FILENAME". The format of SPECIFICATION is + +[TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE + +TYPE is optional; it is a number from one of: + +0: Other + +1: 32x32 pixels 'file icon' (PNG only) + +2: Other file icon + +3: Cover (front) + +4: Cover (back) + +5: Leaflet page + +6: Media (e.g. label side of CD) + +7: Lead artist/lead performer/soloist + +8: Artist/performer + +9: Conductor + +10: Band/Orchestra + +11: Composer + +12: Lyricist/text writer + +13: Recording Location + +14: During recording + +15: During performance + +16: Movie/video screen capture + +17: A bright coloured fish + +18: Illustration + +19: Band/artist logotype + +20: Publisher/Studio logotype + +The default is 3 (front cover). There may only be one picture each of type 1 and 2 in a file. + +MIME-TYPE is optional; if left blank, it will be detected from the file. For best compatibility with players, use pictures with MIME type image/jpeg or image/png. The MIME type can also be --> to mean that FILE is actually a URL to an image, though this use is discouraged. + +DESCRIPTION is optional; the default is an empty string. + +The next part specfies the resolution and color information. If the MIME-TYPE is image/jpeg, image/png, or image/gif, you can usually leave this empty and they can be detected from the file. Otherwise, you must specify the width in pixels, height in pixels, and color depth in bits-per-pixel. If the image has indexed colors you should also specify the number of colors used. When manually specified, it is not checked against the file for accuracy. + +FILE is the path to the picture file to be imported, or the URL if MIME type is --> + +For example, "|image/jpeg|||../cover.jpg" will embed the JPEG file at ../cover.jpg, defaulting to type 3 (front cover) and an empty description. The resolution and color info will be retrieved from the file itself. + +The specification "4|-->|CD|320x300x24/173|http://blah.blah/backcover.tiff" will embed the given URL, with type 4 (back cover), description "CD", and a manually specified resolution of 320x300, 24 bits-per-pixel, and 173 colors. The file at the URL will not be fetched; the URL itself is stored in the PICTURE metadata block. +.TP +\fB--export-picture-to=file\fR +Export PICTURE block to a file. Use '-' for stdout. Only one FLAC file may be specified on the command line. The first PICTURE block will be exported unless --export-picture-to is preceded by a --block-number=# option to specify the exact metadata block to extract. Note that the block number is the one shown by --list. +.TP +\fB--add-replay-gain\fR +Calculates the title and album gains/peaks of the given FLAC +files as if all the files were part of one album, then stores +them as FLAC tags. The tags are the same as +those used by vorbisgain. Existing ReplayGain tags will be +replaced. If only one FLAC file is given, the album and title +gains will be the same. Since this operation requires two +passes, it is always executed last, after all other operations +have been completed and written to disk. All FLAC files +specified must have the same resolution, sample rate, and +number of channels. The sample rate must be one of 8, 11.025, +12, 16, 22.05, 24, 32, 44.1, or 48 kHz. +.TP +\fB--remove-replay-gain\fR +Removes the ReplayGain tags. +.TP +\fB--add-seekpoint={\fI#\fB|\fIX\fB|\fI#x\fB|\fI#s\fB}\fR +Add seek points to a SEEKTABLE block. Using #, a seek point at +that sample number is added. Using X, a placeholder point is +added at the end of a the table. Using #x, # evenly spaced seek +points will be added, the first being at sample 0. Using #s, a +seekpoint will be added every # seconds (# does not have to be a +whole number; it can be, for example, 9.5, meaning a seekpoint +every 9.5 seconds). If no SEEKTABLE block exists, one will be +created. If one already exists, points will be added to the +existing table, and any duplicates will be turned into placeholder +points. You may use many --add-seekpoint options; the resulting +SEEKTABLE will be the unique-ified union of all such values. +Example: --add-seekpoint=100x --add-seekpoint=3.5s will add 100 +evenly spaced seekpoints and a seekpoint every 3.5 seconds. +.TP +\fB--add-padding=length\fR +Add a padding block of the given length (in bytes). The overall +length of the new block will be 4 + length; the extra 4 bytes is +for the metadata block header. +.SH "MAJOR OPERATIONS" +.TP +\fB--list\fR +List the contents of one or more metadata blocks to stdout. By +default, all metadata blocks are listed in text format. Use the +following options to change this behavior: +.RS +.TP +\fB--block-number=#[,#[...]]\fR +An optional comma-separated list of block numbers to display. +The first block, the STREAMINFO block, is block 0. +.TP +\fB--block-type=type[,type[...]]\fR +.TP +\fB--except-block-type=type[,type[...]]\fR +An optional comma-separated list of block types to be included +or ignored with this option. Use only one of --block-type or +--except-block-type. The valid block types are: STREAMINFO, +PADDING, APPLICATION, SEEKTABLE, VORBIS_COMMENT. You may +narrow down the types of APPLICATION blocks displayed as +follows: + +APPLICATION:abcd The APPLICATION block(s) whose textual repre- +sentation of the 4-byte ID is "abcd" +APPLICATION:0xXXXXXXXX The APPLICATION block(s) whose hexadecimal big- +endian representation of the 4-byte ID is +"0xXXXXXXXX". For the example "abcd" above the +hexadecimal equivalalent is 0x61626364 +.sp +.RS +.B "Note:" +if both --block-number and --[except-]block-type are +specified, the result is the logical AND of both +arguments. +.RE +.TP +\fB--application-data-format=hexdump|text\fR +If the application block you are displaying contains binary +data but your --data-format=text, you can display a hex dump +of the application data contents instead using +--application-data-format=hexdump. +.RE +.TP +\fB--remove\fR +Remove one or more metadata blocks from the metadata. Unless +--dont-use-padding is specified, the blocks will be replaced with +padding. You may not remove the STREAMINFO block. +.RS +.TP +\fB--block-number=#[,#[...]]\fR +.TP +\fB--block-type=type[,type[...]]\fR +.TP +\fB--except-block-type=type[,type[...]]\fR +See --list above for usage. +.sp +.RS +.B "Note:" +if both --block-number and --[except-]block-type are +specified, the result is the logical AND of both arguments. +.RE +.RE +.TP +\fB--remove-all\fR +Remove all metadata blocks (except the STREAMINFO block) from the +metadata. Unless --dont-use-padding is specified, the blocks will +be replaced with padding. +.TP +\fB--merge-padding\fR +Merge adjacent PADDING blocks into single blocks. +.TP +\fB--sort-padding\fR +Move all PADDING blocks to the end of the metadata and merge them +into a single block. +.SH "SEE ALSO" +.PP +flac(1). diff --git a/flac/man/metaflac.sgml b/flac/man/metaflac.sgml new file mode 100644 index 0000000..a0d41c8 --- /dev/null +++ b/flac/man/metaflac.sgml @@ -0,0 +1,570 @@ + manpage.1'. You may view + the manual page with: `docbook-to-man manpage.sgml | nroff -man | + less'. A typical entry in a Makefile or Makefile.am is: + +manpage.1: manpage.sgml + docbook-to-man $< > $@ + --> + + + + + dann"> + frazier"> + + 2006-11-14"> + + 1"> + dannf@debian.org"> + + METAFLAC"> + +]> + + + +
      + &manemail; +
      + + &manfirstname; + &mansurname; + + + 2002,2003,2004,2005 + &manusername; + + &mandate; +
      + + &manucpackage; + + &mansection; + + + &manpackage; + + + program to list, add, remove, or edit metadata in one or more FLAC files. + + + + + &manpackage; + + options + + operations + FLACfile + + + + DESCRIPTION + + Use &manpackage; to list, add, remove, or edit + metadata in one or more FLAC files. You may perform one major operation, + or many shorthand operations at a time. + + + + OPTIONS + + + + + + + Preserve the original modification time in spite of edits. + + + + + + + + Prefix each output line with the FLAC file name (the default if + more than one FLAC file is specified). + + + + + + + + Do not prefix each output line with the FLAC file name (the default + if only one FLAC file is specified). + + + + + + + + Do not convert tags from UTF-8 to local charset, or vice versa. This is + useful for scripts, and setting tags in situations where the locale is wrong. + + + + + + + + By default metaflac tries to use padding where possible to avoid + rewriting the entire file if the metadata size changes. Use this + option to tell metaflac to not take advantage of padding this way. + + + + + + + SHORTHAND OPERATIONS + + + + + + + Show the MD5 signature from the STREAMINFO block. + + + + + + + + Show the minimum block size from the STREAMINFO block. + + + + + + + + Show the maximum block size from the STREAMINFO block. + + + + + + + + Show the minimum frame size from the STREAMINFO block. + + + + + + + + Show the maximum frame size from the STREAMINFO block. + + + + + + + + Show the sample rate from the STREAMINFO block. + + + + + + + + Show the number of channels from the STREAMINFO block. + + + + + + + + Show the # of bits per sample from the STREAMINFO block. + + + + + + + + Show the total # of samples from the STREAMINFO block. + + + + + + + + Show the vendor string from the VORBIS_COMMENT block. + + + + + + + + Show all tags where the the field name matches 'name'. + + + + + + + + Remove all tags whose field name is 'name'. + + + + + + + + Remove first tag whose field name is 'name'. + + + + + + + + Remove all tags, leaving only the vendor string. + + + + + + + + Add a tag. The field must comply with the + Vorbis comment spec, of the form "NAME=VALUE". If there is + currently no tag block, one will be created. + + + + + + + + Like --set-tag, except the VALUE is a filename whose + contents will be read verbatim to set the tag value. + Unless --no-utf8-convert is specified, the contents will be + converted to UTF-8 from the local charset. This can be used + to store a cuesheet in a tag (e.g. + --set-tag-from-file="CUESHEET=image.cue"). Do not try to + store binary data in tag fields! Use APPLICATION blocks for + that. + + + + + + + + Import tags from a file. Use '-' for stdin. Each + line should be of the form NAME=VALUE. Multi-line comments + are currently not supported. Specify --remove-all-tags and/or + --no-utf8-convert before --import-tags-from if necessary. If + FILE is '-' (stdin), only one FLAC file may be specified. + + + + + + + + Export tags to a file. Use '-' for stdout. Each + line will be of the form NAME=VALUE. Specify + --no-utf8-convert if necessary. + + + + + + + + Import a cuesheet from a file. Use '-' for stdin. Only one + FLAC file may be specified. A seekpoint will be added for each + index point in the cuesheet to the SEEKTABLE unless + --no-cued-seekpoints is specified. + + + + + + + + Export CUESHEET block to a cuesheet file, suitable for use by + CD authoring software. Use '-' for stdout. Only one FLAC file + may be specified on the command line. + + + + + ={FILENAME|SPECIFICATION} + + Import a picture and store it in a PICTURE metadata block. More than one --import-picture-from command can be specified. Either a filename for the picture file or a more complete specification form can be used. The SPECIFICATION is a string whose parts are separated by | (pipe) characters. Some parts may be left empty to invoke default values. FILENAME is just shorthand for "||||FILENAME". The format of SPECIFICATION is + [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE + TYPE is optional; it is a number from one of: + 0: Other + 1: 32x32 pixels 'file icon' (PNG only) + 2: Other file icon + 3: Cover (front) + 4: Cover (back) + 5: Leaflet page + 6: Media (e.g. label side of CD) + 7: Lead artist/lead performer/soloist + 8: Artist/performer + 9: Conductor + 10: Band/Orchestra + 11: Composer + 12: Lyricist/text writer + 13: Recording Location + 14: During recording + 15: During performance + 16: Movie/video screen capture + 17: A bright coloured fish + 18: Illustration + 19: Band/artist logotype + 20: Publisher/Studio logotype + The default is 3 (front cover). There may only be one picture each of type 1 and 2 in a file. + + MIME-TYPE is optional; if left blank, it will be detected from the file. For best compatibility with players, use pictures with MIME type image/jpeg or image/png. The MIME type can also be --> to mean that FILE is actually a URL to an image, though this use is discouraged. + + DESCRIPTION is optional; the default is an empty string. + + The next part specfies the resolution and color information. If the MIME-TYPE is image/jpeg, image/png, or image/gif, you can usually leave this empty and they can be detected from the file. Otherwise, you must specify the width in pixels, height in pixels, and color depth in bits-per-pixel. If the image has indexed colors you should also specify the number of colors used. When manually specified, it is not checked against the file for accuracy. + + FILE is the path to the picture file to be imported, or the URL if MIME type is --> + + For example, "|image/jpeg|||../cover.jpg" will embed the JPEG file at ../cover.jpg, defaulting to type 3 (front cover) and an empty description. The resolution and color info will be retrieved from the file itself. + + The specification "4|-->|CD|320x300x24/173|http://blah.blah/backcover.tiff" will embed the given URL, with type 4 (back cover), description "CD", and a manually specified resolution of 320x300, 24 bits-per-pixel, and 173 colors. The file at the URL will not be fetched; the URL itself is stored in the PICTURE metadata block. + + + + + + + Export PICTURE block to a file. Use '-' for stdout. Only one FLAC file may be specified on the command line. The first PICTURE block will be exported unless --export-picture-to is preceded by a --block-number=# option to specify the exact metadata block to extract. Note that the block number is the one shown by --list. + + + + + + + + Calculates the title and album gains/peaks of the given FLAC + files as if all the files were part of one album, then stores + them as FLAC tags. The tags are the same as + those used by vorbisgain. Existing ReplayGain tags will be + replaced. If only one FLAC file is given, the album and title + gains will be the same. Since this operation requires two + passes, it is always executed last, after all other operations + have been completed and written to disk. All FLAC files + specified must have the same resolution, sample rate, and + number of channels. The sample rate must be one of 8, 11.025, + 12, 16, 22.05, 24, 32, 44.1, or 48 kHz. + + + + + + + + Removes the ReplayGain tags. + + + + + ={#|X|#x|#s} + + + Add seek points to a SEEKTABLE block. Using #, a seek point at + that sample number is added. Using X, a placeholder point is + added at the end of a the table. Using #x, # evenly spaced seek + points will be added, the first being at sample 0. Using #s, a + seekpoint will be added every # seconds (# does not have to be a + whole number; it can be, for example, 9.5, meaning a seekpoint + every 9.5 seconds). If no SEEKTABLE block exists, one will be + created. If one already exists, points will be added to the + existing table, and any duplicates will be turned into placeholder + points. You may use many --add-seekpoint options; the resulting + SEEKTABLE will be the unique-ified union of all such values. + Example: --add-seekpoint=100x --add-seekpoint=3.5s will add 100 + evenly spaced seekpoints and a seekpoint every 3.5 seconds. + + + + + + + + Add a padding block of the given length (in bytes). The overall + length of the new block will be 4 + length; the extra 4 bytes is + for the metadata block header. + + + + + + + MAJOR OPERATIONS + + + + + + + List the contents of one or more metadata blocks to stdout. By + default, all metadata blocks are listed in text format. Use the + following options to change this behavior: + + + + + + + An optional comma-separated list of block numbers to display. + The first block, the STREAMINFO block, is block 0. + + + + + + + + + + + + An optional comma-separated list of block types to be included + or ignored with this option. Use only one of --block-type or + --except-block-type. The valid block types are: STREAMINFO, + PADDING, APPLICATION, SEEKTABLE, VORBIS_COMMENT. You may + narrow down the types of APPLICATION blocks displayed as + follows: + + + APPLICATION:abcd The APPLICATION block(s) whose textual repre- + sentation of the 4-byte ID is "abcd" + APPLICATION:0xXXXXXXXX The APPLICATION block(s) whose hexadecimal big- + endian representation of the 4-byte ID is + "0xXXXXXXXX". For the example "abcd" above the + hexadecimal equivalalent is 0x61626364 + + + + if both --block-number and --[except-]block-type are + specified, the result is the logical AND of both + arguments. + + + + + + + If the application block you are displaying contains binary + data but your --data-format=text, you can display a hex dump + of the application data contents instead using + --application-data-format=hexdump. + + + + + + + + + + + Remove one or more metadata blocks from the metadata. Unless + --dont-use-padding is specified, the blocks will be replaced with + padding. You may not remove the STREAMINFO block. + + + + + + + + + + + + + + See --list above for usage. + + + if both --block-number and --[except-]block-type are + specified, the result is the logical AND of both arguments. + + + + + + + + + + + Remove all metadata blocks (except the STREAMINFO block) from the + metadata. Unless --dont-use-padding is specified, the blocks will + be replaced with padding. + + + + + + + + Merge adjacent PADDING blocks into single blocks. + + + + + + + + Move all PADDING blocks to the end of the metadata and merge them + into a single block. + + + + + + + + SEE ALSO + + flac(1). + +
      + + diff --git a/flac/obj/Makefile.am b/flac/obj/Makefile.am new file mode 100644 index 0000000..683a476 --- /dev/null +++ b/flac/obj/Makefile.am @@ -0,0 +1,20 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = \ + debug \ + release diff --git a/flac/obj/debug/Makefile.am b/flac/obj/debug/Makefile.am new file mode 100644 index 0000000..202e98c --- /dev/null +++ b/flac/obj/debug/Makefile.am @@ -0,0 +1,20 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = \ + bin \ + lib diff --git a/flac/obj/debug/bin/Makefile.am b/flac/obj/debug/bin/Makefile.am new file mode 100644 index 0000000..9e36390 --- /dev/null +++ b/flac/obj/debug/bin/Makefile.am @@ -0,0 +1,16 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. diff --git a/flac/obj/debug/lib/Makefile.am b/flac/obj/debug/lib/Makefile.am new file mode 100644 index 0000000..9e36390 --- /dev/null +++ b/flac/obj/debug/lib/Makefile.am @@ -0,0 +1,16 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. diff --git a/flac/obj/release/Makefile.am b/flac/obj/release/Makefile.am new file mode 100644 index 0000000..202e98c --- /dev/null +++ b/flac/obj/release/Makefile.am @@ -0,0 +1,20 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = \ + bin \ + lib diff --git a/flac/obj/release/bin/Makefile.am b/flac/obj/release/bin/Makefile.am new file mode 100644 index 0000000..9e36390 --- /dev/null +++ b/flac/obj/release/bin/Makefile.am @@ -0,0 +1,16 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. diff --git a/flac/obj/release/lib/Makefile.am b/flac/obj/release/lib/Makefile.am new file mode 100644 index 0000000..9e36390 --- /dev/null +++ b/flac/obj/release/lib/Makefile.am @@ -0,0 +1,16 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. diff --git a/flac/obj/release/lib/libFLAC_static.lib b/flac/obj/release/lib/libFLAC_static.lib new file mode 100644 index 0000000..6e144e0 Binary files /dev/null and b/flac/obj/release/lib/libFLAC_static.lib differ diff --git a/flac/src/Makefile.am b/flac/src/Makefile.am new file mode 100644 index 0000000..f2b140c --- /dev/null +++ b/flac/src/Makefile.am @@ -0,0 +1,42 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +if FLaC__HAS_XMMS +XMMS_DIRS = plugin_common plugin_xmms +endif + +if FLaC__WITH_CPPLIBS +CPPLIBS_DIRS = libFLAC++ test_libFLAC++ +endif + +SUBDIRS = \ + libFLAC \ + share \ + flac \ + metaflac \ + monkeys_audio_utilities \ + $(XMMS_DIRS) \ + plugin_winamp2 \ + test_grabbag \ + test_libs_common \ + test_libFLAC \ + test_seeking \ + test_streams \ + $(CPPLIBS_DIRS) + +EXTRA_DIST = \ + Makefile.lite diff --git a/flac/src/Makefile.lite b/flac/src/Makefile.lite new file mode 100644 index 0000000..72f3d46 --- /dev/null +++ b/flac/src/Makefile.lite @@ -0,0 +1,67 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +ifeq ($(OS),Darwin) +EXTRA_TARGETS = +else +EXTRA_TARGETS = plugin_xmms +endif + +.PHONY: all flac libFLAC libFLAC++ metaflac plugin_common plugin_xmms share test_grabbag test_libs_common test_libFLAC test_libFLAC++ test_seeking test_streams +all: flac libFLAC libFLAC++ metaflac plugin_common $(EXTRA_TARGETS) share test_grabbag test_libs_common test_libFLAC test_libFLAC++ test_seeking test_streams + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +debug : CONFIG = debug +valgrind: CONFIG = valgrind +release : CONFIG = release + +debug : all +valgrind: all +release : all + +flac libFLAC libFLAC++ metaflac plugin_common plugin_xmms share test_grabbag test_libs_common test_libFLAC test_libFLAC++ test_seeking test_streams: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +clean: + -(cd flac ; $(MAKE) -f Makefile.lite clean) + -(cd libFLAC ; $(MAKE) -f Makefile.lite clean) + -(cd libFLAC++ ; $(MAKE) -f Makefile.lite clean) + -(cd metaflac ; $(MAKE) -f Makefile.lite clean) + -(cd plugin_common ; $(MAKE) -f Makefile.lite clean) + -(cd plugin_xmms ; $(MAKE) -f Makefile.lite clean) + -(cd share ; $(MAKE) -f Makefile.lite clean) + -(cd test_grabbag ; $(MAKE) -f Makefile.lite clean) + -(cd test_libs_common ; $(MAKE) -f Makefile.lite clean) + -(cd test_libFLAC ; $(MAKE) -f Makefile.lite clean) + -(cd test_libFLAC++ ; $(MAKE) -f Makefile.lite clean) + -(cd test_seeking ; $(MAKE) -f Makefile.lite clean) + -(cd test_streams ; $(MAKE) -f Makefile.lite clean) + +flac: libFLAC share +libFLAC++: libFLAC +metaflac: libFLAC share +plugin_common: libFLAC +plugin_xmms: libFLAC plugin_common +share: libFLAC +test_grabbag: share +test_libFLAC++: libFLAC libFLAC++ test_libs_common +test_libFLAC: libFLAC test_libs_common +test_seeking: libFLAC +test_streams: libFLAC diff --git a/flac/src/flac/Makefile.am b/flac/src/flac/Makefile.am new file mode 100644 index 0000000..2db3029 --- /dev/null +++ b/flac/src/flac/Makefile.am @@ -0,0 +1,58 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +bin_PROGRAMS = flac + +AM_CFLAGS = @OGG_CFLAGS@ + +EXTRA_DIST = \ + Makefile.lite \ + Makefile.lite.iffscan \ + flac.dsp \ + flac.vcproj \ + iffscan.c \ + iffscan.dsp \ + iffscan.vcproj + +flac_SOURCES = \ + analyze.c \ + decode.c \ + encode.c \ + foreign_metadata.c \ + main.c \ + local_string_utils.c \ + utils.c \ + vorbiscomment.c \ + analyze.h \ + decode.h \ + encode.h \ + foreign_metadata.h \ + local_string_utils.h \ + utils.h \ + vorbiscomment.h + +flac_LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/getopt/libgetopt.a \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/share/replaygain_synthesis/libreplaygain_synthesis.la \ + $(top_builddir)/src/share/utf8/libutf8.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @LIBICONV@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm diff --git a/flac/src/flac/Makefile.lite b/flac/src/flac/Makefile.lite new file mode 100644 index 0000000..f9d3984 --- /dev/null +++ b/flac/src/flac/Makefile.lite @@ -0,0 +1,47 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = flac + +INCLUDES = -I./include -I$(topdir)/include -I$(OGG_INCLUDE_DIR) + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libFLAC.a $(libdir)/libreplaygain_analysis.a $(libdir)/libreplaygain_synthesis.a $(libdir)/libgetopt.a $(libdir)/libutf8.a $(OGG_LIB_DIR)/libogg.a -liconv -lm +else +LIBS = -lgrabbag -lFLAC -lreplaygain_analysis -lreplaygain_synthesis -lgetopt -lutf8 -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + analyze.c \ + decode.c \ + encode.c \ + foreign_metadata.c \ + local_string_utils.c \ + main.c \ + utils.c \ + vorbiscomment.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/flac/Makefile.lite.iffscan b/flac/src/flac/Makefile.lite.iffscan new file mode 100644 index 0000000..6fc85e0 --- /dev/null +++ b/flac/src/flac/Makefile.lite.iffscan @@ -0,0 +1,41 @@ +# flac - Command-line FLAC encoder/decoder +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = iffscan + +INCLUDES = -I./include -I$(topdir)/include -I$(OGG_INCLUDE_DIR) + +ifeq ($(DARWIN_BUILD),yes) +EXPLICIT_LIBS = $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -liconv -lm +else +LIBS = -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + foreign_metadata.c \ + iffscan.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/flac/analyze.c b/flac/src/flac/analyze.c new file mode 100644 index 0000000..b6d7fa7 --- /dev/null +++ b/flac/src/flac/analyze.c @@ -0,0 +1,247 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include "FLAC/all.h" +#include "analyze.h" + +typedef struct { + FLAC__int32 residual; + unsigned count; +} pair_t; + +typedef struct { + pair_t buckets[FLAC__MAX_BLOCK_SIZE]; + int peak_index; + unsigned nbuckets; + unsigned nsamples; + double sum, sos; + double variance; + double mean; + double stddev; +} subframe_stats_t; + +static subframe_stats_t all_; + +static void init_stats(subframe_stats_t *stats); +static void update_stats(subframe_stats_t *stats, FLAC__int32 residual, unsigned incr); +static void compute_stats(subframe_stats_t *stats); +static FLAC__bool dump_stats(const subframe_stats_t *stats, const char *filename); + +void flac__analyze_init(analysis_options aopts) +{ + if(aopts.do_residual_gnuplot) { + init_stats(&all_); + } +} + +void flac__analyze_frame(const FLAC__Frame *frame, unsigned frame_number, FLAC__uint64 frame_offset, unsigned frame_bytes, analysis_options aopts, FILE *fout) +{ + const unsigned channels = frame->header.channels; + char outfilename[1024]; + subframe_stats_t stats; + unsigned i, channel, partitions; + + /* do the human-readable part first */ +#ifdef _MSC_VER + fprintf(fout, "frame=%u\toffset=%I64u\tbits=%u\tblocksize=%u\tsample_rate=%u\tchannels=%u\tchannel_assignment=%s\n", frame_number, frame_offset, frame_bytes*8, frame->header.blocksize, frame->header.sample_rate, channels, FLAC__ChannelAssignmentString[frame->header.channel_assignment]); +#else + fprintf(fout, "frame=%u\toffset=%llu\tbits=%u\tblocksize=%u\tsample_rate=%u\tchannels=%u\tchannel_assignment=%s\n", frame_number, (unsigned long long)frame_offset, frame_bytes*8, frame->header.blocksize, frame->header.sample_rate, channels, FLAC__ChannelAssignmentString[frame->header.channel_assignment]); +#endif + for(channel = 0; channel < channels; channel++) { + const FLAC__Subframe *subframe = frame->subframes+channel; + const FLAC__bool is_rice2 = subframe->data.fixed.entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2; + const unsigned pesc = is_rice2? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; + fprintf(fout, "\tsubframe=%u\twasted_bits=%u\ttype=%s", channel, subframe->wasted_bits, FLAC__SubframeTypeString[subframe->type]); + switch(subframe->type) { + case FLAC__SUBFRAME_TYPE_CONSTANT: + fprintf(fout, "\tvalue=%d\n", subframe->data.constant.value); + break; + case FLAC__SUBFRAME_TYPE_FIXED: + FLAC__ASSERT(subframe->data.fixed.entropy_coding_method.type <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2); + fprintf(fout, "\torder=%u\tresidual_type=%s\tpartition_order=%u\n", subframe->data.fixed.order, is_rice2? "RICE2":"RICE", subframe->data.fixed.entropy_coding_method.data.partitioned_rice.order); + for(i = 0; i < subframe->data.fixed.order; i++) + fprintf(fout, "\t\twarmup[%u]=%d\n", i, subframe->data.fixed.warmup[i]); + partitions = (1u << subframe->data.fixed.entropy_coding_method.data.partitioned_rice.order); + for(i = 0; i < partitions; i++) { + unsigned parameter = subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents->parameters[i]; + if(parameter == pesc) + fprintf(fout, "\t\tparameter[%u]=ESCAPE, raw_bits=%u\n", i, subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents->raw_bits[i]); + else + fprintf(fout, "\t\tparameter[%u]=%u\n", i, parameter); + } + if(aopts.do_residual_text) { + for(i = 0; i < frame->header.blocksize-subframe->data.fixed.order; i++) + fprintf(fout, "\t\tresidual[%u]=%d\n", i, subframe->data.fixed.residual[i]); + } + break; + case FLAC__SUBFRAME_TYPE_LPC: + FLAC__ASSERT(subframe->data.lpc.entropy_coding_method.type <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2); + fprintf(fout, "\torder=%u\tqlp_coeff_precision=%u\tquantization_level=%d\tresidual_type=%s\tpartition_order=%u\n", subframe->data.lpc.order, subframe->data.lpc.qlp_coeff_precision, subframe->data.lpc.quantization_level, is_rice2? "RICE2":"RICE", subframe->data.lpc.entropy_coding_method.data.partitioned_rice.order); + for(i = 0; i < subframe->data.lpc.order; i++) + fprintf(fout, "\t\tqlp_coeff[%u]=%d\n", i, subframe->data.lpc.qlp_coeff[i]); + for(i = 0; i < subframe->data.lpc.order; i++) + fprintf(fout, "\t\twarmup[%u]=%d\n", i, subframe->data.lpc.warmup[i]); + partitions = (1u << subframe->data.lpc.entropy_coding_method.data.partitioned_rice.order); + for(i = 0; i < partitions; i++) { + unsigned parameter = subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents->parameters[i]; + if(parameter == pesc) + fprintf(fout, "\t\tparameter[%u]=ESCAPE, raw_bits=%u\n", i, subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents->raw_bits[i]); + else + fprintf(fout, "\t\tparameter[%u]=%u\n", i, parameter); + } + if(aopts.do_residual_text) { + for(i = 0; i < frame->header.blocksize-subframe->data.lpc.order; i++) + fprintf(fout, "\t\tresidual[%u]=%d\n", i, subframe->data.lpc.residual[i]); + } + break; + case FLAC__SUBFRAME_TYPE_VERBATIM: + fprintf(fout, "\n"); + break; + } + } + + /* now do the residual distributions if requested */ + if(aopts.do_residual_gnuplot) { + for(channel = 0; channel < channels; channel++) { + const FLAC__Subframe *subframe = frame->subframes+channel; + unsigned residual_samples; + + init_stats(&stats); + + switch(subframe->type) { + case FLAC__SUBFRAME_TYPE_FIXED: + residual_samples = frame->header.blocksize - subframe->data.fixed.order; + for(i = 0; i < residual_samples; i++) + update_stats(&stats, subframe->data.fixed.residual[i], 1); + break; + case FLAC__SUBFRAME_TYPE_LPC: + residual_samples = frame->header.blocksize - subframe->data.lpc.order; + for(i = 0; i < residual_samples; i++) + update_stats(&stats, subframe->data.lpc.residual[i], 1); + break; + default: + break; + } + + /* update all_ */ + for(i = 0; i < stats.nbuckets; i++) { + update_stats(&all_, stats.buckets[i].residual, stats.buckets[i].count); + } + + /* write the subframe */ + sprintf(outfilename, "f%06u.s%u.gp", frame_number, channel); + compute_stats(&stats); + + (void)dump_stats(&stats, outfilename); + } + } +} + +void flac__analyze_finish(analysis_options aopts) +{ + if(aopts.do_residual_gnuplot) { + compute_stats(&all_); + (void)dump_stats(&all_, "all"); + } +} + +void init_stats(subframe_stats_t *stats) +{ + stats->peak_index = -1; + stats->nbuckets = 0; + stats->nsamples = 0; + stats->sum = 0.0; + stats->sos = 0.0; +} + +void update_stats(subframe_stats_t *stats, FLAC__int32 residual, unsigned incr) +{ + unsigned i; + const double r = (double)residual, a = r*incr; + + stats->nsamples += incr; + stats->sum += a; + stats->sos += (a*r); + + for(i = 0; i < stats->nbuckets; i++) { + if(stats->buckets[i].residual == residual) { + stats->buckets[i].count += incr; + goto find_peak; + } + } + /* not found, make a new bucket */ + i = stats->nbuckets; + stats->buckets[i].residual = residual; + stats->buckets[i].count = incr; + stats->nbuckets++; +find_peak: + if(stats->peak_index < 0 || stats->buckets[i].count > stats->buckets[stats->peak_index].count) + stats->peak_index = i; +} + +void compute_stats(subframe_stats_t *stats) +{ + stats->mean = stats->sum / (double)stats->nsamples; + stats->variance = (stats->sos - (stats->sum * stats->sum / stats->nsamples)) / stats->nsamples; + stats->stddev = sqrt(stats->variance); +} + +FLAC__bool dump_stats(const subframe_stats_t *stats, const char *filename) +{ + FILE *outfile; + unsigned i; + const double m = stats->mean; + const double s1 = stats->stddev, s2 = s1*2, s3 = s1*3, s4 = s1*4, s5 = s1*5, s6 = s1*6; + const double p = stats->buckets[stats->peak_index].count; + + outfile = fopen(filename, "w"); + + if(0 == outfile) { + fprintf(stderr, "ERROR opening %s: %s\n", filename, strerror(errno)); + return false; + } + + fprintf(outfile, "plot '-' title 'PDF', '-' title 'mean' with impulses, '-' title '1-stddev' with histeps, '-' title '2-stddev' with histeps, '-' title '3-stddev' with histeps, '-' title '4-stddev' with histeps, '-' title '5-stddev' with histeps, '-' title '6-stddev' with histeps\n"); + + for(i = 0; i < stats->nbuckets; i++) { + fprintf(outfile, "%d %u\n", stats->buckets[i].residual, stats->buckets[i].count); + } + fprintf(outfile, "e\n"); + + fprintf(outfile, "%f %f\ne\n", stats->mean, p); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s1, p*0.8, m+s1, p*0.8); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s2, p*0.7, m+s2, p*0.7); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s3, p*0.6, m+s3, p*0.6); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s4, p*0.5, m+s4, p*0.5); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s5, p*0.4, m+s5, p*0.4); + fprintf(outfile, "%f %f\n%f %f\ne\n", m-s6, p*0.3, m+s6, p*0.3); + + fprintf(outfile, "pause -1 'waiting...'\n"); + + fclose(outfile); + return true; +} diff --git a/flac/src/flac/analyze.h b/flac/src/flac/analyze.h new file mode 100644 index 0000000..f666622 --- /dev/null +++ b/flac/src/flac/analyze.h @@ -0,0 +1,31 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__analyze_h +#define flac__analyze_h + +typedef struct { + FLAC__bool do_residual_text; + FLAC__bool do_residual_gnuplot; +} analysis_options; + +void flac__analyze_init(analysis_options aopts); +void flac__analyze_frame(const FLAC__Frame *frame, unsigned frame_number, FLAC__uint64 frame_offset, unsigned frame_bytes, analysis_options aopts, FILE *fout); +void flac__analyze_finish(analysis_options aopts); + +#endif diff --git a/flac/src/flac/decode.c b/flac/src/flac/decode.c new file mode 100644 index 0000000..6254866 --- /dev/null +++ b/flac/src/flac/decode.c @@ -0,0 +1,1434 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#if defined _WIN32 && !defined __CYGWIN__ +/* where MSVC puts unlink() */ +# include +#else +# include +#endif +#if defined _MSC_VER || defined __MINGW32__ +#include /* for off_t */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include +#include /* for floor() */ +#include /* for FILE etc. */ +#include /* for strcmp(), strerror() */ +#include "FLAC/all.h" +#include "share/grabbag.h" +#include "share/replaygain_synthesis.h" +#include "decode.h" + +typedef struct { +#if FLAC__HAS_OGG + FLAC__bool is_ogg; + FLAC__bool use_first_serial_number; + long serial_number; +#endif + + FileFormat format; + FLAC__bool treat_warnings_as_errors; + FLAC__bool continue_through_decode_errors; + FLAC__bool channel_map_none; + + struct { + replaygain_synthesis_spec_t spec; + FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */ + double scale; + DitherContext dither_context; + } replaygain; + + FLAC__bool test_only; + FLAC__bool analysis_mode; + analysis_options aopts; + utils__SkipUntilSpecification *skip_specification; + utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */ + utils__CueSpecification *cue_specification; + + const char *inbasefilename; + const char *infilename; + const char *outfilename; + + FLAC__uint64 samples_processed; + unsigned frame_counter; + FLAC__bool abort_flag; + FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */ + FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */ + + FLAC__bool iff_headers_need_fixup; + + FLAC__bool is_big_endian; + FLAC__bool is_unsigned_samples; + FLAC__bool got_stream_info; + FLAC__bool has_md5sum; + FLAC__uint64 total_samples; + unsigned bps; + unsigned channels; + unsigned sample_rate; + FLAC__uint32 channel_mask; + + /* these are used only in analyze mode */ + FLAC__uint64 decode_position; + + FLAC__StreamDecoder *decoder; + + FILE *fout; + + foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */ + off_t fm_offset1, fm_offset2, fm_offset3; +} DecoderSession; + + +static FLAC__bool is_big_endian_host_; + + +/* + * local routines + */ +static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename); +static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred); +static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename); +static FLAC__bool DecoderSession_process(DecoderSession *d); +static int DecoderSession_finish_ok(DecoderSession *d); +static int DecoderSession_finish_error(DecoderSession *d); +static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input); +static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples); +static FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask); +static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate); +static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val); +static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val); +static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val); +static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val); +static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val); +static FLAC__bool write_sane_extended(FILE *f, unsigned val); +static FLAC__bool fixup_iff_headers(DecoderSession *d); +static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); +static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status); +static void print_error_with_state(const DecoderSession *d, const char *message); +static void print_stats(const DecoderSession *decoder_session); + + +/* + * public routines + */ +int flac__decode_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options) +{ + DecoderSession decoder_session; + + FLAC__ASSERT( + options.format == FORMAT_WAVE || + options.format == FORMAT_WAVE64 || + options.format == FORMAT_RF64 || + options.format == FORMAT_AIFF || + options.format == FORMAT_AIFF_C || + options.format == FORMAT_RAW + ); + + if(options.format == FORMAT_RAW) { + decoder_session.is_big_endian = options.format_options.raw.is_big_endian; + decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples; + } + + if(! + DecoderSession_construct( + &decoder_session, +#if FLAC__HAS_OGG + options.is_ogg, + options.use_first_serial_number, + options.serial_number, +#else + /*is_ogg=*/false, + /*use_first_serial_number=*/false, + /*serial_number=*/0, +#endif + options.format, + options.treat_warnings_as_errors, + options.continue_through_decode_errors, + options.channel_map_none, + options.replaygain_synthesis_spec, + analysis_mode, + aopts, + &options.skip_specification, + &options.until_specification, + options.has_cue_specification? &options.cue_specification : 0, + options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata, + infilename, + outfilename + ) + ) + return 1; + + if(!DecoderSession_init_decoder(&decoder_session, infilename)) + return DecoderSession_finish_error(&decoder_session); + + if(!DecoderSession_process(&decoder_session)) + return DecoderSession_finish_error(&decoder_session); + + return DecoderSession_finish_ok(&decoder_session); +} + +FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename) +{ +#if FLAC__HAS_OGG + d->is_ogg = is_ogg; + d->use_first_serial_number = use_first_serial_number; + d->serial_number = serial_number; +#else + (void)is_ogg; + (void)use_first_serial_number; + (void)serial_number; +#endif + + d->format = format; + d->treat_warnings_as_errors = treat_warnings_as_errors; + d->continue_through_decode_errors = continue_through_decode_errors; + d->channel_map_none = channel_map_none; + d->replaygain.spec = replaygain_synthesis_spec; + d->replaygain.apply = false; + d->replaygain.scale = 0.0; + /* d->replaygain.dither_context gets initialized later once we know the sample resolution */ + d->test_only = (0 == outfilename); + d->analysis_mode = analysis_mode; + d->aopts = aopts; + d->skip_specification = skip_specification; + d->until_specification = until_specification; + d->cue_specification = cue_specification; + + d->inbasefilename = grabbag__file_get_basename(infilename); + d->infilename = infilename; + d->outfilename = outfilename; + + d->samples_processed = 0; + d->frame_counter = 0; + d->abort_flag = false; + d->aborting_due_to_until = false; + d->aborting_due_to_unparseable = false; + + d->iff_headers_need_fixup = false; + + d->total_samples = 0; + d->got_stream_info = false; + d->has_md5sum = false; + d->bps = 0; + d->channels = 0; + d->sample_rate = 0; + d->channel_mask = 0; + + d->decode_position = 0; + + d->decoder = 0; + + d->fout = 0; /* initialized with an open file later if necessary */ + + d->foreign_metadata = foreign_metadata; + + FLAC__ASSERT(!(d->test_only && d->analysis_mode)); + + if(!d->test_only) { + if(0 == strcmp(outfilename, "-")) { + d->fout = grabbag__file_get_binary_stdout(); + } + else { + if(0 == (d->fout = fopen(outfilename, "wb"))) { + flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno)); + DecoderSession_destroy(d, /*error_occurred=*/true); + return false; + } + } + } + + if(analysis_mode) + flac__analyze_init(aopts); + + return true; +} + +void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred) +{ + if(0 != d->fout && d->fout != stdout) { + fclose(d->fout); + if(error_occurred) + unlink(d->outfilename); + } +} + +FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename) +{ + FLAC__StreamDecoderInitStatus init_status; + FLAC__uint32 test = 1; + + is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true; + + if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata) { + const char *error; + if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) { + flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error); + return false; + } + } + + decoder_session->decoder = FLAC__stream_decoder_new(); + + if(0 == decoder_session->decoder) { + flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename); + return false; + } + + FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true); + if (0 != decoder_session->cue_specification) + FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET); + if (decoder_session->replaygain.spec.apply) + FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT); + +#if FLAC__HAS_OGG + if(decoder_session->is_ogg) { + if(!decoder_session->use_first_serial_number) + FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number); + init_status = FLAC__stream_decoder_init_ogg_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session); + } + else +#endif + { + init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session); + } + + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status); + return false; + } + + return true; +} + +FLAC__bool DecoderSession_process(DecoderSession *d) +{ + if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) { + flac__utils_printf(stderr, 2, "\n"); + print_error_with_state(d, "ERROR while decoding metadata"); + return false; + } + if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) { + flac__utils_printf(stderr, 2, "\n"); + print_error_with_state(d, "ERROR during metadata decoding"); + if(!d->continue_through_decode_errors) + return false; + } + + if(d->abort_flag) + return false; + + /* set channel mapping */ + if(!d->channel_map_none) { + /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */ + /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */ + if(d->channels == 1) { + if(d->channel_mask == 0) + d->channel_mask = 0x0001; + } + else if(d->channels == 2) { + if(d->channel_mask == 0) + d->channel_mask = 0x0003; + } + else if(d->channels == 3) { + if(d->channel_mask == 0) + d->channel_mask = 0x0007; + } + else if(d->channels == 4) { + if(d->channel_mask == 0) + d->channel_mask = 0x0033; + } + else if(d->channels == 5) { + if(d->channel_mask == 0) + d->channel_mask = 0x0607; + } + else if(d->channels == 6) { + if(d->channel_mask == 0) + d->channel_mask = 0x060f; + } + } + + /* write the WAVE/AIFF headers if necessary */ + if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) { + if(!write_iff_headers(d->fout, d, d->total_samples)) { + d->abort_flag = true; + return false; + } + } + + if(d->skip_specification->value.samples > 0) { + const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples; + + if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) { + print_error_with_state(d, "ERROR seeking while skipping bytes"); + return false; + } + } + if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) { + flac__utils_printf(stderr, 2, "\n"); + print_error_with_state(d, "ERROR while decoding data"); + if(!d->continue_through_decode_errors) + return false; + } + if( + (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) || + (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) + ) { + flac__utils_printf(stderr, 2, "\n"); + print_error_with_state(d, "ERROR during decoding"); + return false; + } + + /* write padding bytes for alignment if necessary */ + if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) { + const FLAC__uint64 data_size = d->total_samples * d->channels * ((d->bps+7)/8); + unsigned padding; + if(d->format != FORMAT_WAVE64) { + padding = (unsigned)(data_size & 1); + } + else { + /* 8-byte alignment for Wave64 */ + padding = (8 - (unsigned)(data_size & 7)) & 7; + } + for( ; padding > 0; --padding) { + if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) { + print_error_with_state( + d, + d->format == FORMAT_WAVE? "ERROR writing pad byte to WAVE data chunk" : + d->format == FORMAT_WAVE64? "ERROR writing pad bytes to WAVE64 data chunk" : + d->format == FORMAT_RF64? "ERROR writing pad byte to RF64 data chunk" : + "ERROR writing pad byte to AIFF SSND chunk" + ); + return false; + } + } + } + + return true; +} + +int DecoderSession_finish_ok(DecoderSession *d) +{ + FLAC__bool ok = true, md5_failure = false; + + if(d->decoder) { + md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until; + print_stats(d); + FLAC__stream_decoder_delete(d->decoder); + } + if(d->analysis_mode) + flac__analyze_finish(d->aopts); + if(md5_failure) { + flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename); + ok = d->continue_through_decode_errors; + } + else { + if(!d->got_stream_info) { + flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename); + ok = !d->treat_warnings_as_errors; + } + else if(!d->has_md5sum) { + flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename); + ok = !d->treat_warnings_as_errors; + } + flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done"); + } + DecoderSession_destroy(d, /*error_occurred=*/!ok); + if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) { + if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) { + if(!fixup_iff_headers(d)) + return 1; + } + if(d->foreign_metadata) { + const char *error; + if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) { + flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error); + return 1; + } + } + } + return ok? 0 : 1; +} + +int DecoderSession_finish_error(DecoderSession *d) +{ + if(d->decoder) { + (void)FLAC__stream_decoder_finish(d->decoder); + FLAC__stream_decoder_delete(d->decoder); + } + if(d->analysis_mode) + flac__analyze_finish(d->aopts); + DecoderSession_destroy(d, /*error_occurred=*/true); + return 1; +} + +FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input) +{ + /* convert from mm:ss.sss to sample number if necessary */ + flac__utils_canonicalize_skip_until_specification(spec, sample_rate); + + /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */ + if(spec->is_relative && spec->value.samples == 0) { + spec->is_relative = false; + return true; + } + + /* in any other case the total samples in the input must be known */ + if(total_samples_in_input == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename); + return false; + } + + FLAC__ASSERT(spec->value_is_samples); + + /* convert relative specifications to absolute */ + if(spec->is_relative) { + if(spec->value.samples <= 0) + spec->value.samples += (FLAC__int64)total_samples_in_input; + else + spec->value.samples += skip; + spec->is_relative = false; + } + + /* error check */ + if(spec->value.samples < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename); + return false; + } + if((FLAC__uint64)spec->value.samples <= skip) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename); + return false; + } + if((FLAC__uint64)spec->value.samples > total_samples_in_input) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename); + return false; + } + + return true; +} + +FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples) +{ + const FileFormat format = decoder_session->format; + const char *fmt_desc = + format==FORMAT_WAVE? "WAVE" : + format==FORMAT_WAVE64? "Wave64" : + format==FORMAT_RF64? "RF64" : + "AIFF"; + const FLAC__bool is_waveformatextensible = + (format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) && + ( + decoder_session->channel_mask == 2 || + decoder_session->channel_mask > 3 || + decoder_session->bps%8 || + decoder_session->channels > 2 + ); + const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8); + const FLAC__uint64 aligned_data_size = + format == FORMAT_WAVE64? + (data_size+7) & (~(FLAC__uint64)7) : + (data_size+1) & (~(FLAC__uint64)1); + + FLAC__uint64 iff_size; + unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */ + foreign_metadata_t *fm = decoder_session->foreign_metadata; + size_t i; + + FLAC__ASSERT( + format == FORMAT_WAVE || + format == FORMAT_WAVE64 || + format == FORMAT_RF64 || + format == FORMAT_AIFF || + format == FORMAT_AIFF_C + ); + + if(samples == 0) { + if(f == stdout) { + flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc); + flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc); + flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n"); + if(decoder_session->treat_warnings_as_errors) + return false; + } + else { + decoder_session->iff_headers_need_fixup = true; + } + } + + if(fm) { + FLAC__ASSERT(fm->format_block); + FLAC__ASSERT(fm->audio_block); + FLAC__ASSERT(fm->format_block < fm->audio_block); + /* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */ + for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) { + if(i != fm->format_block && i != fm->audio_block) + foreign_metadata_size += fm->blocks[i].size; + } + } + + if(samples == 0) + iff_size = 0; + else if(format == FORMAT_WAVE || format == FORMAT_RF64) + /* 4 for WAVE form bytes */ + /* +{36,0} for ds64 chunk */ + /* +8+{40,16} for fmt chunk header and body */ + /* +8 for data chunk header */ + iff_size = 4 + (format==FORMAT_RF64?36:0) + 8+(is_waveformatextensible?40:16) + 8 + foreign_metadata_size + aligned_data_size; + else if(format == FORMAT_WAVE64) + /* 16+8 for RIFF GUID and size field */ + /* +16 for WAVE GUID */ + /* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */ + /* +16+8 for data chunk header (GUID and size field) */ + iff_size = 16+8 + 16 + 16+8+(is_waveformatextensible?40:16) + 16+8 + foreign_metadata_size + aligned_data_size; + else /* AIFF */ + iff_size = 46 + foreign_metadata_size + aligned_data_size; + + if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) { + flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc); + return false; + } + + if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) { + /* RIFF header */ + switch(format) { + case FORMAT_WAVE: + if(flac__utils_fwrite("RIFF", 1, 4, f) != 4) + return false; + if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */ + return false; + if(flac__utils_fwrite("WAVE", 1, 4, f) != 4) + return false; + break; + case FORMAT_WAVE64: + /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */ + if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16) + return false; + if(!write_little_endian_uint64(f, iff_size)) + return false; + /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16) + return false; + break; + case FORMAT_RF64: + if(flac__utils_fwrite("RF64", 1, 4, f) != 4) + return false; + if(!write_little_endian_uint32(f, 0xffffffff)) + return false; + if(flac__utils_fwrite("WAVE", 1, 4, f) != 4) + return false; + break; + default: + return false; + } + + /* ds64 chunk for RF64 */ + if(format == FORMAT_RF64) { + if(flac__utils_fwrite("ds64", 1, 4, f) != 4) + return false; + + if(!write_little_endian_uint32(f, 28)) /* chunk size */ + return false; + + if(!write_little_endian_uint64(f, iff_size)) + return false; + + if(!write_little_endian_uint64(f, data_size)) + return false; + + if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */ + return false; + + if(!write_little_endian_uint32(f, 0)) /* table size */ + return false; + } + + decoder_session->fm_offset1 = ftello(f); + + if(fm) { + /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */ + for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) { + if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename); + return false; + } + } + } + + if(format != FORMAT_WAVE64) { + if(flac__utils_fwrite("fmt ", 1, 4, f) != 4) + return false; + if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */ + return false; + } + else { /* Wave64 */ + /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16) + return false; + /* chunk size (+16+8 for GUID and size fields) */ + if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16))) + return false; + } + + if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask)) + return false; + + decoder_session->fm_offset2 = ftello(f); + + if(fm) { + /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */ + for(i = fm->format_block+1; i < fm->audio_block; i++) { + if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename); + return false; + } + } + } + + if(format != FORMAT_WAVE64) { + if(flac__utils_fwrite("data", 1, 4, f) != 4) + return false; + if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size)) + return false; + } + else { /* Wave64 */ + /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16) + return false; + /* +16+8 for GUID and size fields */ + if(!write_little_endian_uint64(f, 16+8 + data_size)) + return false; + } + + decoder_session->fm_offset3 = ftello(f) + aligned_data_size; + } + else { + if(flac__utils_fwrite("FORM", 1, 4, f) != 4) + return false; + + if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */ + return false; + + if(flac__utils_fwrite("AIFF", 1, 4, f) != 4) + return false; + + decoder_session->fm_offset1 = ftello(f); + + if(fm) { + /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */ + for(i = 1; i < fm->format_block; i++) { + if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename); + return false; + } + } + } + + if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate)) + return false; + + decoder_session->fm_offset2 = ftello(f); + + if(fm) { + /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */ + for(i = fm->format_block+1; i < fm->audio_block; i++) { + if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename); + return false; + } + } + } + + if(flac__utils_fwrite("SSND", 1, 4, f) != 4) + return false; + + if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8)) /* data size */ + return false; + + if(!write_big_endian_uint32(f, 0/*offset_size*/)) + return false; + + if(!write_big_endian_uint32(f, 0/*block_size*/)) + return false; + + decoder_session->fm_offset3 = ftello(f) + aligned_data_size; + } + + return true; +} + +FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask) +{ + if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */ + return false; + + if(!write_little_endian_uint16(f, (FLAC__uint16)channels)) + return false; + + if(!write_little_endian_uint32(f, sample_rate)) + return false; + + if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8))) + return false; + + if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */ + return false; + + if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */ + return false; + + if(is_waveformatextensible) { + if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */ + return false; + + if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */ + return false; + + if(!write_little_endian_uint32(f, channel_mask)) + return false; + + /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */ + if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16) + return false; + } + + return true; +} + +FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate) +{ + FLAC__ASSERT(samples <= 0xffffffff); + + if(flac__utils_fwrite("COMM", 1, 4, f) != 4) + return false; + + if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */ + return false; + + if(!write_big_endian_uint16(f, (FLAC__uint16)channels)) + return false; + + if(!write_big_endian_uint32(f, (FLAC__uint32)samples)) + return false; + + if(!write_big_endian_uint16(f, (FLAC__uint16)bps)) + return false; + + if(!write_sane_extended(f, sample_rate)) + return false; + + return true; +} + +FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val) +{ + FLAC__byte *b = (FLAC__byte*)(&val); + if(is_big_endian_host_) { + FLAC__byte tmp; + tmp = b[1]; b[1] = b[0]; b[0] = tmp; + } + return flac__utils_fwrite(b, 1, 2, f) == 2; +} + +FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val) +{ + FLAC__byte *b = (FLAC__byte*)(&val); + if(is_big_endian_host_) { + FLAC__byte tmp; + tmp = b[3]; b[3] = b[0]; b[0] = tmp; + tmp = b[2]; b[2] = b[1]; b[1] = tmp; + } + return flac__utils_fwrite(b, 1, 4, f) == 4; +} + +FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val) +{ + FLAC__byte *b = (FLAC__byte*)(&val); + if(is_big_endian_host_) { + FLAC__byte tmp; + tmp = b[7]; b[7] = b[0]; b[0] = tmp; + tmp = b[6]; b[6] = b[1]; b[1] = tmp; + tmp = b[5]; b[5] = b[2]; b[2] = tmp; + tmp = b[4]; b[4] = b[3]; b[3] = tmp; + } + return flac__utils_fwrite(b, 1, 8, f) == 8; +} + +FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val) +{ + FLAC__byte *b = (FLAC__byte*)(&val); + if(!is_big_endian_host_) { + FLAC__byte tmp; + tmp = b[1]; b[1] = b[0]; b[0] = tmp; + } + return flac__utils_fwrite(b, 1, 2, f) == 2; +} + +FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val) +{ + FLAC__byte *b = (FLAC__byte*)(&val); + if(!is_big_endian_host_) { + FLAC__byte tmp; + tmp = b[3]; b[3] = b[0]; b[0] = tmp; + tmp = b[2]; b[2] = b[1]; b[1] = tmp; + } + return flac__utils_fwrite(b, 1, 4, f) == 4; +} + +FLAC__bool write_sane_extended(FILE *f, unsigned val) + /* Write to 'f' a SANE extended representation of 'val'. Return false if + * the write succeeds; return true otherwise. + * + * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits + * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754 + * representations, it does not imply a 1 above the MSB of the significand. + * + * Preconditions: + * val!=0U + */ +{ + unsigned int shift, exponent; + + FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */ + + for(shift= 0U; (val>>(31-shift))==0U; ++shift) + ; + val<<= shift; + exponent= 63U-(shift+32U); /* add 32 for unused second word */ + + if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF))) + return false; + if(!write_big_endian_uint32(f, val)) + return false; + if(!write_big_endian_uint32(f, 0)) /* unused second word */ + return false; + + return true; +} + +FLAC__bool fixup_iff_headers(DecoderSession *d) +{ + const char *fmt_desc = + d->format==FORMAT_WAVE? "WAVE" : + d->format==FORMAT_WAVE64? "Wave64" : + d->format==FORMAT_RF64? "RF64" : + "AIFF"; + FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */ + + if(0 == f) { + flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno)); + return false; + } + + if(!write_iff_headers(f, d, d->samples_processed)) { + fclose(f); + return false; + } + + fclose(f); + return true; +} + +FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + DecoderSession *decoder_session = (DecoderSession*)client_data; + FILE *fout = decoder_session->fout; + const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels; + const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8))? 8-(bps%8): 0; + FLAC__bool is_big_endian = ( + decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : ( + decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? false : + decoder_session->is_big_endian + )); + FLAC__bool is_unsigned_samples = ( + decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : ( + decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 : + decoder_session->is_unsigned_samples + )); + unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte; + unsigned frame_bytes = 0; + static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */ + FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer; + FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer; + FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer; + FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer; + FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer; + size_t bytes_to_write = 0; + + (void)decoder; + + if(decoder_session->abort_flag) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + /* sanity-check the bits-per-sample */ + if(decoder_session->bps) { + if(bps != decoder_session->bps) { + if(decoder_session->got_stream_info) + flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps); + else + flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps); + if(!decoder_session->continue_through_decode_errors) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + else { + /* must not have gotten STREAMINFO, save the bps from the frame header */ + FLAC__ASSERT(!decoder_session->got_stream_info); + decoder_session->bps = bps; + } + + /* sanity-check the #channels */ + if(decoder_session->channels) { + if(channels != decoder_session->channels) { + if(decoder_session->got_stream_info) + flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels); + else + flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels); + if(!decoder_session->continue_through_decode_errors) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + else { + /* must not have gotten STREAMINFO, save the #channels from the frame header */ + FLAC__ASSERT(!decoder_session->got_stream_info); + decoder_session->channels = channels; + } + + /* sanity-check the sample rate */ + if(decoder_session->sample_rate) { + if(frame->header.sample_rate != decoder_session->sample_rate) { + if(decoder_session->got_stream_info) + flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate); + else + flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate); + if(!decoder_session->continue_through_decode_errors) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + else { + /* must not have gotten STREAMINFO, save the sample rate from the frame header */ + FLAC__ASSERT(!decoder_session->got_stream_info); + decoder_session->sample_rate = frame->header.sample_rate; + } + + /* + * limit the number of samples to accept based on --until + */ + FLAC__ASSERT(!decoder_session->skip_specification->is_relative); + /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */ + if(decoder_session->skip_specification->is_relative) { + if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */ + decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */ + else { + flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + if(decoder_session->until_specification->is_relative) { + if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */ + decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */ + else { + flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0); + FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0); + if(decoder_session->until_specification->value.samples > 0) { + const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples; + const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples; + const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed; + FLAC__ASSERT(until >= input_samples_passed); + if(input_samples_passed + wide_samples > until) + wide_samples = (unsigned)(until - input_samples_passed); + if (wide_samples == 0) { + decoder_session->abort_flag = true; + decoder_session->aborting_due_to_until = true; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + if(decoder_session->analysis_mode) { + FLAC__uint64 dpos; + FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos); + frame_bytes = (unsigned)(dpos-decoder_session->decode_position); + decoder_session->decode_position = dpos; + } + + if(wide_samples > 0) { + decoder_session->samples_processed += wide_samples; + decoder_session->frame_counter++; + + if(!(decoder_session->frame_counter & 0x3f)) + print_stats(decoder_session); + + if(decoder_session->analysis_mode) { + flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout); + } + else if(!decoder_session->test_only) { + if(shift && !decoder_session->replaygain.apply) { + for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++) + ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/ + } + if(decoder_session->replaygain.apply) { + bytes_to_write = FLAC__replaygain_synthesis__apply_gain( + u8buffer, + !is_big_endian, + is_unsigned_samples, + buffer, + wide_samples, + channels, + bps, /* source_bps */ + bps+shift, /* target_bps */ + decoder_session->replaygain.scale, + decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */ + decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */ + &decoder_session->replaygain.dither_context + ); + } + /* first some special code for common cases */ + else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) { + FLAC__int16 *buf1_ = s16buffer + 1; + if(is_big_endian) + memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2); + else + memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples); + for(sample = 0; sample < wide_samples; sample++, buf1_+=2) + *buf1_ = (FLAC__int16)buffer[1][sample]; + bytes_to_write = 4 * sample; + } + else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) { + FLAC__int16 *buf1_ = s16buffer; + for(sample = 0; sample < wide_samples; sample++) + *buf1_++ = (FLAC__int16)buffer[0][sample]; + bytes_to_write = 2 * sample; + } + /* generic code for the rest */ + else if(bps+shift == 16) { + if(is_unsigned_samples) { + if(channels == 2) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) { + u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000); + u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000); + } + } + else if(channels == 1) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000); + } + else { /* works for any 'channels' but above flavors are faster for 1 and 2 */ + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000); + } + } + else { + if(channels == 2) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) { + s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]); + s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]); + } + } + else if(channels == 1) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]); + } + else { /* works for any 'channels' but above flavors are faster for 1 and 2 */ + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]); + } + } + if(is_big_endian != is_big_endian_host_) { + unsigned char tmp; + const unsigned bytes = sample * 2; + for(byte = 0; byte < bytes; byte += 2) { + tmp = u8buffer[byte]; + u8buffer[byte] = u8buffer[byte+1]; + u8buffer[byte+1] = tmp; + } + } + bytes_to_write = 2 * sample; + } + else if(bps+shift == 24) { + if(is_unsigned_samples) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + u32buffer[sample] = buffer[channel][wide_sample] + 0x800000; + } + else { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + s32buffer[sample] = buffer[channel][wide_sample]; + } + if(is_big_endian != is_big_endian_host_) { + unsigned char tmp; + const unsigned bytes = sample * 4; + for(byte = 0; byte < bytes; byte += 4) { + tmp = u8buffer[byte]; + u8buffer[byte] = u8buffer[byte+3]; + u8buffer[byte+3] = tmp; + tmp = u8buffer[byte+1]; + u8buffer[byte+1] = u8buffer[byte+2]; + u8buffer[byte+2] = tmp; + } + } + if(is_big_endian) { + unsigned lbyte; + const unsigned bytes = sample * 4; + for(lbyte = byte = 0; byte < bytes; ) { + byte++; + u8buffer[lbyte++] = u8buffer[byte++]; + u8buffer[lbyte++] = u8buffer[byte++]; + u8buffer[lbyte++] = u8buffer[byte++]; + } + } + else { + unsigned lbyte; + const unsigned bytes = sample * 4; + for(lbyte = byte = 0; byte < bytes; ) { + u8buffer[lbyte++] = u8buffer[byte++]; + u8buffer[lbyte++] = u8buffer[byte++]; + u8buffer[lbyte++] = u8buffer[byte++]; + byte++; + } + } + bytes_to_write = 3 * sample; + } + else if(bps+shift == 8) { + if(is_unsigned_samples) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80); + } + else { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]); + } + bytes_to_write = sample; + } + else { + FLAC__ASSERT(0); + /* double protection */ + decoder_session->abort_flag = true; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + } + if(bytes_to_write > 0) { + if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) { + /* if a pipe closed when writing to stdout, we let it go without an error message */ + if(errno == EPIPE && decoder_session->fout == stdout) + decoder_session->aborting_due_to_until = true; + decoder_session->abort_flag = true; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + DecoderSession *decoder_session = (DecoderSession*)client_data; + + if(decoder_session->analysis_mode) + FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position); + + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + FLAC__uint64 skip, until; + decoder_session->got_stream_info = true; + decoder_session->has_md5sum = memcmp(metadata->data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16); + decoder_session->bps = metadata->data.stream_info.bits_per_sample; + decoder_session->channels = metadata->data.stream_info.channels; + decoder_session->sample_rate = metadata->data.stream_info.sample_rate; + + flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate); + FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0); + skip = (FLAC__uint64)decoder_session->skip_specification->value.samples; + + /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */ + if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) { + flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename); + decoder_session->abort_flag = true; + return; + } + else if(metadata->data.stream_info.total_samples == 0 && skip > 0) { + flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename); + decoder_session->abort_flag = true; + return; + } + FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification); + decoder_session->total_samples = metadata->data.stream_info.total_samples - skip; + + /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */ + if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) { + decoder_session->abort_flag = true; + return; + } + FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0); + until = (FLAC__uint64)decoder_session->until_specification->value.samples; + + if(until > 0) { + FLAC__ASSERT(decoder_session->total_samples != 0); + FLAC__ASSERT(0 == decoder_session->cue_specification); + decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until); + } + + if(decoder_session->bps < 4 || decoder_session->bps > 24) { + flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps); + decoder_session->abort_flag = true; + return; + } + } + else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) { + /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */ + if(decoder_session->total_samples == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename); + decoder_session->abort_flag = true; + return; + } + + flac__utils_canonicalize_cue_specification(decoder_session->cue_specification, &metadata->data.cue_sheet, decoder_session->total_samples, decoder_session->skip_specification, decoder_session->until_specification); + + FLAC__ASSERT(!decoder_session->skip_specification->is_relative); + FLAC__ASSERT(decoder_session->skip_specification->value_is_samples); + + FLAC__ASSERT(!decoder_session->until_specification->is_relative); + FLAC__ASSERT(decoder_session->until_specification->value_is_samples); + + FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0); + FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0); + FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples); + FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples); + + decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples; + } + else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + if (decoder_session->replaygain.spec.apply) { + double reference, gain, peak; + if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) { + flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album"); + if(decoder_session->treat_warnings_as_errors) { + decoder_session->abort_flag = true; + return; + } + } + else { + const char *ls[] = { "no", "peak", "hard" }; + const char *ns[] = { "no", "low", "medium", "high" }; + decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK); + FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32); + FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping); + flac__utils_printf(stderr, 1, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]); + flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename); + /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */ + } + } + (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask); + } +} + +void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + DecoderSession *decoder_session = (DecoderSession*)client_data; + (void)decoder; + flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]); + if(!decoder_session->continue_through_decode_errors) { + decoder_session->abort_flag = true; + if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM) + decoder_session->aborting_due_to_unparseable = true; + } +} + +void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status) +{ + const int ilen = strlen(d->inbasefilename) + 1; + + flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message); + + flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]); + + /* print out some more info for some errors: */ + if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) { + flac__utils_printf(stderr, 1, + "\n" + "An error occurred opening the input file; it is likely that it does not exist\n" + "or is not readable.\n" + ); + } +} + +void print_error_with_state(const DecoderSession *d, const char *message) +{ + const int ilen = strlen(d->inbasefilename) + 1; + + flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message); + flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder)); + + /* print out some more info for some errors: */ + if (d->aborting_due_to_unparseable) { + flac__utils_printf(stderr, 1, + "\n" + "The FLAC stream may have been created by a more advanced encoder. Try\n" + " metaflac --show-vendor-tag %s\n" + "If the version number is greater than %s, this decoder is probably\n" + "not able to decode the file. If the version number is not, the file\n" + "may be corrupted, or you may have found a bug. In this case please\n" + "submit a bug report to\n" + " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n" + "Make sure to use the \"Monitor\" feature to monitor the bug status.\n", + d->inbasefilename, FLAC__VERSION_STRING + ); + } +} + +void print_stats(const DecoderSession *decoder_session) +{ + if(flac__utils_verbosity_ >= 2) { +#if defined _MSC_VER || defined __MINGW32__ + /* with MSVC you have to spoon feed it the casting */ + const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0; +#else + const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0; +#endif + if(decoder_session->total_samples > 0) { + fprintf(stderr, "\r%s: %s%u%% complete", + decoder_session->inbasefilename, + decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "", + (unsigned)floor(progress + 0.5) + ); + } + else { + fprintf(stderr, "\r%s: %s %u samples", + decoder_session->inbasefilename, + decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote", + (unsigned)decoder_session->samples_processed + ); + } + } +} diff --git a/flac/src/flac/decode.h b/flac/src/flac/decode.h new file mode 100644 index 0000000..d025d3b --- /dev/null +++ b/flac/src/flac/decode.h @@ -0,0 +1,70 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__decode_h +#define flac__decode_h + +#if HAVE_CONFIG_H +# include +#endif + +#include "analyze.h" +#include "foreign_metadata.h" +#include "utils.h" +#include "share/replaygain_synthesis.h" + + +typedef struct { + FLAC__bool apply; + FLAC__bool use_album_gain; /* false => use track gain */ + enum { RGSS_LIMIT__NONE, RGSS_LIMIT__PEAK, RGSS_LIMIT__HARD} limiter; + NoiseShaping noise_shaping; + double preamp; +} replaygain_synthesis_spec_t; + +typedef struct { + FLAC__bool treat_warnings_as_errors; + FLAC__bool continue_through_decode_errors; + replaygain_synthesis_spec_t replaygain_synthesis_spec; +#if FLAC__HAS_OGG + FLAC__bool is_ogg; + FLAC__bool use_first_serial_number; + long serial_number; +#endif + utils__SkipUntilSpecification skip_specification; + utils__SkipUntilSpecification until_specification; + FLAC__bool has_cue_specification; + utils__CueSpecification cue_specification; + FLAC__bool channel_map_none; /* --channel-map=none specified, eventually will expand to take actual channel map */ + + FileFormat format; + union { + struct { + FLAC__bool is_big_endian; + FLAC__bool is_unsigned_samples; + } raw; + struct { + foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */ + } iff; + } format_options; +} decode_options_t; + +/* outfile == 0 => test only */ +int flac__decode_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options); + +#endif diff --git a/flac/src/flac/encode.c b/flac/src/flac/encode.c new file mode 100644 index 0000000..226b351 --- /dev/null +++ b/flac/src/flac/encode.c @@ -0,0 +1,2868 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#if defined _WIN32 && !defined __CYGWIN__ +/* where MSVC puts unlink() */ +# include +#else +# include +#endif +#if defined _MSC_VER || defined __MINGW32__ +#include /* for off_t */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include +#include /* for LONG_MAX */ +#include /* for floor() */ +#include /* for FILE etc. */ +#include /* for malloc */ +#include /* for strcmp(), strerror() */ +#include "FLAC/all.h" +#include "share/alloc.h" +#include "share/grabbag.h" +#include "encode.h" + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) +#ifdef max +#undef max +#endif +#define max(x,y) ((x)>(y)?(x):(y)) + +/* this MUST be >= 588 so that sector aligning can take place with one read */ +/* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */ +#define CHUNK_OF_SAMPLES 2048 + +typedef struct { + unsigned sample_rate; + unsigned channels; + unsigned bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */ + unsigned shift; /* # of LSBs samples have been shifted left by */ + unsigned bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */ + FLAC__bool is_unsigned_samples; + FLAC__bool is_big_endian; + FLAC__uint32 channel_mask; +} SampleInfo; + +/* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */ +typedef struct { + off_t filesize; + const FLAC__byte *lookahead; + unsigned lookahead_length; + size_t num_metadata_blocks; + FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */ + FLAC__uint64 samples_left_to_process; + FLAC__bool fatal_error; +} FLACDecoderData; + +typedef struct { +#if FLAC__HAS_OGG + FLAC__bool use_ogg; +#endif + FLAC__bool verify; + FLAC__bool is_stdout; + FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */ + const char *inbasefilename; + const char *infilename; + const char *outfilename; + + FLAC__bool treat_warnings_as_errors; + FLAC__bool continue_through_decode_errors; + FLAC__bool replay_gain; + FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */ + FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */ + FLAC__uint64 bytes_written; + FLAC__uint64 samples_written; + unsigned stats_mask; + + SampleInfo info; + + FileFormat format; + union { + struct { + FLAC__uint64 data_bytes; + } iff; + struct { + FLAC__StreamDecoder *decoder; + FLACDecoderData client_data; + } flac; + } fmt; + + FLAC__StreamEncoder *encoder; + + FILE *fin; + FLAC__StreamMetadata *seek_table_template; +} EncoderSession; + +const int FLAC_ENCODE__DEFAULT_PADDING = 8192; + +static FLAC__bool is_big_endian_host_; + +static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)]; +static signed char *scbuffer_ = (signed char *)ucbuffer_; +static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_; +static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_; + +static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES]; +static FLAC__int32 *input_[FLAC__MAX_CHANNELS]; + + +/* + * unpublished debug routines from the FLAC libs + */ +extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value); +extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value); +extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value); +extern FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value); + +/* + * local routines + */ +static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length); +static void EncoderSession_destroy(EncoderSession *e); +static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata); +static int EncoderSession_finish_error(EncoderSession *e); +static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options); +static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples); +static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e); +static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e); +static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input); +static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata); +static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map); +static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data); +static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data); +static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data); +static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data); +static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data); +static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); +static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors); +static void print_stats(const EncoderSession *encoder_session); +static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status); +static void print_error_with_state(const EncoderSession *e, const char *message); +static void print_verify_error(EncoderSession *e); +static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn); +static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn); +static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn); +static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn); +static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn); +static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset); +static unsigned count_channel_mask_bits(FLAC__uint32 mask); +#if 0 +static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels); +#endif + +static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options) +{ + e->info.sample_rate = options.format_options.raw.sample_rate; + e->info.channels = options.format_options.raw.channels; + e->info.bits_per_sample = options.format_options.raw.bps; + e->info.shift = 0; + e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8); + e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples; + e->info.is_big_endian = options.format_options.raw.is_big_endian; + e->info.channel_mask = 0; + + return true; +} + +static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options) +{ + FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false; + unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0; + FLAC__uint32 channel_mask = 0; + FLAC__uint64 ds64_data_size = 0; + + e->info.is_unsigned_samples = false; + e->info.is_big_endian = false; + + if(e->format == FORMAT_WAVE64) { + /* + * lookahead[] already has "riff\x2E\x91\xCF\x11\xD6\xA5\x28\xDB", skip over remaining header + */ + if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */ + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename); + return false; + } + } + /* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */ + + while(!feof(e->fin) && !got_data_chunk) { + /* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */ + /* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */ + char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' }; + + if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) { + flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename); + return false; + } + if(feof(e->fin)) + break; + + if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */ + FLAC__uint32 xx, data_bytes; + + if(got_ds64_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename); + return false; + } + if(got_fmt_chunk || got_data_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename); + return false; + } + + /* ds64 chunk size */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + data_bytes = xx; + if(data_bytes < 28) { + flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes); + return false; + } + if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */ + data_bytes++; + + /* RIFF 64-bit size, lo/hi */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + + /* 'data' 64-bit size */ + if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename)) + return false; + + data_bytes -= 16; + + /* skip any extra data in the ds64 chunk */ + if(!fskip_ahead(e->fin, data_bytes)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename); + return false; + } + + got_ds64_chunk = true; + } + else if( + !memcmp(chunk_id, "fmt ", 4) && + (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16)) + ) { /* format chunk */ + FLAC__uint16 x; + FLAC__uint32 xx, data_bytes; + FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */ + unsigned block_align; + + if(got_fmt_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename); + return false; + } + + /* see + * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html + * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx + * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp + * + * WAVEFORMAT is + * 4 byte: chunk size + * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE + * 2 byte: # channels + * 4 byte: sample rate (Hz) + * 4 byte: avg bytes per sec + * 2 byte: block align + * 2 byte: bits per sample (not necessarily all significant) + * WAVEFORMATEX adds + * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM) + * WAVEFORMATEXTENSIBLE adds + * 2 byte: valid bits per sample + * 4 byte: channel mask + * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM + * + * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE. + * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo. + * + * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8 + * + * If the channel mask has more set bits than # of channels, the extra MSBs are ignored. + * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker. + * + * Data is supposed to be unsigned for bps <= 8 else signed. + */ + + /* fmt chunk size */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + data_bytes = xx; + if(e->format == FORMAT_WAVE64) { + /* other half of the size field should be 0 */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + if(xx) { + flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes); + return false; + } + /* subtract size of header */ + if (data_bytes < 16+8) { + flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes); + return false; + } + data_bytes -= (16+8); + } + if(data_bytes < 16) { + flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes); + return false; + } + if(e->format != FORMAT_WAVE64) { + if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */ + data_bytes++; + } + else { /* Wave64 */ + data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */ + } + + /* format code */ + if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename)) + return false; + if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (unsigned)wFormatTag); + return false; + } + + /* number of channels */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + channels = (unsigned)x; + + /* sample rate */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + sample_rate = xx; + + /* avg bytes per second (ignored) */ + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + /* block align */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + block_align = (unsigned)x; + /* bits per sample */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + bps = (unsigned)x; + + e->info.is_unsigned_samples = (bps <= 8); + + if(wFormatTag == 1) { + if(bps != 8 && bps != 16) { + if(bps == 24 || bps == 32) { + /* let these slide with a warning since they're unambiguous */ + flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps); + if(e->treat_warnings_as_errors) + return false; + } + else { + /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */ + flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps); + return false; + } + } +#if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */ + if((bps+7)/8 * channels == block_align) { + if(bps % 8) { + /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */ + flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels); + if(e->treat_warnings_as_errors) + return false; + shift = 8 - (bps % 8); + bps += shift; + } + else + shift = 0; + } + else { + flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels); + return false; + } +#else + shift = 0; +#endif + if(channels > 2 && !options.channel_map_none) { + flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename); + return false; + } + FLAC__ASSERT(data_bytes >= 16); + data_bytes -= 16; + } + else { + if(data_bytes < 40) { + flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes); + return false; + } + /* cbSize */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + if(x < 22) { + flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x); + return false; + } + /* valid bps */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + if((unsigned)x > bps) { + flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps); + return false; + } + shift = bps - (unsigned)x; + /* channel mask */ + if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename)) + return false; + /* for mono/stereo and unassigned channels, we fake the mask */ + if(channel_mask == 0) { + if(channels == 1) + channel_mask = 0x0001; + else if(channels == 2) + channel_mask = 0x0003; + } + /* set channel mapping */ + /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */ + /* front left, front right, center, LFE, back left, back right, surround left, surround right */ + /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */ +#if 0 + /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */ + if( + options.channel_map_none || + channel_mask == 0x0001 || /* 1 channel: (mono) */ + channel_mask == 0x0003 || /* 2 channels: front left, front right */ + channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */ + channel_mask == 0x0603 /* 4 channels: front left, front right, side left, side right */ + ) { + /* keep default channel order */ + } + else if( + channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */ + channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */ + channel_mask == 0x0607 /* 5 channels: front left, front right, front center, side left, side right */ + ) { + /* to dolby order: front left, center, front right [, surround left, surround right ] */ + channel_map[1] = 2; + channel_map[2] = 1; + } + else if( + channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */ + channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */ + ) { + /* to dolby order: front left, center, front right, surround left, surround right, LFE */ + channel_map[1] = 2; + channel_map[2] = 1; + channel_map[3] = 5; + channel_map[4] = 3; + channel_map[5] = 4; + } +#else + if( + options.channel_map_none || + channel_mask == 0x0001 || /* 1 channel: (mono) */ + channel_mask == 0x0003 || /* 2 channels: front left, front right */ + channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */ + channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */ + channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */ + channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */ + channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */ + channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */ + channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */ + ) { + /* keep default channel order */ + } +#endif + else { + flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n\nUse --channel-map=none option to store channels in current order; FLAC files\nmust also be decoded with --channel-map=none to restore correct order.\n", e->inbasefilename, (unsigned)channel_mask); + return false; + } + if(!options.channel_map_none) { + if(count_channel_mask_bits(channel_mask) < channels) { + flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels); + return false; + } +#if 0 + /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4? + * there would be holes in the order that would have to be filled in, or the mask would have to be + * limited and the logic above rerun to see if it still fits into the FLAC mapping. + */ + else if(count_channel_mask_bits(channel_mask) > channels) + channel_mask = limit_channel_mask(channel_mask, channels); +#else + else if(count_channel_mask_bits(channel_mask) > channels) { + flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels); + return false; + } +#endif + } + /* first part of GUID */ + if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename)) + return false; + if(x != 1) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x); + return false; + } + data_bytes -= 26; + } + + e->info.bytes_per_wide_sample = channels * (bps / 8); + + /* skip any extra data in the fmt chunk */ + if(!fskip_ahead(e->fin, data_bytes)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename); + return false; + } + + got_fmt_chunk = true; + } + else if( + !memcmp(chunk_id, "data", 4) && + (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16)) + ) { /* data chunk */ + FLAC__uint32 xx; + FLAC__uint64 data_bytes; + + if(!got_fmt_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename); + return false; + } + + /* data size */ + if(e->format != FORMAT_WAVE64) { + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + data_bytes = xx; + } + else { /* Wave64 */ + if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename)) + return false; + /* subtract size of header */ + if (data_bytes < 16+8) { + flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)data_bytes); + return false; + } + data_bytes -= (16+8); + } + if(e->format == FORMAT_RF64) { + if(!got_ds64_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename); + return false; + } + if(data_bytes == 0xffffffff) + data_bytes = ds64_data_size; + } + if(options.ignore_chunk_sizes) { + FLAC__ASSERT(!options.sector_align); + if(data_bytes) { + flac__utils_printf(stderr, 1, "%s: WARNING: 'data' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id); + if(e->treat_warnings_as_errors) + return false; + } + data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */ + } + else if(0 == data_bytes) { + flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename); + return false; + } + + e->fmt.iff.data_bytes = data_bytes; + + got_data_chunk = true; + break; + } + else { + FLAC__uint32 xx; + FLAC__uint64 skip; + if(!options.format_options.iff.foreign_metadata) { + if(e->format != FORMAT_WAVE64) + flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id); + else + flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X (use --keep-foreign-metadata to keep)\n", + e->inbasefilename, + (unsigned)((const unsigned char *)chunk_id)[3], + (unsigned)((const unsigned char *)chunk_id)[2], + (unsigned)((const unsigned char *)chunk_id)[1], + (unsigned)((const unsigned char *)chunk_id)[0], + (unsigned)((const unsigned char *)chunk_id)[5], + (unsigned)((const unsigned char *)chunk_id)[4], + (unsigned)((const unsigned char *)chunk_id)[7], + (unsigned)((const unsigned char *)chunk_id)[6], + (unsigned)((const unsigned char *)chunk_id)[9], + (unsigned)((const unsigned char *)chunk_id)[8], + (unsigned)((const unsigned char *)chunk_id)[10], + (unsigned)((const unsigned char *)chunk_id)[11], + (unsigned)((const unsigned char *)chunk_id)[12], + (unsigned)((const unsigned char *)chunk_id)[13], + (unsigned)((const unsigned char *)chunk_id)[14], + (unsigned)((const unsigned char *)chunk_id)[15] + ); + if(e->treat_warnings_as_errors) + return false; + } + + /* chunk size */ + if(e->format != FORMAT_WAVE64) { + if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename)) + return false; + skip = xx; + skip += skip & 1; + } + else { /* Wave64 */ + if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename)) + return false; + skip = (skip+7) & (~(FLAC__uint64)7); + /* subtract size of header */ + if (skip < 16+8) { + flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)skip); + return false; + } + skip -= (16+8); + } + if(skip) { + if(!fskip_ahead(e->fin, skip)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename); + return false; + } + } + } + } + + if(!got_fmt_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename); + return false; + } + if(!got_data_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename); + return false; + } + + e->info.sample_rate = sample_rate; + e->info.channels = channels; + e->info.bits_per_sample = bps; + e->info.shift = shift; + e->info.channel_mask = channel_mask; + + return true; +} + +static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options) +{ + FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false; + unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0; + FLAC__uint64 sample_frames = 0; + FLAC__uint32 channel_mask = 0; + + e->info.is_unsigned_samples = false; + e->info.is_big_endian = true; + + /* + * lookahead[] already has "FORMxxxxAIFF", do chunks + */ + while(!feof(e->fin) && !got_ssnd_chunk) { + char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */ + if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) { + flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename); + return false; + } + if(feof(e->fin)) + break; + + if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */ + FLAC__uint16 x; + FLAC__uint32 xx; + unsigned long skip; + const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C; + const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18); + + if(got_comm_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename); + return false; + } + + /* COMM chunk size */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + else if(xx < minimum_comm_size) { + flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx); + return false; + } + else if(!is_aifc && xx != minimum_comm_size) { + flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size); + if(e->treat_warnings_as_errors) + return false; + } + skip = (xx-minimum_comm_size)+(xx & 1); + + /* number of channels */ + if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename)) + return false; + channels = (unsigned)x; + if(channels > 2 && !options.channel_map_none) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels); + return false; + } + + /* number of sample frames */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + sample_frames = xx; + + /* bits per sample */ + if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename)) + return false; + bps = (unsigned)x; + shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */ + bps += shift; + + /* sample rate */ + if(!read_sane_extended(e->fin, &xx, e->inbasefilename)) + return false; + sample_rate = xx; + + /* check compression type for AIFF-C */ + if(is_aifc) { + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + if(xx == 0x736F7774) /* "sowt" */ + e->info.is_big_endian = false; + else if(xx == 0x4E4F4E45) /* "NONE" */ + ; /* nothing to do, we already default to big-endian */ + else { + flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", e->inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8)); + return false; + } + } + + /* set channel mapping */ + /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */ + /* front left, front right, center, LFE, back left, back right, surround left, surround right */ + /* specs say the channel ordering is: + * 1 2 3 4 5 6 + * ___________________________________________________ + * 2 stereo l r + * 3 l r c + * 4 l c r S + * quad (ambiguous with 4ch) Fl Fr Bl Br + * 5 Fl Fr Fc Sl Sr + * 6 l lc c r rc S + * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround + * so we only have unambiguous mappings for 2, 3, and 5 channels + */ + if( + options.channel_map_none || + channels == 1 || /* 1 channel: (mono) */ + channels == 2 || /* 2 channels: left, right */ + channels == 3 || /* 3 channels: left, right, center */ + channels == 5 /* 5 channels: front left, front right, center, surround left, surround right */ + ) { + /* keep default channel order */ + } + else { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels); + return false; + } + + e->info.bytes_per_wide_sample = channels * (bps / 8); + + /* skip any extra data in the COMM chunk */ + if(!fskip_ahead(e->fin, skip)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename); + return false; + } + + got_comm_chunk = true; + } + else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */ + FLAC__uint32 xx; + FLAC__uint64 data_bytes; + unsigned offset = 0; + + if(!got_comm_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename); + return false; + } + + /* SSND chunk size */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + data_bytes = xx; + if(options.ignore_chunk_sizes) { + FLAC__ASSERT(!options.sector_align); + if(data_bytes) { + flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id); + if(e->treat_warnings_as_errors) + return false; + } + data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */ + } + else if(data_bytes <= 8) { + flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename); + return false; + } + else { + data_bytes -= 8; /* discount the offset and block size fields */ + } + + /* offset */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + offset = xx; + data_bytes -= offset; + + /* block size */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + if(xx && !options.ignore_chunk_sizes) + data_bytes -= (xx - (data_bytes % xx)); + if(options.ignore_chunk_sizes) { + if(xx) { + flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero blocksize, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id); + if(e->treat_warnings_as_errors) + return false; + } + } + + /* skip any SSND offset bytes */ + if(!fskip_ahead(e->fin, offset)) { + flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename); + return false; + } + + e->fmt.iff.data_bytes = data_bytes; + + got_ssnd_chunk = true; + } + else { + FLAC__uint32 xx; + if(!options.format_options.iff.foreign_metadata) { + flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id); + if(e->treat_warnings_as_errors) + return false; + } + + /* chunk size */ + if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename)) + return false; + else { + unsigned long skip = xx + (xx & 1); + + FLAC__ASSERT(skip <= LONG_MAX); + if(!fskip_ahead(e->fin, skip)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename); + return false; + } + } + } + } + + if(!got_comm_chunk) { + flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename); + return false; + } + if(!got_ssnd_chunk && sample_frames) { + flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename); + return false; + } + + e->info.sample_rate = sample_rate; + e->info.channels = channels; + e->info.bits_per_sample = bps; + e->info.shift = shift; + e->info.channel_mask = channel_mask; + + return true; +} + +static FLAC__bool get_sample_info_flac(EncoderSession *e) +{ + if (!( + FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) && + FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder) + )) { + flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename); + return false; + } + + if (e->format == FORMAT_OGGFLAC) { + if (FLAC__stream_decoder_init_ogg_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder)); + return false; + } + } + else if (FLAC__stream_decoder_init_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder)); + return false; + } + + if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) { + if (e->fmt.flac.client_data.fatal_error) + flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename); + else + flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder)); + return false; + } + + if (e->fmt.flac.client_data.num_metadata_blocks == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename); + return false; + } + else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) { + flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename); + return false; + } + else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename); + return false; + } + + e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate; + e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels; + e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample; + e->info.shift = 0; + e->info.bytes_per_wide_sample = 0; + e->info.is_unsigned_samples = false; /* not applicable for FLAC input */ + e->info.is_big_endian = false; /* not applicable for FLAC input */ + e->info.channel_mask = 0; + + return true; +} + +/* + * public routines + */ +int flac__encode_file(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options) +{ + EncoderSession encoder_session; + size_t channel_map[FLAC__MAX_CHANNELS]; + int info_align_carry = -1, info_align_zero = -1; + + if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length)) + return 1; + + /* initialize default channel map that preserves channel order */ + { + size_t i; + for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++) + channel_map[i] = i; + } + + /* read foreign metadata if requested */ + if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) { + const char *error; + if(!( + options.format == FORMAT_WAVE || options.format == FORMAT_RF64? + flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) : + options.format == FORMAT_WAVE64? + flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) : + flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error) + )) { + flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error); + return EncoderSession_finish_error(&encoder_session); + } + } + + /* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */ + switch(options.format) { + case FORMAT_RAW: + if(!get_sample_info_raw(&encoder_session, options)) + return EncoderSession_finish_error(&encoder_session); + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + if(!get_sample_info_wave(&encoder_session, options)) + return EncoderSession_finish_error(&encoder_session); + break; + case FORMAT_AIFF: + case FORMAT_AIFF_C: + if(!get_sample_info_aiff(&encoder_session, options)) + return EncoderSession_finish_error(&encoder_session); + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + /* + * set up FLAC decoder for the input + */ + if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) { + flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + if(!get_sample_info_flac(&encoder_session)) + return EncoderSession_finish_error(&encoder_session); + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + + /* some more checks */ + if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels); + return EncoderSession_finish_error(&encoder_session); + } + if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate); + return EncoderSession_finish_error(&encoder_session); + } + if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 24) { + flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift); + return EncoderSession_finish_error(&encoder_session); + } + if(options.sector_align) { + if(encoder_session.info.channels != 2) { + flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.channels); + return EncoderSession_finish_error(&encoder_session); + } + if(encoder_session.info.sample_rate != 44100) { + flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.sample_rate); + return EncoderSession_finish_error(&encoder_session); + } + if(encoder_session.info.bits_per_sample-encoder_session.info.shift != 16) { + flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift); + return EncoderSession_finish_error(&encoder_session); + } + } + + { + FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */ + FLAC__uint64 skip; + FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */ + unsigned align_remainder = 0; + + switch(options.format) { + case FORMAT_RAW: + if(infilesize < 0) + total_samples_in_input = 0; + else + total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples; + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + case FORMAT_AIFF: + case FORMAT_AIFF_C: + /* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */ + total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples; + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples + *options.align_reservoir_samples; + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + + /* + * now that we know the sample rate, canonicalize the + * --skip string to an absolute sample number: + */ + flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate); + FLAC__ASSERT(options.skip_specification.value.samples >= 0); + skip = (FLAC__uint64)options.skip_specification.value.samples; + FLAC__ASSERT(!options.sector_align || (options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC && skip == 0)); + /* *options.align_reservoir_samples will be 0 unless --sector-align is used */ + FLAC__ASSERT(options.sector_align || *options.align_reservoir_samples == 0); + + /* + * now that we possibly know the input size, canonicalize the + * --until string to an absolute sample number: + */ + if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input)) + return EncoderSession_finish_error(&encoder_session); + until = (FLAC__uint64)options.until_specification.value.samples; + FLAC__ASSERT(!options.sector_align || until == 0); + + /* adjust encoding parameters based on skip and until values */ + switch(options.format) { + case FORMAT_RAW: + infilesize -= (off_t)skip * encoder_session.info.bytes_per_wide_sample; + encoder_session.total_samples_to_encode = total_samples_in_input - skip; + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + case FORMAT_AIFF: + case FORMAT_AIFF_C: + encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample; + if(options.ignore_chunk_sizes) { + encoder_session.total_samples_to_encode = 0; + flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n"); + FLAC__ASSERT(0 == until); + } + else { + encoder_session.total_samples_to_encode = total_samples_in_input - skip; + } + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + encoder_session.total_samples_to_encode = total_samples_in_input - skip; + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + if(until > 0) { + const FLAC__uint64 trim = total_samples_in_input - until; + FLAC__ASSERT(total_samples_in_input > 0); + FLAC__ASSERT(!options.sector_align); + if(options.format == FORMAT_RAW) + infilesize -= (off_t)trim * encoder_session.info.bytes_per_wide_sample; + else if(EncoderSession_format_is_iff(&encoder_session)) + encoder_session.fmt.iff.data_bytes -= trim * encoder_session.info.bytes_per_wide_sample; + encoder_session.total_samples_to_encode -= trim; + } + if(options.sector_align && (options.format != FORMAT_RAW || infilesize >=0)) { /* for RAW, need to know the filesize */ + FLAC__ASSERT(skip == 0); /* asserted above too, but lest we forget */ + align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588); + if(options.is_last_file) + encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */ + else + encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */ + } + switch(options.format) { + case FORMAT_RAW: + encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample; + break; + case FORMAT_WAVE: + /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */ + encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 44; + break; + case FORMAT_WAVE64: + /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */ + encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 104; + break; + case FORMAT_RF64: + /* +72 for the size of the RF64 headers; this is just an estimate for the progress indicator and doesn't need to be exact */ + encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 80; + break; + case FORMAT_AIFF: + case FORMAT_AIFF_C: + /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */ + encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 54; + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + if(infilesize < 0) + /* if we don't know, use 0 as hint to progress indicator (which is the only place this is used): */ + encoder_session.unencoded_size = 0; + else if(skip == 0 && until == 0) + encoder_session.unencoded_size = (FLAC__uint64)infilesize; + else if(total_samples_in_input) + encoder_session.unencoded_size = (FLAC__uint64)infilesize * encoder_session.total_samples_to_encode / total_samples_in_input; + else + encoder_session.unencoded_size = (FLAC__uint64)infilesize; + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + + if(encoder_session.total_samples_to_encode == 0) + flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n"); + + if(options.format == FORMAT_FLAC || options.format == FORMAT_OGGFLAC) + encoder_session.fmt.flac.client_data.samples_left_to_process = encoder_session.total_samples_to_encode; + + /* init the encoder */ + if(!EncoderSession_init_encoder(&encoder_session, options)) + return EncoderSession_finish_error(&encoder_session); + + /* skip over any samples as requested */ + if(skip > 0) { + switch(options.format) { + case FORMAT_RAW: + { + unsigned skip_bytes = encoder_session.info.bytes_per_wide_sample * (unsigned)skip; + if(skip_bytes > lookahead_length) { + skip_bytes -= lookahead_length; + lookahead_length = 0; + if(!fskip_ahead(encoder_session.fin, skip_bytes)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + } + else { + lookahead += skip_bytes; + lookahead_length -= skip_bytes; + } + } + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + case FORMAT_AIFF: + case FORMAT_AIFF_C: + if(!fskip_ahead(encoder_session.fin, skip * encoder_session.info.bytes_per_wide_sample)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + /* + * have to wait until the FLAC encoder is set up for writing + * before any seeking in the input FLAC file, because the seek + * itself will usually call the decoder's write callback, and + * our decoder's write callback passes samples to our FLAC + * encoder + */ + if(!FLAC__stream_decoder_seek_absolute(encoder_session.fmt.flac.decoder, skip)) { + flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder)); + return EncoderSession_finish_error(&encoder_session); + } + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + } + + /* + * first do any samples in the reservoir + */ + if(options.sector_align && *options.align_reservoir_samples > 0) { + FLAC__ASSERT(options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC); /* check again */ + if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.align_reservoir, *options.align_reservoir_samples)) { + print_error_with_state(&encoder_session, "ERROR during encoding"); + return EncoderSession_finish_error(&encoder_session); + } + } + + /* + * decrement infilesize or the data_bytes counter if we need to align the file + */ + if(options.sector_align) { + if(options.is_last_file) { + *options.align_reservoir_samples = 0; + } + else { + *options.align_reservoir_samples = align_remainder; + if(options.format == FORMAT_RAW) { + FLAC__ASSERT(infilesize >= 0); + infilesize -= (off_t)((*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample); + FLAC__ASSERT(infilesize >= 0); + } + else if(EncoderSession_format_is_iff(&encoder_session)) + encoder_session.fmt.iff.data_bytes -= (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample; + } + } + + /* + * now do samples from the file + */ + switch(options.format) { + case FORMAT_RAW: + if(infilesize < 0) { + size_t bytes_read; + while(!feof(infile)) { + if(lookahead_length > 0) { + FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample); + memcpy(ucbuffer_, lookahead, lookahead_length); + bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample - lookahead_length, infile) + lookahead_length; + if(ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + lookahead_length = 0; + } + else + bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample, infile); + + if(bytes_read == 0) { + if(ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + } + else if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else { + unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample; + if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map)) + return EncoderSession_finish_error(&encoder_session); + + if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) { + print_error_with_state(&encoder_session, "ERROR during encoding"); + return EncoderSession_finish_error(&encoder_session); + } + } + } + } + else { + size_t bytes_read; + const FLAC__uint64 max_input_bytes = infilesize; + FLAC__uint64 total_input_bytes_read = 0; + while(total_input_bytes_read < max_input_bytes) { + { + size_t wanted = (CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample); + wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read); + + if(lookahead_length > 0) { + FLAC__ASSERT(lookahead_length <= wanted); + memcpy(ucbuffer_, lookahead, lookahead_length); + wanted -= lookahead_length; + bytes_read = lookahead_length; + if(wanted > 0) { + bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile); + if(ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + } + lookahead_length = 0; + } + else + bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile); + } + + if(bytes_read == 0) { + if(ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else if(feof(infile)) { + flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written); + if(encoder_session.treat_warnings_as_errors) + return EncoderSession_finish_error(&encoder_session); + total_input_bytes_read = max_input_bytes; + } + } + else { + if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else { + unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample; + if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map)) + return EncoderSession_finish_error(&encoder_session); + + if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) { + print_error_with_state(&encoder_session, "ERROR during encoding"); + return EncoderSession_finish_error(&encoder_session); + } + total_input_bytes_read += bytes_read; + } + } + } + } + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + case FORMAT_AIFF: + case FORMAT_AIFF_C: + while(encoder_session.fmt.iff.data_bytes > 0) { + const size_t bytes_to_read = (size_t)min( + encoder_session.fmt.iff.data_bytes, + (FLAC__uint64)CHUNK_OF_SAMPLES * (FLAC__uint64)encoder_session.info.bytes_per_wide_sample + ); + size_t bytes_read = fread(ucbuffer_, sizeof(unsigned char), bytes_to_read, infile); + if(bytes_read == 0) { + if(ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else if(feof(infile)) { + if(options.ignore_chunk_sizes) { + flac__utils_printf(stderr, 1, "%s: INFO: hit EOF with --ignore-chunk-sizes, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.samples_written); + } + else { + flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written); + if(encoder_session.treat_warnings_as_errors) + return EncoderSession_finish_error(&encoder_session); + } + encoder_session.fmt.iff.data_bytes = 0; + } + } + else { + if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) { + flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else { + unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample; + if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map)) + return EncoderSession_finish_error(&encoder_session); + + if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) { + print_error_with_state(&encoder_session, "ERROR during encoding"); + return EncoderSession_finish_error(&encoder_session); + } + encoder_session.fmt.iff.data_bytes -= bytes_read; + } + } + } + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + while(!encoder_session.fmt.flac.client_data.fatal_error && encoder_session.fmt.flac.client_data.samples_left_to_process > 0) { + /* We can also hit the end of stream without samples_left_to_process + * going to 0 if there are errors and continue_through_decode_errors + * is on, so we want to break in that case too: + */ + if(encoder_session.continue_through_decode_errors && FLAC__stream_decoder_get_state(encoder_session.fmt.flac.decoder) == FLAC__STREAM_DECODER_END_OF_STREAM) + break; + if(!FLAC__stream_decoder_process_single(encoder_session.fmt.flac.decoder)) { + flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder)); + return EncoderSession_finish_error(&encoder_session); + } + } + if(encoder_session.fmt.flac.client_data.fatal_error) { + flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder)); + return EncoderSession_finish_error(&encoder_session); + } + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return EncoderSession_finish_error(&encoder_session); + } + + /* + * now read unaligned samples into reservoir or pad with zeroes if necessary + */ + if(options.sector_align) { + if(options.is_last_file) { + unsigned wide_samples = 588 - align_remainder; + if(wide_samples < 588) { + unsigned channel; + + info_align_zero = wide_samples; + for(channel = 0; channel < encoder_session.info.channels; channel++) + memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples); + + if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) { + print_error_with_state(&encoder_session, "ERROR during encoding"); + return EncoderSession_finish_error(&encoder_session); + } + } + } + else { + if(*options.align_reservoir_samples > 0) { + size_t bytes_read; + FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588); + bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample, infile); + if(bytes_read == 0 && ferror(infile)) { + flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename); + return EncoderSession_finish_error(&encoder_session); + } + else if(bytes_read != (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample) { + flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written); + if(encoder_session.treat_warnings_as_errors) + return EncoderSession_finish_error(&encoder_session); + } + else { + info_align_carry = *options.align_reservoir_samples; + if(!format_input(options.align_reservoir, *options.align_reservoir_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map)) + return EncoderSession_finish_error(&encoder_session); + } + } + } + } + } + + return EncoderSession_finish_ok( + &encoder_session, + info_align_carry, + info_align_zero, + EncoderSession_format_is_iff(&encoder_session)? options.format_options.iff.foreign_metadata : 0 + ); +} + +FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length) +{ + unsigned i; + FLAC__uint32 test = 1; + + /* + * initialize globals + */ + + is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true; + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) + input_[i] = &(in_[i][0]); + + + /* + * initialize instance + */ + +#if FLAC__HAS_OGG + e->use_ogg = options.use_ogg; +#endif + e->verify = options.verify; + e->treat_warnings_as_errors = options.treat_warnings_as_errors; + e->continue_through_decode_errors = options.continue_through_decode_errors; + + e->is_stdout = (0 == strcmp(outfilename, "-")); + e->outputfile_opened = false; + + e->inbasefilename = grabbag__file_get_basename(infilename); + e->infilename = infilename; + e->outfilename = outfilename; + + e->total_samples_to_encode = 0; + e->unencoded_size = 0; + e->bytes_written = 0; + e->samples_written = 0; + e->stats_mask = 0; + + memset(&e->info, 0, sizeof(e->info)); + + e->format = options.format; + + switch(options.format) { + case FORMAT_RAW: + break; + case FORMAT_WAVE: + case FORMAT_WAVE64: + case FORMAT_RF64: + case FORMAT_AIFF: + case FORMAT_AIFF_C: + e->fmt.iff.data_bytes = 0; + break; + case FORMAT_FLAC: + case FORMAT_OGGFLAC: + e->fmt.flac.decoder = 0; + e->fmt.flac.client_data.filesize = infilesize; + e->fmt.flac.client_data.lookahead = lookahead; + e->fmt.flac.client_data.lookahead_length = lookahead_length; + e->fmt.flac.client_data.num_metadata_blocks = 0; + e->fmt.flac.client_data.samples_left_to_process = 0; + e->fmt.flac.client_data.fatal_error = false; + break; + default: + FLAC__ASSERT(0); + /* double protection */ + return false; + } + + e->encoder = 0; + + e->fin = infile; + e->seek_table_template = 0; + + if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename); + return false; + } + + e->encoder = FLAC__stream_encoder_new(); + if(0 == e->encoder) { + flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename); + EncoderSession_destroy(e); + return false; + } + + return true; +} + +void EncoderSession_destroy(EncoderSession *e) +{ + if(e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC) { + size_t i; + if(e->fmt.flac.decoder) + FLAC__stream_decoder_delete(e->fmt.flac.decoder); + e->fmt.flac.decoder = 0; + for(i = 0; i < e->fmt.flac.client_data.num_metadata_blocks; i++) + FLAC__metadata_object_delete(e->fmt.flac.client_data.metadata_blocks[i]); + e->fmt.flac.client_data.num_metadata_blocks = 0; + } + + if(e->fin != stdin) + fclose(e->fin); + + if(0 != e->encoder) { + FLAC__stream_encoder_delete(e->encoder); + e->encoder = 0; + } + + if(0 != e->seek_table_template) { + FLAC__metadata_object_delete(e->seek_table_template); + e->seek_table_template = 0; + } +} + +int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata) +{ + FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK; + int ret = 0; + FLAC__bool verify_error = false; + + if(e->encoder) { + fse_state = FLAC__stream_encoder_get_state(e->encoder); + ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1; + verify_error = + fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA || + FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA + ; + } + /* all errors except verify errors should interrupt the stats */ + if(ret && !verify_error) + print_error_with_state(e, "ERROR during encoding"); + else if(e->total_samples_to_encode > 0) { + print_stats(e); + flac__utils_printf(stderr, 2, "\n"); + } + + if(verify_error) { + print_verify_error(e); + ret = 1; + } + else { + if(info_align_carry >= 0) { + flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry); + } + if(info_align_zero >= 0) { + flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero); + } + } + + /*@@@@@@ should this go here or somewhere else? */ + if(ret == 0 && foreign_metadata) { + const char *error; + if(!flac__foreign_metadata_write_to_flac(foreign_metadata, e->infilename, e->outfilename, &error)) { + flac__utils_printf(stderr, 1, "%s: ERROR: updating foreign metadata in FLAC file: %s\n", e->inbasefilename, error); + ret = 1; + } + } + + EncoderSession_destroy(e); + + return ret; +} + +int EncoderSession_finish_error(EncoderSession *e) +{ + FLAC__ASSERT(e->encoder); + + if(e->total_samples_to_encode > 0) + flac__utils_printf(stderr, 2, "\n"); + + if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) + print_verify_error(e); + else if(e->outputfile_opened) + /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */ + unlink(e->outfilename); + + EncoderSession_destroy(e); + + return 1; +} + +typedef struct { + unsigned num_metadata; + FLAC__bool *needs_delete; + FLAC__StreamMetadata **metadata; + FLAC__StreamMetadata *cuesheet; /* always needs to be deleted */ +} static_metadata_t; + +static void static_metadata_init(static_metadata_t *m) +{ + m->num_metadata = 0; + m->needs_delete = 0; + m->metadata = 0; + m->cuesheet = 0; +} + +static void static_metadata_clear(static_metadata_t *m) +{ + unsigned i; + for(i = 0; i < m->num_metadata; i++) + if(m->needs_delete[i]) + FLAC__metadata_object_delete(m->metadata[i]); + if(m->metadata) + free(m->metadata); + if(m->needs_delete) + free(m->needs_delete); + if(m->cuesheet) + FLAC__metadata_object_delete(m->cuesheet); + static_metadata_init(m); +} + +static FLAC__bool static_metadata_append(static_metadata_t *m, FLAC__StreamMetadata *d, FLAC__bool needs_delete) +{ + void *x; + if(0 == (x = safe_realloc_muladd2_(m->metadata, sizeof(*m->metadata), /*times (*/m->num_metadata, /*+*/1/*)*/))) + return false; + m->metadata = (FLAC__StreamMetadata**)x; + if(0 == (x = safe_realloc_muladd2_(m->needs_delete, sizeof(*m->needs_delete), /*times (*/m->num_metadata, /*+*/1/*)*/))) + return false; + m->needs_delete = (FLAC__bool*)x; + m->metadata[m->num_metadata] = d; + m->needs_delete[m->num_metadata] = needs_delete; + m->num_metadata++; + return true; +} + +FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options) +{ + const unsigned channels = e->info.channels; + const unsigned bps = e->info.bits_per_sample - e->info.shift; + const unsigned sample_rate = e->info.sample_rate; + FLACDecoderData *flac_decoder_data = (e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC)? &e->fmt.flac.client_data : 0; + FLAC__StreamMetadata padding; + FLAC__StreamMetadata **metadata = 0; + static_metadata_t static_metadata; + unsigned num_metadata = 0, i; + FLAC__StreamEncoderInitStatus init_status; + const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100); + char apodizations[2000]; + + FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64); + + static_metadata_init(&static_metadata); + + e->replay_gain = options.replay_gain; + + apodizations[0] = '\0'; + + if(e->replay_gain) { + if(channels != 1 && channels != 2) { + flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels); + return false; + } + if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) { + flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate); + return false; + } + if(options.is_first_file) { + if(!grabbag__replaygain_init(sample_rate)) { + flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename); + return false; + } + } + } + + if(!parse_cuesheet(&static_metadata.cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode, e->treat_warnings_as_errors)) + return false; + + if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? static_metadata.cuesheet : 0, e)) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + + /* build metadata */ + if(flac_decoder_data) { + /* + * we're encoding from FLAC so we will use the FLAC file's + * metadata as the basis for the encoded file + */ + { + /* + * first handle pictures: simple append any --pictures + * specified. + */ + for(i = 0; i < options.num_pictures; i++) { + FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]); + if(0 == pic) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic; + } + } + { + /* + * next handle vorbis comment: if any tags were specified + * or there is no existing vorbis comment, we create a + * new vorbis comment (discarding any existing one); else + * we keep the existing one. also need to make sure to + * propagate any channel mask tag. + */ + /* @@@ change to append -T values from options.vorbis_comment if input has VC already? */ + size_t i, j; + FLAC__bool vc_found = false; + for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) { + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + vc_found = true; + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) { + (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &e->info.channel_mask); + flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]); + flac_decoder_data->metadata_blocks[i] = 0; + } + else + flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i]; + } + flac_decoder_data->num_metadata_blocks = j; + if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) { + /* prepend ours */ + FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment); + if(0 == vc || (e->info.channel_mask && !flac__utils_set_channel_mask_tag(vc, e->info.channel_mask))) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--) + flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1]; + flac_decoder_data->metadata_blocks[1] = vc; + flac_decoder_data->num_metadata_blocks++; + } + } + { + /* + * next handle cuesheet: if --cuesheet was specified, use + * it; else if file has existing CUESHEET and cuesheet's + * lead-out offset is correct, keep it; else no CUESHEET + */ + size_t i, j; + for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) { + FLAC__bool existing_cuesheet_is_bad = false; + /* check if existing cuesheet matches the input audio */ + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == static_metadata.cuesheet) { + const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet; + if(e->total_samples_to_encode == 0) { + flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + existing_cuesheet_is_bad = true; + } + else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) { + flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + existing_cuesheet_is_bad = true; + } + } + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != static_metadata.cuesheet)) { + if(0 != static_metadata.cuesheet) { + flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + } + FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]); + flac_decoder_data->metadata_blocks[i] = 0; + } + else + flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i]; + } + flac_decoder_data->num_metadata_blocks = j; + if(0 != static_metadata.cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) { + /* prepend ours */ + FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(static_metadata.cuesheet); + if(0 == cs) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--) + flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1]; + flac_decoder_data->metadata_blocks[1] = cs; + flac_decoder_data->num_metadata_blocks++; + } + } + { + /* + * next handle seektable: if -S- was specified, no + * SEEKTABLE; else if -S was specified, use it/them; + * else if file has existing SEEKTABLE and input size is + * preserved (no --skip/--until/etc specified), keep it; + * else use default seektable options + * + * note: meanings of num_requested_seek_points: + * -1 : no -S option given, default to some value + * 0 : -S- given (no seektable) + * >0 : one or more -S options given + */ + size_t i, j; + FLAC__bool existing_seektable = false; + for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) { + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) + existing_seektable = true; + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) { + if(options.num_requested_seek_points > 0) { + flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + } + else if(options.num_requested_seek_points == 0) + ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */ + else { + flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + } + FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]); + flac_decoder_data->metadata_blocks[i] = 0; + existing_seektable = false; + } + else + flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i]; + } + flac_decoder_data->num_metadata_blocks = j; + if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) { + /* prepend ours */ + FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template); + if(0 == st) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--) + flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1]; + flac_decoder_data->metadata_blocks[1] = st; + flac_decoder_data->num_metadata_blocks++; + } + } + { + /* + * finally handle padding: if --no-padding was specified, + * then delete all padding; else if -P was specified, + * use that instead of existing padding (if any); else + * if existing file has padding, move all existing + * padding blocks to one padding block at the end; else + * use default padding. + */ + int p = -1; + size_t i, j; + for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) { + if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) { + if(p < 0) + p = 0; + p += flac_decoder_data->metadata_blocks[i]->length; + FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]); + flac_decoder_data->metadata_blocks[i] = 0; + } + else + flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i]; + } + flac_decoder_data->num_metadata_blocks = j; + if(options.padding > 0) + p = options.padding; + if(p < 0) + p = e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8; + if(options.padding != 0) { + if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) { + flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) { + flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */ + flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p; + flac_decoder_data->num_metadata_blocks++; + } + } + } + metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */ + num_metadata = flac_decoder_data->num_metadata_blocks - 1; + } + else { + /* + * we're not encoding from FLAC so we will build the metadata + * from scratch + */ + const foreign_metadata_t *foreign_metadata = EncoderSession_format_is_iff(e)? options.format_options.iff.foreign_metadata : 0; + + if(e->seek_table_template->data.seek_table.num_points > 0) { + e->seek_table_template->is_last = false; /* the encoder will set this for us */ + static_metadata_append(&static_metadata, e->seek_table_template, /*needs_delete=*/false); + } + if(0 != static_metadata.cuesheet) + static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false); + if(e->info.channel_mask) { + if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, e->info.channel_mask)) { + flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + } + static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false); + for(i = 0; i < options.num_pictures; i++) + static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false); + if(foreign_metadata) { + for(i = 0; i < foreign_metadata->num_blocks; i++) { + FLAC__StreamMetadata *p = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + if(!p) { + flac__utils_printf(stderr, 1, "%s: ERROR: out of memory\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + static_metadata_append(&static_metadata, p, /*needs_delete=*/true); + static_metadata.metadata[static_metadata.num_metadata-1]->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8 + foreign_metadata->blocks[i].size; + } + } + if(options.padding != 0) { + padding.is_last = false; /* the encoder will set this for us */ + padding.type = FLAC__METADATA_TYPE_PADDING; + padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8)); + static_metadata_append(&static_metadata, &padding, /*needs_delete=*/false); + } + metadata = static_metadata.metadata; + num_metadata = static_metadata.num_metadata; + } + + /* check for a few things that have not already been checked. the + * FLAC__stream_encoder_init*() will check it but only return + * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some + * up front to give a better error message. + */ + if(!verify_metadata(e, metadata, num_metadata)) { + static_metadata_clear(&static_metadata); + return false; + } + + FLAC__stream_encoder_set_verify(e->encoder, options.verify); + FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax); + FLAC__stream_encoder_set_channels(e->encoder, channels); + FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps); + FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate); + for(i = 0; i < options.num_compression_settings; i++) { + switch(options.compression_settings[i].type) { + case CST_BLOCKSIZE: + FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + case CST_COMPRESSION_LEVEL: + FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[i].value.t_unsigned); + apodizations[0] = '\0'; + break; + case CST_DO_MID_SIDE: + FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool); + break; + case CST_LOOSE_MID_SIDE: + FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool); + break; + case CST_APODIZATION: + if(strlen(apodizations)+strlen(options.compression_settings[i].value.t_string)+2 >= sizeof(apodizations)) { + flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename); + static_metadata_clear(&static_metadata); + return false; + } + else { + strcat(apodizations, options.compression_settings[i].value.t_string); + strcat(apodizations, ";"); + } + break; + case CST_MAX_LPC_ORDER: + FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + case CST_QLP_COEFF_PRECISION: + FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + case CST_DO_QLP_COEFF_PREC_SEARCH: + FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[i].value.t_bool); + break; + case CST_DO_ESCAPE_CODING: + FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[i].value.t_bool); + break; + case CST_DO_EXHAUSTIVE_MODEL_SEARCH: + FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[i].value.t_bool); + break; + case CST_MIN_RESIDUAL_PARTITION_ORDER: + FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + case CST_MAX_RESIDUAL_PARTITION_ORDER: + FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + case CST_RICE_PARAMETER_SEARCH_DIST: + FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[i].value.t_unsigned); + break; + } + } + if(*apodizations) + FLAC__stream_encoder_set_apodization(e->encoder, apodizations); + FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode); + FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata); + + FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes); + FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes); + FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes); + if(!options.debug.do_md5) { + flac__utils_printf(stderr, 1, "%s: WARNING, MD5 computation disabled, resulting file will not have MD5 sum\n", e->inbasefilename); + if(e->treat_warnings_as_errors) { + static_metadata_clear(&static_metadata); + return false; + } + FLAC__stream_encoder_set_do_md5(e->encoder, false); + } + +#if FLAC__HAS_OGG + if(e->use_ogg) { + FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number); + + init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e); + } + else +#endif + { + init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e); + } + + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + print_error_with_init_status(e, "ERROR initializing encoder", init_status); + if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR) + e->outputfile_opened = true; + static_metadata_clear(&static_metadata); + return false; + } + else + e->outputfile_opened = true; + + e->stats_mask = + (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x07 : + (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f : + 0x3f; + + static_metadata_clear(&static_metadata); + + return true; +} + +FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples) +{ + if(e->replay_gain) { + if(!grabbag__replaygain_analyze(buffer, e->info.channels==2, e->info.bits_per_sample, samples)) { + flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename); + if(e->treat_warnings_as_errors) + return false; + } + } + + return FLAC__stream_encoder_process(e->encoder, buffer, samples); +} + +FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e) +{ + return + e->format == FORMAT_WAVE || + e->format == FORMAT_WAVE64 || + e->format == FORMAT_RF64 || + e->format == FORMAT_AIFF || + e->format == FORMAT_AIFF_C; +} + +FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e) +{ + const FLAC__bool only_placeholders = e->is_stdout; + FLAC__bool has_real_points; + + if(num_requested_seek_points == 0 && 0 == cuesheet) + return true; + + if(num_requested_seek_points < 0) { +#if FLAC__HAS_OGG + /*@@@@@@ workaround ogg bug: too many seekpoints makes table not fit in one page */ + if(e->use_ogg && e->total_samples_to_encode > 0 && e->total_samples_to_encode / e->info.sample_rate / 10 > 230) + requested_seek_points = "230x;"; + else +#endif + requested_seek_points = "10s;"; + num_requested_seek_points = 1; + } + + if(num_requested_seek_points > 0) { + if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->info.sample_rate, e->seek_table_template, &has_real_points)) + return false; + } + + if(0 != cuesheet) { + unsigned i, j; + const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet; + for(i = 0; i < cs->num_tracks; i++) { + const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i; + for(j = 0; j < tr->num_indices; j++) { + if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset)) + return false; + has_real_points = true; + } + } + if(has_real_points) + if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true)) + return false; + } + + if(has_real_points) { + if(e->is_stdout) { + flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename); + if(e->treat_warnings_as_errors) + return false; + } + } + + return true; +} + +FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input) +{ + /* convert from mm:ss.sss to sample number if necessary */ + flac__utils_canonicalize_skip_until_specification(spec, sample_rate); + + /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */ + if(spec->is_relative && spec->value.samples == 0) { + spec->is_relative = false; + return true; + } + + /* in any other case the total samples in the input must be known */ + if(total_samples_in_input == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename); + return false; + } + + FLAC__ASSERT(spec->value_is_samples); + + /* convert relative specifications to absolute */ + if(spec->is_relative) { + if(spec->value.samples <= 0) + spec->value.samples += (FLAC__int64)total_samples_in_input; + else + spec->value.samples += skip; + spec->is_relative = false; + } + + /* error check */ + if(spec->value.samples < 0) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename); + return false; + } + if((FLAC__uint64)spec->value.samples <= skip) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename); + return false; + } + if((FLAC__uint64)spec->value.samples > total_samples_in_input) { + flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename); + return false; + } + + return true; +} + +FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata) +{ + FLAC__bool metadata_picture_has_type1 = false; + FLAC__bool metadata_picture_has_type2 = false; + unsigned i; + + FLAC__ASSERT(0 != metadata); + for(i = 0; i < num_metadata; i++) { + const FLAC__StreamMetadata *m = metadata[i]; + if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) { + if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) { + flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename); + return false; + } + } + else if(m->type == FLAC__METADATA_TYPE_CUESHEET) { + if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) { + flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename); + return false; + } + } + else if(m->type == FLAC__METADATA_TYPE_PICTURE) { + const char *error = 0; + if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) { + flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error); + return false; + } + if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) { + if(metadata_picture_has_type1) { + flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename); + return false; + } + metadata_picture_has_type1 = true; + } + else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) { + if(metadata_picture_has_type2) { + flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename); + return false; + } + metadata_picture_has_type2 = true; + } + } + } + + return true; +} + +FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map) +{ + unsigned wide_sample, sample, channel, byte; + FLAC__int32 *out[FLAC__MAX_CHANNELS]; + + if(0 == channel_map) { + for(channel = 0; channel < channels; channel++) + out[channel] = dest[channel]; + } + else { + for(channel = 0; channel < channels; channel++) + out[channel] = dest[channel_map[channel]]; + } + + if(bps == 8) { + if(is_unsigned_samples) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80; + } + else { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample]; + } + } + else if(bps == 16) { + if(is_big_endian != is_big_endian_host_) { + unsigned char tmp; + const unsigned bytes = wide_samples * channels * (bps >> 3); + for(byte = 0; byte < bytes; byte += 2) { + tmp = ucbuffer_[byte]; + ucbuffer_[byte] = ucbuffer_[byte+1]; + ucbuffer_[byte+1] = tmp; + } + } + if(is_unsigned_samples) { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000; + } + else { + for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) + out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample]; + } + } + else if(bps == 24) { + if(!is_big_endian) { + unsigned char tmp; + const unsigned bytes = wide_samples * channels * (bps >> 3); + for(byte = 0; byte < bytes; byte += 3) { + tmp = ucbuffer_[byte]; + ucbuffer_[byte] = ucbuffer_[byte+2]; + ucbuffer_[byte+2] = tmp; + } + } + if(is_unsigned_samples) { + for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) { + out[channel][wide_sample] = ucbuffer_[byte++]; out[channel][wide_sample] <<= 8; + out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8; + out[channel][wide_sample] |= ucbuffer_[byte++]; + out[channel][wide_sample] -= 0x800000; + } + } + else { + for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) + for(channel = 0; channel < channels; channel++, sample++) { + out[channel][wide_sample] = scbuffer_[byte++]; out[channel][wide_sample] <<= 8; + out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8; + out[channel][wide_sample] |= ucbuffer_[byte++]; + } + } + } + else { + FLAC__ASSERT(0); + } + if(shift > 0) { + FLAC__int32 mask = (1<>= shift; + } + } + return true; +} + +void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + + (void)encoder, (void)total_frames_estimate; + + e->bytes_written = bytes_written; + e->samples_written = samples_written; + + if(e->total_samples_to_encode > 0 && !((frames_written-1) & e->stats_mask)) + print_stats(e); +} + +FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + size_t n = 0; + EncoderSession *e = (EncoderSession*)client_data; + FLACDecoderData *data = &e->fmt.flac.client_data; + + (void)decoder; + + if (data->fatal_error) + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + + /* use up lookahead first */ + if (data->lookahead_length) { + n = min(data->lookahead_length, *bytes); + memcpy(buffer, data->lookahead, n); + buffer += n; + data->lookahead += n; + data->lookahead_length -= n; + } + + /* get the rest from file */ + if (*bytes > n) { + *bytes = n + fread(buffer, 1, *bytes-n, e->fin); + if(ferror(e->fin)) + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + else if(0 == *bytes) + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + else + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; +} + +FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + (void)decoder; + + if(fseeko(e->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0) + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + else + return FLAC__STREAM_DECODER_SEEK_STATUS_OK; +} + +FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + off_t pos; + (void)decoder; + + if((pos = ftello(e->fin)) < 0) + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + else { + *absolute_byte_offset = (FLAC__uint64)pos; + return FLAC__STREAM_DECODER_TELL_STATUS_OK; + } +} + +FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) +{ + const EncoderSession *e = (EncoderSession*)client_data; + const FLACDecoderData *data = &e->fmt.flac.client_data; + (void)decoder; + + if(data->filesize < 0) + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + else { + *stream_length = (FLAC__uint64)data->filesize; + return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; + } +} + +FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + (void)decoder; + + return feof(e->fin)? true : false; +} + +FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + FLACDecoderData *data = &e->fmt.flac.client_data; + FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize); + (void)decoder; + + if(!EncoderSession_process(e, buffer, (unsigned)n)) { + print_error_with_state(e, "ERROR during encoding"); + data->fatal_error = true; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + + data->samples_left_to_process -= n; + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + FLACDecoderData *data = &e->fmt.flac.client_data; + (void)decoder; + + if (data->fatal_error) + return; + + if ( + data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) || + 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata)) + ) + data->fatal_error = true; + else + data->num_metadata_blocks++; +} + +void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + EncoderSession *e = (EncoderSession*)client_data; + FLACDecoderData *data = &e->fmt.flac.client_data; + (void)decoder; + + flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", e->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]); + if(!e->continue_through_decode_errors) + data->fatal_error = true; +} + +FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors) +{ + FILE *f; + unsigned last_line_read; + const char *error_message; + + if(0 == cuesheet_filename) + return true; + + if(lead_out_offset == 0) { + flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename); + return false; + } + + if(0 == (f = fopen(cuesheet_filename, "r"))) { + flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno)); + return false; + } + + *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, is_cdda, lead_out_offset); + + fclose(f); + + if(0 == *cuesheet) { + flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message); + return false; + } + + if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) { + flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message); + return false; + } + + /* if we're expecting CDDA, warn about non-compliance */ + if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) { + flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message); + if(treat_warnings_as_errors) + return false; + (*cuesheet)->data.cue_sheet.is_cd = false; + } + + return true; +} + +void print_stats(const EncoderSession *encoder_session) +{ + const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written); + const FLAC__uint64 uesize = encoder_session->unencoded_size; +#if defined _MSC_VER || defined __MINGW32__ + /* with MSVC you have to spoon feed it the casting */ + const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode; + const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)(uesize? uesize:1) * min(1.0, progress)); +#else + const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode; + const double ratio = (double)encoder_session->bytes_written / ((double)(uesize? uesize:1) * min(1.0, progress)); +#endif + + FLAC__ASSERT(encoder_session->total_samples_to_encode > 0); + + if(samples_written == encoder_session->total_samples_to_encode) { + flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=", + encoder_session->inbasefilename, + encoder_session->verify? " Verify OK," : "", + (unsigned)encoder_session->bytes_written + ); + } + else { + flac__utils_printf(stderr, 2, "\r%s: %u%% complete, ratio=", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5)); + } + if(uesize) + flac__utils_printf(stderr, 2, "%0.3f", ratio); + else + flac__utils_printf(stderr, 2, "N/A"); +} + +void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status) +{ + const int ilen = strlen(e->inbasefilename) + 1; + const char *state_string = ""; + + flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message); + + flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]); + + if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) { + state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder); + + flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string); + + /* print out some more info for some errors: */ + if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) { + flac__utils_printf(stderr, 1, + "\n" + "An error occurred while writing; the most common cause is that the disk is full.\n" + ); + } + else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) { + flac__utils_printf(stderr, 1, + "\n" + "An error occurred opening the output file; it is likely that the output\n" + "directory does not exist or is not writable, the output file already exists and\n" + "is not writable, or the disk is full.\n" + ); + } + } + else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) { + flac__utils_printf(stderr, 1, + "\n" + "The encoding parameters specified do not conform to the FLAC Subset and may not\n" + "be streamable or playable in hardware devices. If you really understand the\n" + "consequences, you can add --lax to the command-line options to encode with\n" + "these parameters anyway. See http://flac.sourceforge.net/format.html#subset\n" + ); + } +} + +void print_error_with_state(const EncoderSession *e, const char *message) +{ + const int ilen = strlen(e->inbasefilename) + 1; + const char *state_string; + + flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message); + + state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder); + + flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string); + + /* print out some more info for some errors: */ + if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) { + flac__utils_printf(stderr, 1, + "\n" + "An error occurred while writing; the most common cause is that the disk is full.\n" + ); + } +} + +void print_verify_error(EncoderSession *e) +{ + FLAC__uint64 absolute_sample; + unsigned frame_number; + unsigned channel; + unsigned sample; + FLAC__int32 expected; + FLAC__int32 got; + + FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got); + + flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename); + flac__utils_printf(stderr, 1, " Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got); + flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n"); + flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename); + flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n"); + flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n"); + flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n"); + flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n"); + flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n"); + flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename); + flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n"); + flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n"); + flac__utils_printf(stderr, 1, " monitor the bug status.\n"); + flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename); +} + +FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn) +{ + size_t bytes_read = fread(buf, 1, n, f); + + if(bytes_read == 0) { + if(!eof_ok) { + flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn); + return false; + } + else + return true; + } + if(bytes_read < n) { + flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn); + return false; + } + return true; +} + +FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn) +{ + if(!read_bytes(f, (FLAC__byte*)val, 2, /*eof_ok=*/false, fn)) + return false; + if(is_big_endian_host_ != big_endian) { + FLAC__byte tmp, *b = (FLAC__byte*)val; + tmp = b[1]; b[1] = b[0]; b[0] = tmp; + } + return true; +} + +FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn) +{ + if(!read_bytes(f, (FLAC__byte*)val, 4, /*eof_ok=*/false, fn)) + return false; + if(is_big_endian_host_ != big_endian) { + FLAC__byte tmp, *b = (FLAC__byte*)val; + tmp = b[3]; b[3] = b[0]; b[0] = tmp; + tmp = b[2]; b[2] = b[1]; b[1] = tmp; + } + return true; +} + +FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn) +{ + if(!read_bytes(f, (FLAC__byte*)val, 8, /*eof_ok=*/false, fn)) + return false; + if(is_big_endian_host_ != big_endian) { + FLAC__byte tmp, *b = (FLAC__byte*)val; + tmp = b[7]; b[7] = b[0]; b[0] = tmp; + tmp = b[6]; b[6] = b[1]; b[1] = tmp; + tmp = b[5]; b[5] = b[2]; b[2] = tmp; + tmp = b[4]; b[4] = b[3]; b[3] = tmp; + } + return true; +} + +FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn) + /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f', + * convert it into an integral value and store in 'val'. Return false if only + * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f', or if the + * value is negative, between zero and one, or too large to be represented by + * 'val'; return true otherwise. + */ +{ + unsigned int i; + FLAC__byte buf[10]; + FLAC__uint64 p = 0; + FLAC__int16 e; + FLAC__int16 shift; + + if(!read_bytes(f, buf, sizeof(buf), /*eof_ok=*/false, fn)) + return false; + e = ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF; + shift = 63-e; + if((buf[0]>>7)==1U || e<0 || e>63) { + flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn); + return false; + } + + for(i = 0; i < 8; ++i) + p |= (FLAC__uint64)(buf[i+2])<<(56U-i*8); + *val = (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1)); + + return true; +} + +FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset) +{ + static unsigned char dump[8192]; + +#ifdef _MSC_VER + if(f == stdin) { + /* MS' stdio impl can't even seek forward on stdin, have to use pure non-fseek() version: */ + while(offset > 0) { + const long need = (long)min(offset, sizeof(dump)); + if((long)fread(dump, 1, need, f) < need) + return false; + offset -= need; + } + } + else +#endif + { + while(offset > 0) { + long need = (long)min(offset, LONG_MAX); + if(fseeko(f, need, SEEK_CUR) < 0) { + need = (long)min(offset, sizeof(dump)); + if((long)fread(dump, 1, need, f) < need) + return false; + } + offset -= need; + } + } + return true; +} + +unsigned count_channel_mask_bits(FLAC__uint32 mask) +{ + unsigned count = 0; + while(mask) { + if(mask & 1) + count++; + mask >>= 1; + } + return count; +} + +#if 0 +FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels) +{ + FLAC__uint32 x = 0x80000000; + unsigned count = count_channel_mask_bits(mask); + while(x && count > channels) { + if(mask & x) { + mask &= ~x; + count--; + } + x >>= 1; + } + FLAC__ASSERT(count_channel_mask_bits(mask) == channels); + return mask; +} +#endif diff --git a/flac/src/flac/encode.h b/flac/src/flac/encode.h new file mode 100644 index 0000000..b1b1b0d --- /dev/null +++ b/flac/src/flac/encode.h @@ -0,0 +1,114 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__encode_h +#define flac__encode_h + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/metadata.h" +#include "foreign_metadata.h" +#include "utils.h" + +extern const int FLAC_ENCODE__DEFAULT_PADDING; + +typedef enum { + CST_BLOCKSIZE, + CST_COMPRESSION_LEVEL, + CST_DO_MID_SIDE, + CST_LOOSE_MID_SIDE, + CST_APODIZATION, + CST_MAX_LPC_ORDER, + CST_QLP_COEFF_PRECISION, + CST_DO_QLP_COEFF_PREC_SEARCH, + CST_DO_ESCAPE_CODING, + CST_DO_EXHAUSTIVE_MODEL_SEARCH, + CST_MIN_RESIDUAL_PARTITION_ORDER, + CST_MAX_RESIDUAL_PARTITION_ORDER, + CST_RICE_PARAMETER_SEARCH_DIST +} compression_setting_type_t; + +typedef struct { + compression_setting_type_t type; + union { + FLAC__bool t_bool; + unsigned t_unsigned; + const char *t_string; + } value; +} compression_setting_t; + +typedef struct { + utils__SkipUntilSpecification skip_specification; + utils__SkipUntilSpecification until_specification; + FLAC__bool verify; +#if FLAC__HAS_OGG + FLAC__bool use_ogg; + long serial_number; +#endif + FLAC__bool lax; + int padding; + size_t num_compression_settings; + compression_setting_t compression_settings[64]; + char *requested_seek_points; + int num_requested_seek_points; + const char *cuesheet_filename; + FLAC__bool treat_warnings_as_errors; + FLAC__bool continue_through_decode_errors; /* currently only obeyed when encoding from FLAC or Ogg FLAC */ + FLAC__bool cued_seekpoints; + FLAC__bool channel_map_none; /* --channel-map=none specified, eventually will expand to take actual channel map */ + + /* options related to --replay-gain and --sector-align */ + FLAC__bool is_first_file; + FLAC__bool is_last_file; + FLAC__int32 **align_reservoir; + unsigned *align_reservoir_samples; + FLAC__bool replay_gain; + FLAC__bool ignore_chunk_sizes; + FLAC__bool sector_align; + + FLAC__StreamMetadata *vorbis_comment; + FLAC__StreamMetadata *pictures[64]; + unsigned num_pictures; + + FileFormat format; + union { + struct { + FLAC__bool is_big_endian; + FLAC__bool is_unsigned_samples; + unsigned channels; + unsigned bps; + unsigned sample_rate; + } raw; + struct { + foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */ + } iff; + } format_options; + + struct { + FLAC__bool disable_constant_subframes; + FLAC__bool disable_fixed_subframes; + FLAC__bool disable_verbatim_subframes; + FLAC__bool do_md5; + } debug; +} encode_options_t; + +int flac__encode_file(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options); + +#endif diff --git a/flac/src/flac/flac.dsp b/flac/src/flac/flac.dsp new file mode 100644 index 0000000..490f037 --- /dev/null +++ b/flac/src/flac/flac.dsp @@ -0,0 +1,156 @@ +# Microsoft Developer Studio Project File - Name="flac" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=flac - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "flac.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "flac.mak" CFG="flac - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "flac - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "flac - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "flac - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "." /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\grabbag_static.lib ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\obj\release\lib\replaygain_synthesis_static.lib ..\..\obj\release\lib\getopt_static.lib ..\..\obj\release\lib\utf8_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "flac - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "." /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\grabbag_static.lib ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\obj\debug\lib\replaygain_synthesis_static.lib ..\..\obj\debug\lib\getopt_static.lib ..\..\obj\debug\lib\utf8_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "flac - Win32 Release" +# Name "flac - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\analyze.c +# End Source File +# Begin Source File + +SOURCE=.\decode.c +# End Source File +# Begin Source File + +SOURCE=.\encode.c +# End Source File +# Begin Source File + +SOURCE=.\foreign_metadata.c +# End Source File +# Begin Source File + +SOURCE=.\main.c +# End Source File +# Begin Source File + +SOURCE=.\local_string_utils.c +# End Source File +# Begin Source File + +SOURCE=.\utils.c +# End Source File +# Begin Source File + +SOURCE=.\vorbiscomment.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\analyze.h +# End Source File +# Begin Source File + +SOURCE=.\decode.h +# End Source File +# Begin Source File + +SOURCE=.\encode.h +# End Source File +# Begin Source File + +SOURCE=.\foreign_metadata.h +# End Source File +# Begin Source File + +SOURCE=.\local_string_utils.h +# End Source File +# Begin Source File + +SOURCE=.\utils.h +# End Source File +# Begin Source File + +SOURCE=.\vorbiscomment.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/flac/flac.vcproj b/flac/src/flac/flac.vcproj new file mode 100644 index 0000000..1d85aa7 --- /dev/null +++ b/flac/src/flac/flac.vcproj @@ -0,0 +1,428 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/flac/foreign_metadata.c b/flac/src/flac/foreign_metadata.c new file mode 100644 index 0000000..6011290 --- /dev/null +++ b/flac/src/flac/foreign_metadata.c @@ -0,0 +1,821 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#include /* for off_t */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include /* for FILE etc. */ +#include /* for calloc() etc. */ +#include /* for memcmp() etc. */ +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "share/alloc.h" +#include "foreign_metadata.h" + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) + + +static const char *FLAC__FOREIGN_METADATA_APPLICATION_ID[3] = { "aiff" , "riff", "w64 " }; + +static FLAC__uint32 unpack32be_(const FLAC__byte *b) +{ + return ((FLAC__uint32)b[0]<<24) + ((FLAC__uint32)b[1]<<16) + ((FLAC__uint32)b[2]<<8) + (FLAC__uint32)b[3]; +} + +static FLAC__uint32 unpack32le_(const FLAC__byte *b) +{ + return (FLAC__uint32)b[0] + ((FLAC__uint32)b[1]<<8) + ((FLAC__uint32)b[2]<<16) + ((FLAC__uint32)b[3]<<24); +} + +static FLAC__uint64 unpack64le_(const FLAC__byte *b) +{ + return (FLAC__uint64)b[0] + ((FLAC__uint64)b[1]<<8) + ((FLAC__uint64)b[2]<<16) + ((FLAC__uint64)b[3]<<24) + ((FLAC__uint64)b[4]<<32) + ((FLAC__uint64)b[5]<<40) + ((FLAC__uint64)b[6]<<48) + ((FLAC__uint64)b[7]<<56); +} + +/* copies 'size' bytes from file 'fin' to 'fout', filling in *error with 'read_error' or 'write_error' as necessary */ +static FLAC__bool copy_data_(FILE *fin, FILE *fout, size_t size, const char **error, const char * const read_error, const char * const write_error) +{ + FLAC__byte buffer[4096]; + size_t left; + for(left = size; left > 0; ) { + size_t need = min(sizeof(buffer), left); + if(fread(buffer, 1, need, fin) < need) { + if(error) *error = read_error; + return false; + } + if(fwrite(buffer, 1, need, fout) < need) { + if(error) *error = write_error; + return false; + } + left -= need; + } + return true; +} + +static FLAC__bool append_block_(foreign_metadata_t *fm, off_t offset, FLAC__uint32 size, const char **error) +{ + foreign_block_t *fb = safe_realloc_muladd2_(fm->blocks, sizeof(foreign_block_t), /*times (*/fm->num_blocks, /*+*/1/*)*/); + if(fb) { + fb[fm->num_blocks].offset = offset; + fb[fm->num_blocks].size = size; + fm->num_blocks++; + fm->blocks = fb; + return true; + } + if(error) *error = "out of memory"; + return false; +} + +static FLAC__bool read_from_aiff_(foreign_metadata_t *fm, FILE *f, const char **error) +{ + FLAC__byte buffer[12]; + off_t offset, eof_offset; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (001)"; + return false; + } + if(fread(buffer, 1, 12, f) < 12 || memcmp(buffer, "FORM", 4) || (memcmp(buffer+8, "AIFF", 4) && memcmp(buffer+8, "AIFC", 4))) { + if(error) *error = "unsupported FORM layout (002)"; + return false; + } + if(!append_block_(fm, offset, 12, error)) + return false; + eof_offset = (off_t)8 + (off_t)unpack32be_(buffer+4); + while(!feof(f)) { + FLAC__uint32 size; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (003)"; + return false; + } + if((size = fread(buffer, 1, 8, f)) < 8) { + if(size == 0 && feof(f)) + break; + if(error) *error = "invalid AIFF file (004)"; + return false; + } + size = unpack32be_(buffer+4); + /* check if pad byte needed */ + if(size & 1) + size++; + if(!memcmp(buffer, "COMM", 4)) { + if(fm->format_block) { + if(error) *error = "invalid AIFF file: multiple \"COMM\" chunks (005)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid AIFF file: \"SSND\" chunk before \"COMM\" chunk (006)"; + return false; + } + fm->format_block = fm->num_blocks; + } + else if(!memcmp(buffer, "SSND", 4)) { + if(fm->audio_block) { + if(error) *error = "invalid AIFF file: multiple \"SSND\" chunks (007)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid AIFF file: \"SSND\" chunk before \"COMM\" chunk (008)"; + return false; + } + fm->audio_block = fm->num_blocks; + /* read #offset bytes */ + if(fread(buffer+8, 1, 4, f) < 4) { + if(error) *error = "invalid AIFF file (009)"; + return false; + } + fm->ssnd_offset_size = unpack32be_(buffer+8); + if(fseeko(f, -4, SEEK_CUR) < 0) { + if(error) *error = "invalid AIFF file: seek error (010)"; + return false; + } + /* WATCHOUT: For SSND we ignore the blockSize and are not saving any + * unaligned part at the end of the chunk. In retrospect it is pretty + * pointless to save the unaligned data before the PCM but now it is + * done and cast in stone. + */ + } + if(!append_block_(fm, offset, 8 + (memcmp(buffer, "SSND", 4)? size : 8 + fm->ssnd_offset_size), error)) + return false; + /* skip to next chunk */ + if(fseeko(f, size, SEEK_CUR) < 0) { + if(error) *error = "invalid AIFF file: seek error (011)"; + return false; + } + } + if(eof_offset != ftello(f)) { + if(error) *error = "invalid AIFF file: unexpected EOF (012)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid AIFF file: missing \"COMM\" chunk (013)"; + return false; + } + if(!fm->audio_block) { + if(error) *error = "invalid AIFF file: missing \"SSND\" chunk (014)"; + return false; + } + return true; +} + +static FLAC__bool read_from_wave_(foreign_metadata_t *fm, FILE *f, const char **error) +{ + FLAC__byte buffer[12]; + off_t offset, eof_offset = -1, ds64_data_size = -1; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (001)"; + return false; + } + if(fread(buffer, 1, 12, f) < 12 || (memcmp(buffer, "RIFF", 4) && memcmp(buffer, "RF64", 4)) || memcmp(buffer+8, "WAVE", 4)) { + if(error) *error = "unsupported RIFF layout (002)"; + return false; + } + if(!memcmp(buffer, "RF64", 4)) + fm->is_rf64 = true; + if(fm->is_rf64 && sizeof(off_t) < 8) { + if(error) *error = "RF64 is not supported on this compile (r00)"; + return false; + } + if(!append_block_(fm, offset, 12, error)) + return false; + if(!fm->is_rf64 || unpack32le_(buffer+4) != 0xffffffffu) + eof_offset = (off_t)8 + (off_t)unpack32le_(buffer+4); + while(!feof(f)) { + FLAC__uint32 size; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (003)"; + return false; + } + if((size = fread(buffer, 1, 8, f)) < 8) { + if(size == 0 && feof(f)) + break; + if(error) *error = "invalid WAVE file (004)"; + return false; + } + size = unpack32le_(buffer+4); + /* check if pad byte needed */ + if(size & 1) + size++; + if(!memcmp(buffer, "fmt ", 4)) { + if(fm->format_block) { + if(error) *error = "invalid WAVE file: multiple \"fmt \" chunks (005)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid WAVE file: \"data\" chunk before \"fmt \" chunk (006)"; + return false; + } + fm->format_block = fm->num_blocks; + } + else if(!memcmp(buffer, "data", 4)) { + if(fm->audio_block) { + if(error) *error = "invalid WAVE file: multiple \"data\" chunks (007)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid WAVE file: \"data\" chunk before \"fmt \" chunk (008)"; + return false; + } + fm->audio_block = fm->num_blocks; + if(fm->is_rf64 && fm->num_blocks < 2) { + if(error) *error = "invalid RF64 file: \"data\" chunk before \"ds64\" chunk (r01)"; + return false; + } + } + if(!append_block_(fm, offset, 8 + (memcmp(buffer, "data", 4)? size : 0), error)) + return false; + /* parse ds64 chunk if necessary */ + if(fm->is_rf64 && fm->num_blocks == 2) { + FLAC__byte buffer2[7*4]; + if(memcmp(buffer, "ds64", 4)) { + if(error) *error = "invalid RF64 file: \"ds64\" chunk does not immediately follow \"WAVE\" marker (r02)"; + return false; + } + /* unpack the size again since we don't want the padding byte effect */ + size = unpack32le_(buffer+4); + if(size < sizeof(buffer2)) { + if(error) *error = "invalid RF64 file: \"ds64\" chunk size is < 28 (r03)"; + return false; + } + if(size > sizeof(buffer2)) { + if(error) *error = "RF64 file has \"ds64\" chunk with extra size table, which is not currently supported (r04)"; + return false; + } + if(fread(buffer2, 1, sizeof(buffer2), f) < sizeof(buffer2)) { + if(error) *error = "unexpected EOF reading \"ds64\" chunk data in RF64 file (r05)"; + return false; + } + ds64_data_size = (off_t)unpack64le_(buffer2+8); + if(ds64_data_size == (off_t)(-1)) { + if(error) *error = "RF64 file has \"ds64\" chunk with data size == -1 (r08)"; + return false; + } + /* check if pad byte needed */ + if(ds64_data_size & 1) + ds64_data_size++; + /* @@@ [2^63 limit] */ + if(ds64_data_size < 0) { + if(error) *error = "RF64 file too large (r09)"; + return false; + } + if(unpack32le_(buffer2+24)) { + if(error) *error = "RF64 file has \"ds64\" chunk with extra size table, which is not currently supported (r06)"; + return false; + } + eof_offset = (off_t)8 + (off_t)unpack64le_(buffer2); + /* @@@ [2^63 limit] */ + if((off_t)unpack64le_(buffer2) < 0 || eof_offset < 0) { + if(error) *error = "RF64 file too large (r07)"; + return false; + } + } + else { /* skip to next chunk */ + if(fm->is_rf64 && !memcmp(buffer, "data", 4) && unpack32le_(buffer+4) == 0xffffffffu) { + if(fseeko(f, ds64_data_size, SEEK_CUR) < 0) { + if(error) *error = "invalid RF64 file: seek error (r10)"; + return false; + } + } + else { + if(fseeko(f, size, SEEK_CUR) < 0) { + if(error) *error = "invalid WAVE file: seek error (009)"; + return false; + } + } + } + } + if(fm->is_rf64 && eof_offset == (off_t)(-1)) { + if(error) *error = "invalid RF64 file: all RIFF sizes are -1 (r11)"; + return false; + } + if(eof_offset != ftello(f)) { + if(error) *error = "invalid WAVE file: unexpected EOF (010)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid WAVE file: missing \"fmt \" chunk (011)"; + return false; + } + if(!fm->audio_block) { + if(error) *error = "invalid WAVE file: missing \"data\" chunk (012)"; + return false; + } + return true; +} + +static FLAC__bool read_from_wave64_(foreign_metadata_t *fm, FILE *f, const char **error) +{ + FLAC__byte buffer[40]; + off_t offset, eof_offset = -1; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (001)"; + return false; + } + if( + fread(buffer, 1, 40, f) < 40 || + /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */ + memcmp(buffer, "\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 16) || + /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */ + memcmp(buffer+24, "\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16) + ) { + if(error) *error = "unsupported Wave64 layout (002)"; + return false; + } + if(sizeof(off_t) < 8) { + if(error) *error = "Wave64 is not supported on this compile (r00)"; + return false; + } + if(!append_block_(fm, offset, 40, error)) + return false; + eof_offset = (off_t)unpack64le_(buffer+16); /*@@@ [2^63 limit] */ + while(!feof(f)) { + FLAC__uint64 size; + if((offset = ftello(f)) < 0) { + if(error) *error = "ftello() error (003)"; + return false; + } + if((size = fread(buffer, 1, 24, f)) < 24) { + if(size == 0 && feof(f)) + break; + if(error) *error = "invalid Wave64 file (004)"; + return false; + } + size = unpack64le_(buffer+16); + /* check if pad bytes needed */ + if(size & 7) + size = (size+7) & (~((FLAC__uint64)7)); + /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(!memcmp(buffer, "\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16)) { + if(fm->format_block) { + if(error) *error = "invalid Wave64 file: multiple \"fmt \" chunks (005)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid Wave64 file: \"data\" chunk before \"fmt \" chunk (006)"; + return false; + } + fm->format_block = fm->num_blocks; + } + /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */ + else if(!memcmp(buffer, "\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16)) { + if(fm->audio_block) { + if(error) *error = "invalid Wave64 file: multiple \"data\" chunks (007)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid Wave64 file: \"data\" chunk before \"fmt \" chunk (008)"; + return false; + } + fm->audio_block = fm->num_blocks; + } + if(!append_block_(fm, offset, memcmp(buffer, "\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16)? (FLAC__uint32)size : 16+8, error)) + return false; + /* skip to next chunk */ + if(fseeko(f, size-24, SEEK_CUR) < 0) { + if(error) *error = "invalid Wave64 file: seek error (009)"; + return false; + } + } + if(eof_offset != ftello(f)) { + if(error) *error = "invalid Wave64 file: unexpected EOF (010)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid Wave64 file: missing \"fmt \" chunk (011)"; + return false; + } + if(!fm->audio_block) { + if(error) *error = "invalid Wave64 file: missing \"data\" chunk (012)"; + return false; + } + return true; +} + +static FLAC__bool write_to_flac_(foreign_metadata_t *fm, FILE *fin, FILE *fout, FLAC__Metadata_SimpleIterator *it, const char **error) +{ + FLAC__byte buffer[4]; + const unsigned ID_LEN = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8; + size_t block_num = 0; + FLAC__ASSERT(sizeof(buffer) >= ID_LEN); + while(block_num < fm->num_blocks) { + /* find next matching padding block */ + do { + /* even on the first chunk's loop there will be a skippable STREAMINFO block, on subsequent loops we are first moving past the PADDING we just used */ + if(!FLAC__metadata_simple_iterator_next(it)) { + if(error) *error = "no matching PADDING block found (004)"; + return false; + } + } while(FLAC__metadata_simple_iterator_get_block_type(it) != FLAC__METADATA_TYPE_PADDING); + if(FLAC__metadata_simple_iterator_get_block_length(it) != ID_LEN+fm->blocks[block_num].size) { + if(error) *error = "PADDING block with wrong size found (005)"; + return false; + } + /* transfer chunk into APPLICATION block */ + /* first set up the file pointers */ + if(fseeko(fin, fm->blocks[block_num].offset, SEEK_SET) < 0) { + if(error) *error = "seek failed in WAVE/AIFF file (006)"; + return false; + } + if(fseeko(fout, FLAC__metadata_simple_iterator_get_block_offset(it), SEEK_SET) < 0) { + if(error) *error = "seek failed in FLAC file (007)"; + return false; + } + /* update the type */ + buffer[0] = FLAC__METADATA_TYPE_APPLICATION; + if(FLAC__metadata_simple_iterator_is_last(it)) + buffer[0] |= 0x80; /*MAGIC number*/ + if(fwrite(buffer, 1, 1, fout) < 1) { + if(error) *error = "write failed in FLAC file (008)"; + return false; + } + /* length stays the same so skip over it */ + if(fseeko(fout, FLAC__STREAM_METADATA_LENGTH_LEN/8, SEEK_CUR) < 0) { + if(error) *error = "seek failed in FLAC file (009)"; + return false; + } + /* write the APPLICATION ID */ + memcpy(buffer, FLAC__FOREIGN_METADATA_APPLICATION_ID[fm->type], ID_LEN); + if(fwrite(buffer, 1, ID_LEN, fout) < ID_LEN) { + if(error) *error = "write failed in FLAC file (010)"; + return false; + } + /* transfer the foreign metadata */ + if(!copy_data_(fin, fout, fm->blocks[block_num].size, error, "read failed in WAVE/AIFF file (011)", "write failed in FLAC file (012)")) + return false; + block_num++; + } + return true; +} + +static FLAC__bool read_from_flac_(foreign_metadata_t *fm, FILE *f, FLAC__Metadata_SimpleIterator *it, const char **error) +{ + FLAC__byte id[4], buffer[12]; + off_t offset; + FLAC__bool type_found = false, ds64_found = false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_APPLICATION_ID_LEN == sizeof(id)*8); + + while(FLAC__metadata_simple_iterator_next(it)) { + if(FLAC__metadata_simple_iterator_get_block_type(it) != FLAC__METADATA_TYPE_APPLICATION) + continue; + if(!FLAC__metadata_simple_iterator_get_application_id(it, id)) { + if(error) *error = "FLAC__metadata_simple_iterator_get_application_id() error (002)"; + return false; + } + if(memcmp(id, FLAC__FOREIGN_METADATA_APPLICATION_ID[fm->type], sizeof(id))) + continue; + offset = FLAC__metadata_simple_iterator_get_block_offset(it); + /* skip over header and app ID */ + offset += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8; + offset += sizeof(id); + /* look for format or audio blocks */ + if(fseek(f, offset, SEEK_SET) < 0) { + if(error) *error = "seek error (003)"; + return false; + } + if(fread(buffer, 1, 4, f) != 4) { + if(error) *error = "read error (004)"; + return false; + } + if(fm->num_blocks == 0) { /* first block? */ + fm->is_rf64 = 0 == memcmp(buffer, "RF64", 4); + if(fm->type == FOREIGN_BLOCK_TYPE__RIFF && (0 == memcmp(buffer, "RIFF", 4) || fm->is_rf64)) + type_found = true; + else if(fm->type == FOREIGN_BLOCK_TYPE__WAVE64 && 0 == memcmp(buffer, "riff", 4)) /* use first 4 bytes instead of whole GUID */ + type_found = true; + else if(fm->type == FOREIGN_BLOCK_TYPE__AIFF && 0 == memcmp(buffer, "FORM", 4)) + type_found = true; + else { + if(error) *error = "unsupported foreign metadata found, may need newer FLAC decoder (005)"; + return false; + } + } + else if(!type_found) { + FLAC__ASSERT(0); + /* double protection: */ + if(error) *error = "unsupported foreign metadata found, may need newer FLAC decoder (006)"; + return false; + } + else if(fm->type == FOREIGN_BLOCK_TYPE__RIFF) { + if(!memcmp(buffer, "fmt ", 4)) { + if(fm->format_block) { + if(error) *error = "invalid WAVE metadata: multiple \"fmt \" chunks (007)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid WAVE metadata: \"data\" chunk before \"fmt \" chunk (008)"; + return false; + } + fm->format_block = fm->num_blocks; + } + else if(!memcmp(buffer, "data", 4)) { + if(fm->audio_block) { + if(error) *error = "invalid WAVE metadata: multiple \"data\" chunks (009)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid WAVE metadata: \"data\" chunk before \"fmt \" chunk (010)"; + return false; + } + fm->audio_block = fm->num_blocks; + } + else if(fm->is_rf64 && fm->num_blocks == 1) { + if(memcmp(buffer, "ds64", 4)) { + if(error) *error = "invalid RF64 metadata: second chunk is not \"ds64\" (011)"; + return false; + } + ds64_found = true; + } + } + else if(fm->type == FOREIGN_BLOCK_TYPE__WAVE64) { + if(!memcmp(buffer, "fmt ", 4)) { /* use first 4 bytes instead of whole GUID */ + if(fm->format_block) { + if(error) *error = "invalid Wave64 metadata: multiple \"fmt \" chunks (012)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid Wave64 metadata: \"data\" chunk before \"fmt \" chunk (013)"; + return false; + } + fm->format_block = fm->num_blocks; + } + else if(!memcmp(buffer, "data", 4)) { /* use first 4 bytes instead of whole GUID */ + if(fm->audio_block) { + if(error) *error = "invalid Wave64 metadata: multiple \"data\" chunks (014)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid Wave64 metadata: \"data\" chunk before \"fmt \" chunk (015)"; + return false; + } + fm->audio_block = fm->num_blocks; + } + } + else if(fm->type == FOREIGN_BLOCK_TYPE__AIFF) { + if(!memcmp(buffer, "COMM", 4)) { + if(fm->format_block) { + if(error) *error = "invalid AIFF metadata: multiple \"COMM\" chunks (016)"; + return false; + } + if(fm->audio_block) { + if(error) *error = "invalid AIFF metadata: \"SSND\" chunk before \"COMM\" chunk (017)"; + return false; + } + fm->format_block = fm->num_blocks; + } + else if(!memcmp(buffer, "SSND", 4)) { + if(fm->audio_block) { + if(error) *error = "invalid AIFF metadata: multiple \"SSND\" chunks (018)"; + return false; + } + if(!fm->format_block) { + if(error) *error = "invalid AIFF metadata: \"SSND\" chunk before \"COMM\" chunk (019)"; + return false; + } + fm->audio_block = fm->num_blocks; + /* read SSND offset size */ + if(fread(buffer+4, 1, 8, f) != 8) { + if(error) *error = "read error (020)"; + return false; + } + fm->ssnd_offset_size = unpack32be_(buffer+8); + } + } + else { + FLAC__ASSERT(0); + /* double protection: */ + if(error) *error = "unsupported foreign metadata found, may need newer FLAC decoder (021)"; + return false; + } + if(!append_block_(fm, offset, FLAC__metadata_simple_iterator_get_block_length(it)-sizeof(id), error)) + return false; + } + if(!type_found) { + if(error) *error = "no foreign metadata found (022)"; + return false; + } + if(fm->is_rf64 && !ds64_found) { + if(error) *error = "invalid RF64 file: second chunk is not \"ds64\" (023)"; + return false; + } + if(!fm->format_block) { + if(error) + *error = + fm->type==FOREIGN_BLOCK_TYPE__RIFF? "invalid WAVE file: missing \"fmt \" chunk (024)" : + fm->type==FOREIGN_BLOCK_TYPE__WAVE64? "invalid Wave64 file: missing \"fmt \" chunk (025)" : + "invalid AIFF file: missing \"COMM\" chunk (026)"; + return false; + } + if(!fm->audio_block) { + if(error) + *error = + fm->type==FOREIGN_BLOCK_TYPE__RIFF? "invalid WAVE file: missing \"data\" chunk (027)" : + fm->type==FOREIGN_BLOCK_TYPE__WAVE64? "invalid Wave64 file: missing \"data\" chunk (028)" : + "invalid AIFF file: missing \"SSND\" chunk (029)"; + return false; + } + return true; +} + +static FLAC__bool write_to_iff_(foreign_metadata_t *fm, FILE *fin, FILE *fout, off_t offset1, off_t offset2, off_t offset3, const char **error) +{ + size_t i; + if(fseeko(fout, offset1, SEEK_SET) < 0) { + if(error) *error = "seek failed in WAVE/AIFF file (002)"; + return false; + } + /* don't write first (RIFF/RF64/FORM) chunk, or ds64 chunk in the case of RF64 */ + for(i = fm->is_rf64?2:1; i < fm->format_block; i++) { + if(fseeko(fin, fm->blocks[i].offset, SEEK_SET) < 0) { + if(error) *error = "seek failed in FLAC file (003)"; + return false; + } + if(!copy_data_(fin, fout, fm->blocks[i].size, error, "read failed in WAVE/AIFF file (004)", "write failed in FLAC file (005)")) + return false; + } + if(fseeko(fout, offset2, SEEK_SET) < 0) { + if(error) *error = "seek failed in WAVE/AIFF file (006)"; + return false; + } + for(i = fm->format_block+1; i < fm->audio_block; i++) { + if(fseeko(fin, fm->blocks[i].offset, SEEK_SET) < 0) { + if(error) *error = "seek failed in FLAC file (007)"; + return false; + } + if(!copy_data_(fin, fout, fm->blocks[i].size, error, "read failed in WAVE/AIFF file (008)", "write failed in FLAC file (009)")) + return false; + } + if(fseeko(fout, offset3, SEEK_SET) < 0) { + if(error) *error = "seek failed in WAVE/AIFF file (010)"; + return false; + } + for(i = fm->audio_block+1; i < fm->num_blocks; i++) { + if(fseeko(fin, fm->blocks[i].offset, SEEK_SET) < 0) { + if(error) *error = "seek failed in FLAC file (011)"; + return false; + } + if(!copy_data_(fin, fout, fm->blocks[i].size, error, "read failed in WAVE/AIFF file (012)", "write failed in FLAC file (013)")) + return false; + } + return true; +} + +foreign_metadata_t *flac__foreign_metadata_new(foreign_block_type_t type) +{ + /* calloc() to zero all the member variables */ + foreign_metadata_t *x = (foreign_metadata_t*)calloc(sizeof(foreign_metadata_t), 1); + if(x) { + x->type = type; + x->is_rf64 = false; + } + return x; +} + +void flac__foreign_metadata_delete(foreign_metadata_t *fm) +{ + if(fm) { + if(fm->blocks) + free(fm->blocks); + free(fm); + } +} + +FLAC__bool flac__foreign_metadata_read_from_aiff(foreign_metadata_t *fm, const char *filename, const char **error) +{ + FLAC__bool ok; + FILE *f = fopen(filename, "rb"); + if(!f) { + if(error) *error = "can't open AIFF file for reading (000)"; + return false; + } + ok = read_from_aiff_(fm, f, error); + fclose(f); + return ok; +} + +FLAC__bool flac__foreign_metadata_read_from_wave(foreign_metadata_t *fm, const char *filename, const char **error) +{ + FLAC__bool ok; + FILE *f = fopen(filename, "rb"); + if(!f) { + if(error) *error = "can't open WAVE file for reading (000)"; + return false; + } + ok = read_from_wave_(fm, f, error); + fclose(f); + return ok; +} + +FLAC__bool flac__foreign_metadata_read_from_wave64(foreign_metadata_t *fm, const char *filename, const char **error) +{ + FLAC__bool ok; + FILE *f = fopen(filename, "rb"); + if(!f) { + if(error) *error = "can't open Wave64 file for reading (000)"; + return false; + } + ok = read_from_wave64_(fm, f, error); + fclose(f); + return ok; +} + +FLAC__bool flac__foreign_metadata_write_to_flac(foreign_metadata_t *fm, const char *infilename, const char *outfilename, const char **error) +{ + FLAC__bool ok; + FILE *fin, *fout; + FLAC__Metadata_SimpleIterator *it = FLAC__metadata_simple_iterator_new(); + if(!it) { + if(error) *error = "out of memory (000)"; + return false; + } + if(!FLAC__metadata_simple_iterator_init(it, outfilename, /*read_only=*/true, /*preserve_file_stats=*/false)) { + if(error) *error = "can't initialize iterator (001)"; + FLAC__metadata_simple_iterator_delete(it); + return false; + } + if(0 == (fin = fopen(infilename, "rb"))) { + if(error) *error = "can't open WAVE/AIFF file for reading (002)"; + FLAC__metadata_simple_iterator_delete(it); + return false; + } + if(0 == (fout = fopen(outfilename, "r+b"))) { + if(error) *error = "can't open FLAC file for updating (003)"; + FLAC__metadata_simple_iterator_delete(it); + fclose(fin); + return false; + } + ok = write_to_flac_(fm, fin, fout, it, error); + FLAC__metadata_simple_iterator_delete(it); + fclose(fin); + fclose(fout); + return ok; +} + +FLAC__bool flac__foreign_metadata_read_from_flac(foreign_metadata_t *fm, const char *filename, const char **error) +{ + FLAC__bool ok; + FILE *f; + FLAC__Metadata_SimpleIterator *it = FLAC__metadata_simple_iterator_new(); + if(!it) { + if(error) *error = "out of memory (000)"; + return false; + } + if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/false)) { + if(error) *error = "can't initialize iterator (001)"; + FLAC__metadata_simple_iterator_delete(it); + return false; + } + if(0 == (f = fopen(filename, "rb"))) { + if(error) *error = "can't open FLAC file for reading (002)"; + FLAC__metadata_simple_iterator_delete(it); + return false; + } + ok = read_from_flac_(fm, f, it, error); + FLAC__metadata_simple_iterator_delete(it); + fclose(f); + return ok; +} + +FLAC__bool flac__foreign_metadata_write_to_iff(foreign_metadata_t *fm, const char *infilename, const char *outfilename, off_t offset1, off_t offset2, off_t offset3, const char **error) +{ + FLAC__bool ok; + FILE *fin, *fout; + if(0 == (fin = fopen(infilename, "rb"))) { + if(error) *error = "can't open FLAC file for reading (000)"; + return false; + } + if(0 == (fout = fopen(outfilename, "r+b"))) { + if(error) *error = "can't open WAVE/AIFF file for updating (001)"; + fclose(fin); + return false; + } + ok = write_to_iff_(fm, fin, fout, offset1, offset2, offset3, error); + fclose(fin); + fclose(fout); + return ok; +} diff --git a/flac/src/flac/foreign_metadata.h b/flac/src/flac/foreign_metadata.h new file mode 100644 index 0000000..e6739ee --- /dev/null +++ b/flac/src/flac/foreign_metadata.h @@ -0,0 +1,72 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__foreign_metadata_h +#define flac__foreign_metadata_h + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/metadata.h" +#include "utils.h" + +/* WATCHOUT: these enums are used to index internal arrays */ +typedef enum { + FOREIGN_BLOCK_TYPE__AIFF = 0, /* for AIFF and AIFF-C */ + FOREIGN_BLOCK_TYPE__RIFF = 1, /* for WAVE and RF64 */ + FOREIGN_BLOCK_TYPE__WAVE64 = 2 /* only for Sony's flavor */ +} foreign_block_type_t; + +typedef struct { + /* for encoding, this will be the offset in the WAVE/AIFF file of the chunk */ + /* for decoding, this will be the offset in the FLAC file of the chunk data inside the APPLICATION block */ + off_t offset; + /* size is the actual size in bytes of the chunk to be stored/recreated. */ + /* It includes the 8 bytes of chunk type and size, and any padding byte for alignment. */ + /* For 'data'/'SSND' chunks, the size does not include the actual sound or padding bytes */ + /* because these are not stored, they are recreated from the compressed FLAC stream. */ + /* So for RIFF 'data', size is 8, and for AIFF 'SSND', size is 8 + 8 + ssnd_offset_size */ + /* 32 bit size is OK because we only care about the non-sound data and FLAC metadata */ + /* only supports a few megs anyway. */ + FLAC__uint32 size; +} foreign_block_t; + +typedef struct { + foreign_block_type_t type; /* currently we don't support multiple foreign types in a stream (and maybe never will) */ + foreign_block_t *blocks; + size_t num_blocks; + size_t format_block; /* block number of 'fmt ' or 'COMM' chunk */ + size_t audio_block; /* block number of 'data' or 'SSND' chunk */ + FLAC__bool is_rf64; /* always false if type!=RIFF */ + FLAC__uint32 ssnd_offset_size; /* 0 if type!=AIFF */ +} foreign_metadata_t; + +foreign_metadata_t *flac__foreign_metadata_new(foreign_block_type_t type); + +void flac__foreign_metadata_delete(foreign_metadata_t *fm); + +FLAC__bool flac__foreign_metadata_read_from_aiff(foreign_metadata_t *fm, const char *filename, const char **error); +FLAC__bool flac__foreign_metadata_read_from_wave(foreign_metadata_t *fm, const char *filename, const char **error); +FLAC__bool flac__foreign_metadata_read_from_wave64(foreign_metadata_t *fm, const char *filename, const char **error); +FLAC__bool flac__foreign_metadata_write_to_flac(foreign_metadata_t *fm, const char *infilename, const char *outfilename, const char **error); + +FLAC__bool flac__foreign_metadata_read_from_flac(foreign_metadata_t *fm, const char *filename, const char **error); +FLAC__bool flac__foreign_metadata_write_to_iff(foreign_metadata_t *fm, const char *infilename, const char *outfilename, off_t offset1, off_t offset2, off_t offset3, const char **error); + +#endif diff --git a/flac/src/flac/iffscan.c b/flac/src/flac/iffscan.c new file mode 100644 index 0000000..abff4d0 --- /dev/null +++ b/flac/src/flac/iffscan.c @@ -0,0 +1,133 @@ +/* iffscan - Simple AIFF/RIFF chunk scanner + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#include /* for off_t */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include "foreign_metadata.h" + +static FLAC__uint32 unpack32be_(const FLAC__byte *b) +{ + return ((FLAC__uint32)b[0]<<24) + ((FLAC__uint32)b[1]<<16) + ((FLAC__uint32)b[2]<<8) + (FLAC__uint32)b[3]; +} + +static FLAC__uint32 unpack32le_(const FLAC__byte *b) +{ + return (FLAC__uint32)b[0] + ((FLAC__uint32)b[1]<<8) + ((FLAC__uint32)b[2]<<16) + ((FLAC__uint32)b[3]<<24); +} + +static FLAC__uint64 unpack64le_(const FLAC__byte *b) +{ + return (FLAC__uint64)b[0] + ((FLAC__uint64)b[1]<<8) + ((FLAC__uint64)b[2]<<16) + ((FLAC__uint64)b[3]<<24) + ((FLAC__uint64)b[4]<<32) + ((FLAC__uint64)b[5]<<40) + ((FLAC__uint64)b[6]<<48) + ((FLAC__uint64)b[7]<<56); +} + +static FLAC__uint32 unpack32_(const FLAC__byte *b, foreign_block_type_t type) +{ + if(type == FOREIGN_BLOCK_TYPE__AIFF) + return unpack32be_(b); + else + return unpack32le_(b); +} + +int main(int argc, char *argv[]) +{ + FILE *f; + char buf[36]; + foreign_metadata_t *fm; + const char *fn, *error; + size_t i; + FLAC__uint32 size; + + if(argc != 2) { + fprintf(stderr, "usage: %s { file.wav | file.aif }\n", argv[0]); + return 1; + } + fn = argv[1]; + if(0 == (f = fopen(fn, "rb")) || fread(buf, 1, 4, f) != 4) { + fprintf(stderr, "ERROR opening %s for reading\n", fn); + return 1; + } + fclose(f); + if(0 == (fm = flac__foreign_metadata_new(memcmp(buf, "RIFF", 4) && memcmp(buf, "RF64", 4)? FOREIGN_BLOCK_TYPE__AIFF : FOREIGN_BLOCK_TYPE__RIFF))) { + fprintf(stderr, "ERROR: out of memory\n"); + return 1; + } + if(fm->type == FOREIGN_BLOCK_TYPE__AIFF) { + if(!flac__foreign_metadata_read_from_aiff(fm, fn, &error)) { + fprintf(stderr, "ERROR reading chunks from %s: %s\n", fn, error); + return 1; + } + } + else { + if(!flac__foreign_metadata_read_from_wave(fm, fn, &error)) { + fprintf(stderr, "ERROR reading chunks from %s: %s\n", fn, error); + return 1; + } + } + if(0 == (f = fopen(fn, "rb"))) { + fprintf(stderr, "ERROR opening %s for reading\n", fn); + return 1; + } + for(i = 0; i < fm->num_blocks; i++) { + if(fseeko(f, fm->blocks[i].offset, SEEK_SET) < 0) { + fprintf(stderr, "ERROR seeking in %s\n", fn); + return 1; + } + if(fread(buf, 1, i==0?12:8, f) != (i==0?12:8)) { + fprintf(stderr, "ERROR reading %s\n", fn); + return 1; + } + size = unpack32_((const FLAC__byte*)buf+4, fm->type); + printf("block:[%c%c%c%c] size=%08x=(%10u)", buf[0], buf[1], buf[2], buf[3], size, size); + if(i == 0) + printf(" type:[%c%c%c%c]", buf[8], buf[9], buf[10], buf[11]); + else if(fm->type == FOREIGN_BLOCK_TYPE__AIFF && i == fm->audio_block) + printf(" offset size=%08x=(%10u)", fm->ssnd_offset_size, fm->ssnd_offset_size); + else if(fm->type == FOREIGN_BLOCK_TYPE__RIFF && i == 1 && !memcmp(buf, "ds64", 4)) { + if(fread(buf+8, 1, 36-8, f) != 36-8) { + fprintf(stderr, "ERROR reading %s\n", fn); + return 1; + } +#ifdef _MSC_VER + printf(" RIFF size=%016I64x=(%I64u)", unpack64le_(buf+8), unpack64le_(buf+8)); + printf(" data size=%016I64x=(%I64u)", unpack64le_(buf+16), unpack64le_(buf+16)); + printf(" sample count=%016I64x=(%I64u)", unpack64le_(buf+24), unpack64le_(buf+24)); +#else + printf(" RIFF size=%016llx=(%llu)", unpack64le_(buf+8), unpack64le_(buf+8)); + printf(" data size=%016llx=(%llu)", unpack64le_(buf+16), unpack64le_(buf+16)); + printf(" sample count=%016llx=(%llu)", unpack64le_(buf+24), unpack64le_(buf+24)); +#endif + printf(" table size=%08x=(%u)", unpack32le_(buf+32), unpack32le_(buf+32)); + } + printf("\n"); + } + fclose(f); + flac__foreign_metadata_delete(fm); + return 0; +} diff --git a/flac/src/flac/iffscan.dsp b/flac/src/flac/iffscan.dsp new file mode 100644 index 0000000..c313c63 --- /dev/null +++ b/flac/src/flac/iffscan.dsp @@ -0,0 +1,108 @@ +# Microsoft Developer Studio Project File - Name="iffscan" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=iffscan - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "iffscan.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "iffscan.mak" CFG="iffscan - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "iffscan - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "iffscan - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "iffscan - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "." /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "iffscan - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "." /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "iffscan - Win32 Release" +# Name "iffscan - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\iffscan.c +# End Source File +# Begin Source File + +SOURCE=.\foreign_metadata.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\foreign_metadata.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/flac/iffscan.vcproj b/flac/src/flac/iffscan.vcproj new file mode 100644 index 0000000..a443729 --- /dev/null +++ b/flac/src/flac/iffscan.vcproj @@ -0,0 +1,380 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/flac/local_string_utils.c b/flac/src/flac/local_string_utils.c new file mode 100644 index 0000000..30c2b0d --- /dev/null +++ b/flac/src/flac/local_string_utils.c @@ -0,0 +1,109 @@ +/* flac - Command-line FLAC encoder/decoder + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include + +#include "utils.h" +#include "local_string_utils.h" + +/* $OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $ + * + * Copyright (c) 1998 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * + * Copy src to string dst of size siz. At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns strlen(src); if retval >= siz, truncation occurred. + */ +size_t +flac__strlcpy(char *dst, const char *src, size_t siz) +{ + register char *d = dst; + register const char *s = src; + register size_t n = siz; + + /* Copy as many bytes as will fit */ + if (n != 0 && --n != 0) { + do { + if ((*d++ = *s++) == 0) + break; + } while (--n != 0); + } + + /* Not enough room in dst, add NUL and traverse rest of src */ + if (n == 0) { + if (siz != 0) + *d = '\0'; /* NUL-terminate dst */ + while (*s++) + ; + } + + return(s - src - 1); /* count does not include NUL */ +} + +/* $OpenBSD: strlcat.c,v 1.11 2003/06/17 21:56:24 millert Exp $ + * + * Copyright (c) 1998 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * + * Appends src to string dst of size siz (unlike strncat, siz is the + * full size of dst, not space left). At most siz-1 characters + * will be copied. Always NUL terminates (unless siz <= strlen(dst)). + * Returns strlen(src) + MIN(siz, strlen(initial dst)). + * If retval >= siz, truncation occurred. + */ +size_t +flac__strlcat(char *dst, const char *src, size_t siz) +{ + register char *d = dst; + register const char *s = src; + register size_t n = siz; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while (n-- != 0 && *d != '\0') + d++; + dlen = d - dst; + n = siz - dlen; + + if (n == 0) + return(dlen + strlen(s)); + while (*s != '\0') { + if (n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(dlen + (s - src)); /* count does not include NUL */ +} diff --git a/flac/src/flac/local_string_utils.h b/flac/src/flac/local_string_utils.h new file mode 100644 index 0000000..b2f1ae6 --- /dev/null +++ b/flac/src/flac/local_string_utils.h @@ -0,0 +1,27 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__local_string_utils_h +#define flac__local_string_utils_h + +#include /* for size_t */ + +size_t flac__strlcpy(char *dst, const char *src, size_t siz); +size_t flac__strlcat(char *dst, const char *src, size_t siz); + +#endif diff --git a/flac/src/flac/main.c b/flac/src/flac/main.c new file mode 100644 index 0000000..de371a4 --- /dev/null +++ b/flac/src/flac/main.c @@ -0,0 +1,2253 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined _MSC_VER && !defined __MINGW32__ +/* unlink is in stdio.h in VC++ */ +#include /* for unlink() */ +#endif +#include "FLAC/all.h" +#include "share/alloc.h" +#include "share/grabbag.h" +#include "analyze.h" +#include "decode.h" +#include "encode.h" +#include "local_string_utils.h" /* for flac__strlcat() and flac__strlcpy() */ +#include "utils.h" +#include "vorbiscomment.h" + +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ +#define FLAC__STRCASECMP stricmp +#else +#define FLAC__STRCASECMP strcasecmp +#endif + +#if 0 +/*[JEC] was:#if HAVE_GETOPT_LONG*/ +/*[JEC] see flac/include/share/getopt.h as to why the change */ +# include +#else +# include "share/getopt.h" +#endif + +static int do_it(void); + +static FLAC__bool init_options(void); +static int parse_options(int argc, char *argv[]); +static int parse_option(int short_option, const char *long_option, const char *option_argument); +static void free_options(void); +static void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value); +static void add_compression_setting_string(compression_setting_type_t type, const char *value); +static void add_compression_setting_unsigned(compression_setting_type_t type, unsigned value); + +static int usage_error(const char *message, ...); +static void short_usage(void); +static void show_version(void); +static void show_help(void); +static void show_explain(void); +static void format_mistake(const char *infilename, FileFormat wrong, FileFormat right); + +static int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file); +static int decode_file(const char *infilename); + +static const char *get_encoded_outfilename(const char *infilename); +static const char *get_decoded_outfilename(const char *infilename); +static const char *get_outfilename(const char *infilename, const char *suffix); + +static void die(const char *message); +static int conditional_fclose(FILE *f); +static char *local_strdup(const char *source); +#ifdef _MSC_VER +/* There's no strtoll() in MSVC6 so we just write a specialized one */ +static FLAC__int64 local__strtoll(const char *src, char **endptr); +#endif + + +/* + * share__getopt format struct; note that for long options with no + * short option equivalent we just set the 'val' field to 0. + */ +static struct share__option long_options_[] = { + /* + * general options + */ + { "help" , share__no_argument, 0, 'h' }, + { "explain" , share__no_argument, 0, 'H' }, + { "version" , share__no_argument, 0, 'v' }, + { "decode" , share__no_argument, 0, 'd' }, + { "analyze" , share__no_argument, 0, 'a' }, + { "test" , share__no_argument, 0, 't' }, + { "stdout" , share__no_argument, 0, 'c' }, + { "silent" , share__no_argument, 0, 's' }, + { "totally-silent" , share__no_argument, 0, 0 }, + { "warnings-as-errors" , share__no_argument, 0, 'w' }, + { "force" , share__no_argument, 0, 'f' }, + { "delete-input-file" , share__no_argument, 0, 0 }, + { "preserve-modtime" , share__no_argument, 0, 0 }, + { "keep-foreign-metadata" , share__no_argument, 0, 0 }, + { "output-prefix" , share__required_argument, 0, 0 }, + { "output-name" , share__required_argument, 0, 'o' }, + { "skip" , share__required_argument, 0, 0 }, + { "until" , share__required_argument, 0, 0 }, + { "channel-map" , share__required_argument, 0, 0 }, /* undocumented */ + + /* + * decoding options + */ + { "decode-through-errors", share__no_argument, 0, 'F' }, + { "cue" , share__required_argument, 0, 0 }, + { "apply-replaygain-which-is-not-lossless", share__optional_argument, 0, 0 }, /* undocumented */ + + /* + * encoding options + */ + { "cuesheet" , share__required_argument, 0, 0 }, + { "no-cued-seekpoints" , share__no_argument, 0, 0 }, + { "picture" , share__required_argument, 0, 0 }, + { "tag" , share__required_argument, 0, 'T' }, + { "tag-from-file" , share__required_argument, 0, 0 }, + { "compression-level-0" , share__no_argument, 0, '0' }, + { "compression-level-1" , share__no_argument, 0, '1' }, + { "compression-level-2" , share__no_argument, 0, '2' }, + { "compression-level-3" , share__no_argument, 0, '3' }, + { "compression-level-4" , share__no_argument, 0, '4' }, + { "compression-level-5" , share__no_argument, 0, '5' }, + { "compression-level-6" , share__no_argument, 0, '6' }, + { "compression-level-7" , share__no_argument, 0, '7' }, + { "compression-level-8" , share__no_argument, 0, '8' }, + { "compression-level-9" , share__no_argument, 0, '9' }, + { "best" , share__no_argument, 0, '8' }, + { "fast" , share__no_argument, 0, '0' }, + { "verify" , share__no_argument, 0, 'V' }, + { "force-raw-format" , share__no_argument, 0, 0 }, + { "force-aiff-format" , share__no_argument, 0, 0 }, + { "force-rf64-format" , share__no_argument, 0, 0 }, + { "force-wave64-format" , share__no_argument, 0, 0 }, + { "lax" , share__no_argument, 0, 0 }, + { "replay-gain" , share__no_argument, 0, 0 }, + { "ignore-chunk-sizes" , share__no_argument, 0, 0 }, + { "sector-align" , share__no_argument, 0, 0 }, /* DEPRECATED */ + { "seekpoint" , share__required_argument, 0, 'S' }, + { "padding" , share__required_argument, 0, 'P' }, +#if FLAC__HAS_OGG + { "ogg" , share__no_argument, 0, 0 }, + { "serial-number" , share__required_argument, 0, 0 }, +#endif + { "blocksize" , share__required_argument, 0, 'b' }, + { "exhaustive-model-search" , share__no_argument, 0, 'e' }, + { "max-lpc-order" , share__required_argument, 0, 'l' }, + { "apodization" , share__required_argument, 0, 'A' }, + { "mid-side" , share__no_argument, 0, 'm' }, + { "adaptive-mid-side" , share__no_argument, 0, 'M' }, + { "qlp-coeff-precision-search", share__no_argument, 0, 'p' }, + { "qlp-coeff-precision" , share__required_argument, 0, 'q' }, + { "rice-partition-order" , share__required_argument, 0, 'r' }, + { "endian" , share__required_argument, 0, 0 }, + { "channels" , share__required_argument, 0, 0 }, + { "bps" , share__required_argument, 0, 0 }, + { "sample-rate" , share__required_argument, 0, 0 }, + { "sign" , share__required_argument, 0, 0 }, + { "input-size" , share__required_argument, 0, 0 }, + + /* + * analysis options + */ + { "residual-gnuplot", share__no_argument, 0, 0 }, + { "residual-text", share__no_argument, 0, 0 }, + + /* + * negatives + */ + { "no-preserve-modtime" , share__no_argument, 0, 0 }, + { "no-decode-through-errors" , share__no_argument, 0, 0 }, + { "no-silent" , share__no_argument, 0, 0 }, + { "no-force" , share__no_argument, 0, 0 }, + { "no-seektable" , share__no_argument, 0, 0 }, + { "no-delete-input-file" , share__no_argument, 0, 0 }, + { "no-keep-foreign-metadata" , share__no_argument, 0, 0 }, + { "no-replay-gain" , share__no_argument, 0, 0 }, + { "no-ignore-chunk-sizes" , share__no_argument, 0, 0 }, + { "no-sector-align" , share__no_argument, 0, 0 }, /* DEPRECATED */ + { "no-utf8-convert" , share__no_argument, 0, 0 }, + { "no-lax" , share__no_argument, 0, 0 }, +#if FLAC__HAS_OGG + { "no-ogg" , share__no_argument, 0, 0 }, +#endif + { "no-exhaustive-model-search", share__no_argument, 0, 0 }, + { "no-mid-side" , share__no_argument, 0, 0 }, + { "no-adaptive-mid-side" , share__no_argument, 0, 0 }, + { "no-qlp-coeff-prec-search" , share__no_argument, 0, 0 }, + { "no-padding" , share__no_argument, 0, 0 }, + { "no-verify" , share__no_argument, 0, 0 }, + { "no-warnings-as-errors" , share__no_argument, 0, 0 }, + { "no-residual-gnuplot" , share__no_argument, 0, 0 }, + { "no-residual-text" , share__no_argument, 0, 0 }, + /* + * undocumented debugging options for the test suite + */ + { "disable-constant-subframes", share__no_argument, 0, 0 }, + { "disable-fixed-subframes" , share__no_argument, 0, 0 }, + { "disable-verbatim-subframes", share__no_argument, 0, 0 }, + { "no-md5-sum" , share__no_argument, 0, 0 }, + + {0, 0, 0, 0} +}; + + +/* + * global to hold command-line option values + */ + +static struct { + FLAC__bool show_help; + FLAC__bool show_explain; + FLAC__bool show_version; + FLAC__bool mode_decode; + FLAC__bool verify; + FLAC__bool treat_warnings_as_errors; + FLAC__bool force_file_overwrite; + FLAC__bool continue_through_decode_errors; + replaygain_synthesis_spec_t replaygain_synthesis_spec; + FLAC__bool lax; + FLAC__bool test_only; + FLAC__bool analyze; + FLAC__bool use_ogg; + FLAC__bool has_serial_number; /* true iff --serial-number was used */ + long serial_number; /* this is the Ogg serial number and is unused for native FLAC */ + FLAC__bool force_to_stdout; + FLAC__bool force_raw_format; + FLAC__bool force_aiff_format; + FLAC__bool force_rf64_format; + FLAC__bool force_wave64_format; + FLAC__bool delete_input; + FLAC__bool preserve_modtime; + FLAC__bool keep_foreign_metadata; + FLAC__bool replay_gain; + FLAC__bool ignore_chunk_sizes; + FLAC__bool sector_align; + FLAC__bool utf8_convert; /* true by default, to convert tag strings from locale to utf-8, false if --no-utf8-convert used */ + const char *cmdline_forced_outfilename; + const char *output_prefix; + analysis_options aopts; + int padding; /* -1 => no -P options were given, 0 => -P- was given, else -P value */ + size_t num_compression_settings; + compression_setting_t compression_settings[64]; /* bad MAGIC NUMBER but buffer overflow is checked */ + const char *skip_specification; + const char *until_specification; + const char *cue_specification; + int format_is_big_endian; + int format_is_unsigned_samples; + int format_channels; + int format_bps; + int format_sample_rate; + off_t format_input_size; + char requested_seek_points[5000]; /* bad MAGIC NUMBER but buffer overflow is checked */ + int num_requested_seek_points; /* -1 => no -S options were given, 0 => -S- was given */ + const char *cuesheet_filename; + FLAC__bool cued_seekpoints; + FLAC__bool channel_map_none; /* --channel-map=none specified, eventually will expand to take actual channel map */ + + unsigned num_files; + char **filenames; + + FLAC__StreamMetadata *vorbis_comment; + FLAC__StreamMetadata *pictures[64]; + unsigned num_pictures; + + struct { + FLAC__bool disable_constant_subframes; + FLAC__bool disable_fixed_subframes; + FLAC__bool disable_verbatim_subframes; + FLAC__bool do_md5; + } debug; +} option_values; + + +/* + * miscellaneous globals + */ + +static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carrying over samples from --sector-align */ /* DEPRECATED */ +static FLAC__int32 *align_reservoir[2] = { align_reservoir_0, align_reservoir_1 }; +static unsigned align_reservoir_samples = 0; /* 0 .. 587 */ + + +int main(int argc, char *argv[]) +{ + int retval = 0; + +#ifdef __EMX__ + _response(&argc, &argv); + _wildcard(&argc, &argv); +#endif + + srand((unsigned)time(0)); + setlocale(LC_ALL, ""); + if(!init_options()) { + flac__utils_printf(stderr, 1, "ERROR: allocating memory\n"); + retval = 1; + } + else { + if((retval = parse_options(argc, argv)) == 0) + retval = do_it(); + } + + free_options(); + + return retval; +} + +int do_it(void) +{ + int retval = 0; + + if(option_values.show_version) { + show_version(); + return 0; + } + else if(option_values.show_explain) { + show_explain(); + return 0; + } + else if(option_values.show_help) { + show_help(); + return 0; + } + else { + if(option_values.num_files == 0) { + if(flac__utils_verbosity_ >= 1) + short_usage(); + return 0; + } + + /* + * tweak options; validate the values + */ + if(!option_values.mode_decode) { + if(0 != option_values.cue_specification) + return usage_error("ERROR: --cue is not allowed in test mode\n"); + } + else { + if(option_values.test_only) { + if(0 != option_values.skip_specification) + return usage_error("ERROR: --skip is not allowed in test mode\n"); + if(0 != option_values.until_specification) + return usage_error("ERROR: --until is not allowed in test mode\n"); + if(0 != option_values.cue_specification) + return usage_error("ERROR: --cue is not allowed in test mode\n"); + if(0 != option_values.analyze) + return usage_error("ERROR: analysis mode (-a/--analyze) and test mode (-t/--test) cannot be used together\n"); + } + } + + if(0 != option_values.cue_specification && (0 != option_values.skip_specification || 0 != option_values.until_specification)) + return usage_error("ERROR: --cue may not be combined with --skip or --until\n"); + + if(option_values.format_channels >= 0) { + if(option_values.format_channels == 0 || (unsigned)option_values.format_channels > FLAC__MAX_CHANNELS) + return usage_error("ERROR: invalid number of channels '%u', must be > 0 and <= %u\n", option_values.format_channels, FLAC__MAX_CHANNELS); + } + if(option_values.format_bps >= 0) { + if(option_values.format_bps != 8 && option_values.format_bps != 16 && option_values.format_bps != 24) + return usage_error("ERROR: invalid bits per sample '%u' (must be 8/16/24)\n", option_values.format_bps); + } + if(option_values.format_sample_rate >= 0) { + if(!FLAC__format_sample_rate_is_valid(option_values.format_sample_rate)) + return usage_error("ERROR: invalid sample rate '%u', must be > 0 and <= %u\n", option_values.format_sample_rate, FLAC__MAX_SAMPLE_RATE); + } + if((option_values.force_raw_format?1:0) + (option_values.force_aiff_format?1:0) + (option_values.force_rf64_format?1:0) + (option_values.force_wave64_format?1:0) > 1) + return usage_error("ERROR: only one of --force-raw-format/--force-aiff-format/--force-rf64-format/--force-wave64-format allowed\n"); + if(option_values.mode_decode) { + if(!option_values.force_raw_format) { + if(option_values.format_is_big_endian >= 0) + return usage_error("ERROR: --endian only allowed with --force-raw-format\n"); + if(option_values.format_is_unsigned_samples >= 0) + return usage_error("ERROR: --sign only allowed with --force-raw-format\n"); + } + if(option_values.format_channels >= 0) + return usage_error("ERROR: --channels not allowed with --decode\n"); + if(option_values.format_bps >= 0) + return usage_error("ERROR: --bps not allowed with --decode\n"); + if(option_values.format_sample_rate >= 0) + return usage_error("ERROR: --sample-rate not allowed with --decode\n"); + } + + if(option_values.ignore_chunk_sizes) { + if(option_values.mode_decode) + return usage_error("ERROR: --ignore-chunk-sizes only allowed for encoding\n"); + if(0 != option_values.sector_align) + return usage_error("ERROR: --ignore-chunk-sizes not allowed with --sector-align\n"); + if(0 != option_values.until_specification) + return usage_error("ERROR: --ignore-chunk-sizes not allowed with --until\n"); + if(0 != option_values.cue_specification) + return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cue\n"); + if(0 != option_values.cuesheet_filename) + return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cuesheet\n"); + } + if(option_values.sector_align) { + if(option_values.mode_decode) + return usage_error("ERROR: --sector-align only allowed for encoding\n"); + if(0 != option_values.skip_specification) + return usage_error("ERROR: --sector-align not allowed with --skip\n"); + if(0 != option_values.until_specification) + return usage_error("ERROR: --sector-align not allowed with --until\n"); + if(0 != option_values.cue_specification) + return usage_error("ERROR: --sector-align not allowed with --cue\n"); + if(option_values.format_channels >= 0 && option_values.format_channels != 2) + return usage_error("ERROR: --sector-align can only be done with stereo input\n"); + if(option_values.format_bps >= 0 && option_values.format_bps != 16) + return usage_error("ERROR: --sector-align can only be done with 16-bit samples\n"); + if(option_values.format_sample_rate >= 0 && option_values.format_sample_rate != 44100) + return usage_error("ERROR: --sector-align can only be done with a sample rate of 44100\n"); + } + if(option_values.replay_gain) { + if(option_values.force_to_stdout) + return usage_error("ERROR: --replay-gain not allowed with -c/--stdout\n"); + if(option_values.mode_decode) + return usage_error("ERROR: --replay-gain only allowed for encoding\n"); + if(option_values.format_channels > 2) + return usage_error("ERROR: --replay-gain can only be done with mono/stereo input\n"); + if(option_values.format_sample_rate >= 0 && !grabbag__replaygain_is_valid_sample_frequency(option_values.format_sample_rate)) + return usage_error("ERROR: invalid sample rate used with --replay-gain\n"); + /* + * We want to reserve padding space for the ReplayGain + * tags that we will set later, to avoid rewriting the + * whole file. + */ + if( + (option_values.padding >= 0 && option_values.padding < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED) || + (option_values.padding < 0 && FLAC_ENCODE__DEFAULT_PADDING < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED) + ) { + flac__utils_printf(stderr, 1, "NOTE: --replay-gain may leave a small PADDING block even with --no-padding\n"); + option_values.padding = GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED; + } + else { + option_values.padding += GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED; + } + } + if(option_values.num_files > 1 && option_values.cmdline_forced_outfilename) { + return usage_error("ERROR: -o/--output-name cannot be used with multiple files\n"); + } + if(option_values.cmdline_forced_outfilename && option_values.output_prefix) { + return usage_error("ERROR: --output-prefix conflicts with -o/--output-name\n"); + } + if(!option_values.mode_decode && 0 != option_values.cuesheet_filename && option_values.num_files > 1) { + return usage_error("ERROR: --cuesheet cannot be used when encoding multiple files\n"); + } + if(option_values.keep_foreign_metadata) { + /* we're not going to try and support the re-creation of broken WAVE files */ + if(option_values.ignore_chunk_sizes) + return usage_error("ERROR: using --keep-foreign-metadata cannot be used with --ignore-chunk-sizes\n"); + if(option_values.test_only) + return usage_error("ERROR: --keep-foreign-metadata is not allowed in test mode\n"); + if(option_values.analyze) + return usage_error("ERROR: --keep-foreign-metadata is not allowed in analyis mode\n"); + flac__utils_printf(stderr, 1, "NOTE: --keep-foreign-metadata is a new feature; make sure to test the output file before deleting the original.\n"); + } + } + + flac__utils_printf(stderr, 2, "\n"); + flac__utils_printf(stderr, 2, "flac %s, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson\n", FLAC__VERSION_STRING); + flac__utils_printf(stderr, 2, "flac comes with ABSOLUTELY NO WARRANTY. This is free software, and you are\n"); + flac__utils_printf(stderr, 2, "welcome to redistribute it under certain conditions. Type `flac' for details.\n\n"); + + if(option_values.mode_decode) { + FLAC__bool first = true; + + if(option_values.num_files == 0) { + retval = decode_file("-"); + } + else { + unsigned i; + if(option_values.num_files > 1) + option_values.cmdline_forced_outfilename = 0; + for(i = 0, retval = 0; i < option_values.num_files; i++) { + if(0 == strcmp(option_values.filenames[i], "-") && !first) + continue; + retval |= decode_file(option_values.filenames[i]); + first = false; + } + } + } + else { /* encode */ + FLAC__bool first = true; + + if(option_values.ignore_chunk_sizes) + flac__utils_printf(stderr, 1, "INFO: Make sure you know what you're doing when using --ignore-chunk-sizes.\n Improper use can cause flac to encode non-audio data as audio.\n"); + + if(option_values.num_files == 0) { + retval = encode_file("-", first, true); + } + else { + unsigned i; + if(option_values.num_files > 1) + option_values.cmdline_forced_outfilename = 0; + for(i = 0, retval = 0; i < option_values.num_files; i++) { + if(0 == strcmp(option_values.filenames[i], "-") && !first) + continue; + retval |= encode_file(option_values.filenames[i], first, i == (option_values.num_files-1)); + first = false; + } + if(option_values.replay_gain && retval == 0) { + float album_gain, album_peak; + grabbag__replaygain_get_album(&album_gain, &album_peak); + for(i = 0; i < option_values.num_files; i++) { + const char *error, *outfilename = get_encoded_outfilename(option_values.filenames[i]); + if(0 == outfilename) { + flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", option_values.filenames[i]); + return 1; + } + if(0 == strcmp(option_values.filenames[i], "-")) { + FLAC__ASSERT(0); + /* double protection */ + flac__utils_printf(stderr, 1, "internal error\n"); + return 2; + } + if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, option_values.preserve_modtime))) { + flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags (%s)\n", outfilename, error); + retval = 1; + } + } + } + } + } + + return retval; +} + +FLAC__bool init_options(void) +{ + option_values.show_help = false; + option_values.show_explain = false; + option_values.mode_decode = false; + option_values.verify = false; + option_values.treat_warnings_as_errors = false; + option_values.force_file_overwrite = false; + option_values.continue_through_decode_errors = false; + option_values.replaygain_synthesis_spec.apply = false; + option_values.replaygain_synthesis_spec.use_album_gain = true; + option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD; + option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_LOW; + option_values.replaygain_synthesis_spec.preamp = 0.0; + option_values.lax = false; + option_values.test_only = false; + option_values.analyze = false; + option_values.use_ogg = false; + option_values.has_serial_number = false; + option_values.serial_number = 0; + option_values.force_to_stdout = false; + option_values.force_raw_format = false; + option_values.force_aiff_format = false; + option_values.force_rf64_format = false; + option_values.force_wave64_format = false; + option_values.delete_input = false; + option_values.preserve_modtime = true; + option_values.keep_foreign_metadata = false; + option_values.replay_gain = false; + option_values.ignore_chunk_sizes = false; + option_values.sector_align = false; + option_values.utf8_convert = true; + option_values.cmdline_forced_outfilename = 0; + option_values.output_prefix = 0; + option_values.aopts.do_residual_text = false; + option_values.aopts.do_residual_gnuplot = false; + option_values.padding = -1; + option_values.num_compression_settings = 1; + option_values.compression_settings[0].type = CST_COMPRESSION_LEVEL; + option_values.compression_settings[0].value.t_unsigned = 5; + option_values.skip_specification = 0; + option_values.until_specification = 0; + option_values.cue_specification = 0; + option_values.format_is_big_endian = -1; + option_values.format_is_unsigned_samples = -1; + option_values.format_channels = -1; + option_values.format_bps = -1; + option_values.format_sample_rate = -1; + option_values.format_input_size = (off_t)(-1); + option_values.requested_seek_points[0] = '\0'; + option_values.num_requested_seek_points = -1; + option_values.cuesheet_filename = 0; + option_values.cued_seekpoints = true; + option_values.channel_map_none = false; + + option_values.num_files = 0; + option_values.filenames = 0; + + if(0 == (option_values.vorbis_comment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT))) + return false; + option_values.num_pictures = 0; + + option_values.debug.disable_constant_subframes = false; + option_values.debug.disable_fixed_subframes = false; + option_values.debug.disable_verbatim_subframes = false; + option_values.debug.do_md5 = true; + + return true; +} + +int parse_options(int argc, char *argv[]) +{ + int short_option; + int option_index = 1; + FLAC__bool had_error = false; + const char *short_opts = "0123456789aA:b:cdefFhHl:mMo:pP:q:r:sS:tT:vVw"; + + while ((short_option = share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) { + switch (short_option) { + case 0: /* long option with no equivalent short option */ + had_error |= (parse_option(short_option, long_options_[option_index].name, share__optarg) != 0); + break; + case '?': + case ':': + had_error = true; + break; + default: /* short option */ + had_error |= (parse_option(short_option, 0, share__optarg) != 0); + break; + } + } + + if(had_error) { + return 1; + } + + FLAC__ASSERT(share__optind <= argc); + + option_values.num_files = argc - share__optind; + + if(option_values.num_files > 0) { + unsigned i = 0; + if(0 == (option_values.filenames = (char**)malloc(sizeof(char*) * option_values.num_files))) + die("out of memory allocating space for file names list"); + while(share__optind < argc) + option_values.filenames[i++] = local_strdup(argv[share__optind++]); + } + + return 0; +} + +int parse_option(int short_option, const char *long_option, const char *option_argument) +{ + const char *violation; + char *p; + int i; + + if(short_option == 0) { + FLAC__ASSERT(0 != long_option); + if(0 == strcmp(long_option, "totally-silent")) { + flac__utils_verbosity_ = 0; + } + else if(0 == strcmp(long_option, "delete-input-file")) { + option_values.delete_input = true; + } + else if(0 == strcmp(long_option, "preserve-modtime")) { + option_values.preserve_modtime = true; + } + else if(0 == strcmp(long_option, "keep-foreign-metadata")) { + option_values.keep_foreign_metadata = true; + } + else if(0 == strcmp(long_option, "output-prefix")) { + FLAC__ASSERT(0 != option_argument); + option_values.output_prefix = option_argument; + } + else if(0 == strcmp(long_option, "skip")) { + FLAC__ASSERT(0 != option_argument); + option_values.skip_specification = option_argument; + } + else if(0 == strcmp(long_option, "until")) { + FLAC__ASSERT(0 != option_argument); + option_values.until_specification = option_argument; + } + else if(0 == strcmp(long_option, "input-size")) { + FLAC__ASSERT(0 != option_argument); + { + char *end; +#ifdef _MSC_VER + FLAC__int64 i; + i = local__strtoll(option_argument, &end); +#else + long long i; + i = strtoll(option_argument, &end, 10); +#endif + if(0 == strlen(option_argument) || *end) + return usage_error("ERROR: --%s must be a number\n", long_option); + option_values.format_input_size = (off_t)i; + if(option_values.format_input_size != i) /* check if off_t is smaller than long long */ + return usage_error("ERROR: --%s too large; this build of flac does not support filesizes over 2GB\n", long_option); + if(option_values.format_input_size <= 0) + return usage_error("ERROR: --%s must be > 0\n", long_option); + } + } + else if(0 == strcmp(long_option, "cue")) { + FLAC__ASSERT(0 != option_argument); + option_values.cue_specification = option_argument; + } + else if(0 == strcmp(long_option, "apply-replaygain-which-is-not-lossless")) { + option_values.replaygain_synthesis_spec.apply = true; + if (0 != option_argument) { + char *p; + option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__NONE; + option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_NONE; + option_values.replaygain_synthesis_spec.preamp = strtod(option_argument, &p); + for ( ; *p; p++) { + if (*p == 'a') + option_values.replaygain_synthesis_spec.use_album_gain = true; + else if (*p == 't') + option_values.replaygain_synthesis_spec.use_album_gain = false; + else if (*p == 'l') + option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__PEAK; + else if (*p == 'L') + option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD; + else if (*p == 'n' && p[1] >= '0' && p[1] <= '3') { + option_values.replaygain_synthesis_spec.noise_shaping = p[1] - '0'; + p++; + } + else + return usage_error("ERROR: bad specification string \"%s\" for --%s\n", option_argument, long_option); + } + } + } + else if(0 == strcmp(long_option, "channel-map")) { + if (0 == option_argument || strcmp(option_argument, "none")) + return usage_error("ERROR: only --channel-map=none currently supported\n"); + option_values.channel_map_none = true; + } + else if(0 == strcmp(long_option, "cuesheet")) { + FLAC__ASSERT(0 != option_argument); + option_values.cuesheet_filename = option_argument; + } + else if(0 == strcmp(long_option, "picture")) { + const unsigned max_pictures = sizeof(option_values.pictures)/sizeof(option_values.pictures[0]); + FLAC__ASSERT(0 != option_argument); + if(option_values.num_pictures >= max_pictures) + return usage_error("ERROR: too many --picture arguments, only %u allowed\n", max_pictures); + if(0 == (option_values.pictures[option_values.num_pictures] = grabbag__picture_parse_specification(option_argument, &violation))) + return usage_error("ERROR: (--picture) %s\n", violation); + option_values.num_pictures++; + } + else if(0 == strcmp(long_option, "tag-from-file")) { + FLAC__ASSERT(0 != option_argument); + if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/true, /*raw=*/!option_values.utf8_convert, &violation)) + return usage_error("ERROR: (--tag-from-file) %s\n", violation); + } + else if(0 == strcmp(long_option, "no-cued-seekpoints")) { + option_values.cued_seekpoints = false; + } + else if(0 == strcmp(long_option, "force-raw-format")) { + option_values.force_raw_format = true; + } + else if(0 == strcmp(long_option, "force-aiff-format")) { + option_values.force_aiff_format = true; + } + else if(0 == strcmp(long_option, "force-rf64-format")) { + option_values.force_rf64_format = true; + } + else if(0 == strcmp(long_option, "force-wave64-format")) { + option_values.force_wave64_format = true; + } + else if(0 == strcmp(long_option, "lax")) { + option_values.lax = true; + } + else if(0 == strcmp(long_option, "replay-gain")) { + option_values.replay_gain = true; + } + else if(0 == strcmp(long_option, "ignore-chunk-sizes")) { + option_values.ignore_chunk_sizes = true; + } + else if(0 == strcmp(long_option, "sector-align")) { + flac__utils_printf(stderr, 1, "WARNING: --sector-align is DEPRECATED and may not exist in future versions of flac.\n"); + flac__utils_printf(stderr, 1, " shntool provides similar functionality\n"); + option_values.sector_align = true; + } +#if FLAC__HAS_OGG + else if(0 == strcmp(long_option, "ogg")) { + option_values.use_ogg = true; + } + else if(0 == strcmp(long_option, "serial-number")) { + option_values.has_serial_number = true; + option_values.serial_number = atol(option_argument); + } +#endif + else if(0 == strcmp(long_option, "endian")) { + FLAC__ASSERT(0 != option_argument); + if(0 == strncmp(option_argument, "big", strlen(option_argument))) + option_values.format_is_big_endian = true; + else if(0 == strncmp(option_argument, "little", strlen(option_argument))) + option_values.format_is_big_endian = false; + else + return usage_error("ERROR: argument to --endian must be \"big\" or \"little\"\n"); + } + else if(0 == strcmp(long_option, "channels")) { + FLAC__ASSERT(0 != option_argument); + option_values.format_channels = atoi(option_argument); + } + else if(0 == strcmp(long_option, "bps")) { + FLAC__ASSERT(0 != option_argument); + option_values.format_bps = atoi(option_argument); + } + else if(0 == strcmp(long_option, "sample-rate")) { + FLAC__ASSERT(0 != option_argument); + option_values.format_sample_rate = atoi(option_argument); + } + else if(0 == strcmp(long_option, "sign")) { + FLAC__ASSERT(0 != option_argument); + if(0 == strncmp(option_argument, "signed", strlen(option_argument))) + option_values.format_is_unsigned_samples = false; + else if(0 == strncmp(option_argument, "unsigned", strlen(option_argument))) + option_values.format_is_unsigned_samples = true; + else + return usage_error("ERROR: argument to --sign must be \"signed\" or \"unsigned\"\n"); + } + else if(0 == strcmp(long_option, "residual-gnuplot")) { + option_values.aopts.do_residual_gnuplot = true; + } + else if(0 == strcmp(long_option, "residual-text")) { + option_values.aopts.do_residual_text = true; + } + /* + * negatives + */ + else if(0 == strcmp(long_option, "no-preserve-modtime")) { + option_values.preserve_modtime = false; + } + else if(0 == strcmp(long_option, "no-decode-through-errors")) { + option_values.continue_through_decode_errors = false; + } + else if(0 == strcmp(long_option, "no-silent")) { + flac__utils_verbosity_ = 2; + } + else if(0 == strcmp(long_option, "no-force")) { + option_values.force_file_overwrite = false; + } + else if(0 == strcmp(long_option, "no-seektable")) { + option_values.num_requested_seek_points = 0; + option_values.requested_seek_points[0] = '\0'; + } + else if(0 == strcmp(long_option, "no-delete-input-file")) { + option_values.delete_input = false; + } + else if(0 == strcmp(long_option, "no-keep-foreign-metadata")) { + option_values.keep_foreign_metadata = false; + } + else if(0 == strcmp(long_option, "no-replay-gain")) { + option_values.replay_gain = false; + } + else if(0 == strcmp(long_option, "no-ignore-chunk-sizes")) { + option_values.ignore_chunk_sizes = false; + } + else if(0 == strcmp(long_option, "no-sector-align")) { + option_values.sector_align = false; + } + else if(0 == strcmp(long_option, "no-utf8-convert")) { + option_values.utf8_convert = false; + } + else if(0 == strcmp(long_option, "no-lax")) { + option_values.lax = false; + } +#if FLAC__HAS_OGG + else if(0 == strcmp(long_option, "no-ogg")) { + option_values.use_ogg = false; + } +#endif + else if(0 == strcmp(long_option, "no-exhaustive-model-search")) { + add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, false); + } + else if(0 == strcmp(long_option, "no-mid-side")) { + add_compression_setting_bool(CST_DO_MID_SIDE, false); + add_compression_setting_bool(CST_LOOSE_MID_SIDE, false); + } + else if(0 == strcmp(long_option, "no-adaptive-mid-side")) { + add_compression_setting_bool(CST_DO_MID_SIDE, false); + add_compression_setting_bool(CST_LOOSE_MID_SIDE, false); + } + else if(0 == strcmp(long_option, "no-qlp-coeff-prec-search")) { + add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, false); + } + else if(0 == strcmp(long_option, "no-padding")) { + option_values.padding = 0; + } + else if(0 == strcmp(long_option, "no-verify")) { + option_values.verify = false; + } + else if(0 == strcmp(long_option, "no-warnings-as-errors")) { + option_values.treat_warnings_as_errors = false; + } + else if(0 == strcmp(long_option, "no-residual-gnuplot")) { + option_values.aopts.do_residual_gnuplot = false; + } + else if(0 == strcmp(long_option, "no-residual-text")) { + option_values.aopts.do_residual_text = false; + } + else if(0 == strcmp(long_option, "disable-constant-subframes")) { + option_values.debug.disable_constant_subframes = true; + } + else if(0 == strcmp(long_option, "disable-fixed-subframes")) { + option_values.debug.disable_fixed_subframes = true; + } + else if(0 == strcmp(long_option, "disable-verbatim-subframes")) { + option_values.debug.disable_verbatim_subframes = true; + } + else if(0 == strcmp(long_option, "no-md5-sum")) { + option_values.debug.do_md5 = false; + } + } + else { + switch(short_option) { + case 'h': + option_values.show_help = true; + break; + case 'H': + option_values.show_explain = true; + break; + case 'v': + option_values.show_version = true; + break; + case 'd': + option_values.mode_decode = true; + break; + case 'a': + option_values.mode_decode = true; + option_values.analyze = true; + break; + case 't': + option_values.mode_decode = true; + option_values.test_only = true; + break; + case 'c': + option_values.force_to_stdout = true; + break; + case 's': + flac__utils_verbosity_ = 1; + break; + case 'f': + option_values.force_file_overwrite = true; + break; + case 'o': + FLAC__ASSERT(0 != option_argument); + option_values.cmdline_forced_outfilename = option_argument; + break; + case 'F': + option_values.continue_through_decode_errors = true; + break; + case 'T': + FLAC__ASSERT(0 != option_argument); + if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/false, /*raw=*/!option_values.utf8_convert, &violation)) + return usage_error("ERROR: (-T/--tag) %s\n", violation); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + add_compression_setting_unsigned(CST_COMPRESSION_LEVEL, short_option-'0'); + break; + case '9': + return usage_error("ERROR: compression level '9' is reserved\n"); + case 'V': + option_values.verify = true; + break; + case 'w': + option_values.treat_warnings_as_errors = true; + break; + case 'S': + FLAC__ASSERT(0 != option_argument); + if(0 == strcmp(option_argument, "-")) { + option_values.num_requested_seek_points = 0; + option_values.requested_seek_points[0] = '\0'; + } + else { + if(option_values.num_requested_seek_points < 0) + option_values.num_requested_seek_points = 0; + option_values.num_requested_seek_points++; + if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) { + return usage_error("ERROR: too many seekpoints requested\n"); + } + else { + strcat(option_values.requested_seek_points, option_argument); + strcat(option_values.requested_seek_points, ";"); + } + } + break; + case 'P': + FLAC__ASSERT(0 != option_argument); + option_values.padding = atoi(option_argument); + if(option_values.padding < 0) + return usage_error("ERROR: argument to -%c must be >= 0; for no padding use -%c-\n", short_option, short_option); + break; + case 'b': + FLAC__ASSERT(0 != option_argument); + i = atoi(option_argument); + if((i < (int)FLAC__MIN_BLOCK_SIZE || i > (int)FLAC__MAX_BLOCK_SIZE)) + return usage_error("ERROR: invalid blocksize (-%c) '%d', must be >= %u and <= %u\n", short_option, i, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE); + add_compression_setting_unsigned(CST_BLOCKSIZE, (unsigned)i); + break; + case 'e': + add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, true); + break; + case 'E': + add_compression_setting_bool(CST_DO_ESCAPE_CODING, true); + break; + case 'l': + FLAC__ASSERT(0 != option_argument); + i = atoi(option_argument); + if((i < 0 || i > (int)FLAC__MAX_LPC_ORDER)) + return usage_error("ERROR: invalid LPC order (-%c) '%d', must be >= %u and <= %u\n", short_option, i, 0, FLAC__MAX_LPC_ORDER); + add_compression_setting_unsigned(CST_MAX_LPC_ORDER, (unsigned)i); + break; + case 'A': + FLAC__ASSERT(0 != option_argument); + add_compression_setting_string(CST_APODIZATION, option_argument); + break; + case 'm': + add_compression_setting_bool(CST_DO_MID_SIDE, true); + add_compression_setting_bool(CST_LOOSE_MID_SIDE, false); + break; + case 'M': + add_compression_setting_bool(CST_DO_MID_SIDE, true); + add_compression_setting_bool(CST_LOOSE_MID_SIDE, true); + break; + case 'p': + add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, true); + break; + case 'q': + FLAC__ASSERT(0 != option_argument); + i = atoi(option_argument); + if(i < 0 || (i > 0 && (i < (int)FLAC__MIN_QLP_COEFF_PRECISION || i > (int)FLAC__MAX_QLP_COEFF_PRECISION))) + return usage_error("ERROR: invalid value '%d' for qlp coeff precision (-%c), must be 0 or between %u and %u, inclusive\n", i, short_option, FLAC__MIN_QLP_COEFF_PRECISION, FLAC__MAX_QLP_COEFF_PRECISION); + add_compression_setting_unsigned(CST_QLP_COEFF_PRECISION, (unsigned)i); + break; + case 'r': + FLAC__ASSERT(0 != option_argument); + p = strchr(option_argument, ','); + if(0 == p) { + add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, 0); + i = atoi(option_argument); + if(i < 0) + return usage_error("ERROR: invalid value '%d' for residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER); + add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, (unsigned)i); + } + else { + i = atoi(option_argument); + if(i < 0) + return usage_error("ERROR: invalid value '%d' for min residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER); + add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, (unsigned)i); + i = atoi(++p); + if(i < 0) + return usage_error("ERROR: invalid value '%d' for max residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER); + add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, (unsigned)i); + } + break; + case 'R': + i = atoi(option_argument); + if(i < 0) + return usage_error("ERROR: invalid value '%d' for Rice parameter search distance (-%c), must be >= 0\n", i, short_option); + add_compression_setting_unsigned(CST_RICE_PARAMETER_SEARCH_DIST, (unsigned)i); + break; + default: + FLAC__ASSERT(0); + } + } + + return 0; +} + +void free_options(void) +{ + unsigned i; + if(0 != option_values.filenames) { + for(i = 0; i < option_values.num_files; i++) { + if(0 != option_values.filenames[i]) + free(option_values.filenames[i]); + } + free(option_values.filenames); + } + if(0 != option_values.vorbis_comment) + FLAC__metadata_object_delete(option_values.vorbis_comment); + for(i = 0; i < option_values.num_pictures; i++) + FLAC__metadata_object_delete(option_values.pictures[i]); +} + +void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value) +{ + if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0])) + die("too many compression settings"); + option_values.compression_settings[option_values.num_compression_settings].type = type; + option_values.compression_settings[option_values.num_compression_settings].value.t_bool = value; + option_values.num_compression_settings++; +} + +void add_compression_setting_string(compression_setting_type_t type, const char *value) +{ + if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0])) + die("too many compression settings"); + option_values.compression_settings[option_values.num_compression_settings].type = type; + option_values.compression_settings[option_values.num_compression_settings].value.t_string = value; + option_values.num_compression_settings++; +} + +void add_compression_setting_unsigned(compression_setting_type_t type, unsigned value) +{ + if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0])) + die("too many compression settings"); + option_values.compression_settings[option_values.num_compression_settings].type = type; + option_values.compression_settings[option_values.num_compression_settings].value.t_unsigned = value; + option_values.num_compression_settings++; +} + +int usage_error(const char *message, ...) +{ + if(flac__utils_verbosity_ >= 1) { + va_list args; + + FLAC__ASSERT(0 != message); + + va_start(args, message); + + (void) vfprintf(stderr, message, args); + + va_end(args); + + printf("Type \"flac\" for a usage summary or \"flac --help\" for all options\n"); + } + + return 1; +} + +void show_version(void) +{ + printf("flac %s\n", FLAC__VERSION_STRING); +} + +static void usage_header(void) +{ + printf("===============================================================================\n"); + printf("flac - Command-line FLAC encoder/decoder version %s\n", FLAC__VERSION_STRING); + printf("Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson\n"); + printf("\n"); + printf("This program is free software; you can redistribute it and/or\n"); + printf("modify it under the terms of the GNU General Public License\n"); + printf("as published by the Free Software Foundation; either version 2\n"); + printf("of the License, or (at your option) any later version.\n"); + printf("\n"); + printf("This program is distributed in the hope that it will be useful,\n"); + printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); + printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); + printf("GNU General Public License for more details.\n"); + printf("\n"); + printf("You should have received a copy of the GNU General Public License\n"); + printf("along with this program; if not, write to the Free Software\n"); + printf("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n"); + printf("===============================================================================\n"); +} + +static void usage_summary(void) +{ + printf("Usage:\n"); + printf("\n"); + printf(" Encoding: flac [] [] [INPUTFILE [...]]\n"); + printf(" Decoding: flac -d [] [] [FLACFILE [...]]\n"); + printf(" Testing: flac -t [] [FLACFILE [...]]\n"); + printf("Analyzing: flac -a [] [] [FLACFILE [...]]\n"); + printf("\n"); + printf("Be sure to read the list of known bugs at:\n"); + printf("http://flac.sourceforge.net/documentation_bugs.html\n"); + printf("\n"); +} + +void short_usage(void) +{ + usage_header(); + printf("\n"); + printf("This is the short help; for all options use 'flac --help'; for even more\n"); + printf("instructions use 'flac --explain'\n"); + printf("\n"); + printf("Be sure to read the list of known bugs at:\n"); + printf("http://flac.sourceforge.net/documentation_bugs.html\n"); + printf("\n"); + printf("To encode:\n"); + printf(" flac [-#] [INPUTFILE [...]]\n"); + printf("\n"); + printf(" -# is -0 (fastest compression) to -8 (highest compression); -5 is the default\n"); + printf("\n"); + printf("To decode:\n"); + printf(" flac -d [INPUTFILE [...]]\n"); + printf("\n"); + printf("To test:\n"); + printf(" flac -t [INPUTFILE [...]]\n"); +} + +void show_help(void) +{ + usage_header(); + usage_summary(); + printf("general options:\n"); + printf(" -v, --version Show the flac version number\n"); + printf(" -h, --help Show this screen\n"); + printf(" -H, --explain Show detailed explanation of usage and options\n"); + printf(" -d, --decode Decode (the default behavior is to encode)\n"); + printf(" -t, --test Same as -d except no decoded file is written\n"); + printf(" -a, --analyze Same as -d except an analysis file is written\n"); + printf(" -c, --stdout Write output to stdout\n"); + printf(" -s, --silent Do not write runtime encode/decode statistics\n"); + printf(" --totally-silent Do not print anything, including errors\n"); + printf(" --no-utf8-convert Do not convert tags from local charset to UTF-8\n"); + printf(" -w, --warnings-as-errors Treat all warnings as errors\n"); + printf(" -f, --force Force overwriting of output files\n"); + printf(" -o, --output-name=FILENAME Force the output file name\n"); + printf(" --output-prefix=STRING Prepend STRING to output names\n"); + printf(" --delete-input-file Deletes after a successful encode/decode\n"); + printf(" --preserve-modtime Output files keep timestamp of input (default)\n"); + printf(" --keep-foreign-metadata Save/restore WAVE or AIFF non-audio chunks\n"); + printf(" --skip={#|mm:ss.ss} Skip the given initial samples for each input\n"); + printf(" --until={#|[+|-]mm:ss.ss} Stop at the given sample for each input file\n"); +#if FLAC__HAS_OGG + printf(" --ogg Use Ogg as transport layer\n"); + printf(" --serial-number Serial number to use for the FLAC stream\n"); +#endif + printf("analysis options:\n"); + printf(" --residual-text Include residual signal in text output\n"); + printf(" --residual-gnuplot Generate gnuplot files of residual distribution\n"); + printf("decoding options:\n"); + printf(" -F, --decode-through-errors Continue decoding through stream errors\n"); + printf(" --cue=[#.#][-[#.#]] Set the beginning and ending cuepoints to decode\n"); + printf("encoding options:\n"); + printf(" -V, --verify Verify a correct encoding\n"); + printf(" --lax Allow encoder to generate non-Subset files\n"); +#if 0 /*@@@ currently undocumented */ + printf(" --ignore-chunk-sizes Ignore data chunk sizes in WAVE/AIFF files\n"); +#endif + printf(" --sector-align (DEPRECATED) Align multiple files on sector boundaries\n"); + printf(" --replay-gain Calculate ReplayGain & store in FLAC tags\n"); + printf(" --cuesheet=FILENAME Import cuesheet and store in CUESHEET block\n"); + printf(" --picture=SPECIFICATION Import picture and store in PICTURE block\n"); + printf(" -T, --tag=FIELD=VALUE Add a FLAC tag; may appear multiple times\n"); + printf(" --tag-from-file=FIELD=FILENAME Like --tag but gets value from file\n"); + printf(" -S, --seekpoint={#|X|#x|#s} Add seek point(s)\n"); + printf(" -P, --padding=# Write a PADDING block of length #\n"); + printf(" -0, --compression-level-0, --fast Synonymous with -l 0 -b 1152 -r 3\n"); + printf(" -1, --compression-level-1 Synonymous with -l 0 -b 1152 -M -r 3\n"); + printf(" -2, --compression-level-2 Synonymous with -l 0 -b 1152 -m -r 3\n"); + printf(" -3, --compression-level-3 Synonymous with -l 6 -b 4096 -r 4\n"); + printf(" -4, --compression-level-4 Synonymous with -l 8 -b 4096 -M -r 4\n"); + printf(" -5, --compression-level-5 Synonymous with -l 8 -b 4096 -m -r 5\n"); + printf(" -6, --compression-level-6 Synonymous with -l 8 -b 4096 -m -r 6\n"); + printf(" -7, --compression-level-7 Synonymous with -l 8 -b 4096 -m -e -r 6\n"); + printf(" -8, --compression-level-8, --best Synonymous with -l 12 -b 4096 -m -e -r 6\n"); + printf(" -b, --blocksize=# Specify blocksize in samples\n"); + printf(" -m, --mid-side Try mid-side coding for each frame\n"); + printf(" -M, --adaptive-mid-side Adaptive mid-side coding for all frames\n"); + printf(" -e, --exhaustive-model-search Do exhaustive model search (expensive!)\n"); + printf(" -A, --apodization=\"function\" Window audio data with given the function\n"); + printf(" -l, --max-lpc-order=# Max LPC order; 0 => only fixed predictors\n"); + printf(" -p, --qlp-coeff-precision-search Exhaustively search LP coeff quantization\n"); + printf(" -q, --qlp-coeff-precision=# Specify precision in bits\n"); + printf(" -r, --rice-partition-order=[#,]# Set [min,]max residual partition order\n"); + printf("format options:\n"); + printf(" --endian={big|little} Set byte order for samples\n"); + printf(" --channels=# Number of channels\n"); + printf(" --bps=# Number of bits per sample\n"); + printf(" --sample-rate=# Sample rate in Hz\n"); + printf(" --sign={signed|unsigned} Sign of samples\n"); + printf(" --input-size=# Size of the raw input in bytes\n"); + printf(" --force-raw-format Treat input or output as raw samples\n"); + printf(" --force-aiff-format Force decoding to AIFF format\n"); + printf(" --force-rf64-format Force decoding to RF64 format\n"); + printf(" --force-wave64-format Force decoding to Wave64 format\n"); + printf("negative options:\n"); + printf(" --no-adaptive-mid-side\n"); + printf(" --no-decode-through-errors\n"); + printf(" --no-delete-input-file\n"); + printf(" --no-preserve-modtime\n"); + printf(" --no-keep-foreign-metadata\n"); + printf(" --no-exhaustive-model-search\n"); + printf(" --no-lax\n"); + printf(" --no-mid-side\n"); +#if FLAC__HAS_OGG + printf(" --no-ogg\n"); +#endif + printf(" --no-padding\n"); + printf(" --no-qlp-coeff-prec-search\n"); + printf(" --no-replay-gain\n"); + printf(" --no-residual-gnuplot\n"); + printf(" --no-residual-text\n"); +#if 0 /*@@@ currently undocumented */ + printf(" --no-ignore-chunk-sizes\n"); +#endif + printf(" --no-sector-align\n"); + printf(" --no-seektable\n"); + printf(" --no-silent\n"); + printf(" --no-force\n"); + printf(" --no-verify\n"); + printf(" --no-warnings-as-errors\n"); +} + +void show_explain(void) +{ + usage_header(); + usage_summary(); + printf("For encoding:\n"); + printf(" The input file(s) may be a PCM WAVE or RF64 file, AIFF (or uncompressed\n"); + printf(" AIFF-C) file, or raw samples.\n"); + printf(" The output file(s) will be in native FLAC or Ogg FLAC format\n"); + printf("For decoding, the reverse is true.\n"); + printf("\n"); + printf("A single INPUTFILE may be - for stdin. No INPUTFILE implies stdin. Use of\n"); + printf("stdin implies -c (write to stdout). Normally you should use:\n"); + printf(" flac [options] -o outfilename or flac -d [options] -o outfilename\n"); + printf("instead of:\n"); + printf(" flac [options] > outfilename or flac -d [options] > outfilename\n"); + printf("since the former allows flac to seek backwards to write the STREAMINFO or\n"); + printf("WAVE/AIFF header contents when necessary.\n"); + printf("\n"); + printf("flac checks for the presence of a AIFF/WAVE header to decide whether or not to\n"); + printf("treat an input file as AIFF/WAVE format or raw samples. If any input file is\n"); + printf("raw you must specify the format options {-fb|fl} -fc -fp and -fs, which will\n"); + printf("apply to all raw files. You can force AIFF/WAVE files to be treated as raw\n"); + printf("files using -fr.\n"); + printf("\n"); + printf("general options:\n"); + printf(" -v, --version Show the flac version number\n"); + printf(" -h, --help Show basic usage a list of all options\n"); + printf(" -H, --explain Show this screen\n"); + printf(" -d, --decode Decode (the default behavior is to encode)\n"); + printf(" -t, --test Same as -d except no decoded file is written\n"); + printf(" -a, --analyze Same as -d except an analysis file is written\n"); + printf(" -c, --stdout Write output to stdout\n"); + printf(" -s, --silent Do not write runtime encode/decode statistics\n"); + printf(" --totally-silent Do not print anything of any kind, including\n"); + printf(" warnings or errors. The exit code will be the\n"); + printf(" only way to determine successful completion.\n"); + printf(" --no-utf8-convert Do not convert tags from local charset to UTF-8.\n"); + printf(" This is useful for scripts, and setting tags in\n"); + printf(" situations where the locale is wrong. This\n"); + printf(" option must appear before any tag options!\n"); + printf(" -w, --warnings-as-errors Treat all warnings as errors\n"); + printf(" -f, --force Force overwriting of output files\n"); + printf(" -o, --output-name=FILENAME Force the output file name; usually flac just\n"); + printf(" changes the extension. May only be used when\n"); + printf(" encoding a single file. May not be used in\n"); + printf(" conjunction with --output-prefix.\n"); + printf(" --output-prefix=STRING Prefix each output file name with the given\n"); + printf(" STRING. This can be useful for encoding or\n"); + printf(" decoding files to a different directory. Make\n"); + printf(" sure if your STRING is a path name that it ends\n"); + printf(" with a '/' slash.\n"); + printf(" --delete-input-file Automatically delete the input file after a\n"); + printf(" successful encode or decode. If there was an\n"); + printf(" error (including a verify error) the input file\n"); + printf(" is left intact.\n"); + printf(" --preserve-modtime Output files have their timestamps/permissions\n"); + printf(" set to match those of their inputs (this is\n"); + printf(" default). Use --no-preserve-modtime to make\n"); + printf(" output files have the current time and default\n"); + printf(" permissions.\n"); + printf(" --keep-foreign-metadata If encoding, save WAVE or AIFF non-audio chunks\n"); + printf(" in FLAC metadata. If decoding, restore any saved\n"); + printf(" non-audio chunks from FLAC metadata when writing\n"); + printf(" the decoded file. Foreign metadata cannot be\n"); + printf(" transcoded, e.g. WAVE chunks saved in a FLAC file\n"); + printf(" cannot be restored when decoding to AIFF. Input\n"); + printf(" and output must be regular files, not stdin/out.\n"); + printf(" --skip={#|mm:ss.ss} Skip the first # samples of each input file; can\n"); + printf(" be used both for encoding and decoding. The\n"); + printf(" alternative form mm:ss.ss can be used to specify\n"); + printf(" minutes, seconds, and fractions of a second.\n"); + printf(" --until={#|[+|-]mm:ss.ss} Stop at the given sample number for each input\n"); + printf(" file. The given sample number is not included\n"); + printf(" in the decoded output. The alternative form\n"); + printf(" mm:ss.ss can be used to specify minutes,\n"); + printf(" seconds, and fractions of a second. If a `+'\n"); + printf(" sign is at the beginning, the --until point is\n"); + printf(" relative to the --skip point. If a `-' sign is\n"); + printf(" at the beginning, the --until point is relative\n"); + printf(" to end of the audio.\n"); +#if FLAC__HAS_OGG + printf(" --ogg When encoding, generate Ogg FLAC output instead\n"); + printf(" of native FLAC. Ogg FLAC streams are FLAC\n"); + printf(" streams wrapped in an Ogg transport layer. The\n"); + printf(" resulting file should have an '.oga' extension\n"); + printf(" and will still be decodable by flac. When\n"); + printf(" decoding, force the input to be treated as\n"); + printf(" Ogg FLAC. This is useful when piping input\n"); + printf(" from stdin or when the filename does not end in\n"); + printf(" '.oga' or '.ogg'.\n"); + printf(" --serial-number Serial number to use for the FLAC stream. When\n"); + printf(" encoding and no serial number is given, flac\n"); + printf(" uses a random one. If encoding to multiple files\n"); + printf(" the serial number is incremented for each file.\n"); + printf(" When decoding and no number is given, flac uses\n"); + printf(" the serial number of the first page.\n"); +#endif + printf("analysis options:\n"); + printf(" --residual-text Include residual signal in text output. This\n"); + printf(" will make the file very big, much larger than\n"); + printf(" even the decoded file.\n"); + printf(" --residual-gnuplot Generate gnuplot files of residual distribution\n"); + printf(" of each subframe\n"); + printf("decoding options:\n"); + printf(" -F, --decode-through-errors By default flac stops decoding with an error\n"); + printf(" and removes the partially decoded file if it\n"); + printf(" encounters a bitstream error. With -F, errors\n"); + printf(" are still printed but flac will continue\n"); + printf(" decoding to completion. Note that errors may\n"); + printf(" cause the decoded audio to be missing some\n"); + printf(" samples or have silent sections.\n"); + printf(" --cue=[#.#][-[#.#]] Set the beginning and ending cuepoints to\n"); + printf(" decode. The optional first #.# is the track and\n"); + printf(" index point at which decoding will start; the\n"); + printf(" default is the beginning of the stream. The\n"); + printf(" optional second #.# is the track and index point\n"); + printf(" at which decoding will end; the default is the\n"); + printf(" end of the stream. If the cuepoint does not\n"); + printf(" exist, the closest one before it (for the start\n"); + printf(" point) or after it (for the end point) will be\n"); + printf(" used. The cuepoints are merely translated into\n"); + printf(" sample numbers then used as --skip and --until.\n"); + printf(" A CD track can always be cued by, for example,\n"); + printf(" --cue=9.1-10.1 for track 9, even if the CD has\n"); + printf(" no 10th track.\n"); + printf("encoding options:\n"); + printf(" -V, --verify Verify a correct encoding by decoding the\n"); + printf(" output in parallel and comparing to the\n"); + printf(" original\n"); + printf(" --lax Allow encoder to generate non-Subset files\n"); +#if 0 /*@@@ currently undocumented */ + printf(" --ignore-chunk-sizes Ignore data chunk sizes in WAVE/AIFF files;\n"); + printf(" useful when piping data from programs which\n"); + printf(" generate bogus data chunk sizes.\n"); +#endif + printf(" --sector-align Align encoding of multiple CD format WAVE files\n"); + printf(" on sector boundaries. This option is DEPRECATED\n"); + printf(" and may not exist in future versions of flac.\n"); + printf(" shntool offers similar functionality.\n"); + printf(" --replay-gain Calculate ReplayGain values and store them as\n"); + printf(" FLAC tags. Title gains/peaks will be computed\n"); + printf(" for each file, and an album gain/peak will be\n"); + printf(" computed for all files. All input files must\n"); + printf(" have the same resolution, sample rate, and\n"); + printf(" number of channels. The sample rate must be\n"); + printf(" one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1,\n"); + printf(" or 48 kHz. NOTE: this option may also leave a\n"); + printf(" few extra bytes in the PADDING block.\n"); + printf(" --cuesheet=FILENAME Import the given cuesheet file and store it in\n"); + printf(" a CUESHEET metadata block. This option may only\n"); + printf(" be used when encoding a single file. A\n"); + printf(" seekpoint will be added for each index point in\n"); + printf(" the cuesheet to the SEEKTABLE unless\n"); + printf(" --no-cued-seekpoints is specified.\n"); + printf(" --picture=SPECIFICATION Import a picture and store it in a PICTURE block.\n"); + printf(" More than one --picture command can be specified.\n"); + printf(" The SPECIFICATION can either be a simple filename\n"); + printf(" for the picture file, or a complete specification\n"); + printf(" whose parts are separated by | characters. Some\n"); + printf(" parts may be left empty to invoke default values.\n"); + printf(" Using a filename is shorthand for \"||||FILE\".\n"); + printf(" The SPECIFICATION format is:\n"); + printf(" [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE\n"); + printf(" TYPE is optional; it is a number from one of:\n"); + printf(" 0: Other\n"); + printf(" 1: 32x32 pixels 'file icon' (PNG only)\n"); + printf(" 2: Other file icon\n"); + printf(" 3: Cover (front)\n"); + printf(" 4: Cover (back)\n"); + printf(" 5: Leaflet page\n"); + printf(" 6: Media (e.g. label side of CD)\n"); + printf(" 7: Lead artist/lead performer/soloist\n"); + printf(" 8: Artist/performer\n"); + printf(" 9: Conductor\n"); + printf(" 10: Band/Orchestra\n"); + printf(" 11: Composer\n"); + printf(" 12: Lyricist/text writer\n"); + printf(" 13: Recording Location\n"); + printf(" 14: During recording\n"); + printf(" 15: During performance\n"); + printf(" 16: Movie/video screen capture\n"); + printf(" 17: A bright coloured fish\n"); + printf(" 18: Illustration\n"); + printf(" 19: Band/artist logotype\n"); + printf(" 20: Publisher/Studio logotype\n"); + printf(" The default is 3 (front cover). There may only be one picture each\n"); + printf(" of type 1 and 2 in a file.\n"); + printf(" MIME-TYPE is optional; if left blank, it will be detected from the\n"); + printf(" file. For best compatibility with players, use pictures with MIME\n"); + printf(" type image/jpeg or image/png. The MIME type can also be --> to\n"); + printf(" mean that FILE is actually a URL to an image, though this use is\n"); + printf(" discouraged.\n"); + printf(" DESCRIPTION is optional; the default is an empty string\n"); + printf(" The next part specfies the resolution and color information. If\n"); + printf(" the MIME-TYPE is image/jpeg, image/png, or image/gif, you can\n"); + printf(" usually leave this empty and they can be detected from the file.\n"); + printf(" Otherwise, you must specify the width in pixels, height in pixels,\n"); + printf(" and color depth in bits-per-pixel. If the image has indexed colors\n"); + printf(" you should also specify the number of colors used.\n"); + printf(" FILE is the path to the picture file to be imported, or the URL if\n"); + printf(" MIME type is -->\n"); + printf(" -T, --tag=FIELD=VALUE Add a FLAC tag. Make sure to quote the\n"); + printf(" comment if necessary. This option may appear\n"); + printf(" more than once to add several comments. NOTE:\n"); + printf(" all tags will be added to all encoded files.\n"); + printf(" --tag-from-file=FIELD=FILENAME Like --tag, except FILENAME is a file\n"); + printf(" whose contents will be read verbatim to set the\n"); + printf(" tag value. The contents will be converted to\n"); + printf(" UTF-8 from the local charset. This can be used\n"); + printf(" to store a cuesheet in a tag (e.g.\n"); + printf(" --tag-from-file=\"CUESHEET=image.cue\"). Do not\n"); + printf(" try to store binary data in tag fields! Use\n"); + printf(" APPLICATION blocks for that.\n"); + printf(" -S, --seekpoint={#|X|#x|#s} Include a point or points in a SEEKTABLE\n"); + printf(" # : a specific sample number for a seek point\n"); + printf(" X : a placeholder point (always goes at the end of the SEEKTABLE)\n"); + printf(" #x : # evenly spaced seekpoints, the first being at sample 0\n"); + printf(" #s : a seekpoint every # seconds; # does not have to be a whole number\n"); + printf(" You may use many -S options; the resulting SEEKTABLE will be the unique-\n"); + printf(" ified union of all such values.\n"); + printf(" With no -S options, flac defaults to '-S 10s'. Use -S- for no SEEKTABLE.\n"); + printf(" Note: -S #x and -S #s will not work if the encoder can't determine the\n"); + printf(" input size before starting.\n"); + printf(" Note: if you use -S # and # is >= samples in the input, there will be\n"); + printf(" either no seek point entered (if the input size is determinable\n"); + printf(" before encoding starts) or a placeholder point (if input size is not\n"); + printf(" determinable)\n"); + printf(" -P, --padding=# Tell the encoder to write a PADDING metadata\n"); + printf(" block of the given length (in bytes) after the\n"); + printf(" STREAMINFO block. This is useful if you plan\n"); + printf(" to tag the file later with an APPLICATION\n"); + printf(" block; instead of having to rewrite the entire\n"); + printf(" file later just to insert your block, you can\n"); + printf(" write directly over the PADDING block. Note\n"); + printf(" that the total length of the PADDING block will\n"); + printf(" be 4 bytes longer than the length given because\n"); + printf(" of the 4 metadata block header bytes. You can\n"); + printf(" force no PADDING block at all to be written with\n"); + printf(" --no-padding. The encoder writes a PADDING\n"); + printf(" block of 8192 bytes by default, or 65536 bytes\n"); + printf(" if the input audio is more than 20 minutes long.\n"); + printf(" -b, --blocksize=# Specify the blocksize in samples; the default is\n"); + printf(" 1152 for -l 0, else 4096; must be one of 192,\n"); + printf(" 576, 1152, 2304, 4608, 256, 512, 1024, 2048,\n"); + printf(" 4096 (and 8192 or 16384 if the sample rate is\n"); + printf(" >48kHz) for Subset streams.\n"); + printf(" -0, --compression-level-0, --fast Synonymous with -l 0 -b 1152 -r 3\n"); + printf(" -1, --compression-level-1 Synonymous with -l 0 -b 1152 -M -r 3\n"); + printf(" -2, --compression-level-2 Synonymous with -l 0 -b 1152 -m -r 3\n"); + printf(" -3, --compression-level-3 Synonymous with -l 6 -b 4096 -r 4\n"); + printf(" -4, --compression-level-4 Synonymous with -l 8 -b 4096 -M -r 4\n"); + printf(" -5, --compression-level-5 Synonymous with -l 8 -b 4096 -m -r 5\n"); + printf(" -5 is the default setting\n"); + printf(" -6, --compression-level-6 Synonymous with -l 8 -b 4096 -m -r 6\n"); + printf(" -7, --compression-level-7 Synonymous with -l 8 -b 4096 -m -e -r 6\n"); + printf(" -8, --compression-level-8, --best Synonymous with -l 12 -b 4096 -m -e -r 6\n"); + printf(" -m, --mid-side Try mid-side coding for each frame\n"); + printf(" (stereo only)\n"); + printf(" -M, --adaptive-mid-side Adaptive mid-side coding for all frames\n"); + printf(" (stereo only)\n"); + printf(" -e, --exhaustive-model-search Do exhaustive model search (expensive!)\n"); + printf(" -A, --apodization=\"function\" Window audio data with given the function.\n"); + printf(" The functions are: bartlett, bartlett_hann,\n"); + printf(" blackman, blackman_harris_4term_92db,\n"); + printf(" connes, flattop, gauss(STDDEV), hamming,\n"); + printf(" hann, kaiser_bessel, nuttall, rectangle,\n"); + printf(" triangle, tukey(P), welch. More than one\n"); + printf(" may be specified but encoding time is a\n"); + printf(" multiple of the number of functions since\n"); + printf(" they are each tried in turn. The encoder\n"); + printf(" chooses suitable defaults in the absence\n"); + printf(" of any -A options.\n"); + printf(" -l, --max-lpc-order=# Max LPC order; 0 => only fixed predictors.\n"); + printf(" Must be <= 12 for Subset streams if sample\n"); + printf(" rate is <=48kHz.\n"); + printf(" -p, --qlp-coeff-precision-search Do exhaustive search of LP coefficient\n"); + printf(" quantization (expensive!); overrides -q;\n"); + printf(" does nothing if using -l 0\n"); + printf(" -q, --qlp-coeff-precision=# Specify precision in bits of quantized\n"); + printf(" linear-predictor coefficients; 0 => let\n"); + printf(" encoder decide (the minimun is %u, the\n", FLAC__MIN_QLP_COEFF_PRECISION); + printf(" default is -q 0)\n"); + printf(" -r, --rice-partition-order=[#,]# Set [min,]max residual partition order\n"); + printf(" (# is 0..16; min defaults to 0; the\n"); + printf(" default is -r 0; above 4 doesn't usually\n"); + printf(" help much)\n"); + printf("format options:\n"); + printf(" --endian={big|little} Set byte order for samples\n"); + printf(" --channels=# Number of channels\n"); + printf(" --bps=# Number of bits per sample\n"); + printf(" --sample-rate=# Sample rate in Hz\n"); + printf(" --sign={signed|unsigned} Sign of samples (the default is signed)\n"); + printf(" --input-size=# Size of the raw input in bytes. If you are\n"); + printf(" encoding raw samples from stdin, you must set\n"); + printf(" this option in order to be able to use --skip,\n"); + printf(" --until, --cue-sheet, or other options that need\n"); + printf(" to know the size of the input beforehand. If\n"); + printf(" the size given is greater than what is found in\n"); + printf(" the input stream, the encoder will complain\n"); + printf(" about an unexpected end-of-file. If the size\n"); + printf(" given is less, samples will be truncated.\n"); + printf(" --force-raw-format Force input (when encoding) or output (when\n"); + printf(" decoding) to be treated as raw samples\n"); + printf(" --force-aiff-format Force the decoder to output AIFF format. This\n"); + printf(" option is not needed if the output filename (as\n"); + printf(" set by -o) ends with .aif or .aiff; this option\n"); + printf(" has no effect when encoding since input AIFF is\n"); + printf(" auto-detected.\n"); + printf(" --force-rf64-format Force the decoder to output RF64 format. This\n"); + printf(" option is not needed if the output filename (as\n"); + printf(" set by -o) ends with .rf64; this option\n"); + printf(" has no effect when encoding since input RF64 is\n"); + printf(" auto-detected.\n"); + printf(" --force-wave64-format Force the decoder to output Wave64 format. This\n"); + printf(" option is not needed if the output filename (as\n"); + printf(" set by -o) ends with .w64; this option\n"); + printf(" has no effect when encoding since input Wave64 is\n"); + printf(" auto-detected.\n"); + printf("negative options:\n"); + printf(" --no-adaptive-mid-side\n"); + printf(" --no-decode-through-errors\n"); + printf(" --no-delete-input-file\n"); + printf(" --no-preserve-modtime\n"); + printf(" --no-keep-foreign-metadata\n"); + printf(" --no-exhaustive-model-search\n"); + printf(" --no-lax\n"); + printf(" --no-mid-side\n"); +#if FLAC__HAS_OGG + printf(" --no-ogg\n"); +#endif + printf(" --no-padding\n"); + printf(" --no-qlp-coeff-prec-search\n"); + printf(" --no-residual-gnuplot\n"); + printf(" --no-residual-text\n"); +#if 0 /*@@@ currently undocumented */ + printf(" --no-ignore-chunk-sizes\n"); +#endif + printf(" --no-sector-align\n"); + printf(" --no-seektable\n"); + printf(" --no-silent\n"); + printf(" --no-force\n"); + printf(" --no-verify\n"); + printf(" --no-warnings-as-errors\n"); +} + +void format_mistake(const char *infilename, FileFormat wrong, FileFormat right) +{ + /* WATCHOUT: indexed by FileFormat */ + static const char * const ff[] = { " raw", " WAVE", "n RF64", "n AIFF", "n AIFF-C", " FLAC", "n Ogg FLAC" }; + flac__utils_printf(stderr, 1, "WARNING: %s is not a%s file; treating as a%s file\n", infilename, ff[wrong], ff[right]); +} + +int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file) +{ + FILE *encode_infile; + FLAC__byte lookahead[12]; + unsigned lookahead_length = 0; + FileFormat input_format = FORMAT_RAW; + int retval; + off_t infilesize; + encode_options_t encode_options; + const char *outfilename = get_encoded_outfilename(infilename); /* the final name of the encoded file */ + /* internal_outfilename is the file we will actually write to; it will be a temporary name if infilename==outfilename */ + char *internal_outfilename = 0; /* NULL implies 'use outfilename' */ + + if(0 == outfilename) { + flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename); + return 1; + } + + if(0 == strcmp(infilename, "-")) { + infilesize = (off_t)(-1); + encode_infile = grabbag__file_get_binary_stdin(); + } + else { + infilesize = grabbag__file_get_filesize(infilename); + if(0 == (encode_infile = fopen(infilename, "rb"))) { + flac__utils_printf(stderr, 1, "ERROR: can't open input file %s: %s\n", infilename, strerror(errno)); + return 1; + } + } + + if(!option_values.force_raw_format) { + /* first set format based on name */ + if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".wav")) + input_format = FORMAT_WAVE; + else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".rf64")) + input_format = FORMAT_RF64; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".w64")) + input_format = FORMAT_WAVE64; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".aif")) + input_format = FORMAT_AIFF; + else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".aiff")) + input_format = FORMAT_AIFF; + else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".flac")) + input_format = FORMAT_FLAC; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".oga")) + input_format = FORMAT_OGGFLAC; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg")) + input_format = FORMAT_OGGFLAC; + + /* attempt to guess the file type based on the first 12 bytes */ + if((lookahead_length = fread(lookahead, 1, 12, encode_infile)) < 12) { + /* all supported non-raw formats have at least 12 bytes of header to read */ + if(input_format != FORMAT_RAW) { + format_mistake(infilename, input_format, FORMAT_RAW); + if(option_values.treat_warnings_as_errors) { + conditional_fclose(encode_infile); + return 1; + } + } + /* force to raw */ + input_format = FORMAT_RAW; + } + else { + if(!memcmp(lookahead, "ID3", 3)) { + flac__utils_printf(stderr, 1, "ERROR: input file %s has an ID3v2 tag\n", infilename); + return 1; + } + else if(!memcmp(lookahead, "RIFF", 4) && !memcmp(lookahead+8, "WAVE", 4)) + input_format = FORMAT_WAVE; + else if(!memcmp(lookahead, "RF64", 4) && !memcmp(lookahead+8, "WAVE", 4)) + input_format = FORMAT_RF64; + else if(!memcmp(lookahead, "riff\x2E\x91\xCF\x11\xD6\xA5\x28\xDB", 12)) /* just check 1st 12 bytes of GUID */ + input_format = FORMAT_WAVE64; + else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFF", 4)) + input_format = FORMAT_AIFF; + else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFC", 4)) + input_format = FORMAT_AIFF_C; + else if(!memcmp(lookahead, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING))) + input_format = FORMAT_FLAC; + /*@@@ this could be made more accurate by looking at the first packet to make sure it's Ogg FLAC and not, say, Ogg Vorbis. we do catch such problems later though. */ + else if(!memcmp(lookahead, "OggS", 4)) + input_format = FORMAT_OGGFLAC; + else { + /* didn't find header of any supported format */ + if(input_format != FORMAT_RAW) { + format_mistake(infilename, input_format, FORMAT_RAW); + if(option_values.treat_warnings_as_errors) { + conditional_fclose(encode_infile); + return 1; + } + } + /* force to raw */ + input_format = FORMAT_RAW; + } + } + } + + if(option_values.keep_foreign_metadata) { + if(encode_infile == stdin || option_values.force_to_stdout) { + conditional_fclose(encode_infile); + return usage_error("ERROR: --keep-foreign-metadata cannot be used when encoding from stdin or to stdout\n"); + } + if(input_format != FORMAT_WAVE && input_format != FORMAT_WAVE64 && input_format != FORMAT_RF64 && input_format != FORMAT_AIFF && input_format != FORMAT_AIFF_C) { + conditional_fclose(encode_infile); + return usage_error("ERROR: --keep-foreign-metadata can only be used with WAVE, Wave64, RF64, or AIFF input\n"); + } + } + + /* + * Error if output file already exists (and -f not used). + * Use grabbag__file_get_filesize() as a cheap way to check. + */ + if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) { + if(input_format == FORMAT_FLAC) { + /* need more detailed error message when re-flac'ing to avoid confusing the user */ + flac__utils_printf(stderr, 1, + "ERROR: output file %s already exists.\n\n" + "By default flac encodes files to FLAC format; if you meant to decode this file\n" + "from FLAC to something else, use -d. If you meant to re-encode this file from\n" + "FLAC to FLAC again, use -f to force writing to the same file, or -o to specify\n" + "a different output filename.\n", + outfilename + ); + } + else if(input_format == FORMAT_OGGFLAC) { + /* need more detailed error message when re-flac'ing to avoid confusing the user */ + flac__utils_printf(stderr, 1, + "ERROR: output file %s already exists.\n\n" + "By default 'flac -ogg' encodes files to Ogg FLAC format; if you meant to decode\n" + "this file from Ogg FLAC to something else, use -d. If you meant to re-encode\n" + "this file from Ogg FLAC to Ogg FLAC again, use -f to force writing to the same\n" + "file, or -o to specify a different output filename.\n", + outfilename + ); + } + else + flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename); + conditional_fclose(encode_infile); + return 1; + } + + if(option_values.format_input_size >= 0) { + if (input_format != FORMAT_RAW || infilesize >= 0) { + flac__utils_printf(stderr, 1, "ERROR: can only use --input-size when encoding raw samples from stdin\n"); + conditional_fclose(encode_infile); + return 1; + } + else { + infilesize = option_values.format_input_size; + } + } + + if(option_values.sector_align && (input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC)) { + flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input file is FLAC or Ogg FLAC\n"); + conditional_fclose(encode_infile); + return 1; + } + if(option_values.sector_align && input_format == FORMAT_RAW && infilesize < 0) { + flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input size is unknown\n"); + conditional_fclose(encode_infile); + return 1; + } + + if(input_format == FORMAT_RAW) { + if(option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0 || option_values.format_channels < 0 || option_values.format_bps < 0 || option_values.format_sample_rate < 0) { + conditional_fclose(encode_infile); + return usage_error("ERROR: for encoding a raw file you must specify a value for --endian, --sign, --channels, --bps, and --sample-rate\n"); + } + } + + if(/*@@@@@@why no stdin?*/encode_infile == stdin || option_values.force_to_stdout) { + if(option_values.replay_gain) { + conditional_fclose(encode_infile); + return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n"); + } + } + if(option_values.replay_gain && option_values.use_ogg) { + conditional_fclose(encode_infile); + return usage_error("ERROR: --replay-gain cannot be used when encoding to Ogg FLAC yet\n"); + } + + if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &encode_options.skip_specification) || encode_options.skip_specification.is_relative) { + conditional_fclose(encode_infile); + return usage_error("ERROR: invalid value for --skip\n"); + } + + if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &encode_options.until_specification)) { /*@@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */ + conditional_fclose(encode_infile); + return usage_error("ERROR: invalid value for --until\n"); + } + /* if there is no "--until" we want to default to "--until=-0" */ + if(0 == option_values.until_specification) + encode_options.until_specification.is_relative = true; + + encode_options.verify = option_values.verify; + encode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors; +#if FLAC__HAS_OGG + encode_options.use_ogg = option_values.use_ogg; + /* set a random serial number if one has not yet been specified */ + if(!option_values.has_serial_number) { + option_values.serial_number = rand(); + option_values.has_serial_number = true; + } + encode_options.serial_number = option_values.serial_number++; +#endif + encode_options.lax = option_values.lax; + encode_options.padding = option_values.padding; + encode_options.num_compression_settings = option_values.num_compression_settings; + FLAC__ASSERT(sizeof(encode_options.compression_settings) >= sizeof(option_values.compression_settings)); + memcpy(encode_options.compression_settings, option_values.compression_settings, sizeof(option_values.compression_settings)); + encode_options.requested_seek_points = option_values.requested_seek_points; + encode_options.num_requested_seek_points = option_values.num_requested_seek_points; + encode_options.cuesheet_filename = option_values.cuesheet_filename; + encode_options.continue_through_decode_errors = option_values.continue_through_decode_errors; + encode_options.cued_seekpoints = option_values.cued_seekpoints; + encode_options.channel_map_none = option_values.channel_map_none; + encode_options.is_first_file = is_first_file; + encode_options.is_last_file = is_last_file; + encode_options.align_reservoir = align_reservoir; + encode_options.align_reservoir_samples = &align_reservoir_samples; + encode_options.replay_gain = option_values.replay_gain; + encode_options.ignore_chunk_sizes = option_values.ignore_chunk_sizes; + encode_options.sector_align = option_values.sector_align; + encode_options.vorbis_comment = option_values.vorbis_comment; + FLAC__ASSERT(sizeof(encode_options.pictures) >= sizeof(option_values.pictures)); + memcpy(encode_options.pictures, option_values.pictures, sizeof(option_values.pictures)); + encode_options.num_pictures = option_values.num_pictures; + encode_options.format = input_format; + encode_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes; + encode_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes; + encode_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes; + encode_options.debug.do_md5 = option_values.debug.do_md5; + + /* if infilename and outfilename point to the same file, we need to write to a temporary file */ + if(encode_infile != stdin && grabbag__file_are_same(infilename, outfilename)) { + static const char *tmp_suffix = ".tmp,fl-ac+en'c"; + /*@@@@ still a remote possibility that a file with this filename exists */ + if(0 == (internal_outfilename = (char *)safe_malloc_add_3op_(strlen(outfilename), /*+*/strlen(tmp_suffix), /*+*/1))) { + flac__utils_printf(stderr, 1, "ERROR allocating memory for tempfile name\n"); + conditional_fclose(encode_infile); + return 1; + } + strcpy(internal_outfilename, outfilename); + strcat(internal_outfilename, tmp_suffix); + } + + if(input_format == FORMAT_RAW) { + encode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian; + encode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples; + encode_options.format_options.raw.channels = option_values.format_channels; + encode_options.format_options.raw.bps = option_values.format_bps; + encode_options.format_options.raw.sample_rate = option_values.format_sample_rate; + + retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options); + } + else if(input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC) { + retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options); + } + else if(input_format == FORMAT_WAVE || input_format == FORMAT_WAVE64 || input_format == FORMAT_RF64 || input_format == FORMAT_AIFF || input_format == FORMAT_AIFF_C) { + encode_options.format_options.iff.foreign_metadata = 0; + + /* initialize foreign metadata if requested */ + if(option_values.keep_foreign_metadata) { + encode_options.format_options.iff.foreign_metadata = + flac__foreign_metadata_new( + input_format==FORMAT_WAVE || input_format==FORMAT_RF64? + FOREIGN_BLOCK_TYPE__RIFF : + input_format==FORMAT_WAVE64? + FOREIGN_BLOCK_TYPE__WAVE64 : + FOREIGN_BLOCK_TYPE__AIFF + ); + if(0 == encode_options.format_options.iff.foreign_metadata) { + flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n"); + conditional_fclose(encode_infile); + return 1; + } + } + + retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options); + + if(encode_options.format_options.iff.foreign_metadata) + flac__foreign_metadata_delete(encode_options.format_options.iff.foreign_metadata); + } + else { + FLAC__ASSERT(0); + retval = 1; /* double protection */ + } + + if(retval == 0) { + if(strcmp(outfilename, "-")) { + if(option_values.replay_gain) { + float title_gain, title_peak; + const char *error; + grabbag__replaygain_get_title(&title_gain, &title_peak); + if( + 0 != (error = grabbag__replaygain_store_to_file_reference(internal_outfilename? internal_outfilename : outfilename, option_values.preserve_modtime)) || + 0 != (error = grabbag__replaygain_store_to_file_title(internal_outfilename? internal_outfilename : outfilename, title_gain, title_peak, option_values.preserve_modtime)) + ) { + flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain reference/title tags (%s)\n", outfilename, error); + retval = 1; + } + } + if(option_values.preserve_modtime && strcmp(infilename, "-")) + grabbag__file_copy_metadata(infilename, internal_outfilename? internal_outfilename : outfilename); + } + } + + /* rename temporary file if necessary */ + if(retval == 0 && internal_outfilename != 0) { + if(rename(internal_outfilename, outfilename) < 0) { +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ + /* on some flavors of windows, rename() will fail if the destination already exists, so we unlink and try again */ + if(unlink(outfilename) < 0) { + flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, keeping both\n", internal_outfilename, outfilename); + retval = 1; + } + else if(rename(internal_outfilename, outfilename) < 0) { + flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, you must do it\n", internal_outfilename, outfilename); + retval = 1; + } +#else + flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, keeping both\n", internal_outfilename, outfilename); + retval = 1; +#endif + } + } + + /* handle --delete-input-file, but don't want to delete if piping from stdin, or if input filename and output filename are the same */ + if(retval == 0 && option_values.delete_input && strcmp(infilename, "-") && internal_outfilename == 0) + unlink(infilename); + + if(internal_outfilename != 0) + free(internal_outfilename); + + return retval; +} + +int decode_file(const char *infilename) +{ + int retval; + FLAC__bool treat_as_ogg = false; + FileFormat output_format = FORMAT_WAVE; + decode_options_t decode_options; + const char *outfilename = get_decoded_outfilename(infilename); + + if(0 == outfilename) { + flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename); + return 1; + } + + /* + * Error if output file already exists (and -f not used). + * Use grabbag__file_get_filesize() as a cheap way to check. + */ + if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) { + flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename); + return 1; + } + + if(option_values.force_raw_format) + output_format = FORMAT_RAW; + else if( + option_values.force_aiff_format || + (strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".aif")) || + (strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".aiff")) + ) + output_format = FORMAT_AIFF; + else if( + option_values.force_rf64_format || + (strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".rf64")) + ) + output_format = FORMAT_RF64; + else if( + option_values.force_wave64_format || + (strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".w64")) + ) + output_format = FORMAT_WAVE64; + else + output_format = FORMAT_WAVE; + + if(!option_values.test_only && !option_values.analyze) { + if(output_format == FORMAT_RAW && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0)) + return usage_error("ERROR: for decoding to a raw file you must specify a value for --endian and --sign\n"); + } + + if(option_values.keep_foreign_metadata) { + if(0 == strcmp(infilename, "-") || 0 == strcmp(outfilename, "-")) + return usage_error("ERROR: --keep-foreign-metadata cannot be used when decoding from stdin or to stdout\n"); + if(output_format != FORMAT_WAVE && output_format != FORMAT_WAVE64 && output_format != FORMAT_RF64 && output_format != FORMAT_AIFF && output_format != FORMAT_AIFF_C) + return usage_error("ERROR: --keep-foreign-metadata can only be used with WAVE, Wave64, RF64, or AIFF output\n"); + } + + if(option_values.use_ogg) + treat_as_ogg = true; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".oga")) + treat_as_ogg = true; + else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg")) + treat_as_ogg = true; + else + treat_as_ogg = false; + +#if !FLAC__HAS_OGG + if(treat_as_ogg) { + flac__utils_printf(stderr, 1, "%s: Ogg support has not been built into this copy of flac\n", infilename); + return 1; + } +#endif + + if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &decode_options.skip_specification) || decode_options.skip_specification.is_relative) + return usage_error("ERROR: invalid value for --skip\n"); + + if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &decode_options.until_specification)) /*@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */ + return usage_error("ERROR: invalid value for --until\n"); + /* if there is no "--until" we want to default to "--until=-0" */ + if(0 == option_values.until_specification) + decode_options.until_specification.is_relative = true; + + if(option_values.cue_specification) { + if(!flac__utils_parse_cue_specification(option_values.cue_specification, &decode_options.cue_specification)) + return usage_error("ERROR: invalid value for --cue\n"); + decode_options.has_cue_specification = true; + } + else + decode_options.has_cue_specification = false; + + decode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors; + decode_options.continue_through_decode_errors = option_values.continue_through_decode_errors; + decode_options.replaygain_synthesis_spec = option_values.replaygain_synthesis_spec; +#if FLAC__HAS_OGG + decode_options.is_ogg = treat_as_ogg; + decode_options.use_first_serial_number = !option_values.has_serial_number; + decode_options.serial_number = option_values.serial_number; +#endif + decode_options.channel_map_none = option_values.channel_map_none; + decode_options.format = output_format; + + if(output_format == FORMAT_RAW) { + decode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian; + decode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples; + + retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options); + } + else { + decode_options.format_options.iff.foreign_metadata = 0; + + /* initialize foreign metadata if requested */ + if(option_values.keep_foreign_metadata) { + decode_options.format_options.iff.foreign_metadata = + flac__foreign_metadata_new( + output_format==FORMAT_WAVE || output_format==FORMAT_RF64? + FOREIGN_BLOCK_TYPE__RIFF : + output_format==FORMAT_WAVE64? + FOREIGN_BLOCK_TYPE__WAVE64 : + FOREIGN_BLOCK_TYPE__AIFF + ); + if(0 == decode_options.format_options.iff.foreign_metadata) { + flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n"); + return 1; + } + } + + retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options); + + if(decode_options.format_options.iff.foreign_metadata) + flac__foreign_metadata_delete(decode_options.format_options.iff.foreign_metadata); + } + + if(retval == 0 && strcmp(infilename, "-")) { + if(option_values.preserve_modtime && strcmp(outfilename, "-")) + grabbag__file_copy_metadata(infilename, outfilename); + if(option_values.delete_input && !option_values.test_only && !option_values.analyze) + unlink(infilename); + } + + return retval; +} + +const char *get_encoded_outfilename(const char *infilename) +{ + const char *suffix = (option_values.use_ogg? ".oga" : ".flac"); + return get_outfilename(infilename, suffix); +} + +const char *get_decoded_outfilename(const char *infilename) +{ + const char *suffix; + if(option_values.analyze) { + suffix = ".ana"; + } + else if(option_values.force_raw_format) { + suffix = ".raw"; + } + else if(option_values.force_aiff_format) { + suffix = ".aiff"; + } + else if(option_values.force_rf64_format) { + suffix = ".rf64"; + } + else if(option_values.force_wave64_format) { + suffix = ".w64"; + } + else { + suffix = ".wav"; + } + return get_outfilename(infilename, suffix); +} + +const char *get_outfilename(const char *infilename, const char *suffix) +{ + if(0 == option_values.cmdline_forced_outfilename) { + static char buffer[4096]; /* @@@ bad MAGIC NUMBER */ + + if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) { + strcpy(buffer, "-"); + } + else { + char *p; + if (flac__strlcpy(buffer, option_values.output_prefix? option_values.output_prefix : "", sizeof buffer) >= sizeof buffer) + return 0; + if (flac__strlcat(buffer, infilename, sizeof buffer) >= sizeof buffer) + return 0; + /* the . must come after any / to avoid problems with, e.g. "some.directory/extensionless-filename" */ + if(0 == (p = strrchr(buffer, '.')) || strchr(p, '/')) { + if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer) + return 0; + } + else { + *p = '\0'; + if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer) + return 0; + } + } + return buffer; + } + else + return option_values.cmdline_forced_outfilename; +} + +void die(const char *message) +{ + FLAC__ASSERT(0 != message); + flac__utils_printf(stderr, 1, "ERROR: %s\n", message); + exit(1); +} + +int conditional_fclose(FILE *f) +{ + if(f == 0 || f == stdin || f == stdout) + return 0; + else + return fclose(f); +} + +char *local_strdup(const char *source) +{ + char *ret; + FLAC__ASSERT(0 != source); + if(0 == (ret = strdup(source))) + die("out of memory during strdup()"); + return ret; +} + +#ifdef _MSC_VER +/* There's no strtoll() in MSVC6 so we just write a specialized one */ +FLAC__int64 local__strtoll(const char *src, char **endptr) +{ + FLAC__bool neg = false; + FLAC__int64 ret = 0; + int c; + FLAC__ASSERT(0 != src); + if(*src == '-') { + neg = true; + src++; + } + while(0 != (c = *src)) { + c -= '0'; + if(c >= 0 && c <= 9) + ret = (ret * 10) + c; + else + break; + src++; + } + if(endptr) + *endptr = (char*)src; + return neg? -ret : ret; +} +#endif diff --git a/flac/src/flac/utils.c b/flac/src/flac/utils.c new file mode 100644 index 0000000..1eca946 --- /dev/null +++ b/flac/src/flac/utils.c @@ -0,0 +1,316 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "utils.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include +#include +#include +#include +#include + +const char *CHANNEL_MASK_TAG = "WAVEFORMATEXTENSIBLE_CHANNEL_MASK"; + +int flac__utils_verbosity_ = 2; + +static FLAC__bool local__parse_uint64_(const char *s, FLAC__uint64 *value) +{ + FLAC__uint64 ret = 0; + char c; + + if(*s == '\0') + return false; + + while('\0' != (c = *s++)) + if(c >= '0' && c <= '9') + ret = ret * 10 + (c - '0'); + else + return false; + + *value = ret; + return true; +} + +static FLAC__bool local__parse_timecode_(const char *s, double *value) +{ + double ret; + unsigned i; + char c; + + /* parse [0-9][0-9]*: */ + c = *s++; + if(c >= '0' && c <= '9') + i = (c - '0'); + else + return false; + while(':' != (c = *s++)) { + if(c >= '0' && c <= '9') + i = i * 10 + (c - '0'); + else + return false; + } + ret = (double)i * 60.; + + /* parse [0-9]*[.,]?[0-9]* i.e. a sign-less rational number (. or , OK for fractional seconds, to support different locales) */ + if(strspn(s, "1234567890.,") != strlen(s)) + return false; + { + const char *p = strpbrk(s, ".,"); + if(p && 0 != strpbrk(++p, ".,")) + return false; + } + ret += atof(s); + + *value = ret; + return true; +} + +static FLAC__bool local__parse_cue_(const char *s, const char *end, unsigned *track, unsigned *index) +{ + FLAC__bool got_track = false, got_index = false; + unsigned t = 0, i = 0; + char c; + + while(end? s < end : *s != '\0') { + c = *s++; + if(c >= '0' && c <= '9') { + t = t * 10 + (c - '0'); + got_track = true; + } + else if(c == '.') + break; + else + return false; + } + while(end? s < end : *s != '\0') { + c = *s++; + if(c >= '0' && c <= '9') { + i = i * 10 + (c - '0'); + got_index = true; + } + else + return false; + } + *track = t; + *index = i; + return got_track && got_index; +} + +/* + * this only works with sorted cuesheets (the spec strongly recommends but + * does not require sorted cuesheets). but if it's not sorted, picking a + * nearest cue point has no significance. + */ +static FLAC__uint64 local__find_closest_cue_(const FLAC__StreamMetadata_CueSheet *cuesheet, unsigned track, unsigned index, FLAC__uint64 total_samples, FLAC__bool look_forward) +{ + int t, i; + if(look_forward) { + for(t = 0; t < (int)cuesheet->num_tracks; t++) + for(i = 0; i < (int)cuesheet->tracks[t].num_indices; i++) + if(cuesheet->tracks[t].number > track || (cuesheet->tracks[t].number == track && cuesheet->tracks[t].indices[i].number >= index)) + return cuesheet->tracks[t].offset + cuesheet->tracks[t].indices[i].offset; + return total_samples; + } + else { + for(t = (int)cuesheet->num_tracks - 1; t >= 0; t--) + for(i = (int)cuesheet->tracks[t].num_indices - 1; i >= 0; i--) + if(cuesheet->tracks[t].number < track || (cuesheet->tracks[t].number == track && cuesheet->tracks[t].indices[i].number <= index)) + return cuesheet->tracks[t].offset + cuesheet->tracks[t].indices[i].offset; + return 0; + } +} + +void flac__utils_printf(FILE *stream, int level, const char *format, ...) +{ + if(flac__utils_verbosity_ >= level) { + va_list args; + + FLAC__ASSERT(0 != format); + + va_start(args, format); + + (void) vfprintf(stream, format, args); + + va_end(args); + } +} + +#ifdef FLAC__VALGRIND_TESTING +size_t flac__utils_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#endif + +FLAC__bool flac__utils_parse_skip_until_specification(const char *s, utils__SkipUntilSpecification *spec) +{ + FLAC__uint64 val; + FLAC__bool is_negative = false; + + FLAC__ASSERT(0 != spec); + + spec->is_relative = false; + spec->value_is_samples = true; + spec->value.samples = 0; + + if(0 != s) { + if(s[0] == '-') { + is_negative = true; + spec->is_relative = true; + s++; + } + else if(s[0] == '+') { + spec->is_relative = true; + s++; + } + + if(local__parse_uint64_(s, &val)) { + spec->value_is_samples = true; + spec->value.samples = (FLAC__int64)val; + if(is_negative) + spec->value.samples = -(spec->value.samples); + } + else { + double d; + if(!local__parse_timecode_(s, &d)) + return false; + spec->value_is_samples = false; + spec->value.seconds = d; + if(is_negative) + spec->value.seconds = -(spec->value.seconds); + } + } + + return true; +} + +void flac__utils_canonicalize_skip_until_specification(utils__SkipUntilSpecification *spec, unsigned sample_rate) +{ + FLAC__ASSERT(0 != spec); + if(!spec->value_is_samples) { + spec->value.samples = (FLAC__int64)(spec->value.seconds * (double)sample_rate); + spec->value_is_samples = true; + } +} + +FLAC__bool flac__utils_parse_cue_specification(const char *s, utils__CueSpecification *spec) +{ + const char *start = s, *end = 0; + + FLAC__ASSERT(0 != spec); + + spec->has_start_point = spec->has_end_point = false; + + s = strchr(s, '-'); + + if(0 != s) { + if(s == start) + start = 0; + end = s+1; + if(*end == '\0') + end = 0; + } + + if(start) { + if(!local__parse_cue_(start, s, &spec->start_track, &spec->start_index)) + return false; + spec->has_start_point = true; + } + + if(end) { + if(!local__parse_cue_(end, 0, &spec->end_track, &spec->end_index)) + return false; + spec->has_end_point = true; + } + + return true; +} + +void flac__utils_canonicalize_cue_specification(const utils__CueSpecification *cue_spec, const FLAC__StreamMetadata_CueSheet *cuesheet, FLAC__uint64 total_samples, utils__SkipUntilSpecification *skip_spec, utils__SkipUntilSpecification *until_spec) +{ + FLAC__ASSERT(0 != cue_spec); + FLAC__ASSERT(0 != cuesheet); + FLAC__ASSERT(0 != total_samples); + FLAC__ASSERT(0 != skip_spec); + FLAC__ASSERT(0 != until_spec); + + skip_spec->is_relative = false; + skip_spec->value_is_samples = true; + + until_spec->is_relative = false; + until_spec->value_is_samples = true; + + if(cue_spec->has_start_point) + skip_spec->value.samples = local__find_closest_cue_(cuesheet, cue_spec->start_track, cue_spec->start_index, total_samples, /*look_forward=*/false); + else + skip_spec->value.samples = 0; + + if(cue_spec->has_end_point) + until_spec->value.samples = local__find_closest_cue_(cuesheet, cue_spec->end_track, cue_spec->end_index, total_samples, /*look_forward=*/true); + else + until_spec->value.samples = total_samples; +} + +FLAC__bool flac__utils_set_channel_mask_tag(FLAC__StreamMetadata *object, FLAC__uint32 channel_mask) +{ + FLAC__StreamMetadata_VorbisComment_Entry entry = { 0, 0 }; + char tag[128]; + + FLAC__ASSERT(object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(strlen(CHANNEL_MASK_TAG+1+2+16+1) <= sizeof(tag)); /* +1 for =, +2 for 0x, +16 for digits, +1 for NUL */ + entry.entry = (FLAC__byte*)tag; +#if defined _MSC_VER || defined __MINGW32__ + if((entry.length = _snprintf(tag, sizeof(tag), "%s=0x%04X", CHANNEL_MASK_TAG, (unsigned)channel_mask)) >= sizeof(tag)) +#else + if((entry.length = snprintf(tag, sizeof(tag), "%s=0x%04X", CHANNEL_MASK_TAG, (unsigned)channel_mask)) >= sizeof(tag)) +#endif + return false; + if(!FLAC__metadata_object_vorbiscomment_replace_comment(object, entry, /*all=*/true, /*copy=*/true)) + return false; + return true; +} + +FLAC__bool flac__utils_get_channel_mask_tag(const FLAC__StreamMetadata *object, FLAC__uint32 *channel_mask) +{ + int offset; + unsigned val; + char *p; + FLAC__ASSERT(object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 > (offset = FLAC__metadata_object_vorbiscomment_find_entry_from(object, /*offset=*/0, CHANNEL_MASK_TAG))) + return false; + if(object->data.vorbis_comment.comments[offset].length < strlen(CHANNEL_MASK_TAG)+4) + return false; + if(0 == (p = strchr((const char *)object->data.vorbis_comment.comments[offset].entry, '='))) /* should never happen, but just in case */ + return false; + if(strncmp(p, "=0x", 3)) + return false; + if(sscanf(p+3, "%x", &val) != 1) + return false; + *channel_mask = val; + return true; +} diff --git a/flac/src/flac/utils.h b/flac/src/flac/utils.h new file mode 100644 index 0000000..181a387 --- /dev/null +++ b/flac/src/flac/utils.h @@ -0,0 +1,65 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__utils_h +#define flac__utils_h + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/ordinals.h" +#include "FLAC/format.h" /* for FLAC__StreamMetadata_CueSheet */ +#include /* for FILE */ + +typedef enum { FORMAT_RAW, FORMAT_WAVE, FORMAT_WAVE64, FORMAT_RF64, FORMAT_AIFF, FORMAT_AIFF_C, FORMAT_FLAC, FORMAT_OGGFLAC } FileFormat; + +typedef struct { + FLAC__bool is_relative; /* i.e. specification string started with + or - */ + FLAC__bool value_is_samples; + union { + double seconds; + FLAC__int64 samples; + } value; +} utils__SkipUntilSpecification; + +typedef struct { + FLAC__bool has_start_point, has_end_point; + unsigned start_track, start_index; + unsigned end_track, end_index; +} utils__CueSpecification; + +#ifdef FLAC__VALGRIND_TESTING +size_t flac__utils_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); +#else +#define flac__utils_fwrite fwrite +#endif + +extern int flac__utils_verbosity_; +void flac__utils_printf(FILE *stream, int level, const char *format, ...); + +FLAC__bool flac__utils_parse_skip_until_specification(const char *s, utils__SkipUntilSpecification *spec); +void flac__utils_canonicalize_skip_until_specification(utils__SkipUntilSpecification *spec, unsigned sample_rate); + +FLAC__bool flac__utils_parse_cue_specification(const char *s, utils__CueSpecification *spec); +void flac__utils_canonicalize_cue_specification(const utils__CueSpecification *cue_spec, const FLAC__StreamMetadata_CueSheet *cuesheet, FLAC__uint64 total_samples, utils__SkipUntilSpecification *skip_spec, utils__SkipUntilSpecification *until_spec); + +FLAC__bool flac__utils_set_channel_mask_tag(FLAC__StreamMetadata *object, FLAC__uint32 channel_mask); +FLAC__bool flac__utils_get_channel_mask_tag(const FLAC__StreamMetadata *object, FLAC__uint32 *channel_mask); + +#endif diff --git a/flac/src/flac/vorbiscomment.c b/flac/src/flac/vorbiscomment.c new file mode 100644 index 0000000..9e8af49 --- /dev/null +++ b/flac/src/flac/vorbiscomment.c @@ -0,0 +1,248 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "vorbiscomment.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "share/grabbag.h" /* for grabbag__file_get_filesize() */ +#include "share/utf8.h" +#include +#include +#include +#include + + +/* + * This struct and the following 4 static functions are copied from + * ../metaflac/. Maybe someday there will be a convenience + * library for Vorbis comment parsing. + */ +typedef struct { + char *field; /* the whole field as passed on the command line, i.e. "NAME=VALUE" */ + char *field_name; + /* according to the vorbis spec, field values can contain \0 so simple C strings are not enough here */ + unsigned field_value_length; + char *field_value; + FLAC__bool field_value_from_file; /* true if field_value holds a filename for the value, false for plain value */ +} Argument_VcField; + +static void die(const char *message) +{ + FLAC__ASSERT(0 != message); + fprintf(stderr, "ERROR: %s\n", message); + exit(1); +} + +static char *local_strdup(const char *source) +{ + char *ret; + FLAC__ASSERT(0 != source); + if(0 == (ret = strdup(source))) + die("out of memory during strdup()"); + return ret; +} + +static FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation) +{ + static const char * const violations[] = { + "field name contains invalid character", + "field contains no '=' character" + }; + + char *p, *q, *s; + + if(0 != field) + *field = local_strdup(field_ref); + + s = local_strdup(field_ref); + + if(0 == (p = strchr(s, '='))) { + free(s); + *violation = violations[1]; + return false; + } + *p++ = '\0'; + + for(q = s; *q; q++) { + if(*q < 0x20 || *q > 0x7d || *q == 0x3d) { + free(s); + *violation = violations[0]; + return false; + } + } + + *name = local_strdup(s); + *value = local_strdup(p); + *length = strlen(p); + + free(s); + return true; +} + +/* slight modification: no 'filename' arg, and errors are passed back in 'violation' instead of printed to stderr */ +static FLAC__bool set_vc_field(FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw, const char **violation) +{ + FLAC__StreamMetadata_VorbisComment_Entry entry; + char *converted; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != field); + FLAC__ASSERT(0 != needs_write); + + if(field->field_value_from_file) { + /* read the file into 'data' */ + FILE *f = 0; + char *data = 0; + const off_t size = grabbag__file_get_filesize(field->field_value); + if(size < 0) { + *violation = "can't open file for tag value"; + return false; + } + if(size >= 0x100000) { /* magic arbitrary limit, actual format limit is near 16MB */ + *violation = "file for tag value is too large"; + return false; + } + if(0 == (data = malloc(size+1))) + die("out of memory allocating tag value"); + data[size] = '\0'; + if(0 == (f = fopen(field->field_value, "rb")) || fread(data, 1, size, f) != (size_t)size) { + free(data); + if(f) + fclose(f); + *violation = "error while reading file for tag value"; + return false; + } + fclose(f); + if(strlen(data) != (size_t)size) { + free(data); + *violation = "file for tag value has embedded NULs"; + return false; + } + + /* move 'data' into 'converted', converting to UTF-8 if necessary */ + if(raw) { + converted = data; + } + else if(utf8_encode(data, &converted) >= 0) { + free(data); + } + else { + free(data); + *violation = "error converting file contents to UTF-8 for tag value"; + return false; + } + + /* create and entry and append it */ + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, field->field_name, converted)) { + free(converted); + *violation = "file for tag value is not valid UTF-8"; + return false; + } + free(converted); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/false)) { + *violation = "memory allocation failure"; + return false; + } + + *needs_write = true; + return true; + } + else { + FLAC__bool needs_free = false; + if(raw) { + entry.entry = (FLAC__byte *)field->field; + } + else if(utf8_encode(field->field, &converted) >= 0) { + entry.entry = (FLAC__byte *)converted; + needs_free = true; + } + else { + *violation = "error converting comment to UTF-8"; + return false; + } + entry.length = strlen((const char *)entry.entry); + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) { + if(needs_free) + free(converted); + /* + * our previous parsing has already established that the field + * name is OK, so it must be the field value + */ + *violation = "tag value for is not valid UTF-8"; + return false; + } + + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + if(needs_free) + free(converted); + *violation = "memory allocation failure"; + return false; + } + + *needs_write = true; + if(needs_free) + free(converted); + return true; + } +} + +/* + * The rest of the code is novel + */ + +static void free_field(Argument_VcField *obj) +{ + if(0 != obj->field) + free(obj->field); + if(0 != obj->field_name) + free(obj->field_name); + if(0 != obj->field_value) + free(obj->field_value); +} + +FLAC__bool flac__vorbiscomment_add(FLAC__StreamMetadata *block, const char *comment, FLAC__bool value_from_file, FLAC__bool raw, const char **violation) +{ + Argument_VcField parsed; + FLAC__bool dummy; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != comment); + + memset(&parsed, 0, sizeof(parsed)); + + parsed.field_value_from_file = value_from_file; + if(!parse_vorbis_comment_field(comment, &(parsed.field), &(parsed.field_name), &(parsed.field_value), &(parsed.field_value_length), violation)) { + free_field(&parsed); + return false; + } + + if(!set_vc_field(block, &parsed, &dummy, raw, violation)) { + free_field(&parsed); + return false; + } + else { + free_field(&parsed); + return true; + } +} diff --git a/flac/src/flac/vorbiscomment.h b/flac/src/flac/vorbiscomment.h new file mode 100644 index 0000000..2ba6d2d --- /dev/null +++ b/flac/src/flac/vorbiscomment.h @@ -0,0 +1,26 @@ +/* flac - Command-line FLAC encoder/decoder + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef flac__vorbiscomment_h +#define flac__vorbiscomment_h + +#include "FLAC/metadata.h" + +FLAC__bool flac__vorbiscomment_add(FLAC__StreamMetadata *block, const char *comment, FLAC__bool value_from_file, FLAC__bool raw, const char **violation); + +#endif diff --git a/flac/src/libFLAC++/Makefile.am b/flac/src/libFLAC++/Makefile.am new file mode 100644 index 0000000..02ccf9b --- /dev/null +++ b/flac/src/libFLAC++/Makefile.am @@ -0,0 +1,55 @@ +# libFLAC++ - Free Lossless Audio Codec library +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +lib_LTLIBRARIES = libFLAC++.la + +m4datadir = $(datadir)/aclocal +m4data_DATA = libFLAC++.m4 + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = flac++.pc + +EXTRA_DIST = \ + Makefile.lite \ + flac++.pc.in \ + libFLAC++_dynamic.dsp \ + libFLAC++_dynamic.vcproj \ + libFLAC++_static.dsp \ + libFLAC++_static.vcproj \ + libFLAC++.m4 + +# see 'http://www.gnu.org/software/libtool/manual.html#Libtool-versioning' for numbering convention +libFLAC___la_LDFLAGS = -version-info 8:0:2 +libFLAC___la_LIBADD = ../libFLAC/libFLAC.la + +libFLAC___la_SOURCES = \ + metadata.cpp \ + stream_decoder.cpp \ + stream_encoder.cpp diff --git a/flac/src/libFLAC++/Makefile.lite b/flac/src/libFLAC++/Makefile.lite new file mode 100644 index 0000000..a1d3abb --- /dev/null +++ b/flac/src/libFLAC++/Makefile.lite @@ -0,0 +1,47 @@ +# libFLAC++ - Free Lossless Audio Codec library +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +# +# GNU makefile +# + +topdir = ../.. + +LIB_NAME = libFLAC++ +INCLUDES = -I$(topdir)/include + +SRCS_CPP = \ + metadata.cpp \ + stream_decoder.cpp \ + stream_encoder.cpp + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/libFLAC++/flac++.pc.in b/flac/src/libFLAC++/flac++.pc.in new file mode 100644 index 0000000..a15424f --- /dev/null +++ b/flac/src/libFLAC++/flac++.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: FLAC++ +Description: Free Lossless Audio Codec Library (C++ API) +Version: @VERSION@ +Requires: flac +Libs: -L${libdir} -lFLAC++ -lm +Cflags: -I${includedir}/FLAC++ diff --git a/flac/src/libFLAC++/libFLAC++.m4 b/flac/src/libFLAC++/libFLAC++.m4 new file mode 100644 index 0000000..37f6ab7 --- /dev/null +++ b/flac/src/libFLAC++/libFLAC++.m4 @@ -0,0 +1,117 @@ +# Configure paths for libFLAC++ +# "Inspired" by ogg.m4 +# Caller must first run AM_PATH_LIBFLAC + +dnl AM_PATH_LIBFLACPP([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libFLAC++, and define LIBFLACPP_CFLAGS, LIBFLACPP_LIBS, LIBFLACPP_LIBDIR +dnl +AC_DEFUN([AM_PATH_LIBFLACPP], +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(libFLACPP,[ --with-libFLACPP=PFX Prefix where libFLAC++ is installed (optional)], libFLACPP_prefix="$withval", libFLACPP_prefix="") +AC_ARG_WITH(libFLACPP-libraries,[ --with-libFLACPP-libraries=DIR Directory where libFLAC++ library is installed (optional)], libFLACPP_libraries="$withval", libFLACPP_libraries="") +AC_ARG_WITH(libFLACPP-includes,[ --with-libFLACPP-includes=DIR Directory where libFLAC++ header files are installed (optional)], libFLACPP_includes="$withval", libFLACPP_includes="") +AC_ARG_ENABLE(libFLACPPtest, [ --disable-libFLACPPtest Do not try to compile and run a test libFLAC++ program],, enable_libFLACPPtest=yes) + + if test "x$libFLACPP_libraries" != "x" ; then + LIBFLACPP_LIBDIR="$libFLACPP_libraries" + elif test "x$libFLACPP_prefix" != "x" ; then + LIBFLACPP_LIBDIR="$libFLACPP_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + LIBFLACPP_LIBDIR="$libdir" + fi + + LIBFLACPP_LIBS="-L$LIBFLACPP_LIBDIR -lFLAC++ $LIBFLAC_LIBS" + + if test "x$libFLACPP_includes" != "x" ; then + LIBFLACPP_CFLAGS="-I$libFLACPP_includes" + elif test "x$libFLACPP_prefix" != "x" ; then + LIBFLACPP_CFLAGS="-I$libFLACPP_prefix/include" + elif test "$prefix" != "xNONE"; then + LIBFLACPP_CFLAGS="" + fi + + LIBFLACPP_CFLAGS="$LIBFLACPP_CFLAGS $LIBFLAC_CFLAGS" + + AC_MSG_CHECKING(for libFLAC++) + no_libFLACPP="" + + + if test "x$enable_libFLACPPtest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_CXXFLAGS="$CXXFLAGS" + ac_save_LIBS="$LIBS" + ac_save_LD_LIBRARY_PATH="$LD_LIBRARY_PATH" + CFLAGS="$CFLAGS $LIBFLACPP_CFLAGS" + CXXFLAGS="$CXXFLAGS $LIBFLACPP_CFLAGS" + LIBS="$LIBS $LIBFLACPP_LIBS" + LD_LIBRARY_PATH="$LIBFLACPP_LIBDIR:$LIBFLAC_LIBDIR:$LD_LIBRARY_PATH" +dnl +dnl Now check if the installed libFLAC++ is sufficiently new. +dnl + rm -f conf.libFLAC++test + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.libFLAC++test"); + return 0; +} + +],, no_libFLACPP=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + CXXFLAGS="$ac_save_CXXFLAGS" + LIBS="$ac_save_LIBS" + LD_LIBRARY_PATH="$ac_save_LD_LIBRARY_PATH" + fi + + if test "x$no_libFLACPP" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.libFLAC++test ; then + : + else + echo "*** Could not run libFLAC++ test program, checking why..." + CFLAGS="$CFLAGS $LIBFLACPP_CFLAGS" + CXXFLAGS="$CXXFLAGS $LIBFLACPP_CFLAGS" + LIBS="$LIBS $LIBFLACPP_LIBS" + LD_LIBRARY_PATH="$LIBFLACPP_LIBDIR:$LIBFLAC_LIBDIR:$LD_LIBRARY_PATH" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding libFLAC++ or finding the wrong" + echo "*** version of libFLAC++. If it is not finding libFLAC++, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means libFLAC++ was incorrectly installed" + echo "*** or that you have moved libFLAC++ since it was installed. In the latter case, you" + echo "*** may want to edit the libFLAC++-config script: $LIBFLACPP_CONFIG" ]) + CFLAGS="$ac_save_CFLAGS" + CXXFLAGS="$ac_save_CXXFLAGS" + LIBS="$ac_save_LIBS" + LD_LIBRARY_PATH="$ac_save_LD_LIBRARY_PATH" + fi + LIBFLACPP_CFLAGS="" + LIBFLACPP_LIBDIR="" + LIBFLACPP_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(LIBFLACPP_CFLAGS) + AC_SUBST(LIBFLACPP_LIBDIR) + AC_SUBST(LIBFLACPP_LIBS) + rm -f conf.libFLAC++test +]) diff --git a/flac/src/libFLAC++/libFLAC++_dynamic.dsp b/flac/src/libFLAC++/libFLAC++_dynamic.dsp new file mode 100644 index 0000000..f38d238 --- /dev/null +++ b/flac/src/libFLAC++/libFLAC++_dynamic.dsp @@ -0,0 +1,139 @@ +# Microsoft Developer Studio Project File - Name="libFLAC++_dynamic" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=libFLAC++_dynamic - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libFLAC++_dynamic.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libFLAC++_dynamic.mak" CFG="libFLAC++_dynamic - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libFLAC++_dynamic - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "libFLAC++_dynamic - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "libFLAC++" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libFLAC++_dynamic - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_dynamic" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /I ".\include" /I "..\..\include" /D "NDEBUG" /D "FLACPP_API_EXPORTS" /D "_WINDOWS" /D "_WINDLL" /D "WIN32" /D "_USRDLL" /FR /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" /d "_USRDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\libFLAC.lib /nologo /subsystem:windows /dll /machine:I386 /out:"..\..\obj\release\bin/libFLAC++.dll" + +!ELSEIF "$(CFG)" == "libFLAC++_dynamic - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_dynamic" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I ".\include" /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLACPP_API_EXPORTS" /D "_WINDOWS" /D "_WINDLL" /D "WIN32" /D "_USRDLL" /FR /FD /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" /d "_USRDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\libFLAC.lib /nologo /subsystem:windows /dll /debug /machine:I386 /out:"..\..\obj\debug\bin/libFLAC++.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "libFLAC++_dynamic - Win32 Release" +# Name "libFLAC++_dynamic - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp" +# Begin Source File + +SOURCE=.\metadata.cpp +# End Source File +# Begin Source File + +SOURCE=.\stream_decoder.cpp +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder.cpp +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE="..\..\include\FLAC++\all.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\decoder.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\encoder.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\export.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\metadata.h" +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/libFLAC++/libFLAC++_dynamic.vcproj b/flac/src/libFLAC++/libFLAC++_dynamic.vcproj new file mode 100644 index 0000000..be8df51 --- /dev/null +++ b/flac/src/libFLAC++/libFLAC++_dynamic.vcproj @@ -0,0 +1,392 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/libFLAC++/libFLAC++_static.dsp b/flac/src/libFLAC++/libFLAC++_static.dsp new file mode 100644 index 0000000..5e9c466 --- /dev/null +++ b/flac/src/libFLAC++/libFLAC++_static.dsp @@ -0,0 +1,132 @@ +# Microsoft Developer Studio Project File - Name="libFLAC++_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=libFLAC++_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libFLAC++_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libFLAC++_static.mak" CFG="libFLAC++_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libFLAC++_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "libFLAC++_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "libFLAC++" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libFLAC++_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /I ".\include" /I "..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "libFLAC++_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I ".\include" /I "..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "libFLAC++_static - Win32 Release" +# Name "libFLAC++_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp" +# Begin Source File + +SOURCE=.\metadata.cpp +# End Source File +# Begin Source File + +SOURCE=.\stream_decoder.cpp +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder.cpp +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE="..\..\include\FLAC++\all.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\decoder.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\encoder.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\export.h" +# End Source File +# Begin Source File + +SOURCE="..\..\include\FLAC++\metadata.h" +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/libFLAC++/libFLAC++_static.vcproj b/flac/src/libFLAC++/libFLAC++_static.vcproj new file mode 100644 index 0000000..e51fd90 --- /dev/null +++ b/flac/src/libFLAC++/libFLAC++_static.vcproj @@ -0,0 +1,338 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/libFLAC++/metadata.cpp b/flac/src/libFLAC++/metadata.cpp new file mode 100644 index 0000000..29cb1a8 --- /dev/null +++ b/flac/src/libFLAC++/metadata.cpp @@ -0,0 +1,1589 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#define __STDC_LIMIT_MACROS 1 /* otherwise SIZE_MAX is not defined for c++ */ +#include "share/alloc.h" +#include "FLAC++/metadata.h" +#include "FLAC/assert.h" +#include // for malloc(), free() +#include // for memcpy() etc. + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + +namespace FLAC { + namespace Metadata { + + // local utility routines + + namespace local { + + Prototype *construct_block(::FLAC__StreamMetadata *object) + { + Prototype *ret = 0; + switch(object->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + ret = new StreamInfo(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_PADDING: + ret = new Padding(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_APPLICATION: + ret = new Application(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + ret = new SeekTable(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + ret = new VorbisComment(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_CUESHEET: + ret = new CueSheet(object, /*copy=*/false); + break; + case FLAC__METADATA_TYPE_PICTURE: + ret = new Picture(object, /*copy=*/false); + break; + default: + ret = new Unknown(object, /*copy=*/false); + break; + } + return ret; + } + + } + + FLACPP_API Prototype *clone(const Prototype *object) + { + FLAC__ASSERT(0 != object); + + const StreamInfo *streaminfo = dynamic_cast(object); + const Padding *padding = dynamic_cast(object); + const Application *application = dynamic_cast(object); + const SeekTable *seektable = dynamic_cast(object); + const VorbisComment *vorbiscomment = dynamic_cast(object); + const CueSheet *cuesheet = dynamic_cast(object); + const Picture *picture = dynamic_cast(object); + const Unknown *unknown = dynamic_cast(object); + + if(0 != streaminfo) + return new StreamInfo(*streaminfo); + else if(0 != padding) + return new Padding(*padding); + else if(0 != application) + return new Application(*application); + else if(0 != seektable) + return new SeekTable(*seektable); + else if(0 != vorbiscomment) + return new VorbisComment(*vorbiscomment); + else if(0 != cuesheet) + return new CueSheet(*cuesheet); + else if(0 != picture) + return new Picture(*picture); + else if(0 != unknown) + return new Unknown(*unknown); + else { + FLAC__ASSERT(0); + return 0; + } + } + + // + // Prototype + // + + Prototype::Prototype(const Prototype &object): + object_(::FLAC__metadata_object_clone(object.object_)), + is_reference_(false) + { + FLAC__ASSERT(object.is_valid()); + } + + Prototype::Prototype(const ::FLAC__StreamMetadata &object): + object_(::FLAC__metadata_object_clone(&object)), + is_reference_(false) + { + } + + Prototype::Prototype(const ::FLAC__StreamMetadata *object): + object_(::FLAC__metadata_object_clone(object)), + is_reference_(false) + { + FLAC__ASSERT(0 != object); + } + + Prototype::Prototype(::FLAC__StreamMetadata *object, bool copy): + object_(copy? ::FLAC__metadata_object_clone(object) : object), + is_reference_(false) + { + FLAC__ASSERT(0 != object); + } + + Prototype::~Prototype() + { + clear(); + } + + void Prototype::clear() + { + if(0 != object_ && !is_reference_) + FLAC__metadata_object_delete(object_); + object_ = 0; + } + + Prototype &Prototype::operator=(const Prototype &object) + { + FLAC__ASSERT(object.is_valid()); + clear(); + is_reference_ = false; + object_ = ::FLAC__metadata_object_clone(object.object_); + return *this; + } + + Prototype &Prototype::operator=(const ::FLAC__StreamMetadata &object) + { + clear(); + is_reference_ = false; + object_ = ::FLAC__metadata_object_clone(&object); + return *this; + } + + Prototype &Prototype::operator=(const ::FLAC__StreamMetadata *object) + { + FLAC__ASSERT(0 != object); + clear(); + is_reference_ = false; + object_ = ::FLAC__metadata_object_clone(object); + return *this; + } + + Prototype &Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy) + { + FLAC__ASSERT(0 != object); + clear(); + object_ = (copy? ::FLAC__metadata_object_clone(object) : object); + is_reference_ = false; + return *this; + } + + bool Prototype::get_is_last() const + { + FLAC__ASSERT(is_valid()); + return (bool)object_->is_last; + } + + FLAC__MetadataType Prototype::get_type() const + { + FLAC__ASSERT(is_valid()); + return object_->type; + } + + unsigned Prototype::get_length() const + { + FLAC__ASSERT(is_valid()); + return object_->length; + } + + void Prototype::set_is_last(bool value) + { + FLAC__ASSERT(is_valid()); + object_->is_last = value; + } + + + // + // StreamInfo + // + + StreamInfo::StreamInfo(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_STREAMINFO), /*copy=*/false) + { } + + StreamInfo::~StreamInfo() + { } + + unsigned StreamInfo::get_min_blocksize() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.min_blocksize; + } + + unsigned StreamInfo::get_max_blocksize() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.max_blocksize; + } + + unsigned StreamInfo::get_min_framesize() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.min_framesize; + } + + unsigned StreamInfo::get_max_framesize() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.max_framesize; + } + + unsigned StreamInfo::get_sample_rate() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.sample_rate; + } + + unsigned StreamInfo::get_channels() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.channels; + } + + unsigned StreamInfo::get_bits_per_sample() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.bits_per_sample; + } + + FLAC__uint64 StreamInfo::get_total_samples() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.total_samples; + } + + const FLAC__byte *StreamInfo::get_md5sum() const + { + FLAC__ASSERT(is_valid()); + return object_->data.stream_info.md5sum; + } + + void StreamInfo::set_min_blocksize(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value >= FLAC__MIN_BLOCK_SIZE); + FLAC__ASSERT(value <= FLAC__MAX_BLOCK_SIZE); + object_->data.stream_info.min_blocksize = value; + } + + void StreamInfo::set_max_blocksize(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value >= FLAC__MIN_BLOCK_SIZE); + FLAC__ASSERT(value <= FLAC__MAX_BLOCK_SIZE); + object_->data.stream_info.max_blocksize = value; + } + + void StreamInfo::set_min_framesize(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)); + object_->data.stream_info.min_framesize = value; + } + + void StreamInfo::set_max_framesize(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)); + object_->data.stream_info.max_framesize = value; + } + + void StreamInfo::set_sample_rate(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(FLAC__format_sample_rate_is_valid(value)); + object_->data.stream_info.sample_rate = value; + } + + void StreamInfo::set_channels(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value > 0); + FLAC__ASSERT(value <= FLAC__MAX_CHANNELS); + object_->data.stream_info.channels = value; + } + + void StreamInfo::set_bits_per_sample(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value >= FLAC__MIN_BITS_PER_SAMPLE); + FLAC__ASSERT(value <= FLAC__MAX_BITS_PER_SAMPLE); + object_->data.stream_info.bits_per_sample = value; + } + + void StreamInfo::set_total_samples(FLAC__uint64 value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value < (((FLAC__uint64)1) << FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)); + object_->data.stream_info.total_samples = value; + } + + void StreamInfo::set_md5sum(const FLAC__byte value[16]) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != value); + memcpy(object_->data.stream_info.md5sum, value, 16); + } + + + // + // Padding + // + + Padding::Padding(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING), /*copy=*/false) + { } + + Padding::~Padding() + { } + + void Padding::set_length(unsigned length) + { + FLAC__ASSERT(is_valid()); + object_->length = length; + } + + + // + // Application + // + + Application::Application(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION), /*copy=*/false) + { } + + Application::~Application() + { } + + const FLAC__byte *Application::get_id() const + { + FLAC__ASSERT(is_valid()); + return object_->data.application.id; + } + + const FLAC__byte *Application::get_data() const + { + FLAC__ASSERT(is_valid()); + return object_->data.application.data; + } + + void Application::set_id(const FLAC__byte value[4]) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != value); + memcpy(object_->data.application.id, value, 4); + } + + bool Application::set_data(const FLAC__byte *data, unsigned length) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_application_set_data(object_, (FLAC__byte*)data, length, true); + } + + bool Application::set_data(FLAC__byte *data, unsigned length, bool copy) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_application_set_data(object_, data, length, copy); + } + + + // + // SeekTable + // + + SeekTable::SeekTable(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE), /*copy=*/false) + { } + + SeekTable::~SeekTable() + { } + + unsigned SeekTable::get_num_points() const + { + FLAC__ASSERT(is_valid()); + return object_->data.seek_table.num_points; + } + + ::FLAC__StreamMetadata_SeekPoint SeekTable::get_point(unsigned index) const + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.seek_table.num_points); + return object_->data.seek_table.points[index]; + } + + void SeekTable::set_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.seek_table.num_points); + ::FLAC__metadata_object_seektable_set_point(object_, index, point); + } + + bool SeekTable::insert_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index <= object_->data.seek_table.num_points); + return (bool)::FLAC__metadata_object_seektable_insert_point(object_, index, point); + } + + bool SeekTable::delete_point(unsigned index) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.seek_table.num_points); + return (bool)::FLAC__metadata_object_seektable_delete_point(object_, index); + } + + bool SeekTable::is_legal() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_seektable_is_legal(object_); + } + + + // + // VorbisComment::Entry + // + + VorbisComment::Entry::Entry() + { + zero(); + } + + VorbisComment::Entry::Entry(const char *field, unsigned field_length) + { + zero(); + construct(field, field_length); + } + + VorbisComment::Entry::Entry(const char *field) + { + zero(); + construct(field); + } + + VorbisComment::Entry::Entry(const char *field_name, const char *field_value, unsigned field_value_length) + { + zero(); + construct(field_name, field_value, field_value_length); + } + + VorbisComment::Entry::Entry(const char *field_name, const char *field_value) + { + zero(); + construct(field_name, field_value); + } + + VorbisComment::Entry::Entry(const Entry &entry) + { + FLAC__ASSERT(entry.is_valid()); + zero(); + construct((const char *)entry.entry_.entry, entry.entry_.length); + } + + VorbisComment::Entry &VorbisComment::Entry::operator=(const Entry &entry) + { + FLAC__ASSERT(entry.is_valid()); + clear(); + construct((const char *)entry.entry_.entry, entry.entry_.length); + return *this; + } + + VorbisComment::Entry::~Entry() + { + clear(); + } + + bool VorbisComment::Entry::is_valid() const + { + return is_valid_; + } + + unsigned VorbisComment::Entry::get_field_length() const + { + FLAC__ASSERT(is_valid()); + return entry_.length; + } + + unsigned VorbisComment::Entry::get_field_name_length() const + { + FLAC__ASSERT(is_valid()); + return field_name_length_; + } + + unsigned VorbisComment::Entry::get_field_value_length() const + { + FLAC__ASSERT(is_valid()); + return field_value_length_; + } + + ::FLAC__StreamMetadata_VorbisComment_Entry VorbisComment::Entry::get_entry() const + { + FLAC__ASSERT(is_valid()); + return entry_; + } + + const char *VorbisComment::Entry::get_field() const + { + FLAC__ASSERT(is_valid()); + return (const char *)entry_.entry; + } + + const char *VorbisComment::Entry::get_field_name() const + { + FLAC__ASSERT(is_valid()); + return field_name_; + } + + const char *VorbisComment::Entry::get_field_value() const + { + FLAC__ASSERT(is_valid()); + return field_value_; + } + + bool VorbisComment::Entry::set_field(const char *field, unsigned field_length) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != field); + + if(!::FLAC__format_vorbiscomment_entry_is_legal((const ::FLAC__byte*)field, field_length)) + return is_valid_ = false; + + clear_entry(); + + if(0 == (entry_.entry = (FLAC__byte*)safe_malloc_add_2op_(field_length, /*+*/1))) { + is_valid_ = false; + } + else { + entry_.length = field_length; + memcpy(entry_.entry, field, field_length); + entry_.entry[field_length] = '\0'; + (void) parse_field(); + } + + return is_valid_; + } + + bool VorbisComment::Entry::set_field(const char *field) + { + return set_field(field, strlen(field)); + } + + bool VorbisComment::Entry::set_field_name(const char *field_name) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != field_name); + + if(!::FLAC__format_vorbiscomment_entry_name_is_legal(field_name)) + return is_valid_ = false; + + clear_field_name(); + + if(0 == (field_name_ = strdup(field_name))) { + is_valid_ = false; + } + else { + field_name_length_ = strlen(field_name_); + compose_field(); + } + + return is_valid_; + } + + bool VorbisComment::Entry::set_field_value(const char *field_value, unsigned field_value_length) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != field_value); + + if(!::FLAC__format_vorbiscomment_entry_value_is_legal((const FLAC__byte*)field_value, field_value_length)) + return is_valid_ = false; + + clear_field_value(); + + if(0 == (field_value_ = (char *)safe_malloc_add_2op_(field_value_length, /*+*/1))) { + is_valid_ = false; + } + else { + field_value_length_ = field_value_length; + memcpy(field_value_, field_value, field_value_length); + field_value_[field_value_length] = '\0'; + compose_field(); + } + + return is_valid_; + } + + bool VorbisComment::Entry::set_field_value(const char *field_value) + { + return set_field_value(field_value, strlen(field_value)); + } + + void VorbisComment::Entry::zero() + { + is_valid_ = true; + entry_.length = 0; + entry_.entry = 0; + field_name_ = 0; + field_name_length_ = 0; + field_value_ = 0; + field_value_length_ = 0; + } + + void VorbisComment::Entry::clear() + { + clear_entry(); + clear_field_name(); + clear_field_value(); + is_valid_ = true; + } + + void VorbisComment::Entry::clear_entry() + { + if(0 != entry_.entry) { + free(entry_.entry); + entry_.entry = 0; + entry_.length = 0; + } + } + + void VorbisComment::Entry::clear_field_name() + { + if(0 != field_name_) { + free(field_name_); + field_name_ = 0; + field_name_length_ = 0; + } + } + + void VorbisComment::Entry::clear_field_value() + { + if(0 != field_value_) { + free(field_value_); + field_value_ = 0; + field_value_length_ = 0; + } + } + + void VorbisComment::Entry::construct(const char *field, unsigned field_length) + { + if(set_field(field, field_length)) + parse_field(); + } + + void VorbisComment::Entry::construct(const char *field) + { + construct(field, strlen(field)); + } + + void VorbisComment::Entry::construct(const char *field_name, const char *field_value, unsigned field_value_length) + { + if(set_field_name(field_name) && set_field_value(field_value, field_value_length)) + compose_field(); + } + + void VorbisComment::Entry::construct(const char *field_name, const char *field_value) + { + construct(field_name, field_value, strlen(field_value)); + } + + void VorbisComment::Entry::compose_field() + { + clear_entry(); + + if(0 == (entry_.entry = (FLAC__byte*)safe_malloc_add_4op_(field_name_length_, /*+*/1, /*+*/field_value_length_, /*+*/1))) { + is_valid_ = false; + } + else { + memcpy(entry_.entry, field_name_, field_name_length_); + entry_.length += field_name_length_; + memcpy(entry_.entry + entry_.length, "=", 1); + entry_.length += 1; + memcpy(entry_.entry + entry_.length, field_value_, field_value_length_); + entry_.length += field_value_length_; + entry_.entry[entry_.length] = '\0'; + is_valid_ = true; + } + } + + void VorbisComment::Entry::parse_field() + { + clear_field_name(); + clear_field_value(); + + const char *p = (const char *)memchr(entry_.entry, '=', entry_.length); + + if(0 == p) + p = (const char *)entry_.entry + entry_.length; + + field_name_length_ = (unsigned)(p - (const char *)entry_.entry); + if(0 == (field_name_ = (char *)safe_malloc_add_2op_(field_name_length_, /*+*/1))) { // +1 for the trailing \0 + is_valid_ = false; + return; + } + memcpy(field_name_, entry_.entry, field_name_length_); + field_name_[field_name_length_] = '\0'; + + if(entry_.length - field_name_length_ == 0) { + field_value_length_ = 0; + if(0 == (field_value_ = (char *)safe_malloc_(0))) { + is_valid_ = false; + return; + } + } + else { + field_value_length_ = entry_.length - field_name_length_ - 1; + if(0 == (field_value_ = (char *)safe_malloc_add_2op_(field_value_length_, /*+*/1))) { // +1 for the trailing \0 + is_valid_ = false; + return; + } + memcpy(field_value_, ++p, field_value_length_); + field_value_[field_value_length_] = '\0'; + } + + is_valid_ = true; + } + + + // + // VorbisComment + // + + VorbisComment::VorbisComment(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT), /*copy=*/false) + { } + + VorbisComment::~VorbisComment() + { } + + unsigned VorbisComment::get_num_comments() const + { + FLAC__ASSERT(is_valid()); + return object_->data.vorbis_comment.num_comments; + } + + const FLAC__byte *VorbisComment::get_vendor_string() const + { + FLAC__ASSERT(is_valid()); + return object_->data.vorbis_comment.vendor_string.entry; + } + + VorbisComment::Entry VorbisComment::get_comment(unsigned index) const + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments); + return Entry((const char *)object_->data.vorbis_comment.comments[index].entry, object_->data.vorbis_comment.comments[index].length); + } + + bool VorbisComment::set_vendor_string(const FLAC__byte *string) + { + FLAC__ASSERT(is_valid()); + // vendor_string is a special kind of entry + const ::FLAC__StreamMetadata_VorbisComment_Entry vendor_string = { strlen((const char *)string), (FLAC__byte*)string }; // we can cheat on const-ness because we make a copy below: + return (bool)::FLAC__metadata_object_vorbiscomment_set_vendor_string(object_, vendor_string, /*copy=*/true); + } + + bool VorbisComment::set_comment(unsigned index, const VorbisComment::Entry &entry) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments); + return (bool)::FLAC__metadata_object_vorbiscomment_set_comment(object_, index, entry.get_entry(), /*copy=*/true); + } + + bool VorbisComment::insert_comment(unsigned index, const VorbisComment::Entry &entry) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index <= object_->data.vorbis_comment.num_comments); + return (bool)::FLAC__metadata_object_vorbiscomment_insert_comment(object_, index, entry.get_entry(), /*copy=*/true); + } + + bool VorbisComment::append_comment(const VorbisComment::Entry &entry) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_vorbiscomment_append_comment(object_, entry.get_entry(), /*copy=*/true); + } + + bool VorbisComment::delete_comment(unsigned index) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments); + return (bool)::FLAC__metadata_object_vorbiscomment_delete_comment(object_, index); + } + + + // + // CueSheet::Track + // + + CueSheet::Track::Track(): + object_(::FLAC__metadata_object_cuesheet_track_new()) + { } + + CueSheet::Track::Track(const ::FLAC__StreamMetadata_CueSheet_Track *track): + object_(::FLAC__metadata_object_cuesheet_track_clone(track)) + { } + + CueSheet::Track::Track(const Track &track): + object_(::FLAC__metadata_object_cuesheet_track_clone(track.object_)) + { } + + CueSheet::Track &CueSheet::Track::operator=(const Track &track) + { + if(0 != object_) + ::FLAC__metadata_object_cuesheet_track_delete(object_); + object_ = ::FLAC__metadata_object_cuesheet_track_clone(track.object_); + return *this; + } + + CueSheet::Track::~Track() + { + if(0 != object_) + ::FLAC__metadata_object_cuesheet_track_delete(object_); + } + + bool CueSheet::Track::is_valid() const + { + return(0 != object_); + } + + ::FLAC__StreamMetadata_CueSheet_Index CueSheet::Track::get_index(unsigned i) const + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i < object_->num_indices); + return object_->indices[i]; + } + + void CueSheet::Track::set_isrc(const char value[12]) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != value); + memcpy(object_->isrc, value, 12); + object_->isrc[12] = '\0'; + } + + void CueSheet::Track::set_type(unsigned value) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(value <= 1); + object_->type = value; + } + + void CueSheet::Track::set_index(unsigned i, const ::FLAC__StreamMetadata_CueSheet_Index &index) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i < object_->num_indices); + object_->indices[i] = index; + } + + + // + // CueSheet + // + + CueSheet::CueSheet(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET), /*copy=*/false) + { } + + CueSheet::~CueSheet() + { } + + const char *CueSheet::get_media_catalog_number() const + { + FLAC__ASSERT(is_valid()); + return object_->data.cue_sheet.media_catalog_number; + } + + FLAC__uint64 CueSheet::get_lead_in() const + { + FLAC__ASSERT(is_valid()); + return object_->data.cue_sheet.lead_in; + } + + bool CueSheet::get_is_cd() const + { + FLAC__ASSERT(is_valid()); + return object_->data.cue_sheet.is_cd? true : false; + } + + unsigned CueSheet::get_num_tracks() const + { + FLAC__ASSERT(is_valid()); + return object_->data.cue_sheet.num_tracks; + } + + CueSheet::Track CueSheet::get_track(unsigned i) const + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks); + return Track(object_->data.cue_sheet.tracks + i); + } + + void CueSheet::set_media_catalog_number(const char value[128]) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(0 != value); + memcpy(object_->data.cue_sheet.media_catalog_number, value, 128); + object_->data.cue_sheet.media_catalog_number[128] = '\0'; + } + + void CueSheet::set_lead_in(FLAC__uint64 value) + { + FLAC__ASSERT(is_valid()); + object_->data.cue_sheet.lead_in = value; + } + + void CueSheet::set_is_cd(bool value) + { + FLAC__ASSERT(is_valid()); + object_->data.cue_sheet.is_cd = value; + } + + void CueSheet::set_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks); + FLAC__ASSERT(index_num < object_->data.cue_sheet.tracks[track_num].num_indices); + object_->data.cue_sheet.tracks[track_num].indices[index_num] = index; + } + + bool CueSheet::insert_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks); + FLAC__ASSERT(index_num <= object_->data.cue_sheet.tracks[track_num].num_indices); + return (bool)::FLAC__metadata_object_cuesheet_track_insert_index(object_, track_num, index_num, index); + } + + bool CueSheet::delete_index(unsigned track_num, unsigned index_num) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks); + FLAC__ASSERT(index_num < object_->data.cue_sheet.tracks[track_num].num_indices); + return (bool)::FLAC__metadata_object_cuesheet_track_delete_index(object_, track_num, index_num); + } + + bool CueSheet::set_track(unsigned i, const CueSheet::Track &track) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks); + // We can safely const_cast since copy=true + return (bool)::FLAC__metadata_object_cuesheet_set_track(object_, i, const_cast< ::FLAC__StreamMetadata_CueSheet_Track*>(track.get_track()), /*copy=*/true); + } + + bool CueSheet::insert_track(unsigned i, const CueSheet::Track &track) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i <= object_->data.cue_sheet.num_tracks); + // We can safely const_cast since copy=true + return (bool)::FLAC__metadata_object_cuesheet_insert_track(object_, i, const_cast< ::FLAC__StreamMetadata_CueSheet_Track*>(track.get_track()), /*copy=*/true); + } + + bool CueSheet::delete_track(unsigned i) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks); + return (bool)::FLAC__metadata_object_cuesheet_delete_track(object_, i); + } + + bool CueSheet::is_legal(bool check_cd_da_subset, const char **violation) const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_cuesheet_is_legal(object_, check_cd_da_subset, violation); + } + + FLAC__uint32 CueSheet::calculate_cddb_id() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__metadata_object_cuesheet_calculate_cddb_id(object_); + } + + + // + // Picture + // + + Picture::Picture(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_PICTURE), /*copy=*/false) + { } + + Picture::~Picture() + { } + + ::FLAC__StreamMetadata_Picture_Type Picture::get_type() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.type; + } + + const char *Picture::get_mime_type() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.mime_type; + } + + const FLAC__byte *Picture::get_description() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.description; + } + + FLAC__uint32 Picture::get_width() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.width; + } + + FLAC__uint32 Picture::get_height() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.height; + } + + FLAC__uint32 Picture::get_depth() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.depth; + } + + FLAC__uint32 Picture::get_colors() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.colors; + } + + FLAC__uint32 Picture::get_data_length() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.data_length; + } + + const FLAC__byte *Picture::get_data() const + { + FLAC__ASSERT(is_valid()); + return object_->data.picture.data; + } + + void Picture::set_type(::FLAC__StreamMetadata_Picture_Type type) + { + FLAC__ASSERT(is_valid()); + object_->data.picture.type = type; + } + + bool Picture::set_mime_type(const char *string) + { + FLAC__ASSERT(is_valid()); + // We can safely const_cast since copy=true + return (bool)::FLAC__metadata_object_picture_set_mime_type(object_, const_cast(string), /*copy=*/true); + } + + bool Picture::set_description(const FLAC__byte *string) + { + FLAC__ASSERT(is_valid()); + // We can safely const_cast since copy=true + return (bool)::FLAC__metadata_object_picture_set_description(object_, const_cast(string), /*copy=*/true); + } + + void Picture::set_width(FLAC__uint32 value) const + { + FLAC__ASSERT(is_valid()); + object_->data.picture.width = value; + } + + void Picture::set_height(FLAC__uint32 value) const + { + FLAC__ASSERT(is_valid()); + object_->data.picture.height = value; + } + + void Picture::set_depth(FLAC__uint32 value) const + { + FLAC__ASSERT(is_valid()); + object_->data.picture.depth = value; + } + + void Picture::set_colors(FLAC__uint32 value) const + { + FLAC__ASSERT(is_valid()); + object_->data.picture.colors = value; + } + + bool Picture::set_data(const FLAC__byte *data, FLAC__uint32 data_length) + { + FLAC__ASSERT(is_valid()); + // We can safely const_cast since copy=true + return (bool)::FLAC__metadata_object_picture_set_data(object_, const_cast(data), data_length, /*copy=*/true); + } + + + // + // Unknown + // + + Unknown::Unknown(): + Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION), /*copy=*/false) + { } + + Unknown::~Unknown() + { } + + const FLAC__byte *Unknown::get_data() const + { + FLAC__ASSERT(is_valid()); + return object_->data.application.data; + } + + bool Unknown::set_data(const FLAC__byte *data, unsigned length) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_application_set_data(object_, (FLAC__byte*)data, length, true); + } + + bool Unknown::set_data(FLAC__byte *data, unsigned length, bool copy) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_object_application_set_data(object_, data, length, copy); + } + + + // ============================================================ + // + // Level 0 + // + // ============================================================ + + FLACPP_API bool get_streaminfo(const char *filename, StreamInfo &streaminfo) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata object; + + if(::FLAC__metadata_get_streaminfo(filename, &object)) { + streaminfo = object; + return true; + } + else + return false; + } + + FLACPP_API bool get_tags(const char *filename, VorbisComment *&tags) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + tags = 0; + + if(::FLAC__metadata_get_tags(filename, &object)) { + tags = new VorbisComment(object, /*copy=*/false); + return true; + } + else + return false; + } + + FLACPP_API bool get_tags(const char *filename, VorbisComment &tags) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + if(::FLAC__metadata_get_tags(filename, &object)) { + tags.assign(object, /*copy=*/false); + return true; + } + else + return false; + } + + FLACPP_API bool get_cuesheet(const char *filename, CueSheet *&cuesheet) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + cuesheet = 0; + + if(::FLAC__metadata_get_cuesheet(filename, &object)) { + cuesheet = new CueSheet(object, /*copy=*/false); + return true; + } + else + return false; + } + + FLACPP_API bool get_cuesheet(const char *filename, CueSheet &cuesheet) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + if(::FLAC__metadata_get_cuesheet(filename, &object)) { + cuesheet.assign(object, /*copy=*/false); + return true; + } + else + return false; + } + + FLACPP_API bool get_picture(const char *filename, Picture *&picture, ::FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + picture = 0; + + if(::FLAC__metadata_get_picture(filename, &object, type, mime_type, description, max_width, max_height, max_depth, max_colors)) { + picture = new Picture(object, /*copy=*/false); + return true; + } + else + return false; + } + + FLACPP_API bool get_picture(const char *filename, Picture &picture, ::FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors) + { + FLAC__ASSERT(0 != filename); + + ::FLAC__StreamMetadata *object; + + if(::FLAC__metadata_get_picture(filename, &object, type, mime_type, description, max_width, max_height, max_depth, max_colors)) { + picture.assign(object, /*copy=*/false); + return true; + } + else + return false; + } + + + // ============================================================ + // + // Level 1 + // + // ============================================================ + + SimpleIterator::SimpleIterator(): + iterator_(::FLAC__metadata_simple_iterator_new()) + { } + + SimpleIterator::~SimpleIterator() + { + clear(); + } + + void SimpleIterator::clear() + { + if(0 != iterator_) + FLAC__metadata_simple_iterator_delete(iterator_); + iterator_ = 0; + } + + bool SimpleIterator::init(const char *filename, bool read_only, bool preserve_file_stats) + { + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_init(iterator_, filename, read_only, preserve_file_stats); + } + + bool SimpleIterator::is_valid() const + { + return 0 != iterator_; + } + + SimpleIterator::Status SimpleIterator::status() + { + FLAC__ASSERT(is_valid()); + return Status(::FLAC__metadata_simple_iterator_status(iterator_)); + } + + bool SimpleIterator::is_writable() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_is_writable(iterator_); + } + + bool SimpleIterator::next() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_next(iterator_); + } + + bool SimpleIterator::prev() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_prev(iterator_); + } + + //@@@@ add to tests + bool SimpleIterator::is_last() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_is_last(iterator_); + } + + //@@@@ add to tests + off_t SimpleIterator::get_block_offset() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__metadata_simple_iterator_get_block_offset(iterator_); + } + + ::FLAC__MetadataType SimpleIterator::get_block_type() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__metadata_simple_iterator_get_block_type(iterator_); + } + + //@@@@ add to tests + unsigned SimpleIterator::get_block_length() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__metadata_simple_iterator_get_block_length(iterator_); + } + + //@@@@ add to tests + bool SimpleIterator::get_application_id(FLAC__byte *id) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_get_application_id(iterator_, id); + } + + Prototype *SimpleIterator::get_block() + { + FLAC__ASSERT(is_valid()); + return local::construct_block(::FLAC__metadata_simple_iterator_get_block(iterator_)); + } + + bool SimpleIterator::set_block(Prototype *block, bool use_padding) + { + FLAC__ASSERT(0 != block); + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_set_block(iterator_, block->object_, use_padding); + } + + bool SimpleIterator::insert_block_after(Prototype *block, bool use_padding) + { + FLAC__ASSERT(0 != block); + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_insert_block_after(iterator_, block->object_, use_padding); + } + + bool SimpleIterator::delete_block(bool use_padding) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_simple_iterator_delete_block(iterator_, use_padding); + } + + + // ============================================================ + // + // Level 2 + // + // ============================================================ + + Chain::Chain(): + chain_(::FLAC__metadata_chain_new()) + { } + + Chain::~Chain() + { + clear(); + } + + void Chain::clear() + { + if(0 != chain_) + FLAC__metadata_chain_delete(chain_); + chain_ = 0; + } + + bool Chain::is_valid() const + { + return 0 != chain_; + } + + Chain::Status Chain::status() + { + FLAC__ASSERT(is_valid()); + return Status(::FLAC__metadata_chain_status(chain_)); + } + + bool Chain::read(const char *filename, bool is_ogg) + { + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(is_valid()); + return is_ogg? + (bool)::FLAC__metadata_chain_read_ogg(chain_, filename) : + (bool)::FLAC__metadata_chain_read(chain_, filename) + ; + } + + bool Chain::read(FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, bool is_ogg) + { + FLAC__ASSERT(is_valid()); + return is_ogg? + (bool)::FLAC__metadata_chain_read_ogg_with_callbacks(chain_, handle, callbacks) : + (bool)::FLAC__metadata_chain_read_with_callbacks(chain_, handle, callbacks) + ; + } + + bool Chain::check_if_tempfile_needed(bool use_padding) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_chain_check_if_tempfile_needed(chain_, use_padding); + } + + bool Chain::write(bool use_padding, bool preserve_file_stats) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_chain_write(chain_, use_padding, preserve_file_stats); + } + + bool Chain::write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_chain_write_with_callbacks(chain_, use_padding, handle, callbacks); + } + + bool Chain::write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, ::FLAC__IOHandle temp_handle, ::FLAC__IOCallbacks temp_callbacks) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain_, use_padding, handle, callbacks, temp_handle, temp_callbacks); + } + + void Chain::merge_padding() + { + FLAC__ASSERT(is_valid()); + ::FLAC__metadata_chain_merge_padding(chain_); + } + + void Chain::sort_padding() + { + FLAC__ASSERT(is_valid()); + ::FLAC__metadata_chain_sort_padding(chain_); + } + + + Iterator::Iterator(): + iterator_(::FLAC__metadata_iterator_new()) + { } + + Iterator::~Iterator() + { + clear(); + } + + void Iterator::clear() + { + if(0 != iterator_) + FLAC__metadata_iterator_delete(iterator_); + iterator_ = 0; + } + + bool Iterator::is_valid() const + { + return 0 != iterator_; + } + + void Iterator::init(Chain &chain) + { + FLAC__ASSERT(is_valid()); + FLAC__ASSERT(chain.is_valid()); + ::FLAC__metadata_iterator_init(iterator_, chain.chain_); + } + + bool Iterator::next() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_iterator_next(iterator_); + } + + bool Iterator::prev() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_iterator_prev(iterator_); + } + + ::FLAC__MetadataType Iterator::get_block_type() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__metadata_iterator_get_block_type(iterator_); + } + + Prototype *Iterator::get_block() + { + FLAC__ASSERT(is_valid()); + Prototype *block = local::construct_block(::FLAC__metadata_iterator_get_block(iterator_)); + if(0 != block) + block->set_reference(true); + return block; + } + + bool Iterator::set_block(Prototype *block) + { + FLAC__ASSERT(0 != block); + FLAC__ASSERT(is_valid()); + bool ret = (bool)::FLAC__metadata_iterator_set_block(iterator_, block->object_); + if(ret) { + block->set_reference(true); + delete block; + } + return ret; + } + + bool Iterator::delete_block(bool replace_with_padding) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__metadata_iterator_delete_block(iterator_, replace_with_padding); + } + + bool Iterator::insert_block_before(Prototype *block) + { + FLAC__ASSERT(0 != block); + FLAC__ASSERT(is_valid()); + bool ret = (bool)::FLAC__metadata_iterator_insert_block_before(iterator_, block->object_); + if(ret) { + block->set_reference(true); + delete block; + } + return ret; + } + + bool Iterator::insert_block_after(Prototype *block) + { + FLAC__ASSERT(0 != block); + FLAC__ASSERT(is_valid()); + bool ret = (bool)::FLAC__metadata_iterator_insert_block_after(iterator_, block->object_); + if(ret) { + block->set_reference(true); + delete block; + } + return ret; + } + + } +} diff --git a/flac/src/libFLAC++/stream_decoder.cpp b/flac/src/libFLAC++/stream_decoder.cpp new file mode 100644 index 0000000..7e5d1ea --- /dev/null +++ b/flac/src/libFLAC++/stream_decoder.cpp @@ -0,0 +1,389 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#include "FLAC++/decoder.h" +#include "FLAC/assert.h" + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + +namespace FLAC { + namespace Decoder { + + // ------------------------------------------------------------ + // + // Stream + // + // ------------------------------------------------------------ + + Stream::Stream(): + decoder_(::FLAC__stream_decoder_new()) + { } + + Stream::~Stream() + { + if(0 != decoder_) { + (void)::FLAC__stream_decoder_finish(decoder_); + ::FLAC__stream_decoder_delete(decoder_); + } + } + + bool Stream::is_valid() const + { + return 0 != decoder_; + } + + bool Stream::set_ogg_serial_number(long value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_ogg_serial_number(decoder_, value); + } + + bool Stream::set_md5_checking(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_md5_checking(decoder_, value); + } + + bool Stream::set_metadata_respond(::FLAC__MetadataType type) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_respond(decoder_, type); + } + + bool Stream::set_metadata_respond_application(const FLAC__byte id[4]) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_respond_application(decoder_, id); + } + + bool Stream::set_metadata_respond_all() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_respond_all(decoder_); + } + + bool Stream::set_metadata_ignore(::FLAC__MetadataType type) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_ignore(decoder_, type); + } + + bool Stream::set_metadata_ignore_application(const FLAC__byte id[4]) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_ignore_application(decoder_, id); + } + + bool Stream::set_metadata_ignore_all() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_set_metadata_ignore_all(decoder_); + } + + Stream::State Stream::get_state() const + { + FLAC__ASSERT(is_valid()); + return State(::FLAC__stream_decoder_get_state(decoder_)); + } + + bool Stream::get_md5_checking() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_get_md5_checking(decoder_); + } + + FLAC__uint64 Stream::get_total_samples() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_total_samples(decoder_); + } + + unsigned Stream::get_channels() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_channels(decoder_); + } + + ::FLAC__ChannelAssignment Stream::get_channel_assignment() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_channel_assignment(decoder_); + } + + unsigned Stream::get_bits_per_sample() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_bits_per_sample(decoder_); + } + + unsigned Stream::get_sample_rate() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_sample_rate(decoder_); + } + + unsigned Stream::get_blocksize() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_blocksize(decoder_); + } + + bool Stream::get_decode_position(FLAC__uint64 *position) const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_get_decode_position(decoder_, position); + } + + ::FLAC__StreamDecoderInitStatus Stream::init() + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_init_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamDecoderInitStatus Stream::init_ogg() + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_decoder_init_ogg_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + bool Stream::finish() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_finish(decoder_); + } + + bool Stream::flush() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_flush(decoder_); + } + + bool Stream::reset() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_reset(decoder_); + } + + bool Stream::process_single() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_process_single(decoder_); + } + + bool Stream::process_until_end_of_metadata() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_process_until_end_of_metadata(decoder_); + } + + bool Stream::process_until_end_of_stream() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_process_until_end_of_stream(decoder_); + } + + bool Stream::skip_single_frame() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_skip_single_frame(decoder_); + } + + bool Stream::seek_absolute(FLAC__uint64 sample) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_decoder_seek_absolute(decoder_, sample); + } + + ::FLAC__StreamDecoderSeekStatus Stream::seek_callback(FLAC__uint64 absolute_byte_offset) + { + (void)absolute_byte_offset; + return ::FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; + } + + ::FLAC__StreamDecoderTellStatus Stream::tell_callback(FLAC__uint64 *absolute_byte_offset) + { + (void)absolute_byte_offset; + return ::FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; + } + + ::FLAC__StreamDecoderLengthStatus Stream::length_callback(FLAC__uint64 *stream_length) + { + (void)stream_length; + return ::FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; + } + + bool Stream::eof_callback() + { + return false; + } + + void Stream::metadata_callback(const ::FLAC__StreamMetadata *metadata) + { + (void)metadata; + } + + ::FLAC__StreamDecoderReadStatus Stream::read_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) + { + (void)decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->read_callback(buffer, bytes); + } + + ::FLAC__StreamDecoderSeekStatus Stream::seek_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) + { + (void) decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->seek_callback(absolute_byte_offset); + } + + ::FLAC__StreamDecoderTellStatus Stream::tell_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) + { + (void) decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->tell_callback(absolute_byte_offset); + } + + ::FLAC__StreamDecoderLengthStatus Stream::length_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) + { + (void) decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->length_callback(stream_length); + } + + FLAC__bool Stream::eof_callback_(const ::FLAC__StreamDecoder *decoder, void *client_data) + { + (void) decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->eof_callback(); + } + + ::FLAC__StreamDecoderWriteStatus Stream::write_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) + { + (void)decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->write_callback(frame, buffer); + } + + void Stream::metadata_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *client_data) + { + (void)decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + instance->metadata_callback(metadata); + } + + void Stream::error_callback_(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data) + { + (void)decoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + instance->error_callback(status); + } + + // ------------------------------------------------------------ + // + // File + // + // ------------------------------------------------------------ + + File::File(): + Stream() + { } + + File::~File() + { + } + + ::FLAC__StreamDecoderInitStatus File::init(FILE *file) + { + FLAC__ASSERT(0 != decoder_); + return ::FLAC__stream_decoder_init_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamDecoderInitStatus File::init(const char *filename) + { + FLAC__ASSERT(0 != decoder_); + return ::FLAC__stream_decoder_init_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamDecoderInitStatus File::init(const std::string &filename) + { + return init(filename.c_str()); + } + + ::FLAC__StreamDecoderInitStatus File::init_ogg(FILE *file) + { + FLAC__ASSERT(0 != decoder_); + return ::FLAC__stream_decoder_init_ogg_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamDecoderInitStatus File::init_ogg(const char *filename) + { + FLAC__ASSERT(0 != decoder_); + return ::FLAC__stream_decoder_init_ogg_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamDecoderInitStatus File::init_ogg(const std::string &filename) + { + return init_ogg(filename.c_str()); + } + + // This is a dummy to satisfy the pure virtual from Stream; the + // read callback will never be called since we are initializing + // with FLAC__stream_decoder_init_FILE() or + // FLAC__stream_decoder_init_file() and those supply the read + // callback internally. + ::FLAC__StreamDecoderReadStatus File::read_callback(FLAC__byte buffer[], size_t *bytes) + { + (void)buffer, (void)bytes; + FLAC__ASSERT(false); + return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; // double protection + } + + } +} diff --git a/flac/src/libFLAC++/stream_encoder.cpp b/flac/src/libFLAC++/stream_encoder.cpp new file mode 100644 index 0000000..a21a0ac --- /dev/null +++ b/flac/src/libFLAC++/stream_encoder.cpp @@ -0,0 +1,511 @@ +/* libFLAC++ - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#include "FLAC++/encoder.h" +#include "FLAC++/metadata.h" +#include "FLAC/assert.h" + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + +namespace FLAC { + namespace Encoder { + + // ------------------------------------------------------------ + // + // Stream + // + // ------------------------------------------------------------ + + Stream::Stream(): + encoder_(::FLAC__stream_encoder_new()) + { } + + Stream::~Stream() + { + if(0 != encoder_) { + (void)::FLAC__stream_encoder_finish(encoder_); + ::FLAC__stream_encoder_delete(encoder_); + } + } + + bool Stream::is_valid() const + { + return 0 != encoder_; + } + + bool Stream::set_ogg_serial_number(long value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_ogg_serial_number(encoder_, value); + } + + bool Stream::set_verify(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_verify(encoder_, value); + } + + bool Stream::set_streamable_subset(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_streamable_subset(encoder_, value); + } + + bool Stream::set_channels(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_channels(encoder_, value); + } + + bool Stream::set_bits_per_sample(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_bits_per_sample(encoder_, value); + } + + bool Stream::set_sample_rate(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_sample_rate(encoder_, value); + } + + bool Stream::set_compression_level(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_compression_level(encoder_, value); + } + + bool Stream::set_blocksize(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_blocksize(encoder_, value); + } + + bool Stream::set_do_mid_side_stereo(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_do_mid_side_stereo(encoder_, value); + } + + bool Stream::set_loose_mid_side_stereo(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_, value); + } + + bool Stream::set_apodization(const char *specification) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_apodization(encoder_, specification); + } + + bool Stream::set_max_lpc_order(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_max_lpc_order(encoder_, value); + } + + bool Stream::set_qlp_coeff_precision(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_qlp_coeff_precision(encoder_, value); + } + + bool Stream::set_do_qlp_coeff_prec_search(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_, value); + } + + bool Stream::set_do_escape_coding(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_do_escape_coding(encoder_, value); + } + + bool Stream::set_do_exhaustive_model_search(bool value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_, value); + } + + bool Stream::set_min_residual_partition_order(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_min_residual_partition_order(encoder_, value); + } + + bool Stream::set_max_residual_partition_order(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_max_residual_partition_order(encoder_, value); + } + + bool Stream::set_rice_parameter_search_dist(unsigned value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_, value); + } + + bool Stream::set_total_samples_estimate(FLAC__uint64 value) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_total_samples_estimate(encoder_, value); + } + + bool Stream::set_metadata(::FLAC__StreamMetadata **metadata, unsigned num_blocks) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_set_metadata(encoder_, metadata, num_blocks); + } + + bool Stream::set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks) + { + FLAC__ASSERT(is_valid()); +#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __SUNPRO_CC) + // MSVC++ can't handle: + // ::FLAC__StreamMetadata *m[num_blocks]; + // so we do this ugly workaround + ::FLAC__StreamMetadata **m = new ::FLAC__StreamMetadata*[num_blocks]; +#else + ::FLAC__StreamMetadata *m[num_blocks]; +#endif + for(unsigned i = 0; i < num_blocks; i++) { + // we can get away with the const_cast since we know the encoder will only correct the is_last flags + m[i] = const_cast< ::FLAC__StreamMetadata*>((const ::FLAC__StreamMetadata*)metadata[i]); + } +#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __SUNPRO_CC) + // complete the hack + const bool ok = (bool)::FLAC__stream_encoder_set_metadata(encoder_, m, num_blocks); + delete [] m; + return ok; +#else + return (bool)::FLAC__stream_encoder_set_metadata(encoder_, m, num_blocks); +#endif + } + + Stream::State Stream::get_state() const + { + FLAC__ASSERT(is_valid()); + return State(::FLAC__stream_encoder_get_state(encoder_)); + } + + Decoder::Stream::State Stream::get_verify_decoder_state() const + { + FLAC__ASSERT(is_valid()); + return Decoder::Stream::State(::FLAC__stream_encoder_get_verify_decoder_state(encoder_)); + } + + void Stream::get_verify_decoder_error_stats(FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got) + { + FLAC__ASSERT(is_valid()); + ::FLAC__stream_encoder_get_verify_decoder_error_stats(encoder_, absolute_sample, frame_number, channel, sample, expected, got); + } + + bool Stream::get_verify() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_verify(encoder_); + } + + bool Stream::get_streamable_subset() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_streamable_subset(encoder_); + } + + bool Stream::get_do_mid_side_stereo() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_do_mid_side_stereo(encoder_); + } + + bool Stream::get_loose_mid_side_stereo() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_loose_mid_side_stereo(encoder_); + } + + unsigned Stream::get_channels() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_channels(encoder_); + } + + unsigned Stream::get_bits_per_sample() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_bits_per_sample(encoder_); + } + + unsigned Stream::get_sample_rate() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_sample_rate(encoder_); + } + + unsigned Stream::get_blocksize() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_blocksize(encoder_); + } + + unsigned Stream::get_max_lpc_order() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_max_lpc_order(encoder_); + } + + unsigned Stream::get_qlp_coeff_precision() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_qlp_coeff_precision(encoder_); + } + + bool Stream::get_do_qlp_coeff_prec_search() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder_); + } + + bool Stream::get_do_escape_coding() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_do_escape_coding(encoder_); + } + + bool Stream::get_do_exhaustive_model_search() const + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_get_do_exhaustive_model_search(encoder_); + } + + unsigned Stream::get_min_residual_partition_order() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_min_residual_partition_order(encoder_); + } + + unsigned Stream::get_max_residual_partition_order() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_max_residual_partition_order(encoder_); + } + + unsigned Stream::get_rice_parameter_search_dist() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_rice_parameter_search_dist(encoder_); + } + + FLAC__uint64 Stream::get_total_samples_estimate() const + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_get_total_samples_estimate(encoder_); + } + + ::FLAC__StreamEncoderInitStatus Stream::init() + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_stream(encoder_, write_callback_, seek_callback_, tell_callback_, metadata_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamEncoderInitStatus Stream::init_ogg() + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_ogg_stream(encoder_, read_callback_, write_callback_, seek_callback_, tell_callback_, metadata_callback_, /*client_data=*/(void*)this); + } + + bool Stream::finish() + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_finish(encoder_); + } + + bool Stream::process(const FLAC__int32 * const buffer[], unsigned samples) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_process(encoder_, buffer, samples); + } + + bool Stream::process_interleaved(const FLAC__int32 buffer[], unsigned samples) + { + FLAC__ASSERT(is_valid()); + return (bool)::FLAC__stream_encoder_process_interleaved(encoder_, buffer, samples); + } + + ::FLAC__StreamEncoderReadStatus Stream::read_callback(FLAC__byte buffer[], size_t *bytes) + { + (void)buffer, (void)bytes; + return ::FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED; + } + + ::FLAC__StreamEncoderSeekStatus Stream::seek_callback(FLAC__uint64 absolute_byte_offset) + { + (void)absolute_byte_offset; + return ::FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED; + } + + ::FLAC__StreamEncoderTellStatus Stream::tell_callback(FLAC__uint64 *absolute_byte_offset) + { + (void)absolute_byte_offset; + return ::FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED; + } + + void Stream::metadata_callback(const ::FLAC__StreamMetadata *metadata) + { + (void)metadata; + } + + ::FLAC__StreamEncoderReadStatus Stream::read_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->read_callback(buffer, bytes); + } + + ::FLAC__StreamEncoderWriteStatus Stream::write_callback_(const ::FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->write_callback(buffer, bytes, samples, current_frame); + } + + ::FLAC__StreamEncoderSeekStatus Stream::seek_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->seek_callback(absolute_byte_offset); + } + + ::FLAC__StreamEncoderTellStatus Stream::tell_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + return instance->tell_callback(absolute_byte_offset); + } + + void Stream::metadata_callback_(const ::FLAC__StreamEncoder *encoder, const ::FLAC__StreamMetadata *metadata, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + Stream *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + instance->metadata_callback(metadata); + } + + // ------------------------------------------------------------ + // + // File + // + // ------------------------------------------------------------ + + File::File(): + Stream() + { } + + File::~File() + { + } + + ::FLAC__StreamEncoderInitStatus File::init(FILE *file) + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_FILE(encoder_, file, progress_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamEncoderInitStatus File::init(const char *filename) + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_file(encoder_, filename, progress_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamEncoderInitStatus File::init(const std::string &filename) + { + return init(filename.c_str()); + } + + ::FLAC__StreamEncoderInitStatus File::init_ogg(FILE *file) + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_ogg_FILE(encoder_, file, progress_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamEncoderInitStatus File::init_ogg(const char *filename) + { + FLAC__ASSERT(is_valid()); + return ::FLAC__stream_encoder_init_ogg_file(encoder_, filename, progress_callback_, /*client_data=*/(void*)this); + } + + ::FLAC__StreamEncoderInitStatus File::init_ogg(const std::string &filename) + { + return init_ogg(filename.c_str()); + } + + // This is a dummy to satisfy the pure virtual from Stream; the + // read callback will never be called since we are initializing + // with FLAC__stream_decoder_init_FILE() or + // FLAC__stream_decoder_init_file() and those supply the read + // callback internally. + ::FLAC__StreamEncoderWriteStatus File::write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame) + { + (void)buffer, (void)bytes, (void)samples, (void)current_frame; + FLAC__ASSERT(false); + return ::FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; // double protection + } + + void File::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate) + { + (void)bytes_written, (void)samples_written, (void)frames_written, (void)total_frames_estimate; + } + + void File::progress_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data) + { + (void)encoder; + FLAC__ASSERT(0 != client_data); + File *instance = reinterpret_cast(client_data); + FLAC__ASSERT(0 != instance); + instance->progress_callback(bytes_written, samples_written, frames_written, total_frames_estimate); + } + + } +} diff --git a/flac/src/libFLAC/Makefile.am b/flac/src/libFLAC/Makefile.am new file mode 100644 index 0000000..a44ed5b --- /dev/null +++ b/flac/src/libFLAC/Makefile.am @@ -0,0 +1,118 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +lib_LTLIBRARIES = libFLAC.la +if DEBUG +DEBUGCFLAGS = -DFLAC__OVERFLOW_DETECT +endif +if FLaC__CPU_PPC +# The -force_cpusubtype_ALL is needed to insert a ppc64 instruction +# into cpu.c with an asm(). +if FLaC__SYS_DARWIN +#@@@ PPC optimizations temporarily disabled +CPUCFLAGS = -faltivec -force_cpusubtype_ALL -DFLAC__NO_ASM +else +# Linux-gcc for PPC does not have -force_cpusubtype_ALL, it is Darwin-specific +#@@@ PPC optimizations temporarily disabled +CPUCFLAGS = -maltivec -mabi=altivec -DFLAC__NO_ASM +endif +endif + +AM_CFLAGS = $(DEBUGCFLAGS) $(CPUCFLAGS) @OGG_CFLAGS@ + +if FLaC__NO_ASM +else +if FLaC__CPU_IA32 +if FLaC__HAS_NASM +ARCH_SUBDIRS = ia32 +LOCAL_EXTRA_LIBADD = ia32/libFLAC-asm.la +endif +endif +if FLaC__CPU_PPC +ARCH_SUBDIRS = ppc +if FLaC__HAS_AS__TEMPORARILY_DISABLED +LOCAL_EXTRA_LIBADD = ppc/as/libFLAC-asm.la +LOCAL_EXTRA_LDFLAGS = "-Wl,-read_only_relocs,warning" +else +if FLaC__HAS_GAS__TEMPORARILY_DISABLED +LOCAL_EXTRA_LIBADD = ppc/gas/libFLAC-asm.la +LOCAL_EXTRA_LDFLAGS = "" +endif +endif +endif +endif + +libFLAC_la_LIBADD = $(LOCAL_EXTRA_LIBADD) @OGG_LIBS@ + +SUBDIRS = $(ARCH_SUBDIRS) include . + +m4datadir = $(datadir)/aclocal +m4data_DATA = libFLAC.m4 + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = flac.pc + +EXTRA_DIST = \ + Makefile.lite \ + flac.pc.in \ + libFLAC_dynamic.dsp \ + libFLAC_dynamic.vcproj \ + libFLAC_static.dsp \ + libFLAC_static.vcproj \ + libFLAC.m4 + +if FLaC__HAS_OGG +extra_ogg_sources = \ + ogg_decoder_aspect.c \ + ogg_encoder_aspect.c \ + ogg_helper.c \ + ogg_mapping.c +endif +# see 'http://www.gnu.org/software/libtool/manual.html#Libtool-versioning' for numbering convention +libFLAC_la_LDFLAGS = -version-info 10:0:2 -lm $(LOCAL_EXTRA_LDFLAGS) +libFLAC_la_SOURCES = \ + bitmath.c \ + bitreader.c \ + bitwriter.c \ + cpu.c \ + crc.c \ + fixed.c \ + float.c \ + format.c \ + lpc.c \ + md5.c \ + memory.c \ + metadata_iterators.c \ + metadata_object.c \ + stream_decoder.c \ + stream_encoder.c \ + stream_encoder_framing.c \ + window.c \ + $(extra_ogg_sources) diff --git a/flac/src/libFLAC/Makefile.lite b/flac/src/libFLAC/Makefile.lite new file mode 100644 index 0000000..37a6abe --- /dev/null +++ b/flac/src/libFLAC/Makefile.lite @@ -0,0 +1,93 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +# +# GNU makefile +# + +topdir = ../.. + +LIB_NAME = libFLAC +ifeq ($(OS),Darwin) +DEFINES = -DFLAC__CPU_PPC -DFLAC__USE_ALTIVEC -DFLAC__ALIGN_MALLOC_DATA +else +ifeq ($(OS),Solaris) +DEFINES = -DFLAC__NO_ASM -DFLAC__ALIGN_MALLOC_DATA +else +ifeq ($(PROC),i386) +DEFINES = -DFLAC__CPU_IA32 -DFLAC__USE_3DNOW -DFLAC__HAS_NASM -DFLAC__ALIGN_MALLOC_DATA +else +DEFINES = -DFLAC__ALIGN_MALLOC_DATA +endif +endif +endif +INCLUDES = -I./include -I$(topdir)/include -I$(OGG_INCLUDE_DIR) +DEBUG_CFLAGS = -DFLAC__OVERFLOW_DETECT + +ifeq ($(OS),Darwin) +SRCS_S = \ + ppc/as/lpc_asm.s +else +ifeq ($(PROC),i386) +SRCS_NASM = \ + ia32/bitreader_asm.nasm \ + ia32/cpu_asm.nasm \ + ia32/fixed_asm.nasm \ + ia32/lpc_asm.nasm \ + ia32/stream_encoder_asm.nasm +endif +endif + +SRCS_C = \ + bitmath.c \ + bitreader.c \ + bitwriter.c \ + cpu.c \ + crc.c \ + fixed.c \ + float.c \ + format.c \ + lpc.c \ + md5.c \ + memory.c \ + metadata_iterators.c \ + metadata_object.c \ + ogg_decoder_aspect.c \ + ogg_encoder_aspect.c \ + ogg_helper.c \ + ogg_mapping.c \ + stream_decoder.c \ + stream_encoder.c \ + stream_encoder_framing.c \ + window.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/libFLAC/bitmath.c b/flac/src/libFLAC/bitmath.c new file mode 100644 index 0000000..4fca42f --- /dev/null +++ b/flac/src/libFLAC/bitmath.c @@ -0,0 +1,149 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "private/bitmath.h" +#include "FLAC/assert.h" + +/* An example of what FLAC__bitmath_ilog2() computes: + * + * ilog2( 0) = assertion failure + * ilog2( 1) = 0 + * ilog2( 2) = 1 + * ilog2( 3) = 1 + * ilog2( 4) = 2 + * ilog2( 5) = 2 + * ilog2( 6) = 2 + * ilog2( 7) = 2 + * ilog2( 8) = 3 + * ilog2( 9) = 3 + * ilog2(10) = 3 + * ilog2(11) = 3 + * ilog2(12) = 3 + * ilog2(13) = 3 + * ilog2(14) = 3 + * ilog2(15) = 3 + * ilog2(16) = 4 + * ilog2(17) = 4 + * ilog2(18) = 4 + */ +unsigned FLAC__bitmath_ilog2(FLAC__uint32 v) +{ + unsigned l = 0; + FLAC__ASSERT(v > 0); + while(v >>= 1) + l++; + return l; +} + +unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v) +{ + unsigned l = 0; + FLAC__ASSERT(v > 0); + while(v >>= 1) + l++; + return l; +} + +/* An example of what FLAC__bitmath_silog2() computes: + * + * silog2(-10) = 5 + * silog2(- 9) = 5 + * silog2(- 8) = 4 + * silog2(- 7) = 4 + * silog2(- 6) = 4 + * silog2(- 5) = 4 + * silog2(- 4) = 3 + * silog2(- 3) = 3 + * silog2(- 2) = 2 + * silog2(- 1) = 2 + * silog2( 0) = 0 + * silog2( 1) = 2 + * silog2( 2) = 3 + * silog2( 3) = 3 + * silog2( 4) = 4 + * silog2( 5) = 4 + * silog2( 6) = 4 + * silog2( 7) = 4 + * silog2( 8) = 5 + * silog2( 9) = 5 + * silog2( 10) = 5 + */ +unsigned FLAC__bitmath_silog2(int v) +{ + while(1) { + if(v == 0) { + return 0; + } + else if(v > 0) { + unsigned l = 0; + while(v) { + l++; + v >>= 1; + } + return l+1; + } + else if(v == -1) { + return 2; + } + else { + v++; + v = -v; + } + } +} + +unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v) +{ + while(1) { + if(v == 0) { + return 0; + } + else if(v > 0) { + unsigned l = 0; + while(v) { + l++; + v >>= 1; + } + return l+1; + } + else if(v == -1) { + return 2; + } + else { + v++; + v = -v; + } + } +} diff --git a/flac/src/libFLAC/bitreader.c b/flac/src/libFLAC/bitreader.c new file mode 100644 index 0000000..efb77cc --- /dev/null +++ b/flac/src/libFLAC/bitreader.c @@ -0,0 +1,1380 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for malloc() */ +#include /* for memcpy(), memset() */ +#ifdef _MSC_VER +#include /* for ntohl() */ +#elif defined FLAC__SYS_DARWIN +#include /* for ntohl() */ +#elif defined __MINGW32__ +#include /* for ntohl() */ +#else +#include /* for ntohl() */ +#endif +#include "private/bitmath.h" +#include "private/bitreader.h" +#include "private/crc.h" +#include "FLAC/assert.h" + +/* Things should be fastest when this matches the machine word size */ +/* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */ +/* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */ +/* also, some sections currently only have fast versions for 4 or 8 bytes per word */ +typedef FLAC__uint32 brword; +#define FLAC__BYTES_PER_WORD 4 +#define FLAC__BITS_PER_WORD 32 +#define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff) +/* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */ +#if WORDS_BIGENDIAN +#define SWAP_BE_WORD_TO_HOST(x) (x) +#else +#ifdef _MSC_VER +#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x) +#else +#define SWAP_BE_WORD_TO_HOST(x) ntohl(x) +#endif +#endif +/* counts the # of zero MSBs in a word */ +#define COUNT_ZERO_MSBS(word) ( \ + (word) <= 0xffff ? \ + ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \ + ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \ +) +/* this alternate might be slightly faster on some systems/compilers: */ +#define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) ) + + +/* + * This should be at least twice as large as the largest number of words + * required to represent any 'number' (in any encoding) you are going to + * read. With FLAC this is on the order of maybe a few hundred bits. + * If the buffer is smaller than that, the decoder won't be able to read + * in a whole number that is in a variable length encoding (e.g. Rice). + * But to be practical it should be at least 1K bytes. + * + * Increase this number to decrease the number of read callbacks, at the + * expense of using more memory. Or decrease for the reverse effect, + * keeping in mind the limit from the first paragraph. The optimal size + * also depends on the CPU cache size and other factors; some twiddling + * may be necessary to squeeze out the best performance. + */ +static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */ + +static const unsigned char byte_to_unary_table[] = { + 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) +#ifdef max +#undef max +#endif +#define max(x,y) ((x)>(y)?(x):(y)) + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +/* WATCHOUT: assembly routines rely on the order in which these fields are declared */ +struct FLAC__BitReader { + /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */ + /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */ + brword *buffer; + unsigned capacity; /* in words */ + unsigned words; /* # of completed words in buffer */ + unsigned bytes; /* # of bytes in incomplete word at buffer[words] */ + unsigned consumed_words; /* #words ... */ + unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */ + unsigned read_crc16; /* the running frame CRC */ + unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */ + FLAC__BitReaderReadCallback read_callback; + void *client_data; + FLAC__CPUInfo cpu_info; +}; + +#ifdef _MSC_VER +/* OPT: an MSVC built-in would be better */ +/* OPT: use _byteswap_ulong intrinsic? */ +static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x) +{ + x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); + return (x>>16) | (x<<16); +} +#ifdef _WIN64 +#else +static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len) +{ + __asm { + mov edx, start + mov ecx, len + test ecx, ecx +loop1: + jz done1 + mov eax, [edx] + bswap eax + mov [edx], eax + add edx, 4 + dec ecx + jmp short loop1 +done1: + } +} +#endif +#endif + +static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word) +{ + register unsigned crc = br->read_crc16; +#if FLAC__BYTES_PER_WORD == 4 + switch(br->crc16_align) { + case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc); + case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc); + case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc); + case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc); + } +#elif FLAC__BYTES_PER_WORD == 8 + switch(br->crc16_align) { + case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc); + case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc); + case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc); + case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc); + case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc); + case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc); + case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc); + case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc); + } +#else + for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8) + crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc); + br->read_crc16 = crc; +#endif + br->crc16_align = 0; +} + +/* would be static except it needs to be called by asm routines */ +FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br) +{ + unsigned start, end; + size_t bytes; + FLAC__byte *target; + + /* first shift the unconsumed buffer data toward the front as much as possible */ + if(br->consumed_words > 0) { + start = br->consumed_words; + end = br->words + (br->bytes? 1:0); + memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start)); + + br->words -= start; + br->consumed_words = 0; + } + + /* + * set the target for reading, taking into account word alignment and endianness + */ + bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes; + if(bytes == 0) + return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */ + target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes; + + /* before reading, if the existing reader looks like this (say brword is 32 bits wide) + * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified) + * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory) + * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care) + * ^^-------target, bytes=3 + * on LE machines, have to byteswap the odd tail word so nothing is + * overwritten: + */ +#if WORDS_BIGENDIAN +#else + if(br->bytes) + br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]); +#endif + + /* now it looks like: + * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 + * buffer[BE]: 11 22 33 44 55 ?? ?? ?? + * buffer[LE]: 44 33 22 11 55 ?? ?? ?? + * ^^-------target, bytes=3 + */ + + /* read in the data; note that the callback may return a smaller number of bytes */ + if(!br->read_callback(target, &bytes, br->client_data)) + return false; + + /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client: + * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF + * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ?? + * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ?? + * now have to byteswap on LE machines: + */ +#if WORDS_BIGENDIAN +#else + end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD; +# if defined(_MSC_VER) && !defined(_WIN64) && (FLAC__BYTES_PER_WORD == 4) + if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) { + start = br->words; + local_swap32_block_(br->buffer + start, end - start); + } + else +# endif + for(start = br->words; start < end; start++) + br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]); +#endif + + /* now it looks like: + * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF + * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ?? + * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD + * finally we'll update the reader values: + */ + end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes; + br->words = end / FLAC__BYTES_PER_WORD; + br->bytes = end % FLAC__BYTES_PER_WORD; + + return true; +} + +/*********************************************************************** + * + * Class constructor/destructor + * + ***********************************************************************/ + +FLAC__BitReader *FLAC__bitreader_new(void) +{ + FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader)); + + /* calloc() implies: + memset(br, 0, sizeof(FLAC__BitReader)); + br->buffer = 0; + br->capacity = 0; + br->words = br->bytes = 0; + br->consumed_words = br->consumed_bits = 0; + br->read_callback = 0; + br->client_data = 0; + */ + return br; +} + +void FLAC__bitreader_delete(FLAC__BitReader *br) +{ + FLAC__ASSERT(0 != br); + + FLAC__bitreader_free(br); + free(br); +} + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd) +{ + FLAC__ASSERT(0 != br); + + br->words = br->bytes = 0; + br->consumed_words = br->consumed_bits = 0; + br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY; + br->buffer = (brword*)malloc(sizeof(brword) * br->capacity); + if(br->buffer == 0) + return false; + br->read_callback = rcb; + br->client_data = cd; + br->cpu_info = cpu; + + return true; +} + +void FLAC__bitreader_free(FLAC__BitReader *br) +{ + FLAC__ASSERT(0 != br); + + if(0 != br->buffer) + free(br->buffer); + br->buffer = 0; + br->capacity = 0; + br->words = br->bytes = 0; + br->consumed_words = br->consumed_bits = 0; + br->read_callback = 0; + br->client_data = 0; +} + +FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br) +{ + br->words = br->bytes = 0; + br->consumed_words = br->consumed_bits = 0; + return true; +} + +void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out) +{ + unsigned i, j; + if(br == 0) { + fprintf(out, "bitreader is NULL\n"); + } + else { + fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits); + + for(i = 0; i < br->words; i++) { + fprintf(out, "%08X: ", i); + for(j = 0; j < FLAC__BITS_PER_WORD; j++) + if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits)) + fprintf(out, "."); + else + fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0); + fprintf(out, "\n"); + } + if(br->bytes > 0) { + fprintf(out, "%08X: ", i); + for(j = 0; j < br->bytes*8; j++) + if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits)) + fprintf(out, "."); + else + fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0); + fprintf(out, "\n"); + } + } +} + +void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed) +{ + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + FLAC__ASSERT((br->consumed_bits & 7) == 0); + + br->read_crc16 = (unsigned)seed; + br->crc16_align = br->consumed_bits; +} + +FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br) +{ + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + FLAC__ASSERT((br->consumed_bits & 7) == 0); + FLAC__ASSERT(br->crc16_align <= br->consumed_bits); + + /* CRC any tail bytes in a partially-consumed word */ + if(br->consumed_bits) { + const brword tail = br->buffer[br->consumed_words]; + for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8) + br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16); + } + return br->read_crc16; +} + +FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br) +{ + return ((br->consumed_bits & 7) == 0); +} + +FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br) +{ + return 8 - (br->consumed_bits & 7); +} + +FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br) +{ + return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits; +} + +FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits) +{ + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + FLAC__ASSERT(bits <= 32); + FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits); + FLAC__ASSERT(br->consumed_words <= br->words); + + /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ + FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); + + if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */ + *val = 0; + return true; + } + + while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) { + if(!bitreader_read_from_client_(br)) + return false; + } + if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */ + /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */ + if(br->consumed_bits) { + /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits; + const brword word = br->buffer[br->consumed_words]; + if(bits < n) { + *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits); + br->consumed_bits += bits; + return true; + } + *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits); + bits -= n; + crc16_update_word_(br, word); + br->consumed_words++; + br->consumed_bits = 0; + if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */ + *val <<= bits; + *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits)); + br->consumed_bits = bits; + } + return true; + } + else { + const brword word = br->buffer[br->consumed_words]; + if(bits < FLAC__BITS_PER_WORD) { + *val = word >> (FLAC__BITS_PER_WORD-bits); + br->consumed_bits = bits; + return true; + } + /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */ + *val = word; + crc16_update_word_(br, word); + br->consumed_words++; + return true; + } + } + else { + /* in this case we're starting our read at a partial tail word; + * the reader has guaranteed that we have at least 'bits' bits + * available to read, which makes this case simpler. + */ + /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */ + if(br->consumed_bits) { + /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8); + *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits); + br->consumed_bits += bits; + return true; + } + else { + *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits); + br->consumed_bits += bits; + return true; + } + } +} + +FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits) +{ + /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */ + if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits)) + return false; + /* sign-extend: */ + *val <<= (32-bits); + *val >>= (32-bits); + return true; +} + +FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits) +{ + FLAC__uint32 hi, lo; + + if(bits > 32) { + if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32)) + return false; + if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32)) + return false; + *val = hi; + *val <<= 32; + *val |= lo; + } + else { + if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits)) + return false; + *val = lo; + } + return true; +} + +FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val) +{ + FLAC__uint32 x8, x32 = 0; + + /* this doesn't need to be that fast as currently it is only used for vorbis comments */ + + if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8)) + return false; + + if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8)) + return false; + x32 |= (x8 << 8); + + if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8)) + return false; + x32 |= (x8 << 16); + + if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8)) + return false; + x32 |= (x8 << 24); + + *val = x32; + return true; +} + +FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits) +{ + /* + * OPT: a faster implementation is possible but probably not that useful + * since this is only called a couple of times in the metadata readers. + */ + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + if(bits > 0) { + const unsigned n = br->consumed_bits & 7; + unsigned m; + FLAC__uint32 x; + + if(n != 0) { + m = min(8-n, bits); + if(!FLAC__bitreader_read_raw_uint32(br, &x, m)) + return false; + bits -= m; + } + m = bits / 8; + if(m > 0) { + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m)) + return false; + bits %= 8; + } + if(bits > 0) { + if(!FLAC__bitreader_read_raw_uint32(br, &x, bits)) + return false; + } + } + + return true; +} + +FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals) +{ + FLAC__uint32 x; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br)); + + /* step 1: skip over partial head word to get word aligned */ + while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */ + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + nvals--; + } + if(0 == nvals) + return true; + /* step 2: skip whole words in chunks */ + while(nvals >= FLAC__BYTES_PER_WORD) { + if(br->consumed_words < br->words) { + br->consumed_words++; + nvals -= FLAC__BYTES_PER_WORD; + } + else if(!bitreader_read_from_client_(br)) + return false; + } + /* step 3: skip any remainder from partial tail bytes */ + while(nvals) { + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + nvals--; + } + + return true; +} + +FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals) +{ + FLAC__uint32 x; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br)); + + /* step 1: read from partial head word to get word aligned */ + while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */ + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + *val++ = (FLAC__byte)x; + nvals--; + } + if(0 == nvals) + return true; + /* step 2: read whole words in chunks */ + while(nvals >= FLAC__BYTES_PER_WORD) { + if(br->consumed_words < br->words) { + const brword word = br->buffer[br->consumed_words++]; +#if FLAC__BYTES_PER_WORD == 4 + val[0] = (FLAC__byte)(word >> 24); + val[1] = (FLAC__byte)(word >> 16); + val[2] = (FLAC__byte)(word >> 8); + val[3] = (FLAC__byte)word; +#elif FLAC__BYTES_PER_WORD == 8 + val[0] = (FLAC__byte)(word >> 56); + val[1] = (FLAC__byte)(word >> 48); + val[2] = (FLAC__byte)(word >> 40); + val[3] = (FLAC__byte)(word >> 32); + val[4] = (FLAC__byte)(word >> 24); + val[5] = (FLAC__byte)(word >> 16); + val[6] = (FLAC__byte)(word >> 8); + val[7] = (FLAC__byte)word; +#else + for(x = 0; x < FLAC__BYTES_PER_WORD; x++) + val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1))); +#endif + val += FLAC__BYTES_PER_WORD; + nvals -= FLAC__BYTES_PER_WORD; + } + else if(!bitreader_read_from_client_(br)) + return false; + } + /* step 3: read any remainder from partial tail bytes */ + while(nvals) { + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + *val++ = (FLAC__byte)x; + nvals--; + } + + return true; +} + +FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val) +#if 0 /* slow but readable version */ +{ + unsigned bit; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + *val = 0; + while(1) { + if(!FLAC__bitreader_read_bit(br, &bit)) + return false; + if(bit) + break; + else + *val++; + } + return true; +} +#else +{ + unsigned i; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + *val = 0; + while(1) { + while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */ + brword b = br->buffer[br->consumed_words] << br->consumed_bits; + if(b) { + i = COUNT_ZERO_MSBS(b); + *val += i; + i++; + br->consumed_bits += i; + if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */ + crc16_update_word_(br, br->buffer[br->consumed_words]); + br->consumed_words++; + br->consumed_bits = 0; + } + return true; + } + else { + *val += FLAC__BITS_PER_WORD - br->consumed_bits; + crc16_update_word_(br, br->buffer[br->consumed_words]); + br->consumed_words++; + br->consumed_bits = 0; + /* didn't find stop bit yet, have to keep going... */ + } + } + /* at this point we've eaten up all the whole words; have to try + * reading through any tail bytes before calling the read callback. + * this is a repeat of the above logic adjusted for the fact we + * don't have a whole word. note though if the client is feeding + * us data a byte at a time (unlikely), br->consumed_bits may not + * be zero. + */ + if(br->bytes) { + const unsigned end = br->bytes * 8; + brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits; + if(b) { + i = COUNT_ZERO_MSBS(b); + *val += i; + i++; + br->consumed_bits += i; + FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD); + return true; + } + else { + *val += end - br->consumed_bits; + br->consumed_bits += end; + FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD); + /* didn't find stop bit yet, have to keep going... */ + } + } + if(!bitreader_read_from_client_(br)) + return false; + } +} +#endif + +FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter) +{ + FLAC__uint32 lsbs = 0, msbs = 0; + unsigned uval; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + FLAC__ASSERT(parameter <= 31); + + /* read the unary MSBs and end bit */ + if(!FLAC__bitreader_read_unary_unsigned(br, &msbs)) + return false; + + /* read the binary LSBs */ + if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter)) + return false; + + /* compose the value */ + uval = (msbs << parameter) | lsbs; + if(uval & 1) + *val = -((int)(uval >> 1)) - 1; + else + *val = (int)(uval >> 1); + + return true; +} + +/* this is by far the most heavily used reader call. it ain't pretty but it's fast */ +/* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */ +FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter) +/* OPT: possibly faster version for use with MSVC */ +#ifdef _MSC_VER +{ + unsigned i; + unsigned uval = 0; + unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */ + + /* try and get br->consumed_words and br->consumed_bits into register; + * must remember to flush them back to *br before calling other + * bitwriter functions that use them, and before returning */ + register unsigned cwords; + register unsigned cbits; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ + FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); + FLAC__ASSERT(parameter < 32); + /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */ + + if(nvals == 0) + return true; + + cbits = br->consumed_bits; + cwords = br->consumed_words; + + while(1) { + + /* read unary part */ + while(1) { + while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */ + brword b = br->buffer[cwords] << cbits; + if(b) { +#if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 + __asm { + bsr eax, b + not eax + and eax, 31 + mov i, eax + } +#else + i = COUNT_ZERO_MSBS(b); +#endif + uval += i; + bits = parameter; + i++; + cbits += i; + if(cbits == FLAC__BITS_PER_WORD) { + crc16_update_word_(br, br->buffer[cwords]); + cwords++; + cbits = 0; + } + goto break1; + } + else { + uval += FLAC__BITS_PER_WORD - cbits; + crc16_update_word_(br, br->buffer[cwords]); + cwords++; + cbits = 0; + /* didn't find stop bit yet, have to keep going... */ + } + } + /* at this point we've eaten up all the whole words; have to try + * reading through any tail bytes before calling the read callback. + * this is a repeat of the above logic adjusted for the fact we + * don't have a whole word. note though if the client is feeding + * us data a byte at a time (unlikely), br->consumed_bits may not + * be zero. + */ + if(br->bytes) { + const unsigned end = br->bytes * 8; + brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits; + if(b) { + i = COUNT_ZERO_MSBS(b); + uval += i; + bits = parameter; + i++; + cbits += i; + FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD); + goto break1; + } + else { + uval += end - cbits; + cbits += end; + FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD); + /* didn't find stop bit yet, have to keep going... */ + } + } + /* flush registers and read; bitreader_read_from_client_() does + * not touch br->consumed_bits at all but we still need to set + * it in case it fails and we have to return false. + */ + br->consumed_bits = cbits; + br->consumed_words = cwords; + if(!bitreader_read_from_client_(br)) + return false; + cwords = br->consumed_words; + } +break1: + /* read binary part */ + FLAC__ASSERT(cwords <= br->words); + + if(bits) { + while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) { + /* flush registers and read; bitreader_read_from_client_() does + * not touch br->consumed_bits at all but we still need to set + * it in case it fails and we have to return false. + */ + br->consumed_bits = cbits; + br->consumed_words = cwords; + if(!bitreader_read_from_client_(br)) + return false; + cwords = br->consumed_words; + } + if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */ + if(cbits) { + /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + const unsigned n = FLAC__BITS_PER_WORD - cbits; + const brword word = br->buffer[cwords]; + if(bits < n) { + uval <<= bits; + uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits); + cbits += bits; + goto break2; + } + uval <<= n; + uval |= word & (FLAC__WORD_ALL_ONES >> cbits); + bits -= n; + crc16_update_word_(br, word); + cwords++; + cbits = 0; + if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */ + uval <<= bits; + uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits)); + cbits = bits; + } + goto break2; + } + else { + FLAC__ASSERT(bits < FLAC__BITS_PER_WORD); + uval <<= bits; + uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits); + cbits = bits; + goto break2; + } + } + else { + /* in this case we're starting our read at a partial tail word; + * the reader has guaranteed that we have at least 'bits' bits + * available to read, which makes this case simpler. + */ + uval <<= bits; + if(cbits) { + /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + FLAC__ASSERT(cbits + bits <= br->bytes*8); + uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits); + cbits += bits; + goto break2; + } + else { + uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits); + cbits += bits; + goto break2; + } + } + } +break2: + /* compose the value */ + *vals = (int)(uval >> 1 ^ -(int)(uval & 1)); + + /* are we done? */ + --nvals; + if(nvals == 0) { + br->consumed_bits = cbits; + br->consumed_words = cwords; + return true; + } + + uval = 0; + ++vals; + + } +} +#else +{ + unsigned i; + unsigned uval = 0; + + /* try and get br->consumed_words and br->consumed_bits into register; + * must remember to flush them back to *br before calling other + * bitwriter functions that use them, and before returning */ + register unsigned cwords; + register unsigned cbits; + unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */ + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ + FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); + FLAC__ASSERT(parameter < 32); + /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */ + + if(nvals == 0) + return true; + + cbits = br->consumed_bits; + cwords = br->consumed_words; + ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits; + + while(1) { + + /* read unary part */ + while(1) { + while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */ + brword b = br->buffer[cwords] << cbits; + if(b) { +#if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__ + asm volatile ( + "bsrl %1, %0;" + "notl %0;" + "andl $31, %0;" + : "=r"(i) + : "r"(b) + ); +#else + i = COUNT_ZERO_MSBS(b); +#endif + uval += i; + cbits += i; + cbits++; /* skip over stop bit */ + if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */ + crc16_update_word_(br, br->buffer[cwords]); + cwords++; + cbits = 0; + } + goto break1; + } + else { + uval += FLAC__BITS_PER_WORD - cbits; + crc16_update_word_(br, br->buffer[cwords]); + cwords++; + cbits = 0; + /* didn't find stop bit yet, have to keep going... */ + } + } + /* at this point we've eaten up all the whole words; have to try + * reading through any tail bytes before calling the read callback. + * this is a repeat of the above logic adjusted for the fact we + * don't have a whole word. note though if the client is feeding + * us data a byte at a time (unlikely), br->consumed_bits may not + * be zero. + */ + if(br->bytes) { + const unsigned end = br->bytes * 8; + brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits; + if(b) { + i = COUNT_ZERO_MSBS(b); + uval += i; + cbits += i; + cbits++; /* skip over stop bit */ + FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD); + goto break1; + } + else { + uval += end - cbits; + cbits += end; + FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD); + /* didn't find stop bit yet, have to keep going... */ + } + } + /* flush registers and read; bitreader_read_from_client_() does + * not touch br->consumed_bits at all but we still need to set + * it in case it fails and we have to return false. + */ + br->consumed_bits = cbits; + br->consumed_words = cwords; + if(!bitreader_read_from_client_(br)) + return false; + cwords = br->consumed_words; + ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval; + /* + uval to offset our count by the # of unary bits already + * consumed before the read, because we will add these back + * in all at once at break1 + */ + } +break1: + ucbits -= uval; + ucbits--; /* account for stop bit */ + + /* read binary part */ + FLAC__ASSERT(cwords <= br->words); + + if(parameter) { + while(ucbits < parameter) { + /* flush registers and read; bitreader_read_from_client_() does + * not touch br->consumed_bits at all but we still need to set + * it in case it fails and we have to return false. + */ + br->consumed_bits = cbits; + br->consumed_words = cwords; + if(!bitreader_read_from_client_(br)) + return false; + cwords = br->consumed_words; + ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits; + } + if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */ + if(cbits) { + /* this also works when consumed_bits==0, it's just slower than necessary for that case */ + const unsigned n = FLAC__BITS_PER_WORD - cbits; + const brword word = br->buffer[cwords]; + if(parameter < n) { + uval <<= parameter; + uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter); + cbits += parameter; + } + else { + uval <<= n; + uval |= word & (FLAC__WORD_ALL_ONES >> cbits); + crc16_update_word_(br, word); + cwords++; + cbits = parameter - n; + if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */ + uval <<= cbits; + uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits)); + } + } + } + else { + cbits = parameter; + uval <<= parameter; + uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits); + } + } + else { + /* in this case we're starting our read at a partial tail word; + * the reader has guaranteed that we have at least 'parameter' + * bits available to read, which makes this case simpler. + */ + uval <<= parameter; + if(cbits) { + /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + FLAC__ASSERT(cbits + parameter <= br->bytes*8); + uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter); + cbits += parameter; + } + else { + cbits = parameter; + uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits); + } + } + } + + ucbits -= parameter; + + /* compose the value */ + *vals = (int)(uval >> 1 ^ -(int)(uval & 1)); + + /* are we done? */ + --nvals; + if(nvals == 0) { + br->consumed_bits = cbits; + br->consumed_words = cwords; + return true; + } + + uval = 0; + ++vals; + + } +} +#endif + +#if 0 /* UNUSED */ +FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter) +{ + FLAC__uint32 lsbs = 0, msbs = 0; + unsigned bit, uval, k; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + k = FLAC__bitmath_ilog2(parameter); + + /* read the unary MSBs and end bit */ + if(!FLAC__bitreader_read_unary_unsigned(br, &msbs)) + return false; + + /* read the binary LSBs */ + if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k)) + return false; + + if(parameter == 1u<= d) { + if(!FLAC__bitreader_read_bit(br, &bit)) + return false; + lsbs <<= 1; + lsbs |= bit; + lsbs -= d; + } + /* compose the value */ + uval = msbs * parameter + lsbs; + } + + /* unfold unsigned to signed */ + if(uval & 1) + *val = -((int)(uval >> 1)) - 1; + else + *val = (int)(uval >> 1); + + return true; +} + +FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter) +{ + FLAC__uint32 lsbs, msbs = 0; + unsigned bit, k; + + FLAC__ASSERT(0 != br); + FLAC__ASSERT(0 != br->buffer); + + k = FLAC__bitmath_ilog2(parameter); + + /* read the unary MSBs and end bit */ + if(!FLAC__bitreader_read_unary_unsigned(br, &msbs)) + return false; + + /* read the binary LSBs */ + if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k)) + return false; + + if(parameter == 1u<= d) { + if(!FLAC__bitreader_read_bit(br, &bit)) + return false; + lsbs <<= 1; + lsbs |= bit; + lsbs -= d; + } + /* compose the value */ + *val = msbs * parameter + lsbs; + } + + return true; +} +#endif /* UNUSED */ + +/* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */ +FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen) +{ + FLAC__uint32 v = 0; + FLAC__uint32 x; + unsigned i; + + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + if(raw) + raw[(*rawlen)++] = (FLAC__byte)x; + if(!(x & 0x80)) { /* 0xxxxxxx */ + v = x; + i = 0; + } + else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */ + v = x & 0x1F; + i = 1; + } + else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */ + v = x & 0x0F; + i = 2; + } + else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */ + v = x & 0x07; + i = 3; + } + else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */ + v = x & 0x03; + i = 4; + } + else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */ + v = x & 0x01; + i = 5; + } + else { + *val = 0xffffffff; + return true; + } + for( ; i; i--) { + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + if(raw) + raw[(*rawlen)++] = (FLAC__byte)x; + if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */ + *val = 0xffffffff; + return true; + } + v <<= 6; + v |= (x & 0x3F); + } + *val = v; + return true; +} + +/* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */ +FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen) +{ + FLAC__uint64 v = 0; + FLAC__uint32 x; + unsigned i; + + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + if(raw) + raw[(*rawlen)++] = (FLAC__byte)x; + if(!(x & 0x80)) { /* 0xxxxxxx */ + v = x; + i = 0; + } + else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */ + v = x & 0x1F; + i = 1; + } + else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */ + v = x & 0x0F; + i = 2; + } + else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */ + v = x & 0x07; + i = 3; + } + else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */ + v = x & 0x03; + i = 4; + } + else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */ + v = x & 0x01; + i = 5; + } + else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */ + v = 0; + i = 6; + } + else { + *val = FLAC__U64L(0xffffffffffffffff); + return true; + } + for( ; i; i--) { + if(!FLAC__bitreader_read_raw_uint32(br, &x, 8)) + return false; + if(raw) + raw[(*rawlen)++] = (FLAC__byte)x; + if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */ + *val = FLAC__U64L(0xffffffffffffffff); + return true; + } + v <<= 6; + v |= (x & 0x3F); + } + *val = v; + return true; +} diff --git a/flac/src/libFLAC/bitwriter.c b/flac/src/libFLAC/bitwriter.c new file mode 100644 index 0000000..a7b1930 --- /dev/null +++ b/flac/src/libFLAC/bitwriter.c @@ -0,0 +1,889 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for malloc() */ +#include /* for memcpy(), memset() */ +#ifdef _MSC_VER +#include /* for ntohl() */ +#elif defined FLAC__SYS_DARWIN +#include /* for ntohl() */ +#elif defined __MINGW32__ +#include /* for ntohl() */ +#else +#include /* for ntohl() */ +#endif +#if 0 /* UNUSED */ +#include "private/bitmath.h" +#endif +#include "private/bitwriter.h" +#include "private/crc.h" +#include "FLAC/assert.h" +#include "share/alloc.h" + +/* Things should be fastest when this matches the machine word size */ +/* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */ +/* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */ +typedef FLAC__uint32 bwword; +#define FLAC__BYTES_PER_WORD 4 +#define FLAC__BITS_PER_WORD 32 +#define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff) +/* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */ +#if WORDS_BIGENDIAN +#define SWAP_BE_WORD_TO_HOST(x) (x) +#else +#ifdef _MSC_VER +#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x) +#else +#define SWAP_BE_WORD_TO_HOST(x) ntohl(x) +#endif +#endif + +/* + * The default capacity here doesn't matter too much. The buffer always grows + * to hold whatever is written to it. Usually the encoder will stop adding at + * a frame or metadata block, then write that out and clear the buffer for the + * next one. + */ +static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */ +/* When growing, increment 4K at a time */ +static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */ + +#define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD) +#define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits) + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +struct FLAC__BitWriter { + bwword *buffer; + bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */ + unsigned capacity; /* capacity of buffer in words */ + unsigned words; /* # of complete words in buffer */ + unsigned bits; /* # of used bits in accum */ +}; + +#ifdef _MSC_VER +/* OPT: an MSVC built-in would be better */ +static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x) +{ + x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); + return (x>>16) | (x<<16); +} +#endif + +/* * WATCHOUT: The current implementation only grows the buffer. */ +static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add) +{ + unsigned new_capacity; + bwword *new_buffer; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + + /* calculate total words needed to store 'bits_to_add' additional bits */ + new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD); + + /* it's possible (due to pessimism in the growth estimation that + * leads to this call) that we don't actually need to grow + */ + if(bw->capacity >= new_capacity) + return true; + + /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */ + if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT) + new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT); + /* make sure we got everything right */ + FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT); + FLAC__ASSERT(new_capacity > bw->capacity); + FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD)); + + new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity); + if(new_buffer == 0) + return false; + bw->buffer = new_buffer; + bw->capacity = new_capacity; + return true; +} + + +/*********************************************************************** + * + * Class constructor/destructor + * + ***********************************************************************/ + +FLAC__BitWriter *FLAC__bitwriter_new(void) +{ + FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter)); + /* note that calloc() sets all members to 0 for us */ + return bw; +} + +void FLAC__bitwriter_delete(FLAC__BitWriter *bw) +{ + FLAC__ASSERT(0 != bw); + + FLAC__bitwriter_free(bw); + free(bw); +} + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw) +{ + FLAC__ASSERT(0 != bw); + + bw->words = bw->bits = 0; + bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY; + bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity); + if(bw->buffer == 0) + return false; + + return true; +} + +void FLAC__bitwriter_free(FLAC__BitWriter *bw) +{ + FLAC__ASSERT(0 != bw); + + if(0 != bw->buffer) + free(bw->buffer); + bw->buffer = 0; + bw->capacity = 0; + bw->words = bw->bits = 0; +} + +void FLAC__bitwriter_clear(FLAC__BitWriter *bw) +{ + bw->words = bw->bits = 0; +} + +void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out) +{ + unsigned i, j; + if(bw == 0) { + fprintf(out, "bitwriter is NULL\n"); + } + else { + fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw)); + + for(i = 0; i < bw->words; i++) { + fprintf(out, "%08X: ", i); + for(j = 0; j < FLAC__BITS_PER_WORD; j++) + fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0); + fprintf(out, "\n"); + } + if(bw->bits > 0) { + fprintf(out, "%08X: ", i); + for(j = 0; j < bw->bits; j++) + fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0); + fprintf(out, "\n"); + } + } +} + +FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc) +{ + const FLAC__byte *buffer; + size_t bytes; + + FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */ + + if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes)) + return false; + + *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes); + FLAC__bitwriter_release_buffer(bw); + return true; +} + +FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc) +{ + const FLAC__byte *buffer; + size_t bytes; + + FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */ + + if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes)) + return false; + + *crc = FLAC__crc8(buffer, bytes); + FLAC__bitwriter_release_buffer(bw); + return true; +} + +FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw) +{ + return ((bw->bits & 7) == 0); +} + +unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw) +{ + return FLAC__TOTAL_BITS(bw); +} + +FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes) +{ + FLAC__ASSERT((bw->bits & 7) == 0); + /* double protection */ + if(bw->bits & 7) + return false; + /* if we have bits in the accumulator we have to flush those to the buffer first */ + if(bw->bits) { + FLAC__ASSERT(bw->words <= bw->capacity); + if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD)) + return false; + /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */ + bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits)); + } + /* now we can just return what we have */ + *buffer = (FLAC__byte*)bw->buffer; + *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3); + return true; +} + +void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw) +{ + /* nothing to do. in the future, strict checking of a 'writer-is-in- + * get-mode' flag could be added everywhere and then cleared here + */ + (void)bw; +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits) +{ + unsigned n; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + + if(bits == 0) + return true; + /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */ + if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits)) + return false; + /* first part gets to word alignment */ + if(bw->bits) { + n = min(FLAC__BITS_PER_WORD - bw->bits, bits); + bw->accum <<= n; + bits -= n; + bw->bits += n; + if(bw->bits == FLAC__BITS_PER_WORD) { + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum); + bw->bits = 0; + } + else + return true; + } + /* do whole words */ + while(bits >= FLAC__BITS_PER_WORD) { + bw->buffer[bw->words++] = 0; + bits -= FLAC__BITS_PER_WORD; + } + /* do any leftovers */ + if(bits > 0) { + bw->accum = 0; + bw->bits = bits; + } + return true; +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits) +{ + register unsigned left; + + /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ + FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + + FLAC__ASSERT(bits <= 32); + if(bits == 0) + return true; + + /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */ + if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits)) + return false; + + left = FLAC__BITS_PER_WORD - bw->bits; + if(bits < left) { + bw->accum <<= bits; + bw->accum |= val; + bw->bits += bits; + } + else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */ + bw->accum <<= left; + bw->accum |= val >> (bw->bits = bits - left); + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum); + bw->accum = val; + } + else { + bw->accum = val; + bw->bits = 0; + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val); + } + + return true; +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits) +{ + /* zero-out unused bits */ + if(bits < 32) + val &= (~(0xffffffff << bits)); + + return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits); +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits) +{ + /* this could be a little faster but it's not used for much */ + if(bits > 32) { + return + FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) && + FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32); + } + else + return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits); +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val) +{ + /* this doesn't need to be that fast as currently it is only used for vorbis comments */ + + if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8)) + return false; + + return true; +} + +FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals) +{ + unsigned i; + + /* this could be faster but currently we don't need it to be since it's only used for writing metadata */ + for(i = 0; i < nvals; i++) { + if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8)) + return false; + } + + return true; +} + +FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val) +{ + if(val < 32) + return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val); + else + return + FLAC__bitwriter_write_zeroes(bw, val) && + FLAC__bitwriter_write_raw_uint32(bw, 1, 1); +} + +unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter) +{ + FLAC__uint32 uval; + + FLAC__ASSERT(parameter < sizeof(unsigned)*8); + + /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */ + uval = (val<<1) ^ (val>>31); + + return 1 + parameter + (uval >> parameter); +} + +#if 0 /* UNUSED */ +unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter) +{ + unsigned bits, msbs, uval; + unsigned k; + + FLAC__ASSERT(parameter > 0); + + /* fold signed to unsigned */ + if(val < 0) + uval = (unsigned)(((-(++val)) << 1) + 1); + else + uval = (unsigned)(val << 1); + + k = FLAC__bitmath_ilog2(parameter); + if(parameter == 1u<> k; + bits = 1 + k + msbs; + } + else { + unsigned q, r, d; + + d = (1 << (k+1)) - parameter; + q = uval / parameter; + r = uval - (q * parameter); + + bits = 1 + q + k; + if(r >= d) + bits++; + } + return bits; +} + +unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter) +{ + unsigned bits, msbs; + unsigned k; + + FLAC__ASSERT(parameter > 0); + + k = FLAC__bitmath_ilog2(parameter); + if(parameter == 1u<> k; + bits = 1 + k + msbs; + } + else { + unsigned q, r, d; + + d = (1 << (k+1)) - parameter; + q = uval / parameter; + r = uval - (q * parameter); + + bits = 1 + q + k; + if(r >= d) + bits++; + } + return bits; +} +#endif /* UNUSED */ + +FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter) +{ + unsigned total_bits, interesting_bits, msbs; + FLAC__uint32 uval, pattern; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + FLAC__ASSERT(parameter < 8*sizeof(uval)); + + /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */ + uval = (val<<1) ^ (val>>31); + + msbs = uval >> parameter; + interesting_bits = 1 + parameter; + total_bits = interesting_bits + msbs; + pattern = 1 << parameter; /* the unary end bit */ + pattern |= (uval & ((1<> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/ + FLAC__uint32 uval; + unsigned left; + const unsigned lsbits = 1 + parameter; + unsigned msbits; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + FLAC__ASSERT(parameter < 8*sizeof(bwword)-1); + /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ + FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); + + while(nvals) { + /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */ + uval = (*vals<<1) ^ (*vals>>31); + + msbits = uval >> parameter; + +#if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */ + if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */ + /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */ + bw->bits = bw->bits + msbits + lsbits; + uval |= mask1; /* set stop bit */ + uval &= mask2; /* mask off unused top bits */ + /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */ + bw->accum <<= msbits; + bw->accum <<= lsbits; + bw->accum |= uval; + if(bw->bits == FLAC__BITS_PER_WORD) { + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum); + bw->bits = 0; + /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */ + if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) { + FLAC__ASSERT(bw->capacity == bw->words); + return false; + } + } + } + else { +#elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */ + if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */ + /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */ + bw->bits = bw->bits + msbits + lsbits; + uval |= mask1; /* set stop bit */ + uval &= mask2; /* mask off unused top bits */ + bw->accum <<= msbits + lsbits; + bw->accum |= uval; + } + else { +#endif + /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */ + /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */ + if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits)) + return false; + + if(msbits) { + /* first part gets to word alignment */ + if(bw->bits) { + left = FLAC__BITS_PER_WORD - bw->bits; + if(msbits < left) { + bw->accum <<= msbits; + bw->bits += msbits; + goto break1; + } + else { + bw->accum <<= left; + msbits -= left; + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum); + bw->bits = 0; + } + } + /* do whole words */ + while(msbits >= FLAC__BITS_PER_WORD) { + bw->buffer[bw->words++] = 0; + msbits -= FLAC__BITS_PER_WORD; + } + /* do any leftovers */ + if(msbits > 0) { + bw->accum = 0; + bw->bits = msbits; + } + } +break1: + uval |= mask1; /* set stop bit */ + uval &= mask2; /* mask off unused top bits */ + + left = FLAC__BITS_PER_WORD - bw->bits; + if(lsbits < left) { + bw->accum <<= lsbits; + bw->accum |= uval; + bw->bits += lsbits; + } + else { + /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always + * be > lsbits (because of previous assertions) so it would have + * triggered the (lsbitsbits); + FLAC__ASSERT(left < FLAC__BITS_PER_WORD); + bw->accum <<= left; + bw->accum |= uval >> (bw->bits = lsbits - left); + bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum); + bw->accum = uval; + } +#if 1 + } +#endif + vals++; + nvals--; + } + return true; +} + +#if 0 /* UNUSED */ +FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter) +{ + unsigned total_bits, msbs, uval; + unsigned k; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + FLAC__ASSERT(parameter > 0); + + /* fold signed to unsigned */ + if(val < 0) + uval = (unsigned)(((-(++val)) << 1) + 1); + else + uval = (unsigned)(val << 1); + + k = FLAC__bitmath_ilog2(parameter); + if(parameter == 1u<> k; + total_bits = 1 + k + msbs; + pattern = 1 << k; /* the unary end bit */ + pattern |= (uval & ((1u<= d) { + if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1)) + return false; + } + else { + if(!FLAC__bitwriter_write_raw_uint32(bw, r, k)) + return false; + } + } + return true; +} + +FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter) +{ + unsigned total_bits, msbs; + unsigned k; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + FLAC__ASSERT(parameter > 0); + + k = FLAC__bitmath_ilog2(parameter); + if(parameter == 1u<> k; + total_bits = 1 + k + msbs; + pattern = 1 << k; /* the unary end bit */ + pattern |= (uval & ((1u<= d) { + if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1)) + return false; + } + else { + if(!FLAC__bitwriter_write_raw_uint32(bw, r, k)) + return false; + } + } + return true; +} +#endif /* UNUSED */ + +FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val) +{ + FLAC__bool ok = 1; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + + FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */ + + if(val < 0x80) { + return FLAC__bitwriter_write_raw_uint32(bw, val, 8); + } + else if(val < 0x800) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8); + } + else if(val < 0x10000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8); + } + else if(val < 0x200000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8); + } + else if(val < 0x4000000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8); + } + else { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8); + } + + return ok; +} + +FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val) +{ + FLAC__bool ok = 1; + + FLAC__ASSERT(0 != bw); + FLAC__ASSERT(0 != bw->buffer); + + FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */ + + if(val < 0x80) { + return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8); + } + else if(val < 0x800) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + else if(val < 0x10000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + else if(val < 0x200000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + else if(val < 0x4000000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + else if(val < 0x80000000) { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + else { + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8); + ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8); + } + + return ok; +} + +FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw) +{ + /* 0-pad to byte boundary */ + if(bw->bits & 7u) + return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u)); + else + return true; +} diff --git a/flac/src/libFLAC/cpu.c b/flac/src/libFLAC/cpu.c new file mode 100644 index 0000000..b97275f --- /dev/null +++ b/flac/src/libFLAC/cpu.c @@ -0,0 +1,418 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "private/cpu.h" +#include +#include + +#if defined FLAC__CPU_IA32 +# include +#elif defined FLAC__CPU_PPC +# if !defined FLAC__NO_ASM +# if defined FLAC__SYS_DARWIN +# include +# include +# include +# include +# include +# ifndef CPU_SUBTYPE_POWERPC_970 +# define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100) +# endif +# else /* FLAC__SYS_DARWIN */ + +# include +# include + +static sigjmp_buf jmpbuf; +static volatile sig_atomic_t canjump = 0; + +static void sigill_handler (int sig) +{ + if (!canjump) { + signal (sig, SIG_DFL); + raise (sig); + } + canjump = 0; + siglongjmp (jmpbuf, 1); +} +# endif /* FLAC__SYS_DARWIN */ +# endif /* FLAC__NO_ASM */ +#endif /* FLAC__CPU_PPC */ + +#if defined (__NetBSD__) || defined(__OpenBSD__) +#include +#include +#include +#endif + +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +#include +#include +#endif + +#if defined(__APPLE__) +/* how to get sysctlbyname()? */ +#endif + +/* these are flags in EDX of CPUID AX=00000001 */ +static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000; +/* these are flags in ECX of CPUID AX=00000001 */ +static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001; +static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200; +/* these are flags in EDX of CPUID AX=80000001 */ +static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000; +static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000; + + +/* + * Extra stuff needed for detection of OS support for SSE on IA-32 + */ +#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS +# if defined(__linux__) +/* + * If the OS doesn't support SSE, we will get here with a SIGILL. We + * modify the return address to jump over the offending SSE instruction + * and also the operation following it that indicates the instruction + * executed successfully. In this way we use no global variables and + * stay thread-safe. + * + * 3 + 3 + 6: + * 3 bytes for "xorps xmm0,xmm0" + * 3 bytes for estimate of how long the follwing "inc var" instruction is + * 6 bytes extra in case our estimate is wrong + * 12 bytes puts us in the NOP "landing zone" + */ +# undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */ +# ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR + static void sigill_handler_sse_os(int signal, struct sigcontext sc) + { + (void)signal; + sc.eip += 3 + 3 + 6; + } +# else +# include + static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc) + { + (void)signal, (void)si; + ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6; + } +# endif +# elif defined(_MSC_VER) +# include +# undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */ +# ifdef USE_TRY_CATCH_FLAVOR +# else + LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep) + { + if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) { + ep->ContextRecord->Eip += 3 + 3 + 6; + return EXCEPTION_CONTINUE_EXECUTION; + } + return EXCEPTION_CONTINUE_SEARCH; + } +# endif +# endif +#endif + + +void FLAC__cpu_info(FLAC__CPUInfo *info) +{ +/* + * IA32-specific + */ +#ifdef FLAC__CPU_IA32 + info->type = FLAC__CPUINFO_TYPE_IA32; +#if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM + info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */ + info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false; + info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */ + info->data.ia32.cmov = false; + info->data.ia32.mmx = false; + info->data.ia32.fxsr = false; + info->data.ia32.sse = false; + info->data.ia32.sse2 = false; + info->data.ia32.sse3 = false; + info->data.ia32.ssse3 = false; + info->data.ia32._3dnow = false; + info->data.ia32.ext3dnow = false; + info->data.ia32.extmmx = false; + if(info->data.ia32.cpuid) { + /* http://www.sandpile.org/ia32/cpuid.htm */ + FLAC__uint32 flags_edx, flags_ecx; + FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx); + info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false; + info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false; + info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false; + info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false; + info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false; + info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false; + info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false; + +#ifdef FLAC__USE_3DNOW + flags_edx = FLAC__cpu_info_extended_amd_asm_ia32(); + info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false; + info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false; + info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false; +#else + info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false; +#endif + +#ifdef DEBUG + fprintf(stderr, "CPU info (IA-32):\n"); + fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n'); + fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n'); + fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n'); + fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n'); + fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n'); + fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n'); + fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n'); + fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n'); + fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n'); + fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n'); + fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n'); + fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n'); +#endif + + /* + * now have to check for OS support of SSE/SSE2 + */ + if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) { +#if defined FLAC__NO_SSE_OS + /* assume user knows better than us; turn it off */ + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +#elif defined FLAC__SSE_OS + /* assume user knows better than us; leave as detected above */ +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__) + int sse = 0; + size_t len; + /* at least one of these must work: */ + len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse); + len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */ + if(!sse) + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +#elif defined(__NetBSD__) || defined (__OpenBSD__) +# if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__) + int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE }; + size_t len = sizeof(val); + if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val) + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; + else { /* double-check SSE2 */ + mib[1] = CPU_SSE2; + len = sizeof(val); + if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val) + info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; + } +# else + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +# endif +#elif defined(__linux__) + int sse = 0; + struct sigaction sigill_save; +#ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR + if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR) +#else + struct sigaction sigill_sse; + sigill_sse.sa_sigaction = sigill_handler_sse_os; + __sigemptyset(&sigill_sse.sa_mask); + sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */ + if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save)) +#endif + { + /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */ + /* see sigill_handler_sse_os() for an explanation of the following: */ + asm volatile ( + "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */ + "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */ + "incl %0\n\t" /* SIGILL handler will jump over this */ + /* landing zone */ + "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */ + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */ + "nop\n\t" + "nop" /* SIGILL jump lands here if "inc" is 1 byte */ + : "=r"(sse) + : "r"(sse) + ); + + sigaction(SIGILL, &sigill_save, NULL); + } + + if(!sse) + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +#elif defined(_MSC_VER) +# ifdef USE_TRY_CATCH_FLAVOR + _try { + __asm { +# if _MSC_VER <= 1200 + /* VC6 assembler doesn't know SSE, have to emit bytecode instead */ + _emit 0x0F + _emit 0x57 + _emit 0xC0 +# else + xorps xmm0,xmm0 +# endif + } + } + _except(EXCEPTION_EXECUTE_HANDLER) { + if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION) + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; + } +# else + int sse = 0; + LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os); + /* see GCC version above for explanation */ + /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */ + /* http://www.codeproject.com/cpp/gccasm.asp */ + /* http://www.hick.org/~mmiller/msvc_inline_asm.html */ + __asm { +# if _MSC_VER <= 1200 + /* VC6 assembler doesn't know SSE, have to emit bytecode instead */ + _emit 0x0F + _emit 0x57 + _emit 0xC0 +# else + xorps xmm0,xmm0 +# endif + inc sse + nop + nop + nop + nop + nop + nop + nop + nop + nop + } + SetUnhandledExceptionFilter(save); + if(!sse) + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +# endif +#else + /* no way to test, disable to be safe */ + info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; +#endif +#ifdef DEBUG + fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n'); +#endif + + } + } +#else + info->use_asm = false; +#endif + +/* + * PPC-specific + */ +#elif defined FLAC__CPU_PPC + info->type = FLAC__CPUINFO_TYPE_PPC; +# if !defined FLAC__NO_ASM + info->use_asm = true; +# ifdef FLAC__USE_ALTIVEC +# if defined FLAC__SYS_DARWIN + { + int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT }; + size_t len = sizeof(val); + info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val); + } + { + host_basic_info_data_t hostInfo; + mach_msg_type_number_t infoCount; + + infoCount = HOST_BASIC_INFO_COUNT; + host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount); + + info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970); + } +# else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */ + { + /* no Darwin, do it the brute-force way */ + /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */ + info->data.ppc.altivec = 0; + info->data.ppc.ppc64 = 0; + + signal (SIGILL, sigill_handler); + canjump = 0; + if (!sigsetjmp (jmpbuf, 1)) { + canjump = 1; + + asm volatile ( + "mtspr 256, %0\n\t" + "vand %%v0, %%v0, %%v0" + : + : "r" (-1) + ); + + info->data.ppc.altivec = 1; + } + canjump = 0; + if (!sigsetjmp (jmpbuf, 1)) { + int x = 0; + canjump = 1; + + /* PPC64 hardware implements the cntlzd instruction */ + asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) ); + + info->data.ppc.ppc64 = 1; + } + signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */ + } +# endif +# else /* !FLAC__USE_ALTIVEC */ + info->data.ppc.altivec = 0; + info->data.ppc.ppc64 = 0; +# endif +# else + info->use_asm = false; +# endif + +/* + * unknown CPI + */ +#else + info->type = FLAC__CPUINFO_TYPE_UNKNOWN; + info->use_asm = false; +#endif +} diff --git a/flac/src/libFLAC/crc.c b/flac/src/libFLAC/crc.c new file mode 100644 index 0000000..b74ad9c --- /dev/null +++ b/flac/src/libFLAC/crc.c @@ -0,0 +1,142 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "private/crc.h" + +/* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */ + +FLAC__byte const FLAC__crc8_table[256] = { + 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, + 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, + 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, + 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, + 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, + 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, + 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, + 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, + 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, + 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, + 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, + 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, + 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, + 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, + 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, + 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, + 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, + 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, + 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, + 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, + 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, + 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, + 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, + 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, + 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, + 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, + 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, + 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, + 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, + 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, + 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, + 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3 +}; + +/* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */ + +unsigned const FLAC__crc16_table[256] = { + 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011, + 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022, + 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072, + 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041, + 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2, + 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1, + 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1, + 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082, + 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192, + 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1, + 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1, + 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2, + 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151, + 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162, + 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132, + 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101, + 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312, + 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321, + 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371, + 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342, + 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1, + 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2, + 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2, + 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381, + 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291, + 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2, + 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2, + 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1, + 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252, + 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261, + 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231, + 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202 +}; + + +void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc) +{ + *crc = FLAC__crc8_table[*crc ^ data]; +} + +void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc) +{ + while(len--) + *crc = FLAC__crc8_table[*crc ^ *data++]; +} + +FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len) +{ + FLAC__uint8 crc = 0; + + while(len--) + crc = FLAC__crc8_table[crc ^ *data++]; + + return crc; +} + +unsigned FLAC__crc16(const FLAC__byte *data, unsigned len) +{ + unsigned crc = 0; + + while(len--) + crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff; + + return crc; +} diff --git a/flac/src/libFLAC/fixed.c b/flac/src/libFLAC/fixed.c new file mode 100644 index 0000000..e8403b7 --- /dev/null +++ b/flac/src/libFLAC/fixed.c @@ -0,0 +1,435 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "private/bitmath.h" +#include "private/fixed.h" +#include "FLAC/assert.h" + +#ifndef M_LN2 +/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */ +#define M_LN2 0.69314718055994530942 +#endif + +#ifdef min +#undef min +#endif +#define min(x,y) ((x) < (y)? (x) : (y)) + +#ifdef local_abs +#undef local_abs +#endif +#define local_abs(x) ((unsigned)((x)<0? -(x) : (x))) + +#ifdef FLAC__INTEGER_ONLY_LIBRARY +/* rbps stands for residual bits per sample + * + * (ln(2) * err) + * rbps = log (-----------) + * 2 ( n ) + */ +static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n) +{ + FLAC__uint32 rbps; + unsigned bits; /* the number of bits required to represent a number */ + int fracbits; /* the number of bits of rbps that comprise the fractional part */ + + FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint)); + FLAC__ASSERT(err > 0); + FLAC__ASSERT(n > 0); + + FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE); + if(err <= n) + return 0; + /* + * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1. + * These allow us later to know we won't lose too much precision in the + * fixed-point division (err< 0); + bits = FLAC__bitmath_ilog2(err)+1; + if(bits > 16) { + err >>= (bits-16); + fracbits -= (bits-16); + } + rbps = (FLAC__uint32)err; + + /* Multiply by fixed-point version of ln(2), with 16 fractional bits */ + rbps *= FLAC__FP_LN2; + fracbits += 16; + FLAC__ASSERT(fracbits >= 0); + + /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */ + { + const int f = fracbits & 3; + if(f) { + rbps >>= f; + fracbits -= f; + } + } + + rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1)); + + if(rbps == 0) + return 0; + + /* + * The return value must have 16 fractional bits. Since the whole part + * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits + * must be >= -3, these assertion allows us to be able to shift rbps + * left if necessary to get 16 fracbits without losing any bits of the + * whole part of rbps. + * + * There is a slight chance due to accumulated error that the whole part + * will require 6 bits, so we use 6 in the assertion. Really though as + * long as it fits in 13 bits (32 - (16 - (-3))) we are fine. + */ + FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6); + FLAC__ASSERT(fracbits >= -3); + + /* now shift the decimal point into place */ + if(fracbits < 16) + return rbps << (16-fracbits); + else if(fracbits > 16) + return rbps >> (fracbits-16); + else + return rbps; +} + +static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n) +{ + FLAC__uint32 rbps; + unsigned bits; /* the number of bits required to represent a number */ + int fracbits; /* the number of bits of rbps that comprise the fractional part */ + + FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint)); + FLAC__ASSERT(err > 0); + FLAC__ASSERT(n > 0); + + FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE); + if(err <= n) + return 0; + /* + * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1. + * These allow us later to know we won't lose too much precision in the + * fixed-point division (err< 0); + bits = FLAC__bitmath_ilog2_wide(err)+1; + if(bits > 16) { + err >>= (bits-16); + fracbits -= (bits-16); + } + rbps = (FLAC__uint32)err; + + /* Multiply by fixed-point version of ln(2), with 16 fractional bits */ + rbps *= FLAC__FP_LN2; + fracbits += 16; + FLAC__ASSERT(fracbits >= 0); + + /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */ + { + const int f = fracbits & 3; + if(f) { + rbps >>= f; + fracbits -= f; + } + } + + rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1)); + + if(rbps == 0) + return 0; + + /* + * The return value must have 16 fractional bits. Since the whole part + * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits + * must be >= -3, these assertion allows us to be able to shift rbps + * left if necessary to get 16 fracbits without losing any bits of the + * whole part of rbps. + * + * There is a slight chance due to accumulated error that the whole part + * will require 6 bits, so we use 6 in the assertion. Really though as + * long as it fits in 13 bits (32 - (16 - (-3))) we are fine. + */ + FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6); + FLAC__ASSERT(fracbits >= -3); + + /* now shift the decimal point into place */ + if(fracbits < 16) + return rbps << (16-fracbits); + else if(fracbits > 16) + return rbps >> (fracbits-16); + else + return rbps; +} +#endif + +#ifndef FLAC__INTEGER_ONLY_LIBRARY +unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]) +#else +unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]) +#endif +{ + FLAC__int32 last_error_0 = data[-1]; + FLAC__int32 last_error_1 = data[-1] - data[-2]; + FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]); + FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]); + FLAC__int32 error, save; + FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0; + unsigned i, order; + + for(i = 0; i < data_len; i++) { + error = data[i] ; total_error_0 += local_abs(error); save = error; + error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error; + error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error; + error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error; + error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save; + } + + if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4)) + order = 0; + else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4)) + order = 1; + else if(total_error_2 < min(total_error_3, total_error_4)) + order = 2; + else if(total_error_3 < total_error_4) + order = 3; + else + order = 4; + + /* Estimate the expected number of bits per residual signal sample. */ + /* 'total_error*' is linearly related to the variance of the residual */ + /* signal, so we use it directly to compute E(|x|) */ + FLAC__ASSERT(data_len > 0 || total_error_0 == 0); + FLAC__ASSERT(data_len > 0 || total_error_1 == 0); + FLAC__ASSERT(data_len > 0 || total_error_2 == 0); + FLAC__ASSERT(data_len > 0 || total_error_3 == 0); + FLAC__ASSERT(data_len > 0 || total_error_4 == 0); +#ifndef FLAC__INTEGER_ONLY_LIBRARY + residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0); +#else + residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0; + residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0; + residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0; + residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0; + residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0; +#endif + + return order; +} + +#ifndef FLAC__INTEGER_ONLY_LIBRARY +unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]) +#else +unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]) +#endif +{ + FLAC__int32 last_error_0 = data[-1]; + FLAC__int32 last_error_1 = data[-1] - data[-2]; + FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]); + FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]); + FLAC__int32 error, save; + /* total_error_* are 64-bits to avoid overflow when encoding + * erratic signals when the bits-per-sample and blocksize are + * large. + */ + FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0; + unsigned i, order; + + for(i = 0; i < data_len; i++) { + error = data[i] ; total_error_0 += local_abs(error); save = error; + error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error; + error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error; + error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error; + error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save; + } + + if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4)) + order = 0; + else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4)) + order = 1; + else if(total_error_2 < min(total_error_3, total_error_4)) + order = 2; + else if(total_error_3 < total_error_4) + order = 3; + else + order = 4; + + /* Estimate the expected number of bits per residual signal sample. */ + /* 'total_error*' is linearly related to the variance of the residual */ + /* signal, so we use it directly to compute E(|x|) */ + FLAC__ASSERT(data_len > 0 || total_error_0 == 0); + FLAC__ASSERT(data_len > 0 || total_error_1 == 0); + FLAC__ASSERT(data_len > 0 || total_error_2 == 0); + FLAC__ASSERT(data_len > 0 || total_error_3 == 0); + FLAC__ASSERT(data_len > 0 || total_error_4 == 0); +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if defined _MSC_VER || defined __MINGW32__ + /* with MSVC you have to spoon feed it the casting */ + residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0); +#else + residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0); + residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0); +#endif +#else + residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0; + residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0; + residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0; + residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0; + residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0; +#endif + + return order; +} + +void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]) +{ + const int idata_len = (int)data_len; + int i; + + switch(order) { + case 0: + FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0])); + memcpy(residual, data, sizeof(residual[0])*data_len); + break; + case 1: + for(i = 0; i < idata_len; i++) + residual[i] = data[i] - data[i-1]; + break; + case 2: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + residual[i] = data[i] - (data[i-1] << 1) + data[i-2]; +#else + residual[i] = data[i] - 2*data[i-1] + data[i-2]; +#endif + break; + case 3: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3]; +#else + residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3]; +#endif + break; + case 4: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4]; +#else + residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4]; +#endif + break; + default: + FLAC__ASSERT(0); + } +} + +void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]) +{ + int i, idata_len = (int)data_len; + + switch(order) { + case 0: + FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0])); + memcpy(data, residual, sizeof(residual[0])*data_len); + break; + case 1: + for(i = 0; i < idata_len; i++) + data[i] = residual[i] + data[i-1]; + break; + case 2: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + data[i] = residual[i] + (data[i-1]<<1) - data[i-2]; +#else + data[i] = residual[i] + 2*data[i-1] - data[i-2]; +#endif + break; + case 3: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3]; +#else + data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3]; +#endif + break; + case 4: + for(i = 0; i < idata_len; i++) +#if 1 /* OPT: may be faster with some compilers on some systems */ + data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4]; +#else + data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4]; +#endif + break; + default: + FLAC__ASSERT(0); + } +} diff --git a/flac/src/libFLAC/flac.pc.in b/flac/src/libFLAC/flac.pc.in new file mode 100644 index 0000000..8ce1c96 --- /dev/null +++ b/flac/src/libFLAC/flac.pc.in @@ -0,0 +1,10 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: FLAC +Description: Free Lossless Audio Codec Library +Version: @VERSION@ +Libs: -L${libdir} -lFLAC -lm +Cflags: -I${includedir}/FLAC diff --git a/flac/src/libFLAC/float.c b/flac/src/libFLAC/float.c new file mode 100644 index 0000000..5415f30 --- /dev/null +++ b/flac/src/libFLAC/float.c @@ -0,0 +1,308 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" + +#include "private/float.h" + +#ifdef FLAC__INTEGER_ONLY_LIBRARY + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + +const FLAC__fixedpoint FLAC__FP_ZERO = 0; +const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000; +const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000; +const FLAC__fixedpoint FLAC__FP_LN2 = 45426; +const FLAC__fixedpoint FLAC__FP_E = 178145; + +/* Lookup tables for Knuth's logarithm algorithm */ +#define LOG2_LOOKUP_PRECISION 16 +static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = { + { + /* + * 0 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00000001, + /* lg(4/3) = */ 0x00000000, + /* lg(8/7) = */ 0x00000000, + /* lg(16/15) = */ 0x00000000, + /* lg(32/31) = */ 0x00000000, + /* lg(64/63) = */ 0x00000000, + /* lg(128/127) = */ 0x00000000, + /* lg(256/255) = */ 0x00000000, + /* lg(512/511) = */ 0x00000000, + /* lg(1024/1023) = */ 0x00000000, + /* lg(2048/2047) = */ 0x00000000, + /* lg(4096/4095) = */ 0x00000000, + /* lg(8192/8191) = */ 0x00000000, + /* lg(16384/16383) = */ 0x00000000, + /* lg(32768/32767) = */ 0x00000000 + }, + { + /* + * 4 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00000010, + /* lg(4/3) = */ 0x00000007, + /* lg(8/7) = */ 0x00000003, + /* lg(16/15) = */ 0x00000001, + /* lg(32/31) = */ 0x00000001, + /* lg(64/63) = */ 0x00000000, + /* lg(128/127) = */ 0x00000000, + /* lg(256/255) = */ 0x00000000, + /* lg(512/511) = */ 0x00000000, + /* lg(1024/1023) = */ 0x00000000, + /* lg(2048/2047) = */ 0x00000000, + /* lg(4096/4095) = */ 0x00000000, + /* lg(8192/8191) = */ 0x00000000, + /* lg(16384/16383) = */ 0x00000000, + /* lg(32768/32767) = */ 0x00000000 + }, + { + /* + * 8 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00000100, + /* lg(4/3) = */ 0x0000006a, + /* lg(8/7) = */ 0x00000031, + /* lg(16/15) = */ 0x00000018, + /* lg(32/31) = */ 0x0000000c, + /* lg(64/63) = */ 0x00000006, + /* lg(128/127) = */ 0x00000003, + /* lg(256/255) = */ 0x00000001, + /* lg(512/511) = */ 0x00000001, + /* lg(1024/1023) = */ 0x00000000, + /* lg(2048/2047) = */ 0x00000000, + /* lg(4096/4095) = */ 0x00000000, + /* lg(8192/8191) = */ 0x00000000, + /* lg(16384/16383) = */ 0x00000000, + /* lg(32768/32767) = */ 0x00000000 + }, + { + /* + * 12 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00001000, + /* lg(4/3) = */ 0x000006a4, + /* lg(8/7) = */ 0x00000315, + /* lg(16/15) = */ 0x0000017d, + /* lg(32/31) = */ 0x000000bc, + /* lg(64/63) = */ 0x0000005d, + /* lg(128/127) = */ 0x0000002e, + /* lg(256/255) = */ 0x00000017, + /* lg(512/511) = */ 0x0000000c, + /* lg(1024/1023) = */ 0x00000006, + /* lg(2048/2047) = */ 0x00000003, + /* lg(4096/4095) = */ 0x00000001, + /* lg(8192/8191) = */ 0x00000001, + /* lg(16384/16383) = */ 0x00000000, + /* lg(32768/32767) = */ 0x00000000 + }, + { + /* + * 16 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00010000, + /* lg(4/3) = */ 0x00006a40, + /* lg(8/7) = */ 0x00003151, + /* lg(16/15) = */ 0x000017d6, + /* lg(32/31) = */ 0x00000bba, + /* lg(64/63) = */ 0x000005d1, + /* lg(128/127) = */ 0x000002e6, + /* lg(256/255) = */ 0x00000172, + /* lg(512/511) = */ 0x000000b9, + /* lg(1024/1023) = */ 0x0000005c, + /* lg(2048/2047) = */ 0x0000002e, + /* lg(4096/4095) = */ 0x00000017, + /* lg(8192/8191) = */ 0x0000000c, + /* lg(16384/16383) = */ 0x00000006, + /* lg(32768/32767) = */ 0x00000003 + }, + { + /* + * 20 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x00100000, + /* lg(4/3) = */ 0x0006a3fe, + /* lg(8/7) = */ 0x00031513, + /* lg(16/15) = */ 0x00017d60, + /* lg(32/31) = */ 0x0000bb9d, + /* lg(64/63) = */ 0x00005d10, + /* lg(128/127) = */ 0x00002e59, + /* lg(256/255) = */ 0x00001721, + /* lg(512/511) = */ 0x00000b8e, + /* lg(1024/1023) = */ 0x000005c6, + /* lg(2048/2047) = */ 0x000002e3, + /* lg(4096/4095) = */ 0x00000171, + /* lg(8192/8191) = */ 0x000000b9, + /* lg(16384/16383) = */ 0x0000005c, + /* lg(32768/32767) = */ 0x0000002e + }, + { + /* + * 24 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x01000000, + /* lg(4/3) = */ 0x006a3fe6, + /* lg(8/7) = */ 0x00315130, + /* lg(16/15) = */ 0x0017d605, + /* lg(32/31) = */ 0x000bb9ca, + /* lg(64/63) = */ 0x0005d0fc, + /* lg(128/127) = */ 0x0002e58f, + /* lg(256/255) = */ 0x0001720e, + /* lg(512/511) = */ 0x0000b8d8, + /* lg(1024/1023) = */ 0x00005c61, + /* lg(2048/2047) = */ 0x00002e2d, + /* lg(4096/4095) = */ 0x00001716, + /* lg(8192/8191) = */ 0x00000b8b, + /* lg(16384/16383) = */ 0x000005c5, + /* lg(32768/32767) = */ 0x000002e3 + }, + { + /* + * 28 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ 0x10000000, + /* lg(4/3) = */ 0x06a3fe5c, + /* lg(8/7) = */ 0x03151301, + /* lg(16/15) = */ 0x017d6049, + /* lg(32/31) = */ 0x00bb9ca6, + /* lg(64/63) = */ 0x005d0fba, + /* lg(128/127) = */ 0x002e58f7, + /* lg(256/255) = */ 0x001720da, + /* lg(512/511) = */ 0x000b8d87, + /* lg(1024/1023) = */ 0x0005c60b, + /* lg(2048/2047) = */ 0x0002e2d7, + /* lg(4096/4095) = */ 0x00017160, + /* lg(8192/8191) = */ 0x0000b8ad, + /* lg(16384/16383) = */ 0x00005c56, + /* lg(32768/32767) = */ 0x00002e2b + } +}; + +#if 0 +static const FLAC__uint64 log2_lookup_wide[] = { + { + /* + * 32 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ FLAC__U64L(0x100000000), + /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6), + /* lg(8/7) = */ FLAC__U64L(0x31513015), + /* lg(16/15) = */ FLAC__U64L(0x17d60497), + /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65), + /* lg(64/63) = */ FLAC__U64L(0x05d0fba2), + /* lg(128/127) = */ FLAC__U64L(0x02e58f74), + /* lg(256/255) = */ FLAC__U64L(0x01720d9c), + /* lg(512/511) = */ FLAC__U64L(0x00b8d875), + /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa), + /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72), + /* lg(4096/4095) = */ FLAC__U64L(0x00171600), + /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2), + /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d), + /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac) + }, + { + /* + * 48 fraction bits + */ + /* undefined */ 0x00000000, + /* lg(2/1) = */ FLAC__U64L(0x1000000000000), + /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429), + /* lg(8/7) = */ FLAC__U64L(0x315130157f7a), + /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb), + /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac), + /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd), + /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee), + /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8), + /* lg(512/511) = */ FLAC__U64L(0xb8d8752173), + /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e), + /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8), + /* lg(4096/4095) = */ FLAC__U64L(0x1716001719), + /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b), + /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d), + /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52) + } +}; +#endif + +FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision) +{ + const FLAC__uint32 ONE = (1u << fracbits); + const FLAC__uint32 *table = log2_lookup[fracbits >> 2]; + + FLAC__ASSERT(fracbits < 32); + FLAC__ASSERT((fracbits & 0x3) == 0); + + if(x < ONE) + return 0; + + if(precision > LOG2_LOOKUP_PRECISION) + precision = LOG2_LOOKUP_PRECISION; + + /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */ + { + FLAC__uint32 y = 0; + FLAC__uint32 z = x >> 1, k = 1; + while (x > ONE && k < precision) { + if (x - z >= ONE) { + x -= z; + z = x >> k; + y += table[k]; + } + else { + z >>= 1; + k++; + } + } + return y; + } +} + +#endif /* defined FLAC__INTEGER_ONLY_LIBRARY */ diff --git a/flac/src/libFLAC/format.c b/flac/src/libFLAC/format.c new file mode 100644 index 0000000..0c9954c --- /dev/null +++ b/flac/src/libFLAC/format.c @@ -0,0 +1,603 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for qsort() */ +#include /* for memset() */ +#include "FLAC/assert.h" +#include "FLAC/format.h" +#include "private/format.h" + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +#ifdef min +#undef min +#endif +#define min(a,b) ((a)<(b)?(a):(b)) + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + +/* VERSION should come from configure */ +FLAC_API const char *FLAC__VERSION_STRING = VERSION; + +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__ +/* yet one more hack because of MSVC6: */ +FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917"; +#else +FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917"; +#endif + +FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' }; +FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143; +FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */ + +FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff); + +FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */ + +FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */ +FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */ + +FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe; +FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */ +FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */ + +FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */ + +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */ +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */ +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */ +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */ +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */ + +FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1< FLAC__MAX_SAMPLE_RATE) { + return false; + } + else + return true; +} + +FLAC_API FLAC__bool FLAC__format_blocksize_is_subset(unsigned blocksize, unsigned sample_rate) +{ + if(blocksize > 16384) + return false; + else if(sample_rate <= 48000 && blocksize > 4608) + return false; + else + return true; +} + +FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate) +{ + if( + !FLAC__format_sample_rate_is_valid(sample_rate) || + ( + sample_rate >= (1u << 16) && + !(sample_rate % 1000 == 0 || sample_rate % 10 == 0) + ) + ) { + return false; + } + else + return true; +} + +/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */ +FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table) +{ + unsigned i; + FLAC__uint64 prev_sample_number = 0; + FLAC__bool got_prev = false; + + FLAC__ASSERT(0 != seek_table); + + for(i = 0; i < seek_table->num_points; i++) { + if(got_prev) { + if( + seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && + seek_table->points[i].sample_number <= prev_sample_number + ) + return false; + } + prev_sample_number = seek_table->points[i].sample_number; + got_prev = true; + } + + return true; +} + +/* used as the sort predicate for qsort() */ +static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r) +{ + /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */ + if(l->sample_number == r->sample_number) + return 0; + else if(l->sample_number < r->sample_number) + return -1; + else + return 1; +} + +/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */ +FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table) +{ + unsigned i, j; + FLAC__bool first; + + FLAC__ASSERT(0 != seek_table); + + /* sort the seekpoints */ + qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_); + + /* uniquify the seekpoints */ + first = true; + for(i = j = 0; i < seek_table->num_points; i++) { + if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) { + if(!first) { + if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number) + continue; + } + } + first = false; + seek_table->points[j++] = seek_table->points[i]; + } + + for(i = j; i < seek_table->num_points; i++) { + seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seek_table->points[i].stream_offset = 0; + seek_table->points[i].frame_samples = 0; + } + + return j; +} + +/* + * also disallows non-shortest-form encodings, c.f. + * http://www.unicode.org/versions/corrigendum1.html + * and a more clear explanation at the end of this section: + * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + */ +static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8) +{ + FLAC__ASSERT(0 != utf8); + if ((utf8[0] & 0x80) == 0) { + return 1; + } + else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) { + if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */ + return 0; + return 2; + } + else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) { + if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */ + return 0; + /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */ + if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */ + return 0; + if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */ + return 0; + return 3; + } + else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) { + if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */ + return 0; + return 4; + } + else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) { + if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */ + return 0; + return 5; + } + else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) { + if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */ + return 0; + return 6; + } + else { + return 0; + } +} + +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name) +{ + char c; + for(c = *name; c; c = *(++name)) + if(c < 0x20 || c == 0x3d || c > 0x7d) + return false; + return true; +} + +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length) +{ + if(length == (unsigned)(-1)) { + while(*value) { + unsigned n = utf8len_(value); + if(n == 0) + return false; + value += n; + } + } + else { + const FLAC__byte *end = value + length; + while(value < end) { + unsigned n = utf8len_(value); + if(n == 0) + return false; + value += n; + } + if(value != end) + return false; + } + return true; +} + +FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length) +{ + const FLAC__byte *s, *end; + + for(s = entry, end = s + length; s < end && *s != '='; s++) { + if(*s < 0x20 || *s > 0x7D) + return false; + } + if(s == end) + return false; + + s++; /* skip '=' */ + + while(s < end) { + unsigned n = utf8len_(s); + if(n == 0) + return false; + s += n; + } + if(s != end) + return false; + + return true; +} + +/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */ +FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation) +{ + unsigned i, j; + + if(check_cd_da_subset) { + if(cue_sheet->lead_in < 2 * 44100) { + if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds"; + return false; + } + if(cue_sheet->lead_in % 588 != 0) { + if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples"; + return false; + } + } + + if(cue_sheet->num_tracks == 0) { + if(violation) *violation = "cue sheet must have at least one track (the lead-out)"; + return false; + } + + if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) { + if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)"; + return false; + } + + for(i = 0; i < cue_sheet->num_tracks; i++) { + if(cue_sheet->tracks[i].number == 0) { + if(violation) *violation = "cue sheet may not have a track number 0"; + return false; + } + + if(check_cd_da_subset) { + if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) { + if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170"; + return false; + } + } + + if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) { + if(violation) { + if(i == cue_sheet->num_tracks-1) /* the lead-out track... */ + *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples"; + else + *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples"; + } + return false; + } + + if(i < cue_sheet->num_tracks - 1) { + if(cue_sheet->tracks[i].num_indices == 0) { + if(violation) *violation = "cue sheet track must have at least one index point"; + return false; + } + + if(cue_sheet->tracks[i].indices[0].number > 1) { + if(violation) *violation = "cue sheet track's first index number must be 0 or 1"; + return false; + } + } + + for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) { + if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) { + if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples"; + return false; + } + + if(j > 0) { + if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) { + if(violation) *violation = "cue sheet track index numbers must increase by 1"; + return false; + } + } + } + } + + return true; +} + +/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */ +FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation) +{ + char *p; + FLAC__byte *b; + + for(p = picture->mime_type; *p; p++) { + if(*p < 0x20 || *p > 0x7e) { + if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)"; + return false; + } + } + + for(b = picture->description; *b; ) { + unsigned n = utf8len_(b); + if(n == 0) { + if(violation) *violation = "description string must be valid UTF-8"; + return false; + } + b += n; + } + + return true; +} + +/* + * These routines are private to libFLAC + */ +unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order) +{ + return + FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order( + FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize), + blocksize, + predictor_order + ); +} + +unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize) +{ + unsigned max_rice_partition_order = 0; + while(!(blocksize & 1)) { + max_rice_partition_order++; + blocksize >>= 1; + } + return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order); +} + +unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order) +{ + unsigned max_rice_partition_order = limit; + + while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order) + max_rice_partition_order--; + + FLAC__ASSERT( + (max_rice_partition_order == 0 && blocksize >= predictor_order) || + (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order) + ); + + return max_rice_partition_order; +} + +void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object) +{ + FLAC__ASSERT(0 != object); + + object->parameters = 0; + object->raw_bits = 0; + object->capacity_by_order = 0; +} + +void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object) +{ + FLAC__ASSERT(0 != object); + + if(0 != object->parameters) + free(object->parameters); + if(0 != object->raw_bits) + free(object->raw_bits); + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object); +} + +FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order) +{ + FLAC__ASSERT(0 != object); + + FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits)); + + if(object->capacity_by_order < max_partition_order) { + if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order)))) + return false; + if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order)))) + return false; + memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order)); + object->capacity_by_order = max_partition_order; + } + + return true; +} diff --git a/flac/src/libFLAC/ia32/Makefile.am b/flac/src/libFLAC/ia32/Makefile.am new file mode 100644 index 0000000..136a7f2 --- /dev/null +++ b/flac/src/libFLAC/ia32/Makefile.am @@ -0,0 +1,45 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +SUFFIXES = .nasm .lo + +STRIP_NON_ASM = sh $(top_srcdir)/strip_non_asm_libtool_args.sh + +.nasm.lo: + $(LIBTOOL) --tag=CC --mode=compile $(STRIP_NON_ASM) $(NASM) -f $(OBJ_FORMAT) -d OBJ_FORMAT_$(OBJ_FORMAT) -i$(srcdir)/ $< -o $@ + +noinst_LTLIBRARIES = libFLAC-asm.la +libFLAC_asm_la_SOURCES = \ + bitreader_asm.nasm \ + cpu_asm.nasm \ + fixed_asm.nasm \ + lpc_asm.nasm \ + nasm.h \ + stream_encoder_asm.nasm diff --git a/flac/src/libFLAC/ia32/bitreader_asm.nasm b/flac/src/libFLAC/ia32/bitreader_asm.nasm new file mode 100644 index 0000000..5746679 --- /dev/null +++ b/flac/src/libFLAC/ia32/bitreader_asm.nasm @@ -0,0 +1,568 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +%include "nasm.h" + + data_section + +cextern FLAC__crc16_table ; unsigned FLAC__crc16_table[256]; +cextern bitreader_read_from_client_ ; FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br); + +cglobal FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap + + code_section + + +; ********************************************************************** +; +; void FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter) +; +; Some details like assertions and other checking is performed by the caller. + ALIGN 16 +cident FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap + + ;ASSERT(0 != br); + ;ASSERT(0 != br->buffer); + ; WATCHOUT: code only works if sizeof(brword)==32; we can make things much faster with this assertion + ;ASSERT(FLAC__BITS_PER_WORD == 32); + ;ASSERT(parameter < 32); + ; the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it + + ;; peppered throughout the code at major checkpoints are keys like this as to where things are at that point in time + ;; [esp + 16] unsigned parameter + ;; [esp + 12] unsigned nvals + ;; [esp + 8] int vals[] + ;; [esp + 4] FLAC__BitReader *br + mov eax, [esp + 12] ; if(nvals == 0) + test eax, eax + ja .nvals_gt_0 + mov eax, 1 ; return true; + ret + +.nvals_gt_0: + push ebp + push ebx + push esi + push edi + sub esp, 4 + ;; [esp + 36] unsigned parameter + ;; [esp + 32] unsigned nvals + ;; [esp + 28] int vals[] + ;; [esp + 24] FLAC__BitReader *br + ;; [esp] ucbits + mov ebp, [esp + 24] ; ebp <- br == br->buffer + mov esi, [ebp + 16] ; esi <- br->consumed_words (aka 'cwords' in the C version) + mov ecx, [ebp + 20] ; ecx <- br->consumed_bits (aka 'cbits' in the C version) + xor edi, edi ; edi <- 0 'uval' + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + ;; [ebp] br->buffer + ;; [ebp + 8] br->words + ;; [ebp + 12] br->bytes + ;; [ebp + 16] br->consumed_words + ;; [ebp + 20] br->consumed_bits + ;; [ebp + 24] br->read_crc + ;; [ebp + 28] br->crc16_align + + ; ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits; + mov eax, [ebp + 8] ; eax <- br->words + sub eax, esi ; eax <- br->words-cwords + shl eax, 2 ; eax <- (br->words-cwords)*FLAC__BYTES_PER_WORD + add eax, [ebp + 12] ; eax <- (br->words-cwords)*FLAC__BYTES_PER_WORD + br->bytes + shl eax, 3 ; eax <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 + sub eax, ecx ; eax <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + mov [esp], eax ; ucbits <- eax + + ALIGN 16 +.val_loop: ; while(1) { + + ; + ; read unary part + ; +.unary_loop: ; while(1) { + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + cmp esi, [ebp + 8] ; while(cwords < br->words) /* if we've not consumed up to a partial tail word... */ + jae near .c1_next1 +.c1_loop: ; { + mov ebx, [ebp] + mov eax, [ebx + 4*esi] ; b = br->buffer[cwords] + mov edx, eax ; edx = br->buffer[cwords] (saved for later use) + shl eax, cl ; b = br->buffer[cwords] << cbits + test eax, eax ; (still have to test since cbits may be 0, thus ZF not updated for shl eax,0) + jz near .c1_next2 ; if(b) { + bsr ebx, eax + not ebx + and ebx, 31 ; ebx = 'i' = # of leading 0 bits in 'b' (eax) + add ecx, ebx ; cbits += i; + add edi, ebx ; uval += i; + add ecx, byte 1 ; cbits++; /* skip over stop bit */ + test ecx, ~31 + jz near .break1 ; if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */ + ; crc16_update_word_(br, br->buffer[cwords]); + push edi ; [need more registers] + bswap edx ; edx = br->buffer[cwords] swapped; now we can CRC the bytes from LSByte to MSByte which makes things much easier + mov ecx, [ebp + 28] ; ecx <- br->crc16_align + mov eax, [ebp + 24] ; ax <- br->read_crc (a.k.a. crc) +%ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + mov edi, _FLAC__crc16_table +%else + mov edi, FLAC__crc16_table +%endif + ;; eax (ax) crc a.k.a. br->read_crc + ;; ebx (bl) intermediate result index into FLAC__crc16_table[] + ;; ecx br->crc16_align + ;; edx byteswapped brword to CRC + ;; esi cwords + ;; edi unsigned FLAC__crc16_table[] + ;; ebp br + test ecx, ecx ; switch(br->crc16_align) ... + jnz .c0b4 ; [br->crc16_align is 0 the vast majority of the time so we optimize the common case] +.c0b0: xor dl, ah ; dl <- (crc>>8)^(word>>24) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word>>24)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word>>24)] +.c0b1: xor dh, ah ; dh <- (crc>>8)^((word>>16)&0xff)) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shr edx, 16 +.c0b2: xor dl, ah ; dl <- (crc>>8)^((word>>8)&0xff)) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] +.c0b3: xor dh, ah ; dh <- (crc>>8)^(word&0xff) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word&0xff)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word&0xff)] + movzx eax, ax + mov [ebp + 24], eax ; br->read_crc <- crc + pop edi + + add esi, byte 1 ; cwords++; + xor ecx, ecx ; cbits = 0; + ; } + jmp near .break1 ; goto break1; + ;; this section relocated out of the way for performance +.c0b4: + mov [ebp + 28], dword 0 ; br->crc16_align <- 0 + cmp ecx, 8 + je .c0b1 + shr edx, 16 + cmp ecx, 16 + je .c0b2 + jmp .c0b3 + + ;; this section relocated out of the way for performance +.c1b4: + mov [ebp + 28], dword 0 ; br->crc16_align <- 0 + cmp ecx, 8 + je .c1b1 + shr edx, 16 + cmp ecx, 16 + je .c1b2 + jmp .c1b3 + +.c1_next2: ; } else { + ;; ecx cbits + ;; edx current brword 'b' + ;; esi cwords + ;; edi uval + ;; ebp br + add edi, 32 + sub edi, ecx ; uval += FLAC__BITS_PER_WORD - cbits; + ; crc16_update_word_(br, br->buffer[cwords]); + push edi ; [need more registers] + bswap edx ; edx = br->buffer[cwords] swapped; now we can CRC the bytes from LSByte to MSByte which makes things much easier + mov ecx, [ebp + 28] ; ecx <- br->crc16_align + mov eax, [ebp + 24] ; ax <- br->read_crc (a.k.a. crc) +%ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + mov edi, _FLAC__crc16_table +%else + mov edi, FLAC__crc16_table +%endif + ;; eax (ax) crc a.k.a. br->read_crc + ;; ebx (bl) intermediate result index into FLAC__crc16_table[] + ;; ecx br->crc16_align + ;; edx byteswapped brword to CRC + ;; esi cwords + ;; edi unsigned FLAC__crc16_table[] + ;; ebp br + test ecx, ecx ; switch(br->crc16_align) ... + jnz .c1b4 ; [br->crc16_align is 0 the vast majority of the time so we optimize the common case] +.c1b0: xor dl, ah ; dl <- (crc>>8)^(word>>24) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word>>24)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word>>24)] +.c1b1: xor dh, ah ; dh <- (crc>>8)^((word>>16)&0xff)) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shr edx, 16 +.c1b2: xor dl, ah ; dl <- (crc>>8)^((word>>8)&0xff)) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] +.c1b3: xor dh, ah ; dh <- (crc>>8)^(word&0xff) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word&0xff)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word&0xff)] + movzx eax, ax + mov [ebp + 24], eax ; br->read_crc <- crc + pop edi + + add esi, byte 1 ; cwords++; + xor ecx, ecx ; cbits = 0; + ; /* didn't find stop bit yet, have to keep going... */ + ; } + + cmp esi, [ebp + 8] ; } while(cwords < br->words) /* if we've not consumed up to a partial tail word... */ + jb near .c1_loop + +.c1_next1: + ; at this point we've eaten up all the whole words; have to try + ; reading through any tail bytes before calling the read callback. + ; this is a repeat of the above logic adjusted for the fact we + ; don't have a whole word. note though if the client is feeding + ; us data a byte at a time (unlikely), br->consumed_bits may not + ; be zero. + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + mov edx, [ebp + 12] ; edx <- br->bytes + test edx, edx + jz .read1 ; if(br->bytes) { [NOTE: this case is rare so it doesn't have to be all that fast ] + mov ebx, [ebp] + shl edx, 3 ; edx <- const unsigned end = br->bytes * 8; + mov eax, [ebx + 4*esi] ; b = br->buffer[cwords] + xchg edx, ecx ; [edx <- cbits , ecx <- end] + mov ebx, 0xffffffff ; ebx <- FLAC__WORD_ALL_ONES + shr ebx, cl ; ebx <- FLAC__WORD_ALL_ONES >> end + not ebx ; ebx <- ~(FLAC__WORD_ALL_ONES >> end) + xchg edx, ecx ; [edx <- end , ecx <- cbits] + and eax, ebx ; b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)); + shl eax, cl ; b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits; + test eax, eax ; (still have to test since cbits may be 0, thus ZF not updated for shl eax,0) + jz .c1_next3 ; if(b) { + bsr ebx, eax + not ebx + and ebx, 31 ; ebx = 'i' = # of leading 0 bits in 'b' (eax) + add ecx, ebx ; cbits += i; + add edi, ebx ; uval += i; + add ecx, byte 1 ; cbits++; /* skip over stop bit */ + jmp short .break1 ; goto break1; +.c1_next3: ; } else { + sub edi, ecx + add edi, edx ; uval += end - cbits; + add ecx, edx ; cbits += end + ; /* didn't find stop bit yet, have to keep going... */ + ; } + ; } +.read1: + ; flush registers and read; bitreader_read_from_client_() does + ; not touch br->consumed_bits at all but we still need to set + ; it in case it fails and we have to return false. + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + mov [ebp + 16], esi ; br->consumed_words = cwords; + mov [ebp + 20], ecx ; br->consumed_bits = cbits; + push ecx ; /* save */ + push ebp ; /* push br argument */ +%ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + call _bitreader_read_from_client_ +%else + call bitreader_read_from_client_ +%endif + pop edx ; /* discard, unused */ + pop ecx ; /* restore */ + mov esi, [ebp + 16] ; cwords = br->consumed_words; + ; ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits; + mov ebx, [ebp + 8] ; ebx <- br->words + sub ebx, esi ; ebx <- br->words-cwords + shl ebx, 2 ; ebx <- (br->words-cwords)*FLAC__BYTES_PER_WORD + add ebx, [ebp + 12] ; ebx <- (br->words-cwords)*FLAC__BYTES_PER_WORD + br->bytes + shl ebx, 3 ; ebx <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 + sub ebx, ecx ; ebx <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + add ebx, edi ; ebx <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval + ; + uval to offset our count by the # of unary bits already + ; consumed before the read, because we will add these back + ; in all at once at break1 + mov [esp], ebx ; ucbits <- ebx + test eax, eax ; if(!bitreader_read_from_client_(br)) + jnz near .unary_loop + jmp .end ; return false; /* eax (the return value) is already 0 */ + ; } /* end while(1) unary part */ + + ALIGN 16 +.break1: + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + ;; [esp] ucbits + sub [esp], edi ; ucbits -= uval; + sub dword [esp], byte 1 ; ucbits--; /* account for stop bit */ + + ; + ; read binary part + ; + mov ebx, [esp + 36] ; ebx <- parameter + test ebx, ebx ; if(parameter) { + jz near .break2 +.read2: + cmp [esp], ebx ; while(ucbits < parameter) { + jae .c2_next1 + ; flush registers and read; bitreader_read_from_client_() does + ; not touch br->consumed_bits at all but we still need to set + ; it in case it fails and we have to return false. + mov [ebp + 16], esi ; br->consumed_words = cwords; + mov [ebp + 20], ecx ; br->consumed_bits = cbits; + push ecx ; /* save */ + push ebp ; /* push br argument */ +%ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + call _bitreader_read_from_client_ +%else + call bitreader_read_from_client_ +%endif + pop edx ; /* discard, unused */ + pop ecx ; /* restore */ + mov esi, [ebp + 16] ; cwords = br->consumed_words; + ; ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits; + mov edx, [ebp + 8] ; edx <- br->words + sub edx, esi ; edx <- br->words-cwords + shl edx, 2 ; edx <- (br->words-cwords)*FLAC__BYTES_PER_WORD + add edx, [ebp + 12] ; edx <- (br->words-cwords)*FLAC__BYTES_PER_WORD + br->bytes + shl edx, 3 ; edx <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 + sub edx, ecx ; edx <- (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + mov [esp], edx ; ucbits <- edx + test eax, eax ; if(!bitreader_read_from_client_(br)) + jnz .read2 + jmp .end ; return false; /* eax (the return value) is already 0 */ + ; } +.c2_next1: + ;; ebx parameter + ;; ecx cbits + ;; esi cwords + ;; edi uval + ;; ebp br + ;; [esp] ucbits + cmp esi, [ebp + 8] ; if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */ + jae near .c2_next2 + test ecx, ecx ; if(cbits) { + jz near .c2_next3 ; /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + mov eax, 32 + mov edx, [ebp] + sub eax, ecx ; const unsigned n = FLAC__BITS_PER_WORD - cbits; + mov edx, [edx + 4*esi] ; const brword word = br->buffer[cwords]; + cmp ebx, eax ; if(parameter < n) { + jae .c2_next4 + ; uval <<= parameter; + ; uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter); + shl edx, cl + xchg ebx, ecx + shld edi, edx, cl + add ebx, ecx ; cbits += parameter; + xchg ebx, ecx ; ebx <- parameter, ecx <- cbits + jmp .break2 ; goto break2; + ; } +.c2_next4: + ; uval <<= n; + ; uval |= word & (FLAC__WORD_ALL_ONES >> cbits); +%if 1 + rol edx, cl ; @@@@@@OPT: may be faster to use rol to save edx so we can restore it for CRC'ing + ; @@@@@@OPT: or put parameter in ch instead and free up ebx completely again +%else + shl edx, cl +%endif + xchg eax, ecx + shld edi, edx, cl + xchg eax, ecx +%if 1 + ror edx, cl ; restored. +%else + mov edx, [ebp] + mov edx, [edx + 4*esi] +%endif + ; crc16_update_word_(br, br->buffer[cwords]); + push edi ; [need more registers] + push ebx ; [need more registers] + push eax ; [need more registers] + bswap edx ; edx = br->buffer[cwords] swapped; now we can CRC the bytes from LSByte to MSByte which makes things much easier + mov ecx, [ebp + 28] ; ecx <- br->crc16_align + mov eax, [ebp + 24] ; ax <- br->read_crc (a.k.a. crc) +%ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + mov edi, _FLAC__crc16_table +%else + mov edi, FLAC__crc16_table +%endif + ;; eax (ax) crc a.k.a. br->read_crc + ;; ebx (bl) intermediate result index into FLAC__crc16_table[] + ;; ecx br->crc16_align + ;; edx byteswapped brword to CRC + ;; esi cwords + ;; edi unsigned FLAC__crc16_table[] + ;; ebp br + test ecx, ecx ; switch(br->crc16_align) ... + jnz .c2b4 ; [br->crc16_align is 0 the vast majority of the time so we optimize the common case] +.c2b0: xor dl, ah ; dl <- (crc>>8)^(word>>24) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word>>24)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word>>24)] +.c2b1: xor dh, ah ; dh <- (crc>>8)^((word>>16)&0xff)) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>16)&0xff))] + shr edx, 16 +.c2b2: xor dl, ah ; dl <- (crc>>8)^((word>>8)&0xff)) + movzx ebx, dl + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^((word>>8)&0xff))] +.c2b3: xor dh, ah ; dh <- (crc>>8)^(word&0xff) + movzx ebx, dh + mov ecx, [ebx*4 + edi] ; cx <- FLAC__crc16_table[(crc>>8)^(word&0xff)] + shl eax, 8 ; ax <- (crc<<8) + xor eax, ecx ; crc <- ax <- (crc<<8) ^ FLAC__crc16_table[(crc>>8)^(word&0xff)] + movzx eax, ax + mov [ebp + 24], eax ; br->read_crc <- crc + pop eax + pop ebx + pop edi + add esi, byte 1 ; cwords++; + mov ecx, ebx + sub ecx, eax ; cbits = parameter - n; + jz .break2 ; if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */ + ; uval <<= cbits; + ; uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits)); + mov eax, [ebp] + mov eax, [eax + 4*esi] + shld edi, eax, cl + ; } + jmp .break2 ; goto break2; + + ;; this section relocated out of the way for performance +.c2b4: + mov [ebp + 28], dword 0 ; br->crc16_align <- 0 + cmp ecx, 8 + je .c2b1 + shr edx, 16 + cmp ecx, 16 + je .c2b2 + jmp .c2b3 + +.c2_next3: ; } else { + mov ecx, ebx ; cbits = parameter; + ; uval <<= cbits; + ; uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits)); + mov eax, [ebp] + mov eax, [eax + 4*esi] + shld edi, eax, cl + jmp .break2 ; goto break2; + ; } +.c2_next2: ; } else { + ; in this case we're starting our read at a partial tail word; + ; the reader has guaranteed that we have at least 'parameter' + ; bits available to read, which makes this case simpler. + ; uval <<= parameter; + ; if(cbits) { + ; /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */ + ; uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter); + ; cbits += parameter; + ; goto break2; + ; } else { + ; cbits = parameter; + ; uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits); + ; goto break2; + ; } + ; the above is much shorter in assembly: + mov eax, [ebp] + mov eax, [eax + 4*esi] ; eax <- br->buffer[cwords] + shl eax, cl ; eax <- br->buffer[cwords] << cbits + add ecx, ebx ; cbits += parameter + xchg ebx, ecx ; ebx <- cbits, ecx <- parameter + shld edi, eax, cl ; uval <<= parameter <<< 'parameter' bits of tail word + xchg ebx, ecx ; ebx <- parameter, ecx <- cbits + ; } + ; } +.break2: + sub [esp], ebx ; ucbits -= parameter; + + ; + ; compose the value + ; + mov ebx, [esp + 28] ; ebx <- vals + mov edx, edi ; edx <- uval + and edi, 1 ; edi <- uval & 1 + shr edx, 1 ; edx <- uval >> 1 + neg edi ; edi <- -(int)(uval & 1) + xor edx, edi ; edx <- (uval >> 1 ^ -(int)(uval & 1)) + mov [ebx], edx ; *vals <- edx + sub dword [esp + 32], byte 1 ; --nvals; + jz .finished ; if(nvals == 0) /* jump to finish */ + xor edi, edi ; uval = 0; + add dword [esp + 28], 4 ; ++vals + jmp .val_loop ; } + +.finished: + mov [ebp + 16], esi ; br->consumed_words = cwords; + mov [ebp + 20], ecx ; br->consumed_bits = cbits; + mov eax, 1 +.end: + add esp, 4 + pop edi + pop esi + pop ebx + pop ebp + ret + +end + +%ifdef OBJ_FORMAT_elf + section .note.GNU-stack noalloc +%endif diff --git a/flac/src/libFLAC/ia32/bitreader_asm.obj b/flac/src/libFLAC/ia32/bitreader_asm.obj new file mode 100644 index 0000000..fcfff60 Binary files /dev/null and b/flac/src/libFLAC/ia32/bitreader_asm.obj differ diff --git a/flac/src/libFLAC/ia32/cpu_asm.nasm b/flac/src/libFLAC/ia32/cpu_asm.nasm new file mode 100644 index 0000000..f20c79d --- /dev/null +++ b/flac/src/libFLAC/ia32/cpu_asm.nasm @@ -0,0 +1,121 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +%include "nasm.h" + + data_section + +cglobal FLAC__cpu_have_cpuid_asm_ia32 +cglobal FLAC__cpu_info_asm_ia32 +cglobal FLAC__cpu_info_extended_amd_asm_ia32 + + code_section + +; ********************************************************************** +; +; FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32() +; + +cident FLAC__cpu_have_cpuid_asm_ia32 + push ebx + pushfd + pop eax + mov edx, eax + xor eax, 0x00200000 + push eax + popfd + pushfd + pop eax + cmp eax, edx + jz .no_cpuid + mov eax, 1 + jmp .end +.no_cpuid: + xor eax, eax +.end: + pop ebx + ret + +; ********************************************************************** +; +; void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx) +; + +cident FLAC__cpu_info_asm_ia32 + ;[esp + 8] == flags_edx + ;[esp + 12] == flags_ecx + + push ebx + call FLAC__cpu_have_cpuid_asm_ia32 + test eax, eax + jz .no_cpuid + mov eax, 1 + cpuid + mov ebx, [esp + 8] + mov [ebx], edx + mov ebx, [esp + 12] + mov [ebx], ecx + jmp .end +.no_cpuid: + xor eax, eax + mov ebx, [esp + 8] + mov [ebx], eax + mov ebx, [esp + 12] + mov [ebx], eax +.end: + pop ebx + ret + +cident FLAC__cpu_info_extended_amd_asm_ia32 + push ebx + call FLAC__cpu_have_cpuid_asm_ia32 + test eax, eax + jz .no_cpuid + mov eax, 0x80000000 + cpuid + cmp eax, 0x80000001 + jb .no_cpuid + mov eax, 0x80000001 + cpuid + mov eax, edx + jmp .end +.no_cpuid: + xor eax, eax +.end: + pop ebx + ret + +end + +%ifdef OBJ_FORMAT_elf + section .note.GNU-stack noalloc +%endif diff --git a/flac/src/libFLAC/ia32/cpu_asm.obj b/flac/src/libFLAC/ia32/cpu_asm.obj new file mode 100644 index 0000000..c2a0513 Binary files /dev/null and b/flac/src/libFLAC/ia32/cpu_asm.obj differ diff --git a/flac/src/libFLAC/ia32/fixed_asm.nasm b/flac/src/libFLAC/ia32/fixed_asm.nasm new file mode 100644 index 0000000..4794d1f --- /dev/null +++ b/flac/src/libFLAC/ia32/fixed_asm.nasm @@ -0,0 +1,312 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +%include "nasm.h" + + data_section + +cglobal FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov + + code_section + +; ********************************************************************** +; +; unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 *data, unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]) +; { +; FLAC__int32 last_error_0 = data[-1]; +; FLAC__int32 last_error_1 = data[-1] - data[-2]; +; FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]); +; FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]); +; FLAC__int32 error, save; +; FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0; +; unsigned i, order; +; +; for(i = 0; i < data_len; i++) { +; error = data[i] ; total_error_0 += local_abs(error); save = error; +; error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error; +; error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error; +; error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error; +; error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save; +; } +; +; if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4)) +; order = 0; +; else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4)) +; order = 1; +; else if(total_error_2 < min(total_error_3, total_error_4)) +; order = 2; +; else if(total_error_3 < total_error_4) +; order = 3; +; else +; order = 4; +; +; residual_bits_per_sample[0] = (FLAC__float)((data_len > 0 && total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0); +; residual_bits_per_sample[1] = (FLAC__float)((data_len > 0 && total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0); +; residual_bits_per_sample[2] = (FLAC__float)((data_len > 0 && total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0); +; residual_bits_per_sample[3] = (FLAC__float)((data_len > 0 && total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0); +; residual_bits_per_sample[4] = (FLAC__float)((data_len > 0 && total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0); +; +; return order; +; } + ALIGN 16 +cident FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov + + ; esp + 36 == data[] + ; esp + 40 == data_len + ; esp + 44 == residual_bits_per_sample[] + + push ebp + push ebx + push esi + push edi + sub esp, byte 16 + ; qword [esp] == temp space for loading FLAC__uint64s to FPU regs + + ; ebx == &data[i] + ; ecx == loop counter (i) + ; ebp == order + ; mm0 == total_error_1:total_error_0 + ; mm1 == total_error_2:total_error_3 + ; mm2 == :total_error_4 + ; mm3 == last_error_1:last_error_0 + ; mm4 == last_error_2:last_error_3 + + mov ecx, [esp + 40] ; ecx = data_len + test ecx, ecx + jz near .data_len_is_0 + + mov ebx, [esp + 36] ; ebx = data[] + movd mm3, [ebx - 4] ; mm3 = 0:last_error_0 + movd mm2, [ebx - 8] ; mm2 = 0:data[-2] + movd mm1, [ebx - 12] ; mm1 = 0:data[-3] + movd mm0, [ebx - 16] ; mm0 = 0:data[-4] + movq mm5, mm3 ; mm5 = 0:last_error_0 + psubd mm5, mm2 ; mm5 = 0:last_error_1 + punpckldq mm3, mm5 ; mm3 = last_error_1:last_error_0 + psubd mm2, mm1 ; mm2 = 0:data[-2] - data[-3] + psubd mm5, mm2 ; mm5 = 0:last_error_2 + movq mm4, mm5 ; mm4 = 0:last_error_2 + psubd mm4, mm2 ; mm4 = 0:last_error_2 - (data[-2] - data[-3]) + paddd mm4, mm1 ; mm4 = 0:last_error_2 - (data[-2] - 2 * data[-3]) + psubd mm4, mm0 ; mm4 = 0:last_error_3 + punpckldq mm4, mm5 ; mm4 = last_error_2:last_error_3 + pxor mm0, mm0 ; mm0 = total_error_1:total_error_0 + pxor mm1, mm1 ; mm1 = total_error_2:total_error_3 + pxor mm2, mm2 ; mm2 = 0:total_error_4 + + ALIGN 16 +.loop: + movd mm7, [ebx] ; mm7 = 0:error_0 + add ebx, byte 4 + movq mm6, mm7 ; mm6 = 0:error_0 + psubd mm7, mm3 ; mm7 = :error_1 + punpckldq mm6, mm7 ; mm6 = error_1:error_0 + movq mm5, mm6 ; mm5 = error_1:error_0 + movq mm7, mm6 ; mm7 = error_1:error_0 + psubd mm5, mm3 ; mm5 = error_2: + movq mm3, mm6 ; mm3 = error_1:error_0 + psrad mm6, 31 + pxor mm7, mm6 + psubd mm7, mm6 ; mm7 = abs(error_1):abs(error_0) + paddd mm0, mm7 ; mm0 = total_error_1:total_error_0 + movq mm6, mm5 ; mm6 = error_2: + psubd mm5, mm4 ; mm5 = error_3: + punpckhdq mm5, mm6 ; mm5 = error_2:error_3 + movq mm7, mm5 ; mm7 = error_2:error_3 + movq mm6, mm5 ; mm6 = error_2:error_3 + psubd mm5, mm4 ; mm5 = :error_4 + movq mm4, mm6 ; mm4 = error_2:error_3 + psrad mm6, 31 + pxor mm7, mm6 + psubd mm7, mm6 ; mm7 = abs(error_2):abs(error_3) + paddd mm1, mm7 ; mm1 = total_error_2:total_error_3 + movq mm6, mm5 ; mm6 = :error_4 + psrad mm5, 31 + pxor mm6, mm5 + psubd mm6, mm5 ; mm6 = :abs(error_4) + paddd mm2, mm6 ; mm2 = :total_error_4 + + dec ecx + jnz short .loop + +; if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4)) +; order = 0; +; else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4)) +; order = 1; +; else if(total_error_2 < min(total_error_3, total_error_4)) +; order = 2; +; else if(total_error_3 < total_error_4) +; order = 3; +; else +; order = 4; + movq mm3, mm0 ; mm3 = total_error_1:total_error_0 + movd edi, mm2 ; edi = total_error_4 + movd esi, mm1 ; esi = total_error_3 + movd eax, mm0 ; eax = total_error_0 + punpckhdq mm1, mm1 ; mm1 = total_error_2:total_error_2 + punpckhdq mm3, mm3 ; mm3 = total_error_1:total_error_1 + movd edx, mm1 ; edx = total_error_2 + movd ecx, mm3 ; ecx = total_error_1 + + xor ebx, ebx + xor ebp, ebp + inc ebx + cmp ecx, eax + cmovb eax, ecx ; eax = min(total_error_0, total_error_1) + cmovbe ebp, ebx + inc ebx + cmp edx, eax + cmovb eax, edx ; eax = min(total_error_0, total_error_1, total_error_2) + cmovbe ebp, ebx + inc ebx + cmp esi, eax + cmovb eax, esi ; eax = min(total_error_0, total_error_1, total_error_2, total_error_3) + cmovbe ebp, ebx + inc ebx + cmp edi, eax + cmovb eax, edi ; eax = min(total_error_0, total_error_1, total_error_2, total_error_3, total_error_4) + cmovbe ebp, ebx + movd ebx, mm0 ; ebx = total_error_0 + emms + + ; residual_bits_per_sample[0] = (FLAC__float)((data_len > 0 && total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0); + ; residual_bits_per_sample[1] = (FLAC__float)((data_len > 0 && total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0); + ; residual_bits_per_sample[2] = (FLAC__float)((data_len > 0 && total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0); + ; residual_bits_per_sample[3] = (FLAC__float)((data_len > 0 && total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0); + ; residual_bits_per_sample[4] = (FLAC__float)((data_len > 0 && total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0); + xor eax, eax + fild dword [esp + 40] ; ST = data_len (NOTE: assumes data_len is <2gigs) +.rbps_0: + test ebx, ebx + jz .total_error_0_is_0 + fld1 ; ST = 1.0 data_len + mov [esp], ebx + mov [esp + 4], eax ; [esp] = (FLAC__uint64)total_error_0 + mov ebx, [esp + 44] + fild qword [esp] ; ST = total_error_0 1.0 data_len + fdiv st2 ; ST = total_error_0/data_len 1.0 data_len + fldln2 ; ST = ln2 total_error_0/data_len 1.0 data_len + fmulp st1 ; ST = ln2*total_error_0/data_len 1.0 data_len + fyl2x ; ST = log2(ln2*total_error_0/data_len) data_len + fstp dword [ebx] ; residual_bits_per_sample[0] = log2(ln2*total_error_0/data_len) ST = data_len + jmp short .rbps_1 +.total_error_0_is_0: + mov ebx, [esp + 44] + mov [ebx], eax ; residual_bits_per_sample[0] = 0.0 +.rbps_1: + test ecx, ecx + jz .total_error_1_is_0 + fld1 ; ST = 1.0 data_len + mov [esp], ecx + mov [esp + 4], eax ; [esp] = (FLAC__uint64)total_error_1 + fild qword [esp] ; ST = total_error_1 1.0 data_len + fdiv st2 ; ST = total_error_1/data_len 1.0 data_len + fldln2 ; ST = ln2 total_error_1/data_len 1.0 data_len + fmulp st1 ; ST = ln2*total_error_1/data_len 1.0 data_len + fyl2x ; ST = log2(ln2*total_error_1/data_len) data_len + fstp dword [ebx + 4] ; residual_bits_per_sample[1] = log2(ln2*total_error_1/data_len) ST = data_len + jmp short .rbps_2 +.total_error_1_is_0: + mov [ebx + 4], eax ; residual_bits_per_sample[1] = 0.0 +.rbps_2: + test edx, edx + jz .total_error_2_is_0 + fld1 ; ST = 1.0 data_len + mov [esp], edx + mov [esp + 4], eax ; [esp] = (FLAC__uint64)total_error_2 + fild qword [esp] ; ST = total_error_2 1.0 data_len + fdiv st2 ; ST = total_error_2/data_len 1.0 data_len + fldln2 ; ST = ln2 total_error_2/data_len 1.0 data_len + fmulp st1 ; ST = ln2*total_error_2/data_len 1.0 data_len + fyl2x ; ST = log2(ln2*total_error_2/data_len) data_len + fstp dword [ebx + 8] ; residual_bits_per_sample[2] = log2(ln2*total_error_2/data_len) ST = data_len + jmp short .rbps_3 +.total_error_2_is_0: + mov [ebx + 8], eax ; residual_bits_per_sample[2] = 0.0 +.rbps_3: + test esi, esi + jz .total_error_3_is_0 + fld1 ; ST = 1.0 data_len + mov [esp], esi + mov [esp + 4], eax ; [esp] = (FLAC__uint64)total_error_3 + fild qword [esp] ; ST = total_error_3 1.0 data_len + fdiv st2 ; ST = total_error_3/data_len 1.0 data_len + fldln2 ; ST = ln2 total_error_3/data_len 1.0 data_len + fmulp st1 ; ST = ln2*total_error_3/data_len 1.0 data_len + fyl2x ; ST = log2(ln2*total_error_3/data_len) data_len + fstp dword [ebx + 12] ; residual_bits_per_sample[3] = log2(ln2*total_error_3/data_len) ST = data_len + jmp short .rbps_4 +.total_error_3_is_0: + mov [ebx + 12], eax ; residual_bits_per_sample[3] = 0.0 +.rbps_4: + test edi, edi + jz .total_error_4_is_0 + fld1 ; ST = 1.0 data_len + mov [esp], edi + mov [esp + 4], eax ; [esp] = (FLAC__uint64)total_error_4 + fild qword [esp] ; ST = total_error_4 1.0 data_len + fdiv st2 ; ST = total_error_4/data_len 1.0 data_len + fldln2 ; ST = ln2 total_error_4/data_len 1.0 data_len + fmulp st1 ; ST = ln2*total_error_4/data_len 1.0 data_len + fyl2x ; ST = log2(ln2*total_error_4/data_len) data_len + fstp dword [ebx + 16] ; residual_bits_per_sample[4] = log2(ln2*total_error_4/data_len) ST = data_len + jmp short .rbps_end +.total_error_4_is_0: + mov [ebx + 16], eax ; residual_bits_per_sample[4] = 0.0 +.rbps_end: + fstp st0 ; ST = [empty] + jmp short .end +.data_len_is_0: + ; data_len == 0, so residual_bits_per_sample[*] = 0.0 + xor ebp, ebp + mov edi, [esp + 44] + mov [edi], ebp + mov [edi + 4], ebp + mov [edi + 8], ebp + mov [edi + 12], ebp + mov [edi + 16], ebp + add ebp, byte 4 ; order = 4 + +.end: + mov eax, ebp ; return order + add esp, byte 16 + pop edi + pop esi + pop ebx + pop ebp + ret + +end + +%ifdef OBJ_FORMAT_elf + section .note.GNU-stack noalloc +%endif diff --git a/flac/src/libFLAC/ia32/fixed_asm.obj b/flac/src/libFLAC/ia32/fixed_asm.obj new file mode 100644 index 0000000..05d61a0 Binary files /dev/null and b/flac/src/libFLAC/ia32/fixed_asm.obj differ diff --git a/flac/src/libFLAC/ia32/lpc_asm-unrolled.nasm b/flac/src/libFLAC/ia32/lpc_asm-unrolled.nasm new file mode 100644 index 0000000..70fe909 --- /dev/null +++ b/flac/src/libFLAC/ia32/lpc_asm-unrolled.nasm @@ -0,0 +1,784 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +; [CR] is a note to flag that the instruction can be easily reordered + +%include "nasm.h" + + data_section + +cglobal FLAC__lpc_compute_autocorrelation_asm + + code_section + +; ********************************************************************** +; +; void FLAC__lpc_compute_autocorrelation_asm(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]) +; { +; FLAC__real d; +; unsigned sample, coeff; +; const unsigned limit = data_len - lag; +; +; assert(lag > 0); +; assert(lag <= data_len); +; +; for(coeff = 0; coeff < lag; coeff++) +; autoc[coeff] = 0.0; +; for(sample = 0; sample <= limit; sample++){ +; d = data[sample]; +; for(coeff = 0; coeff < lag; coeff++) +; autoc[coeff] += d * data[sample+coeff]; +; } +; for(; sample < data_len; sample++){ +; d = data[sample]; +; for(coeff = 0; coeff < data_len - sample; coeff++) +; autoc[coeff] += d * data[sample+coeff]; +; } +; } +; +FLAC__lpc_compute_autocorrelation_asm: + + push ebp + lea ebp, [esp + 8] + push ebx + push esi + push edi + + mov edx, [ebp + 8] ; edx == lag + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + + cmp edx, 1 + ja short .lag_above_1 +.lag_eq_1: + fldz ; will accumulate autoc[0] + ALIGN 16 +.lag_1_loop: + fld dword [esi] + add esi, byte 4 ; sample++ + fmul st0, st0 + faddp st1, st0 + dec ecx + jnz .lag_1_loop + fstp dword [edi] + jmp .end + +.lag_above_1: + cmp edx, 2 + ja short .lag_above_2 +.lag_eq_2: + fldz ; will accumulate autoc[1] + dec ecx + fldz ; will accumulate autoc[0] + fld dword [esi] + ALIGN 16 +.lag_2_loop: + add esi, byte 4 ; [CR] sample++ + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi] + fmul st1, st0 + fxch + faddp st3, st0 ; add to autoc[1] + dec ecx + jnz .lag_2_loop + ; clean up the leftovers + fmul st0, st0 + faddp st1, st0 ; add to autoc[0] + fstp dword [edi] + fstp dword [edi + 4] + jmp .end + +.lag_above_2: + cmp edx, 3 + ja short .lag_above_3 +.lag_eq_3: + fldz ; will accumulate autoc[2] + dec ecx + fldz ; will accumulate autoc[1] + dec ecx + fldz ; will accumulate autoc[0] + ALIGN 16 +.lag_3_loop: + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[2] + dec ecx + jnz .lag_3_loop + ; clean up the leftovers + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st1, st0 + fxch + faddp st3, st0 ; add to autoc[1] + fmul st0, st0 + faddp st1, st0 ; add to autoc[0] + fstp dword [edi] + fstp dword [edi + 4] + fstp dword [edi + 8] + jmp .end + +.lag_above_3: + cmp edx, 4 + ja near .lag_above_4 +.lag_eq_4: + fldz ; will accumulate autoc[3] + dec ecx + fldz ; will accumulate autoc[2] + dec ecx + fldz ; will accumulate autoc[1] + dec ecx + fldz ; will accumulate autoc[0] + ALIGN 16 +.lag_4_loop: + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[3] + dec ecx + jnz .lag_4_loop + ; clean up the leftovers + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[2] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st1, st0 + fxch + faddp st3, st0 ; add to autoc[1] + fmul st0, st0 + faddp st1, st0 ; add to autoc[0] + fstp dword [edi] + fstp dword [edi + 4] + fstp dword [edi + 8] + fstp dword [edi + 12] + jmp .end + +.lag_above_4: + cmp edx, 5 + ja near .lag_above_5 +.lag_eq_5: + fldz ; will accumulate autoc[4] + fldz ; will accumulate autoc[3] + fldz ; will accumulate autoc[2] + fldz ; will accumulate autoc[1] + fldz ; will accumulate autoc[0] + sub ecx, byte 4 + ALIGN 16 +.lag_5_loop: + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmul st0, st1 + faddp st5, st0 ; add to autoc[3] + fld dword [esi + 16] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st5, st0 ; add to autoc[4] + dec ecx + jnz .lag_5_loop + ; clean up the leftovers + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[3] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[2] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st1, st0 + fxch + faddp st3, st0 ; add to autoc[1] + fmul st0, st0 + faddp st1, st0 ; add to autoc[0] + fstp dword [edi] + fstp dword [edi + 4] + fstp dword [edi + 8] + fstp dword [edi + 12] + fstp dword [edi + 16] + jmp .end + +.lag_above_5: + cmp edx, 6 + ja .lag_above_6 +.lag_eq_6: + fldz ; will accumulate autoc[5] + fldz ; will accumulate autoc[4] + fldz ; will accumulate autoc[3] + fldz ; will accumulate autoc[2] + fldz ; will accumulate autoc[1] + fldz ; will accumulate autoc[0] + sub ecx, byte 5 + ALIGN 16 +.lag_6_loop: + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmul st0, st1 + faddp st5, st0 ; add to autoc[3] + fld dword [esi + 16] + fmul st0, st1 + faddp st6, st0 ; add to autoc[4] + fld dword [esi + 20] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st6, st0 ; add to autoc[5] + dec ecx + jnz .lag_6_loop + ; clean up the leftovers + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmul st0, st1 + faddp st5, st0 ; add to autoc[3] + fld dword [esi + 16] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st5, st0 ; add to autoc[4] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmul st0, st1 + faddp st4, st0 ; add to autoc[2] + fld dword [esi + 12] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[3] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st0, st1 + faddp st3, st0 ; add to autoc[1] + fld dword [esi + 8] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[2] + fld dword [esi] + fld st0 + fmul st0, st0 + faddp st2, st0 ; add to autoc[0] + fld dword [esi + 4] + fmul st1, st0 + fxch + faddp st3, st0 ; add to autoc[1] + fmul st0, st0 + faddp st1, st0 ; add to autoc[0] + fstp dword [edi] + fstp dword [edi + 4] + fstp dword [edi + 8] + fstp dword [edi + 12] + fstp dword [edi + 16] + fstp dword [edi + 20] + jmp .end + +.lag_above_6: + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] = 0.0; + lea ecx, [edx * 2] ; ecx = # of dwords of 0 to write + xor eax, eax + rep stosd + mov ecx, [ebp + 4] ; ecx == data_len + mov edi, [ebp + 12] ; edi == autoc + ; const unsigned limit = data_len - lag; + sub ecx, edx + inc ecx ; we are looping <= limit so we add one to the counter + ; for(sample = 0; sample <= limit; sample++){ + ; d = data[sample]; + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] += d * data[sample+coeff]; + ; } + xor eax, eax ; eax == sample <- 0 + ALIGN 16 +.outer_loop: + push eax ; save sample + fld dword [esi + eax * 4] ; ST = d <- data[sample] + mov ebx, eax ; ebx == sample+coeff <- sample + mov edx, [ebp + 8] ; edx <- lag + xor eax, eax ; eax == coeff <- 0 + ALIGN 16 +.inner_loop: + fld st0 ; ST = d d + fmul dword [esi + ebx * 4] ; ST = d*data[sample+coeff] d + fadd dword [edi + eax * 4] ; ST = autoc[coeff]+d*data[sample+coeff] d + fstp dword [edi + eax * 4] ; autoc[coeff]+=d*data[sample+coeff] ST = d + inc ebx ; (sample+coeff)++ + inc eax ; coeff++ + dec edx + jnz .inner_loop + pop eax ; restore sample + fstp st0 ; pop d, ST = empty + inc eax ; sample++ + loop .outer_loop + ; for(; sample < data_len; sample++){ + ; d = data[sample]; + ; for(coeff = 0; coeff < data_len - sample; coeff++) + ; autoc[coeff] += d * data[sample+coeff]; + ; } + mov ecx, [ebp + 8] ; ecx <- lag + dec ecx ; ecx <- lag - 1 + jz .outer_end ; skip loop if 0 +.outer_loop2: + push eax ; save sample + fld dword [esi + eax * 4] ; ST = d <- data[sample] + mov ebx, eax ; ebx == sample+coeff <- sample + mov edx, [ebp + 4] ; edx <- data_len + sub edx, eax ; edx <- data_len-sample + xor eax, eax ; eax == coeff <- 0 +.inner_loop2: + fld st0 ; ST = d d + fmul dword [esi + ebx * 4] ; ST = d*data[sample+coeff] d + fadd dword [edi + eax * 4] ; ST = autoc[coeff]+d*data[sample+coeff] d + fstp dword [edi + eax * 4] ; autoc[coeff]+=d*data[sample+coeff] ST = d + inc ebx ; (sample+coeff)++ + inc eax ; coeff++ + dec edx + jnz .inner_loop2 + pop eax ; restore sample + fstp st0 ; pop d, ST = empty + inc eax ; sample++ + loop .outer_loop2 +.outer_end: + jmp .end + +.lag_eq_6_plus_1: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[6] + sub ecx, byte 6 + ALIGN 16 +.lag_6_1_loop: + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st1, st0 ; add to autoc[6] + dec ecx + jnz .lag_6_1_loop + fstp dword [edi + 24] + jmp .end + +.lag_eq_6_plus_2: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[7] + fldz ; will accumulate autoc[6] + sub ecx, byte 7 + ALIGN 16 +.lag_6_2_loop: + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st2, st0 ; add to autoc[7] + dec ecx + jnz .lag_6_2_loop + ; clean up the leftovers + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + faddp st1, st0 ; add to autoc[6] + fstp dword [edi + 24] + fstp dword [edi + 28] + jmp .end + +.lag_eq_6_plus_3: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[8] + fldz ; will accumulate autoc[7] + fldz ; will accumulate autoc[6] + sub ecx, byte 8 + ALIGN 16 +.lag_6_3_loop: + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[8] + dec ecx + jnz .lag_6_3_loop + ; clean up the leftovers + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st2, st0 ; add to autoc[7] + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + faddp st1, st0 ; add to autoc[6] + fstp dword [edi + 24] + fstp dword [edi + 28] + fstp dword [edi + 32] + jmp .end + +.lag_eq_6_plus_4: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[9] + fldz ; will accumulate autoc[8] + fldz ; will accumulate autoc[7] + fldz ; will accumulate autoc[6] + sub ecx, byte 9 + ALIGN 16 +.lag_6_4_loop: + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[9] + dec ecx + jnz .lag_6_4_loop + ; clean up the leftovers + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[8] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st2, st0 ; add to autoc[7] + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + faddp st1, st0 ; add to autoc[6] + fstp dword [edi + 24] + fstp dword [edi + 28] + fstp dword [edi + 32] + fstp dword [edi + 36] + jmp .end + +.lag_eq_6_plus_5: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[10] + fldz ; will accumulate autoc[9] + fldz ; will accumulate autoc[8] + fldz ; will accumulate autoc[7] + fldz ; will accumulate autoc[6] + sub ecx, byte 10 + ALIGN 16 +.lag_6_5_loop: + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmul st0, st1 + faddp st5, st0 ; add to autoc[9] + fld dword [esi + 40] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st5, st0 ; add to autoc[10] + dec ecx + jnz .lag_6_5_loop + ; clean up the leftovers + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[9] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[8] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st2, st0 ; add to autoc[7] + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + faddp st1, st0 ; add to autoc[6] + fstp dword [edi + 24] + fstp dword [edi + 28] + fstp dword [edi + 32] + fstp dword [edi + 36] + fstp dword [edi + 40] + jmp .end + +.lag_eq_6_plus_6: + mov ecx, [ebp + 4] ; ecx == data_len + mov esi, [ebp] ; esi == data + mov edi, [ebp + 12] ; edi == autoc + fldz ; will accumulate autoc[11] + fldz ; will accumulate autoc[10] + fldz ; will accumulate autoc[9] + fldz ; will accumulate autoc[8] + fldz ; will accumulate autoc[7] + fldz ; will accumulate autoc[6] + sub ecx, byte 11 + ALIGN 16 +.lag_6_6_loop: + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmul st0, st1 + faddp st5, st0 ; add to autoc[9] + fld dword [esi + 40] + fmul st0, st1 + faddp st6, st0 ; add to autoc[10] + fld dword [esi + 44] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st6, st0 ; add to autoc[11] + dec ecx + jnz .lag_6_6_loop + ; clean up the leftovers + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmul st0, st1 + faddp st5, st0 ; add to autoc[9] + fld dword [esi + 40] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st5, st0 ; add to autoc[10] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmul st0, st1 + faddp st4, st0 ; add to autoc[8] + fld dword [esi + 36] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st4, st0 ; add to autoc[9] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmul st0, st1 + faddp st3, st0 ; add to autoc[7] + fld dword [esi + 32] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st3, st0 ; add to autoc[8] + fld dword [esi] + fld dword [esi + 24] + fmul st0, st1 + faddp st2, st0 ; add to autoc[6] + fld dword [esi + 28] + fmulp st1, st0 + add esi, byte 4 ; [CR] sample++ + faddp st2, st0 ; add to autoc[7] + fld dword [esi] + fld dword [esi + 24] + fmulp st1, st0 + faddp st1, st0 ; add to autoc[6] + fstp dword [edi + 24] + fstp dword [edi + 28] + fstp dword [edi + 32] + fstp dword [edi + 36] + fstp dword [edi + 40] + fstp dword [edi + 44] + jmp .end + +.end: + pop edi + pop esi + pop ebx + pop ebp + ret + +end diff --git a/flac/src/libFLAC/ia32/lpc_asm.nasm b/flac/src/libFLAC/ia32/lpc_asm.nasm new file mode 100644 index 0000000..52b3f85 --- /dev/null +++ b/flac/src/libFLAC/ia32/lpc_asm.nasm @@ -0,0 +1,1511 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +%include "nasm.h" + + data_section + +cglobal FLAC__lpc_compute_autocorrelation_asm_ia32 +cglobal FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4 +cglobal FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8 +cglobal FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12 +cglobal FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow +cglobal FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32 +cglobal FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx +cglobal FLAC__lpc_restore_signal_asm_ia32 +cglobal FLAC__lpc_restore_signal_asm_ia32_mmx + + code_section + +; ********************************************************************** +; +; void FLAC__lpc_compute_autocorrelation_asm(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]) +; { +; FLAC__real d; +; unsigned sample, coeff; +; const unsigned limit = data_len - lag; +; +; FLAC__ASSERT(lag > 0); +; FLAC__ASSERT(lag <= data_len); +; +; for(coeff = 0; coeff < lag; coeff++) +; autoc[coeff] = 0.0; +; for(sample = 0; sample <= limit; sample++) { +; d = data[sample]; +; for(coeff = 0; coeff < lag; coeff++) +; autoc[coeff] += d * data[sample+coeff]; +; } +; for(; sample < data_len; sample++) { +; d = data[sample]; +; for(coeff = 0; coeff < data_len - sample; coeff++) +; autoc[coeff] += d * data[sample+coeff]; +; } +; } +; + ALIGN 16 +cident FLAC__lpc_compute_autocorrelation_asm_ia32 + ;[esp + 28] == autoc[] + ;[esp + 24] == lag + ;[esp + 20] == data_len + ;[esp + 16] == data[] + + ;ASSERT(lag > 0) + ;ASSERT(lag <= 33) + ;ASSERT(lag <= data_len) + +.begin: + push esi + push edi + push ebx + + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] = 0.0; + mov edi, [esp + 28] ; edi == autoc + mov ecx, [esp + 24] ; ecx = # of dwords (=lag) of 0 to write + xor eax, eax + rep stosd + + ; const unsigned limit = data_len - lag; + mov eax, [esp + 24] ; eax == lag + mov ecx, [esp + 20] + sub ecx, eax ; ecx == limit + + mov edi, [esp + 28] ; edi == autoc + mov esi, [esp + 16] ; esi == data + inc ecx ; we are looping <= limit so we add one to the counter + + ; for(sample = 0; sample <= limit; sample++) { + ; d = data[sample]; + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] += d * data[sample+coeff]; + ; } + fld dword [esi] ; ST = d <- data[sample] + ; each iteration is 11 bytes so we need (-eax)*11, so we do (-12*eax + eax) + lea edx, [eax + eax*2] + neg edx + lea edx, [eax + edx*4 + .jumper1_0 - .get_eip1] + call .get_eip1 +.get_eip1: + pop ebx + add edx, ebx + inc edx ; compensate for the shorter opcode on the last iteration + inc edx ; compensate for the shorter opcode on the last iteration + inc edx ; compensate for the shorter opcode on the last iteration + cmp eax, 33 + jne .loop1_start + sub edx, byte 9 ; compensate for the longer opcodes on the first iteration +.loop1_start: + jmp edx + + fld st0 ; ST = d d + fmul dword [esi + (32*4)] ; ST = d*data[sample+32] d WATCHOUT: not a byte displacement here! + fadd dword [edi + (32*4)] ; ST = autoc[32]+d*data[sample+32] d WATCHOUT: not a byte displacement here! + fstp dword [edi + (32*4)] ; autoc[32]+=d*data[sample+32] ST = d WATCHOUT: not a byte displacement here! + fld st0 ; ST = d d + fmul dword [esi + (31*4)] ; ST = d*data[sample+31] d + fadd dword [edi + (31*4)] ; ST = autoc[31]+d*data[sample+31] d + fstp dword [edi + (31*4)] ; autoc[31]+=d*data[sample+31] ST = d + fld st0 ; ST = d d + fmul dword [esi + (30*4)] ; ST = d*data[sample+30] d + fadd dword [edi + (30*4)] ; ST = autoc[30]+d*data[sample+30] d + fstp dword [edi + (30*4)] ; autoc[30]+=d*data[sample+30] ST = d + fld st0 ; ST = d d + fmul dword [esi + (29*4)] ; ST = d*data[sample+29] d + fadd dword [edi + (29*4)] ; ST = autoc[29]+d*data[sample+29] d + fstp dword [edi + (29*4)] ; autoc[29]+=d*data[sample+29] ST = d + fld st0 ; ST = d d + fmul dword [esi + (28*4)] ; ST = d*data[sample+28] d + fadd dword [edi + (28*4)] ; ST = autoc[28]+d*data[sample+28] d + fstp dword [edi + (28*4)] ; autoc[28]+=d*data[sample+28] ST = d + fld st0 ; ST = d d + fmul dword [esi + (27*4)] ; ST = d*data[sample+27] d + fadd dword [edi + (27*4)] ; ST = autoc[27]+d*data[sample+27] d + fstp dword [edi + (27*4)] ; autoc[27]+=d*data[sample+27] ST = d + fld st0 ; ST = d d + fmul dword [esi + (26*4)] ; ST = d*data[sample+26] d + fadd dword [edi + (26*4)] ; ST = autoc[26]+d*data[sample+26] d + fstp dword [edi + (26*4)] ; autoc[26]+=d*data[sample+26] ST = d + fld st0 ; ST = d d + fmul dword [esi + (25*4)] ; ST = d*data[sample+25] d + fadd dword [edi + (25*4)] ; ST = autoc[25]+d*data[sample+25] d + fstp dword [edi + (25*4)] ; autoc[25]+=d*data[sample+25] ST = d + fld st0 ; ST = d d + fmul dword [esi + (24*4)] ; ST = d*data[sample+24] d + fadd dword [edi + (24*4)] ; ST = autoc[24]+d*data[sample+24] d + fstp dword [edi + (24*4)] ; autoc[24]+=d*data[sample+24] ST = d + fld st0 ; ST = d d + fmul dword [esi + (23*4)] ; ST = d*data[sample+23] d + fadd dword [edi + (23*4)] ; ST = autoc[23]+d*data[sample+23] d + fstp dword [edi + (23*4)] ; autoc[23]+=d*data[sample+23] ST = d + fld st0 ; ST = d d + fmul dword [esi + (22*4)] ; ST = d*data[sample+22] d + fadd dword [edi + (22*4)] ; ST = autoc[22]+d*data[sample+22] d + fstp dword [edi + (22*4)] ; autoc[22]+=d*data[sample+22] ST = d + fld st0 ; ST = d d + fmul dword [esi + (21*4)] ; ST = d*data[sample+21] d + fadd dword [edi + (21*4)] ; ST = autoc[21]+d*data[sample+21] d + fstp dword [edi + (21*4)] ; autoc[21]+=d*data[sample+21] ST = d + fld st0 ; ST = d d + fmul dword [esi + (20*4)] ; ST = d*data[sample+20] d + fadd dword [edi + (20*4)] ; ST = autoc[20]+d*data[sample+20] d + fstp dword [edi + (20*4)] ; autoc[20]+=d*data[sample+20] ST = d + fld st0 ; ST = d d + fmul dword [esi + (19*4)] ; ST = d*data[sample+19] d + fadd dword [edi + (19*4)] ; ST = autoc[19]+d*data[sample+19] d + fstp dword [edi + (19*4)] ; autoc[19]+=d*data[sample+19] ST = d + fld st0 ; ST = d d + fmul dword [esi + (18*4)] ; ST = d*data[sample+18] d + fadd dword [edi + (18*4)] ; ST = autoc[18]+d*data[sample+18] d + fstp dword [edi + (18*4)] ; autoc[18]+=d*data[sample+18] ST = d + fld st0 ; ST = d d + fmul dword [esi + (17*4)] ; ST = d*data[sample+17] d + fadd dword [edi + (17*4)] ; ST = autoc[17]+d*data[sample+17] d + fstp dword [edi + (17*4)] ; autoc[17]+=d*data[sample+17] ST = d + fld st0 ; ST = d d + fmul dword [esi + (16*4)] ; ST = d*data[sample+16] d + fadd dword [edi + (16*4)] ; ST = autoc[16]+d*data[sample+16] d + fstp dword [edi + (16*4)] ; autoc[16]+=d*data[sample+16] ST = d + fld st0 ; ST = d d + fmul dword [esi + (15*4)] ; ST = d*data[sample+15] d + fadd dword [edi + (15*4)] ; ST = autoc[15]+d*data[sample+15] d + fstp dword [edi + (15*4)] ; autoc[15]+=d*data[sample+15] ST = d + fld st0 ; ST = d d + fmul dword [esi + (14*4)] ; ST = d*data[sample+14] d + fadd dword [edi + (14*4)] ; ST = autoc[14]+d*data[sample+14] d + fstp dword [edi + (14*4)] ; autoc[14]+=d*data[sample+14] ST = d + fld st0 ; ST = d d + fmul dword [esi + (13*4)] ; ST = d*data[sample+13] d + fadd dword [edi + (13*4)] ; ST = autoc[13]+d*data[sample+13] d + fstp dword [edi + (13*4)] ; autoc[13]+=d*data[sample+13] ST = d + fld st0 ; ST = d d + fmul dword [esi + (12*4)] ; ST = d*data[sample+12] d + fadd dword [edi + (12*4)] ; ST = autoc[12]+d*data[sample+12] d + fstp dword [edi + (12*4)] ; autoc[12]+=d*data[sample+12] ST = d + fld st0 ; ST = d d + fmul dword [esi + (11*4)] ; ST = d*data[sample+11] d + fadd dword [edi + (11*4)] ; ST = autoc[11]+d*data[sample+11] d + fstp dword [edi + (11*4)] ; autoc[11]+=d*data[sample+11] ST = d + fld st0 ; ST = d d + fmul dword [esi + (10*4)] ; ST = d*data[sample+10] d + fadd dword [edi + (10*4)] ; ST = autoc[10]+d*data[sample+10] d + fstp dword [edi + (10*4)] ; autoc[10]+=d*data[sample+10] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 9*4)] ; ST = d*data[sample+9] d + fadd dword [edi + ( 9*4)] ; ST = autoc[9]+d*data[sample+9] d + fstp dword [edi + ( 9*4)] ; autoc[9]+=d*data[sample+9] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 8*4)] ; ST = d*data[sample+8] d + fadd dword [edi + ( 8*4)] ; ST = autoc[8]+d*data[sample+8] d + fstp dword [edi + ( 8*4)] ; autoc[8]+=d*data[sample+8] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 7*4)] ; ST = d*data[sample+7] d + fadd dword [edi + ( 7*4)] ; ST = autoc[7]+d*data[sample+7] d + fstp dword [edi + ( 7*4)] ; autoc[7]+=d*data[sample+7] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 6*4)] ; ST = d*data[sample+6] d + fadd dword [edi + ( 6*4)] ; ST = autoc[6]+d*data[sample+6] d + fstp dword [edi + ( 6*4)] ; autoc[6]+=d*data[sample+6] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 5*4)] ; ST = d*data[sample+4] d + fadd dword [edi + ( 5*4)] ; ST = autoc[4]+d*data[sample+4] d + fstp dword [edi + ( 5*4)] ; autoc[4]+=d*data[sample+4] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 4*4)] ; ST = d*data[sample+4] d + fadd dword [edi + ( 4*4)] ; ST = autoc[4]+d*data[sample+4] d + fstp dword [edi + ( 4*4)] ; autoc[4]+=d*data[sample+4] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 3*4)] ; ST = d*data[sample+3] d + fadd dword [edi + ( 3*4)] ; ST = autoc[3]+d*data[sample+3] d + fstp dword [edi + ( 3*4)] ; autoc[3]+=d*data[sample+3] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 2*4)] ; ST = d*data[sample+2] d + fadd dword [edi + ( 2*4)] ; ST = autoc[2]+d*data[sample+2] d + fstp dword [edi + ( 2*4)] ; autoc[2]+=d*data[sample+2] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 1*4)] ; ST = d*data[sample+1] d + fadd dword [edi + ( 1*4)] ; ST = autoc[1]+d*data[sample+1] d + fstp dword [edi + ( 1*4)] ; autoc[1]+=d*data[sample+1] ST = d + fld st0 ; ST = d d + fmul dword [esi] ; ST = d*data[sample] d WATCHOUT: no displacement byte here! + fadd dword [edi] ; ST = autoc[0]+d*data[sample] d WATCHOUT: no displacement byte here! + fstp dword [edi] ; autoc[0]+=d*data[sample] ST = d WATCHOUT: no displacement byte here! +.jumper1_0: + + fstp st0 ; pop d, ST = empty + add esi, byte 4 ; sample++ + dec ecx + jz .loop1_end + fld dword [esi] ; ST = d <- data[sample] + jmp edx +.loop1_end: + + ; for(; sample < data_len; sample++) { + ; d = data[sample]; + ; for(coeff = 0; coeff < data_len - sample; coeff++) + ; autoc[coeff] += d * data[sample+coeff]; + ; } + mov ecx, [esp + 24] ; ecx <- lag + dec ecx ; ecx <- lag - 1 + jz near .end ; skip loop if 0 (i.e. lag == 1) + + fld dword [esi] ; ST = d <- data[sample] + mov eax, ecx ; eax <- lag - 1 == data_len - sample the first time through + ; each iteration is 11 bytes so we need (-eax)*11, so we do (-12*eax + eax) + lea edx, [eax + eax*2] + neg edx + lea edx, [eax + edx*4 + .jumper2_0 - .get_eip2] + call .get_eip2 +.get_eip2: + pop ebx + add edx, ebx + inc edx ; compensate for the shorter opcode on the last iteration + inc edx ; compensate for the shorter opcode on the last iteration + inc edx ; compensate for the shorter opcode on the last iteration + jmp edx + + fld st0 ; ST = d d + fmul dword [esi + (31*4)] ; ST = d*data[sample+31] d + fadd dword [edi + (31*4)] ; ST = autoc[31]+d*data[sample+31] d + fstp dword [edi + (31*4)] ; autoc[31]+=d*data[sample+31] ST = d + fld st0 ; ST = d d + fmul dword [esi + (30*4)] ; ST = d*data[sample+30] d + fadd dword [edi + (30*4)] ; ST = autoc[30]+d*data[sample+30] d + fstp dword [edi + (30*4)] ; autoc[30]+=d*data[sample+30] ST = d + fld st0 ; ST = d d + fmul dword [esi + (29*4)] ; ST = d*data[sample+29] d + fadd dword [edi + (29*4)] ; ST = autoc[29]+d*data[sample+29] d + fstp dword [edi + (29*4)] ; autoc[29]+=d*data[sample+29] ST = d + fld st0 ; ST = d d + fmul dword [esi + (28*4)] ; ST = d*data[sample+28] d + fadd dword [edi + (28*4)] ; ST = autoc[28]+d*data[sample+28] d + fstp dword [edi + (28*4)] ; autoc[28]+=d*data[sample+28] ST = d + fld st0 ; ST = d d + fmul dword [esi + (27*4)] ; ST = d*data[sample+27] d + fadd dword [edi + (27*4)] ; ST = autoc[27]+d*data[sample+27] d + fstp dword [edi + (27*4)] ; autoc[27]+=d*data[sample+27] ST = d + fld st0 ; ST = d d + fmul dword [esi + (26*4)] ; ST = d*data[sample+26] d + fadd dword [edi + (26*4)] ; ST = autoc[26]+d*data[sample+26] d + fstp dword [edi + (26*4)] ; autoc[26]+=d*data[sample+26] ST = d + fld st0 ; ST = d d + fmul dword [esi + (25*4)] ; ST = d*data[sample+25] d + fadd dword [edi + (25*4)] ; ST = autoc[25]+d*data[sample+25] d + fstp dword [edi + (25*4)] ; autoc[25]+=d*data[sample+25] ST = d + fld st0 ; ST = d d + fmul dword [esi + (24*4)] ; ST = d*data[sample+24] d + fadd dword [edi + (24*4)] ; ST = autoc[24]+d*data[sample+24] d + fstp dword [edi + (24*4)] ; autoc[24]+=d*data[sample+24] ST = d + fld st0 ; ST = d d + fmul dword [esi + (23*4)] ; ST = d*data[sample+23] d + fadd dword [edi + (23*4)] ; ST = autoc[23]+d*data[sample+23] d + fstp dword [edi + (23*4)] ; autoc[23]+=d*data[sample+23] ST = d + fld st0 ; ST = d d + fmul dword [esi + (22*4)] ; ST = d*data[sample+22] d + fadd dword [edi + (22*4)] ; ST = autoc[22]+d*data[sample+22] d + fstp dword [edi + (22*4)] ; autoc[22]+=d*data[sample+22] ST = d + fld st0 ; ST = d d + fmul dword [esi + (21*4)] ; ST = d*data[sample+21] d + fadd dword [edi + (21*4)] ; ST = autoc[21]+d*data[sample+21] d + fstp dword [edi + (21*4)] ; autoc[21]+=d*data[sample+21] ST = d + fld st0 ; ST = d d + fmul dword [esi + (20*4)] ; ST = d*data[sample+20] d + fadd dword [edi + (20*4)] ; ST = autoc[20]+d*data[sample+20] d + fstp dword [edi + (20*4)] ; autoc[20]+=d*data[sample+20] ST = d + fld st0 ; ST = d d + fmul dword [esi + (19*4)] ; ST = d*data[sample+19] d + fadd dword [edi + (19*4)] ; ST = autoc[19]+d*data[sample+19] d + fstp dword [edi + (19*4)] ; autoc[19]+=d*data[sample+19] ST = d + fld st0 ; ST = d d + fmul dword [esi + (18*4)] ; ST = d*data[sample+18] d + fadd dword [edi + (18*4)] ; ST = autoc[18]+d*data[sample+18] d + fstp dword [edi + (18*4)] ; autoc[18]+=d*data[sample+18] ST = d + fld st0 ; ST = d d + fmul dword [esi + (17*4)] ; ST = d*data[sample+17] d + fadd dword [edi + (17*4)] ; ST = autoc[17]+d*data[sample+17] d + fstp dword [edi + (17*4)] ; autoc[17]+=d*data[sample+17] ST = d + fld st0 ; ST = d d + fmul dword [esi + (16*4)] ; ST = d*data[sample+16] d + fadd dword [edi + (16*4)] ; ST = autoc[16]+d*data[sample+16] d + fstp dword [edi + (16*4)] ; autoc[16]+=d*data[sample+16] ST = d + fld st0 ; ST = d d + fmul dword [esi + (15*4)] ; ST = d*data[sample+15] d + fadd dword [edi + (15*4)] ; ST = autoc[15]+d*data[sample+15] d + fstp dword [edi + (15*4)] ; autoc[15]+=d*data[sample+15] ST = d + fld st0 ; ST = d d + fmul dword [esi + (14*4)] ; ST = d*data[sample+14] d + fadd dword [edi + (14*4)] ; ST = autoc[14]+d*data[sample+14] d + fstp dword [edi + (14*4)] ; autoc[14]+=d*data[sample+14] ST = d + fld st0 ; ST = d d + fmul dword [esi + (13*4)] ; ST = d*data[sample+13] d + fadd dword [edi + (13*4)] ; ST = autoc[13]+d*data[sample+13] d + fstp dword [edi + (13*4)] ; autoc[13]+=d*data[sample+13] ST = d + fld st0 ; ST = d d + fmul dword [esi + (12*4)] ; ST = d*data[sample+12] d + fadd dword [edi + (12*4)] ; ST = autoc[12]+d*data[sample+12] d + fstp dword [edi + (12*4)] ; autoc[12]+=d*data[sample+12] ST = d + fld st0 ; ST = d d + fmul dword [esi + (11*4)] ; ST = d*data[sample+11] d + fadd dword [edi + (11*4)] ; ST = autoc[11]+d*data[sample+11] d + fstp dword [edi + (11*4)] ; autoc[11]+=d*data[sample+11] ST = d + fld st0 ; ST = d d + fmul dword [esi + (10*4)] ; ST = d*data[sample+10] d + fadd dword [edi + (10*4)] ; ST = autoc[10]+d*data[sample+10] d + fstp dword [edi + (10*4)] ; autoc[10]+=d*data[sample+10] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 9*4)] ; ST = d*data[sample+9] d + fadd dword [edi + ( 9*4)] ; ST = autoc[9]+d*data[sample+9] d + fstp dword [edi + ( 9*4)] ; autoc[9]+=d*data[sample+9] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 8*4)] ; ST = d*data[sample+8] d + fadd dword [edi + ( 8*4)] ; ST = autoc[8]+d*data[sample+8] d + fstp dword [edi + ( 8*4)] ; autoc[8]+=d*data[sample+8] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 7*4)] ; ST = d*data[sample+7] d + fadd dword [edi + ( 7*4)] ; ST = autoc[7]+d*data[sample+7] d + fstp dword [edi + ( 7*4)] ; autoc[7]+=d*data[sample+7] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 6*4)] ; ST = d*data[sample+6] d + fadd dword [edi + ( 6*4)] ; ST = autoc[6]+d*data[sample+6] d + fstp dword [edi + ( 6*4)] ; autoc[6]+=d*data[sample+6] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 5*4)] ; ST = d*data[sample+4] d + fadd dword [edi + ( 5*4)] ; ST = autoc[4]+d*data[sample+4] d + fstp dword [edi + ( 5*4)] ; autoc[4]+=d*data[sample+4] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 4*4)] ; ST = d*data[sample+4] d + fadd dword [edi + ( 4*4)] ; ST = autoc[4]+d*data[sample+4] d + fstp dword [edi + ( 4*4)] ; autoc[4]+=d*data[sample+4] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 3*4)] ; ST = d*data[sample+3] d + fadd dword [edi + ( 3*4)] ; ST = autoc[3]+d*data[sample+3] d + fstp dword [edi + ( 3*4)] ; autoc[3]+=d*data[sample+3] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 2*4)] ; ST = d*data[sample+2] d + fadd dword [edi + ( 2*4)] ; ST = autoc[2]+d*data[sample+2] d + fstp dword [edi + ( 2*4)] ; autoc[2]+=d*data[sample+2] ST = d + fld st0 ; ST = d d + fmul dword [esi + ( 1*4)] ; ST = d*data[sample+1] d + fadd dword [edi + ( 1*4)] ; ST = autoc[1]+d*data[sample+1] d + fstp dword [edi + ( 1*4)] ; autoc[1]+=d*data[sample+1] ST = d + fld st0 ; ST = d d + fmul dword [esi] ; ST = d*data[sample] d WATCHOUT: no displacement byte here! + fadd dword [edi] ; ST = autoc[0]+d*data[sample] d WATCHOUT: no displacement byte here! + fstp dword [edi] ; autoc[0]+=d*data[sample] ST = d WATCHOUT: no displacement byte here! +.jumper2_0: + + fstp st0 ; pop d, ST = empty + add esi, byte 4 ; sample++ + dec ecx + jz .loop2_end + add edx, byte 11 ; adjust our inner loop counter by adjusting the jump target + fld dword [esi] ; ST = d <- data[sample] + jmp edx +.loop2_end: + +.end: + pop ebx + pop edi + pop esi + ret + + ALIGN 16 +cident FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4 + ;[esp + 16] == autoc[] + ;[esp + 12] == lag + ;[esp + 8] == data_len + ;[esp + 4] == data[] + + ;ASSERT(lag > 0) + ;ASSERT(lag <= 4) + ;ASSERT(lag <= data_len) + + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] = 0.0; + xorps xmm5, xmm5 + + mov edx, [esp + 8] ; edx == data_len + mov eax, [esp + 4] ; eax == &data[sample] <- &data[0] + + movss xmm0, [eax] ; xmm0 = 0,0,0,data[0] + add eax, 4 + movaps xmm2, xmm0 ; xmm2 = 0,0,0,data[0] + shufps xmm0, xmm0, 0 ; xmm0 == data[sample],data[sample],data[sample],data[sample] = data[0],data[0],data[0],data[0] +.warmup: ; xmm2 == data[sample-3],data[sample-2],data[sample-1],data[sample] + mulps xmm0, xmm2 ; xmm0 = xmm0 * xmm2 + addps xmm5, xmm0 ; xmm5 += xmm0 * xmm2 + dec edx + jz .loop_end + ALIGN 16 +.loop_start: + ; start by reading the next sample + movss xmm0, [eax] ; xmm0 = 0,0,0,data[sample] + add eax, 4 + shufps xmm0, xmm0, 0 ; xmm0 = data[sample],data[sample],data[sample],data[sample] + shufps xmm2, xmm2, 93h ; 93h=2-1-0-3 => xmm2 gets rotated left by one float + movss xmm2, xmm0 + mulps xmm0, xmm2 ; xmm0 = xmm0 * xmm2 + addps xmm5, xmm0 ; xmm5 += xmm0 * xmm2 + dec edx + jnz .loop_start +.loop_end: + ; store autoc + mov edx, [esp + 16] ; edx == autoc + movups [edx], xmm5 + +.end: + ret + + ALIGN 16 +cident FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8 + ;[esp + 16] == autoc[] + ;[esp + 12] == lag + ;[esp + 8] == data_len + ;[esp + 4] == data[] + + ;ASSERT(lag > 0) + ;ASSERT(lag <= 8) + ;ASSERT(lag <= data_len) + + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] = 0.0; + xorps xmm5, xmm5 + xorps xmm6, xmm6 + + mov edx, [esp + 8] ; edx == data_len + mov eax, [esp + 4] ; eax == &data[sample] <- &data[0] + + movss xmm0, [eax] ; xmm0 = 0,0,0,data[0] + add eax, 4 + movaps xmm2, xmm0 ; xmm2 = 0,0,0,data[0] + shufps xmm0, xmm0, 0 ; xmm0 == data[sample],data[sample],data[sample],data[sample] = data[0],data[0],data[0],data[0] + movaps xmm1, xmm0 ; xmm1 == data[sample],data[sample],data[sample],data[sample] = data[0],data[0],data[0],data[0] + xorps xmm3, xmm3 ; xmm3 = 0,0,0,0 +.warmup: ; xmm3:xmm2 == data[sample-7],data[sample-6],...,data[sample] + mulps xmm0, xmm2 + mulps xmm1, xmm3 ; xmm1:xmm0 = xmm1:xmm0 * xmm3:xmm2 + addps xmm5, xmm0 + addps xmm6, xmm1 ; xmm6:xmm5 += xmm1:xmm0 * xmm3:xmm2 + dec edx + jz .loop_end + ALIGN 16 +.loop_start: + ; start by reading the next sample + movss xmm0, [eax] ; xmm0 = 0,0,0,data[sample] + ; here we reorder the instructions; see the (#) indexes for a logical order + shufps xmm2, xmm2, 93h ; (3) 93h=2-1-0-3 => xmm2 gets rotated left by one float + add eax, 4 ; (0) + shufps xmm3, xmm3, 93h ; (4) 93h=2-1-0-3 => xmm3 gets rotated left by one float + shufps xmm0, xmm0, 0 ; (1) xmm0 = data[sample],data[sample],data[sample],data[sample] + movss xmm3, xmm2 ; (5) + movaps xmm1, xmm0 ; (2) xmm1 = data[sample],data[sample],data[sample],data[sample] + movss xmm2, xmm0 ; (6) + mulps xmm1, xmm3 ; (8) + mulps xmm0, xmm2 ; (7) xmm1:xmm0 = xmm1:xmm0 * xmm3:xmm2 + addps xmm6, xmm1 ; (10) + addps xmm5, xmm0 ; (9) xmm6:xmm5 += xmm1:xmm0 * xmm3:xmm2 + dec edx + jnz .loop_start +.loop_end: + ; store autoc + mov edx, [esp + 16] ; edx == autoc + movups [edx], xmm5 + movups [edx + 16], xmm6 + +.end: + ret + + ALIGN 16 +cident FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12 + ;[esp + 16] == autoc[] + ;[esp + 12] == lag + ;[esp + 8] == data_len + ;[esp + 4] == data[] + + ;ASSERT(lag > 0) + ;ASSERT(lag <= 12) + ;ASSERT(lag <= data_len) + + ; for(coeff = 0; coeff < lag; coeff++) + ; autoc[coeff] = 0.0; + xorps xmm5, xmm5 + xorps xmm6, xmm6 + xorps xmm7, xmm7 + + mov edx, [esp + 8] ; edx == data_len + mov eax, [esp + 4] ; eax == &data[sample] <- &data[0] + + movss xmm0, [eax] ; xmm0 = 0,0,0,data[0] + add eax, 4 + movaps xmm2, xmm0 ; xmm2 = 0,0,0,data[0] + shufps xmm0, xmm0, 0 ; xmm0 == data[sample],data[sample],data[sample],data[sample] = data[0],data[0],data[0],data[0] + xorps xmm3, xmm3 ; xmm3 = 0,0,0,0 + xorps xmm4, xmm4 ; xmm4 = 0,0,0,0 +.warmup: ; xmm3:xmm2 == data[sample-7],data[sample-6],...,data[sample] + movaps xmm1, xmm0 + mulps xmm1, xmm2 + addps xmm5, xmm1 + movaps xmm1, xmm0 + mulps xmm1, xmm3 + addps xmm6, xmm1 + mulps xmm0, xmm4 + addps xmm7, xmm0 ; xmm7:xmm6:xmm5 += xmm0:xmm0:xmm0 * xmm4:xmm3:xmm2 + dec edx + jz .loop_end + ALIGN 16 +.loop_start: + ; start by reading the next sample + movss xmm0, [eax] ; xmm0 = 0,0,0,data[sample] + add eax, 4 + shufps xmm0, xmm0, 0 ; xmm0 = data[sample],data[sample],data[sample],data[sample] + + ; shift xmm4:xmm3:xmm2 left by one float + shufps xmm2, xmm2, 93h ; 93h=2-1-0-3 => xmm2 gets rotated left by one float + shufps xmm3, xmm3, 93h ; 93h=2-1-0-3 => xmm3 gets rotated left by one float + shufps xmm4, xmm4, 93h ; 93h=2-1-0-3 => xmm4 gets rotated left by one float + movss xmm4, xmm3 + movss xmm3, xmm2 + movss xmm2, xmm0 + + ; xmm7:xmm6:xmm5 += xmm0:xmm0:xmm0 * xmm3:xmm3:xmm2 + movaps xmm1, xmm0 + mulps xmm1, xmm2 + addps xmm5, xmm1 + movaps xmm1, xmm0 + mulps xmm1, xmm3 + addps xmm6, xmm1 + mulps xmm0, xmm4 + addps xmm7, xmm0 + + dec edx + jnz .loop_start +.loop_end: + ; store autoc + mov edx, [esp + 16] ; edx == autoc + movups [edx], xmm5 + movups [edx + 16], xmm6 + movups [edx + 32], xmm7 + +.end: + ret + + ALIGN 16 +cident FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow + ;[ebp + 32] autoc + ;[ebp + 28] lag + ;[ebp + 24] data_len + ;[ebp + 20] data + + push ebp + push ebx + push esi + push edi + mov ebp, esp + + mov esi, [ebp + 20] + mov edi, [ebp + 24] + mov edx, [ebp + 28] + inc edx + and edx, byte -2 + mov eax, edx + neg eax + and esp, byte -8 + lea esp, [esp + 4 * eax] + mov ecx, edx + xor eax, eax +.loop0: + dec ecx + mov [esp + 4 * ecx], eax + jnz short .loop0 + + mov eax, edi + sub eax, edx + mov ebx, edx + and ebx, byte 1 + sub eax, ebx + lea ecx, [esi + 4 * eax - 12] + cmp esi, ecx + mov eax, esi + ja short .loop2_pre + ALIGN 16 ;4 nops +.loop1_i: + movd mm0, [eax] + movd mm2, [eax + 4] + movd mm4, [eax + 8] + movd mm6, [eax + 12] + mov ebx, edx + punpckldq mm0, mm0 + punpckldq mm2, mm2 + punpckldq mm4, mm4 + punpckldq mm6, mm6 + ALIGN 16 ;3 nops +.loop1_j: + sub ebx, byte 2 + movd mm1, [eax + 4 * ebx] + movd mm3, [eax + 4 * ebx + 4] + movd mm5, [eax + 4 * ebx + 8] + movd mm7, [eax + 4 * ebx + 12] + punpckldq mm1, mm3 + punpckldq mm3, mm5 + pfmul mm1, mm0 + punpckldq mm5, mm7 + pfmul mm3, mm2 + punpckldq mm7, [eax + 4 * ebx + 16] + pfmul mm5, mm4 + pfmul mm7, mm6 + pfadd mm1, mm3 + movq mm3, [esp + 4 * ebx] + pfadd mm5, mm7 + pfadd mm1, mm5 + pfadd mm3, mm1 + movq [esp + 4 * ebx], mm3 + jg short .loop1_j + + add eax, byte 16 + cmp eax, ecx + jb short .loop1_i + +.loop2_pre: + mov ebx, eax + sub eax, esi + shr eax, 2 + lea ecx, [esi + 4 * edi] + mov esi, ebx +.loop2_i: + movd mm0, [esi] + mov ebx, edi + sub ebx, eax + cmp ebx, edx + jbe short .loop2_j + mov ebx, edx +.loop2_j: + dec ebx + movd mm1, [esi + 4 * ebx] + pfmul mm1, mm0 + movd mm2, [esp + 4 * ebx] + pfadd mm1, mm2 + movd [esp + 4 * ebx], mm1 + + jnz short .loop2_j + + add esi, byte 4 + inc eax + cmp esi, ecx + jnz short .loop2_i + + mov edi, [ebp + 32] + mov edx, [ebp + 28] +.loop3: + dec edx + mov eax, [esp + 4 * edx] + mov [edi + 4 * edx], eax + jnz short .loop3 + + femms + + mov esp, ebp + pop edi + pop esi + pop ebx + pop ebp + ret + +;void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]) +; +; for(i = 0; i < data_len; i++) { +; sum = 0; +; for(j = 0; j < order; j++) +; sum += qlp_coeff[j] * data[i-j-1]; +; residual[i] = data[i] - (sum >> lp_quantization); +; } +; + ALIGN 16 +cident FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32 + ;[esp + 40] residual[] + ;[esp + 36] lp_quantization + ;[esp + 32] order + ;[esp + 28] qlp_coeff[] + ;[esp + 24] data_len + ;[esp + 20] data[] + + ;ASSERT(order > 0) + + push ebp + push ebx + push esi + push edi + + mov esi, [esp + 20] ; esi = data[] + mov edi, [esp + 40] ; edi = residual[] + mov eax, [esp + 32] ; eax = order + mov ebx, [esp + 24] ; ebx = data_len + + test ebx, ebx + jz near .end ; do nothing if data_len == 0 +.begin: + cmp eax, byte 1 + jg short .i_1more + + mov ecx, [esp + 28] + mov edx, [ecx] ; edx = qlp_coeff[0] + mov eax, [esi - 4] ; eax = data[-1] + mov cl, [esp + 36] ; cl = lp_quantization + ALIGN 16 +.i_1_loop_i: + imul eax, edx + sar eax, cl + neg eax + add eax, [esi] + mov [edi], eax + mov eax, [esi] + add edi, byte 4 + add esi, byte 4 + dec ebx + jnz .i_1_loop_i + + jmp .end + +.i_1more: + cmp eax, byte 32 ; for order <= 32 there is a faster routine + jbe short .i_32 + + ; This version is here just for completeness, since FLAC__MAX_LPC_ORDER == 32 + ALIGN 16 +.i_32more_loop_i: + xor ebp, ebp + mov ecx, [esp + 32] + mov edx, ecx + shl edx, 2 + add edx, [esp + 28] + neg ecx + ALIGN 16 +.i_32more_loop_j: + sub edx, byte 4 + mov eax, [edx] + imul eax, [esi + 4 * ecx] + add ebp, eax + inc ecx + jnz short .i_32more_loop_j + + mov cl, [esp + 36] + sar ebp, cl + neg ebp + add ebp, [esi] + mov [edi], ebp + add esi, byte 4 + add edi, byte 4 + + dec ebx + jnz .i_32more_loop_i + + jmp .end + +.i_32: + sub edi, esi + neg eax + lea edx, [eax + eax * 8 + .jumper_0 - .get_eip0] + call .get_eip0 +.get_eip0: + pop eax + add edx, eax + inc edx + mov eax, [esp + 28] ; eax = qlp_coeff[] + xor ebp, ebp + jmp edx + + mov ecx, [eax + 124] + imul ecx, [esi - 128] + add ebp, ecx + mov ecx, [eax + 120] + imul ecx, [esi - 124] + add ebp, ecx + mov ecx, [eax + 116] + imul ecx, [esi - 120] + add ebp, ecx + mov ecx, [eax + 112] + imul ecx, [esi - 116] + add ebp, ecx + mov ecx, [eax + 108] + imul ecx, [esi - 112] + add ebp, ecx + mov ecx, [eax + 104] + imul ecx, [esi - 108] + add ebp, ecx + mov ecx, [eax + 100] + imul ecx, [esi - 104] + add ebp, ecx + mov ecx, [eax + 96] + imul ecx, [esi - 100] + add ebp, ecx + mov ecx, [eax + 92] + imul ecx, [esi - 96] + add ebp, ecx + mov ecx, [eax + 88] + imul ecx, [esi - 92] + add ebp, ecx + mov ecx, [eax + 84] + imul ecx, [esi - 88] + add ebp, ecx + mov ecx, [eax + 80] + imul ecx, [esi - 84] + add ebp, ecx + mov ecx, [eax + 76] + imul ecx, [esi - 80] + add ebp, ecx + mov ecx, [eax + 72] + imul ecx, [esi - 76] + add ebp, ecx + mov ecx, [eax + 68] + imul ecx, [esi - 72] + add ebp, ecx + mov ecx, [eax + 64] + imul ecx, [esi - 68] + add ebp, ecx + mov ecx, [eax + 60] + imul ecx, [esi - 64] + add ebp, ecx + mov ecx, [eax + 56] + imul ecx, [esi - 60] + add ebp, ecx + mov ecx, [eax + 52] + imul ecx, [esi - 56] + add ebp, ecx + mov ecx, [eax + 48] + imul ecx, [esi - 52] + add ebp, ecx + mov ecx, [eax + 44] + imul ecx, [esi - 48] + add ebp, ecx + mov ecx, [eax + 40] + imul ecx, [esi - 44] + add ebp, ecx + mov ecx, [eax + 36] + imul ecx, [esi - 40] + add ebp, ecx + mov ecx, [eax + 32] + imul ecx, [esi - 36] + add ebp, ecx + mov ecx, [eax + 28] + imul ecx, [esi - 32] + add ebp, ecx + mov ecx, [eax + 24] + imul ecx, [esi - 28] + add ebp, ecx + mov ecx, [eax + 20] + imul ecx, [esi - 24] + add ebp, ecx + mov ecx, [eax + 16] + imul ecx, [esi - 20] + add ebp, ecx + mov ecx, [eax + 12] + imul ecx, [esi - 16] + add ebp, ecx + mov ecx, [eax + 8] + imul ecx, [esi - 12] + add ebp, ecx + mov ecx, [eax + 4] + imul ecx, [esi - 8] + add ebp, ecx + mov ecx, [eax] ; there is one byte missing + imul ecx, [esi - 4] + add ebp, ecx +.jumper_0: + + mov cl, [esp + 36] + sar ebp, cl + neg ebp + add ebp, [esi] + mov [edi + esi], ebp + add esi, byte 4 + + dec ebx + jz short .end + xor ebp, ebp + jmp edx + +.end: + pop edi + pop esi + pop ebx + pop ebp + ret + +; WATCHOUT: this routine works on 16 bit data which means bits-per-sample for +; the channel and qlp_coeffs must be <= 16. Especially note that this routine +; cannot be used for side-channel coded 16bps channels since the effective bps +; is 17. + ALIGN 16 +cident FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx + ;[esp + 40] residual[] + ;[esp + 36] lp_quantization + ;[esp + 32] order + ;[esp + 28] qlp_coeff[] + ;[esp + 24] data_len + ;[esp + 20] data[] + + ;ASSERT(order > 0) + + push ebp + push ebx + push esi + push edi + + mov esi, [esp + 20] ; esi = data[] + mov edi, [esp + 40] ; edi = residual[] + mov eax, [esp + 32] ; eax = order + mov ebx, [esp + 24] ; ebx = data_len + + test ebx, ebx + jz near .end ; do nothing if data_len == 0 + dec ebx + test ebx, ebx + jz near .last_one + + mov edx, [esp + 28] ; edx = qlp_coeff[] + movd mm6, [esp + 36] ; mm6 = 0:lp_quantization + mov ebp, esp + + and esp, 0xfffffff8 + + xor ecx, ecx +.copy_qlp_loop: + push word [edx + 4 * ecx] + inc ecx + cmp ecx, eax + jnz short .copy_qlp_loop + + and ecx, 0x3 + test ecx, ecx + je short .za_end + sub ecx, byte 4 +.za_loop: + push word 0 + inc eax + inc ecx + jnz short .za_loop +.za_end: + + movq mm5, [esp + 2 * eax - 8] + movd mm4, [esi - 16] + punpckldq mm4, [esi - 12] + movd mm0, [esi - 8] + punpckldq mm0, [esi - 4] + packssdw mm4, mm0 + + cmp eax, byte 4 + jnbe short .mmx_4more + + ALIGN 16 +.mmx_4_loop_i: + movd mm1, [esi] + movq mm3, mm4 + punpckldq mm1, [esi + 4] + psrlq mm4, 16 + movq mm0, mm1 + psllq mm0, 48 + por mm4, mm0 + movq mm2, mm4 + psrlq mm4, 16 + pxor mm0, mm0 + punpckhdq mm0, mm1 + pmaddwd mm3, mm5 + pmaddwd mm2, mm5 + psllq mm0, 16 + por mm4, mm0 + movq mm0, mm3 + punpckldq mm3, mm2 + punpckhdq mm0, mm2 + paddd mm3, mm0 + psrad mm3, mm6 + psubd mm1, mm3 + movd [edi], mm1 + punpckhdq mm1, mm1 + movd [edi + 4], mm1 + + add edi, byte 8 + add esi, byte 8 + + sub ebx, 2 + jg .mmx_4_loop_i + jmp .mmx_end + +.mmx_4more: + shl eax, 2 + neg eax + add eax, byte 16 + + ALIGN 16 +.mmx_4more_loop_i: + movd mm1, [esi] + punpckldq mm1, [esi + 4] + movq mm3, mm4 + psrlq mm4, 16 + movq mm0, mm1 + psllq mm0, 48 + por mm4, mm0 + movq mm2, mm4 + psrlq mm4, 16 + pxor mm0, mm0 + punpckhdq mm0, mm1 + pmaddwd mm3, mm5 + pmaddwd mm2, mm5 + psllq mm0, 16 + por mm4, mm0 + + mov ecx, esi + add ecx, eax + mov edx, esp + + ALIGN 16 +.mmx_4more_loop_j: + movd mm0, [ecx - 16] + movd mm7, [ecx - 8] + punpckldq mm0, [ecx - 12] + punpckldq mm7, [ecx - 4] + packssdw mm0, mm7 + pmaddwd mm0, [edx] + punpckhdq mm7, mm7 + paddd mm3, mm0 + movd mm0, [ecx - 12] + punpckldq mm0, [ecx - 8] + punpckldq mm7, [ecx] + packssdw mm0, mm7 + pmaddwd mm0, [edx] + paddd mm2, mm0 + + add edx, byte 8 + add ecx, byte 16 + cmp ecx, esi + jnz .mmx_4more_loop_j + + movq mm0, mm3 + punpckldq mm3, mm2 + punpckhdq mm0, mm2 + paddd mm3, mm0 + psrad mm3, mm6 + psubd mm1, mm3 + movd [edi], mm1 + punpckhdq mm1, mm1 + movd [edi + 4], mm1 + + add edi, byte 8 + add esi, byte 8 + + sub ebx, 2 + jg near .mmx_4more_loop_i + +.mmx_end: + emms + mov esp, ebp +.last_one: + mov eax, [esp + 32] + inc ebx + jnz near FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32.begin + +.end: + pop edi + pop esi + pop ebx + pop ebp + ret + +; ********************************************************************** +; +; void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]) +; { +; unsigned i, j; +; FLAC__int32 sum; +; +; FLAC__ASSERT(order > 0); +; +; for(i = 0; i < data_len; i++) { +; sum = 0; +; for(j = 0; j < order; j++) +; sum += qlp_coeff[j] * data[i-j-1]; +; data[i] = residual[i] + (sum >> lp_quantization); +; } +; } + ALIGN 16 +cident FLAC__lpc_restore_signal_asm_ia32 + ;[esp + 40] data[] + ;[esp + 36] lp_quantization + ;[esp + 32] order + ;[esp + 28] qlp_coeff[] + ;[esp + 24] data_len + ;[esp + 20] residual[] + + ;ASSERT(order > 0) + + push ebp + push ebx + push esi + push edi + + mov esi, [esp + 20] ; esi = residual[] + mov edi, [esp + 40] ; edi = data[] + mov eax, [esp + 32] ; eax = order + mov ebx, [esp + 24] ; ebx = data_len + + test ebx, ebx + jz near .end ; do nothing if data_len == 0 + +.begin: + cmp eax, byte 1 + jg short .x87_1more + + mov ecx, [esp + 28] + mov edx, [ecx] + mov eax, [edi - 4] + mov cl, [esp + 36] + ALIGN 16 +.x87_1_loop_i: + imul eax, edx + sar eax, cl + add eax, [esi] + mov [edi], eax + add esi, byte 4 + add edi, byte 4 + dec ebx + jnz .x87_1_loop_i + + jmp .end + +.x87_1more: + cmp eax, byte 32 ; for order <= 32 there is a faster routine + jbe short .x87_32 + + ; This version is here just for completeness, since FLAC__MAX_LPC_ORDER == 32 + ALIGN 16 +.x87_32more_loop_i: + xor ebp, ebp + mov ecx, [esp + 32] + mov edx, ecx + shl edx, 2 + add edx, [esp + 28] + neg ecx + ALIGN 16 +.x87_32more_loop_j: + sub edx, byte 4 + mov eax, [edx] + imul eax, [edi + 4 * ecx] + add ebp, eax + inc ecx + jnz short .x87_32more_loop_j + + mov cl, [esp + 36] + sar ebp, cl + add ebp, [esi] + mov [edi], ebp + add edi, byte 4 + add esi, byte 4 + + dec ebx + jnz .x87_32more_loop_i + + jmp .end + +.x87_32: + sub esi, edi + neg eax + lea edx, [eax + eax * 8 + .jumper_0 - .get_eip0] + call .get_eip0 +.get_eip0: + pop eax + add edx, eax + inc edx ; compensate for the shorter opcode on the last iteration + mov eax, [esp + 28] ; eax = qlp_coeff[] + xor ebp, ebp + jmp edx + + mov ecx, [eax + 124] ; ecx = qlp_coeff[31] + imul ecx, [edi - 128] ; ecx = qlp_coeff[31] * data[i-32] + add ebp, ecx ; sum += qlp_coeff[31] * data[i-32] + mov ecx, [eax + 120] ; ecx = qlp_coeff[30] + imul ecx, [edi - 124] ; ecx = qlp_coeff[30] * data[i-31] + add ebp, ecx ; sum += qlp_coeff[30] * data[i-31] + mov ecx, [eax + 116] ; ecx = qlp_coeff[29] + imul ecx, [edi - 120] ; ecx = qlp_coeff[29] * data[i-30] + add ebp, ecx ; sum += qlp_coeff[29] * data[i-30] + mov ecx, [eax + 112] ; ecx = qlp_coeff[28] + imul ecx, [edi - 116] ; ecx = qlp_coeff[28] * data[i-29] + add ebp, ecx ; sum += qlp_coeff[28] * data[i-29] + mov ecx, [eax + 108] ; ecx = qlp_coeff[27] + imul ecx, [edi - 112] ; ecx = qlp_coeff[27] * data[i-28] + add ebp, ecx ; sum += qlp_coeff[27] * data[i-28] + mov ecx, [eax + 104] ; ecx = qlp_coeff[26] + imul ecx, [edi - 108] ; ecx = qlp_coeff[26] * data[i-27] + add ebp, ecx ; sum += qlp_coeff[26] * data[i-27] + mov ecx, [eax + 100] ; ecx = qlp_coeff[25] + imul ecx, [edi - 104] ; ecx = qlp_coeff[25] * data[i-26] + add ebp, ecx ; sum += qlp_coeff[25] * data[i-26] + mov ecx, [eax + 96] ; ecx = qlp_coeff[24] + imul ecx, [edi - 100] ; ecx = qlp_coeff[24] * data[i-25] + add ebp, ecx ; sum += qlp_coeff[24] * data[i-25] + mov ecx, [eax + 92] ; ecx = qlp_coeff[23] + imul ecx, [edi - 96] ; ecx = qlp_coeff[23] * data[i-24] + add ebp, ecx ; sum += qlp_coeff[23] * data[i-24] + mov ecx, [eax + 88] ; ecx = qlp_coeff[22] + imul ecx, [edi - 92] ; ecx = qlp_coeff[22] * data[i-23] + add ebp, ecx ; sum += qlp_coeff[22] * data[i-23] + mov ecx, [eax + 84] ; ecx = qlp_coeff[21] + imul ecx, [edi - 88] ; ecx = qlp_coeff[21] * data[i-22] + add ebp, ecx ; sum += qlp_coeff[21] * data[i-22] + mov ecx, [eax + 80] ; ecx = qlp_coeff[20] + imul ecx, [edi - 84] ; ecx = qlp_coeff[20] * data[i-21] + add ebp, ecx ; sum += qlp_coeff[20] * data[i-21] + mov ecx, [eax + 76] ; ecx = qlp_coeff[19] + imul ecx, [edi - 80] ; ecx = qlp_coeff[19] * data[i-20] + add ebp, ecx ; sum += qlp_coeff[19] * data[i-20] + mov ecx, [eax + 72] ; ecx = qlp_coeff[18] + imul ecx, [edi - 76] ; ecx = qlp_coeff[18] * data[i-19] + add ebp, ecx ; sum += qlp_coeff[18] * data[i-19] + mov ecx, [eax + 68] ; ecx = qlp_coeff[17] + imul ecx, [edi - 72] ; ecx = qlp_coeff[17] * data[i-18] + add ebp, ecx ; sum += qlp_coeff[17] * data[i-18] + mov ecx, [eax + 64] ; ecx = qlp_coeff[16] + imul ecx, [edi - 68] ; ecx = qlp_coeff[16] * data[i-17] + add ebp, ecx ; sum += qlp_coeff[16] * data[i-17] + mov ecx, [eax + 60] ; ecx = qlp_coeff[15] + imul ecx, [edi - 64] ; ecx = qlp_coeff[15] * data[i-16] + add ebp, ecx ; sum += qlp_coeff[15] * data[i-16] + mov ecx, [eax + 56] ; ecx = qlp_coeff[14] + imul ecx, [edi - 60] ; ecx = qlp_coeff[14] * data[i-15] + add ebp, ecx ; sum += qlp_coeff[14] * data[i-15] + mov ecx, [eax + 52] ; ecx = qlp_coeff[13] + imul ecx, [edi - 56] ; ecx = qlp_coeff[13] * data[i-14] + add ebp, ecx ; sum += qlp_coeff[13] * data[i-14] + mov ecx, [eax + 48] ; ecx = qlp_coeff[12] + imul ecx, [edi - 52] ; ecx = qlp_coeff[12] * data[i-13] + add ebp, ecx ; sum += qlp_coeff[12] * data[i-13] + mov ecx, [eax + 44] ; ecx = qlp_coeff[11] + imul ecx, [edi - 48] ; ecx = qlp_coeff[11] * data[i-12] + add ebp, ecx ; sum += qlp_coeff[11] * data[i-12] + mov ecx, [eax + 40] ; ecx = qlp_coeff[10] + imul ecx, [edi - 44] ; ecx = qlp_coeff[10] * data[i-11] + add ebp, ecx ; sum += qlp_coeff[10] * data[i-11] + mov ecx, [eax + 36] ; ecx = qlp_coeff[ 9] + imul ecx, [edi - 40] ; ecx = qlp_coeff[ 9] * data[i-10] + add ebp, ecx ; sum += qlp_coeff[ 9] * data[i-10] + mov ecx, [eax + 32] ; ecx = qlp_coeff[ 8] + imul ecx, [edi - 36] ; ecx = qlp_coeff[ 8] * data[i- 9] + add ebp, ecx ; sum += qlp_coeff[ 8] * data[i- 9] + mov ecx, [eax + 28] ; ecx = qlp_coeff[ 7] + imul ecx, [edi - 32] ; ecx = qlp_coeff[ 7] * data[i- 8] + add ebp, ecx ; sum += qlp_coeff[ 7] * data[i- 8] + mov ecx, [eax + 24] ; ecx = qlp_coeff[ 6] + imul ecx, [edi - 28] ; ecx = qlp_coeff[ 6] * data[i- 7] + add ebp, ecx ; sum += qlp_coeff[ 6] * data[i- 7] + mov ecx, [eax + 20] ; ecx = qlp_coeff[ 5] + imul ecx, [edi - 24] ; ecx = qlp_coeff[ 5] * data[i- 6] + add ebp, ecx ; sum += qlp_coeff[ 5] * data[i- 6] + mov ecx, [eax + 16] ; ecx = qlp_coeff[ 4] + imul ecx, [edi - 20] ; ecx = qlp_coeff[ 4] * data[i- 5] + add ebp, ecx ; sum += qlp_coeff[ 4] * data[i- 5] + mov ecx, [eax + 12] ; ecx = qlp_coeff[ 3] + imul ecx, [edi - 16] ; ecx = qlp_coeff[ 3] * data[i- 4] + add ebp, ecx ; sum += qlp_coeff[ 3] * data[i- 4] + mov ecx, [eax + 8] ; ecx = qlp_coeff[ 2] + imul ecx, [edi - 12] ; ecx = qlp_coeff[ 2] * data[i- 3] + add ebp, ecx ; sum += qlp_coeff[ 2] * data[i- 3] + mov ecx, [eax + 4] ; ecx = qlp_coeff[ 1] + imul ecx, [edi - 8] ; ecx = qlp_coeff[ 1] * data[i- 2] + add ebp, ecx ; sum += qlp_coeff[ 1] * data[i- 2] + mov ecx, [eax] ; ecx = qlp_coeff[ 0] (NOTE: one byte missing from instruction) + imul ecx, [edi - 4] ; ecx = qlp_coeff[ 0] * data[i- 1] + add ebp, ecx ; sum += qlp_coeff[ 0] * data[i- 1] +.jumper_0: + + mov cl, [esp + 36] + sar ebp, cl ; ebp = (sum >> lp_quantization) + add ebp, [esi + edi] ; ebp = residual[i] + (sum >> lp_quantization) + mov [edi], ebp ; data[i] = residual[i] + (sum >> lp_quantization) + add edi, byte 4 + + dec ebx + jz short .end + xor ebp, ebp + jmp edx + +.end: + pop edi + pop esi + pop ebx + pop ebp + ret + +; WATCHOUT: this routine works on 16 bit data which means bits-per-sample for +; the channel and qlp_coeffs must be <= 16. Especially note that this routine +; cannot be used for side-channel coded 16bps channels since the effective bps +; is 17. +; WATCHOUT: this routine requires that each data array have a buffer of up to +; 3 zeroes in front (at negative indices) for alignment purposes, i.e. for each +; channel n, data[n][-1] through data[n][-3] should be accessible and zero. + ALIGN 16 +cident FLAC__lpc_restore_signal_asm_ia32_mmx + ;[esp + 40] data[] + ;[esp + 36] lp_quantization + ;[esp + 32] order + ;[esp + 28] qlp_coeff[] + ;[esp + 24] data_len + ;[esp + 20] residual[] + + ;ASSERT(order > 0) + + push ebp + push ebx + push esi + push edi + + mov esi, [esp + 20] + mov edi, [esp + 40] + mov eax, [esp + 32] + mov ebx, [esp + 24] + + test ebx, ebx + jz near .end ; do nothing if data_len == 0 + cmp eax, byte 4 + jb near FLAC__lpc_restore_signal_asm_ia32.begin + + mov edx, [esp + 28] + movd mm6, [esp + 36] + mov ebp, esp + + and esp, 0xfffffff8 + + xor ecx, ecx +.copy_qlp_loop: + push word [edx + 4 * ecx] + inc ecx + cmp ecx, eax + jnz short .copy_qlp_loop + + and ecx, 0x3 + test ecx, ecx + je short .za_end + sub ecx, byte 4 +.za_loop: + push word 0 + inc eax + inc ecx + jnz short .za_loop +.za_end: + + movq mm5, [esp + 2 * eax - 8] + movd mm4, [edi - 16] + punpckldq mm4, [edi - 12] + movd mm0, [edi - 8] + punpckldq mm0, [edi - 4] + packssdw mm4, mm0 + + cmp eax, byte 4 + jnbe short .mmx_4more + + ALIGN 16 +.mmx_4_loop_i: + movq mm7, mm4 + pmaddwd mm7, mm5 + movq mm0, mm7 + punpckhdq mm7, mm7 + paddd mm7, mm0 + psrad mm7, mm6 + movd mm1, [esi] + paddd mm7, mm1 + movd [edi], mm7 + psllq mm7, 48 + psrlq mm4, 16 + por mm4, mm7 + + add esi, byte 4 + add edi, byte 4 + + dec ebx + jnz .mmx_4_loop_i + jmp .mmx_end +.mmx_4more: + shl eax, 2 + neg eax + add eax, byte 16 + ALIGN 16 +.mmx_4more_loop_i: + mov ecx, edi + add ecx, eax + mov edx, esp + + movq mm7, mm4 + pmaddwd mm7, mm5 + + ALIGN 16 +.mmx_4more_loop_j: + movd mm0, [ecx - 16] + punpckldq mm0, [ecx - 12] + movd mm1, [ecx - 8] + punpckldq mm1, [ecx - 4] + packssdw mm0, mm1 + pmaddwd mm0, [edx] + paddd mm7, mm0 + + add edx, byte 8 + add ecx, byte 16 + cmp ecx, edi + jnz .mmx_4more_loop_j + + movq mm0, mm7 + punpckhdq mm7, mm7 + paddd mm7, mm0 + psrad mm7, mm6 + movd mm1, [esi] + paddd mm7, mm1 + movd [edi], mm7 + psllq mm7, 48 + psrlq mm4, 16 + por mm4, mm7 + + add esi, byte 4 + add edi, byte 4 + + dec ebx + jnz short .mmx_4more_loop_i +.mmx_end: + emms + mov esp, ebp + +.end: + pop edi + pop esi + pop ebx + pop ebp + ret + +end + +%ifdef OBJ_FORMAT_elf + section .note.GNU-stack noalloc +%endif diff --git a/flac/src/libFLAC/ia32/lpc_asm.obj b/flac/src/libFLAC/ia32/lpc_asm.obj new file mode 100644 index 0000000..f91ea46 Binary files /dev/null and b/flac/src/libFLAC/ia32/lpc_asm.obj differ diff --git a/flac/src/libFLAC/ia32/nasm.h b/flac/src/libFLAC/ia32/nasm.h new file mode 100644 index 0000000..cd54cde --- /dev/null +++ b/flac/src/libFLAC/ia32/nasm.h @@ -0,0 +1,75 @@ +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + + bits 32 + +%ifdef OBJ_FORMAT_win32 + %define FLAC__PUBLIC_NEEDS_UNDERSCORE + %idefine code_section section .text align=16 class=CODE use32 + %idefine data_section section .data align=32 class=DATA use32 + %idefine bss_section section .bss align=32 class=DATA use32 +%elifdef OBJ_FORMAT_aout + %define FLAC__PUBLIC_NEEDS_UNDERSCORE + %idefine code_section section .text + %idefine data_section section .data + %idefine bss_section section .bss +%elifdef OBJ_FORMAT_aoutb + %define FLAC__PUBLIC_NEEDS_UNDERSCORE + %idefine code_section section .text + %idefine data_section section .data + %idefine bss_section section .bss +%elifdef OBJ_FORMAT_elf + %idefine code_section section .text align=16 + %idefine data_section section .data align=32 + %idefine bss_section section .bss align=32 +%else + %error unsupported object format! +%endif + +%imacro cglobal 1 + %ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + global _%1 + %else + global %1 + %endif +%endmacro + +%imacro cextern 1 + %ifdef FLAC__PUBLIC_NEEDS_UNDERSCORE + extern _%1 + %else + extern %1 + %endif +%endmacro + +%imacro cident 1 +_%1: +%1: +%endmacro diff --git a/flac/src/libFLAC/ia32/stream_encoder_asm.nasm b/flac/src/libFLAC/ia32/stream_encoder_asm.nasm new file mode 100644 index 0000000..9287134 --- /dev/null +++ b/flac/src/libFLAC/ia32/stream_encoder_asm.nasm @@ -0,0 +1,159 @@ +; vim:filetype=nasm ts=8 + +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +%include "nasm.h" + + data_section + +cglobal precompute_partition_info_sums_32bit_asm_ia32_ + + code_section + + +; ********************************************************************** +; +; void FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter) +; void precompute_partition_info_sums_32bit_( +; const FLAC__int32 residual[], +; FLAC__uint64 abs_residual_partition_sums[], +; unsigned blocksize, +; unsigned predictor_order, +; unsigned min_partition_order, +; unsigned max_partition_order +; ) +; + ALIGN 16 +cident precompute_partition_info_sums_32bit_asm_ia32_ + + ;; peppered throughout the code at major checkpoints are keys like this as to where things are at that point in time + ;; [esp + 4] const FLAC__int32 residual[] + ;; [esp + 8] FLAC__uint64 abs_residual_partition_sums[] + ;; [esp + 12] unsigned blocksize + ;; [esp + 16] unsigned predictor_order + ;; [esp + 20] unsigned min_partition_order + ;; [esp + 24] unsigned max_partition_order + push ebp + push ebx + push esi + push edi + sub esp, 8 + ;; [esp + 28] const FLAC__int32 residual[] + ;; [esp + 32] FLAC__uint64 abs_residual_partition_sums[] + ;; [esp + 36] unsigned blocksize + ;; [esp + 40] unsigned predictor_order + ;; [esp + 44] unsigned min_partition_order + ;; [esp + 48] unsigned max_partition_order + ;; [esp] partitions + ;; [esp + 4] default_partition_samples + + mov ecx, [esp + 48] + mov eax, 1 + shl eax, cl + mov [esp], eax ; [esp] <- partitions = 1u << max_partition_order; + mov eax, [esp + 36] + shr eax, cl + mov [esp + 4], eax ; [esp + 4] <- default_partition_samples = blocksize >> max_partition_order; + + ; + ; first do max_partition_order + ; + mov edi, [esp + 4] + sub edi, [esp + 40] ; edi <- end = (unsigned)(-(int)predictor_order) + default_partition_samples + xor esi, esi ; esi <- residual_sample = 0 + xor ecx, ecx ; ecx <- partition = 0 + mov ebp, [esp + 28] ; ebp <- residual[] + xor ebx, ebx ; ebx <- abs_residual_partition_sum = 0; + ; note we put the updates to 'end' and 'abs_residual_partition_sum' at the end of loop0 and in the initialization above so we could align loop0 and loop1 + ALIGN 16 +.loop0: ; for(partition = residual_sample = 0; partition < partitions; partition++) { +.loop1: ; for( ; residual_sample < end; residual_sample++) + mov eax, [ebp + esi * 4] + cdq + xor eax, edx + sub eax, edx + add ebx, eax ; abs_residual_partition_sum += abs(residual[residual_sample]); + ;@@@@@@ check overflow flag and abort here? + add esi, byte 1 + cmp esi, edi ; /* since the loop will always run at least once, we can put the loop check down here */ + jb .loop1 +.next1: + add edi, [esp + 4] ; end += default_partition_samples; + mov eax, [esp + 32] + mov [eax + ecx * 8], ebx ; abs_residual_partition_sums[partition] = abs_residual_partition_sum; + mov [eax + ecx * 8 + 4], dword 0 + xor ebx, ebx ; abs_residual_partition_sum = 0; + add ecx, byte 1 + cmp ecx, [esp] ; /* since the loop will always run at least once, we can put the loop check down here */ + jb .loop0 +.next0: ; } + ; + ; now merge partitions for lower orders + ; + mov esi, [esp + 32] ; esi <- abs_residual_partition_sums[from_partition==0]; + mov eax, [esp] + lea edi, [esi + eax * 8] ; edi <- abs_residual_partition_sums[to_partition==partitions]; + mov ecx, [esp + 48] + sub ecx, byte 1 ; ecx <- partition_order = (int)max_partition_order - 1; + ALIGN 16 +.loop2: ; for(; partition_order >= (int)min_partition_order; partition_order--) { + cmp ecx, [esp + 44] + jl .next2 + mov edx, 1 + shl edx, cl ; const unsigned partitions = 1u << partition_order; + ALIGN 16 +.loop3: ; for(i = 0; i < partitions; i++) { + mov eax, [esi] + mov ebx, [esi + 4] + add eax, [esi + 8] + adc ebx, [esi + 12] + mov [edi], eax + mov [edi + 4], ebx ; a_r_p_s[to_partition] = a_r_p_s[from_partition] + a_r_p_s[from_partition+1]; + add esi, byte 16 + add edi, byte 8 + sub edx, byte 1 + jnz .loop3 ; } + sub ecx, byte 1 + jmp .loop2 ; } +.next2: + + add esp, 8 + pop edi + pop esi + pop ebx + pop ebp + ret + +end + +%ifdef OBJ_FORMAT_elf + section .note.GNU-stack noalloc +%endif diff --git a/flac/src/libFLAC/ia32/stream_encoder_asm.obj b/flac/src/libFLAC/ia32/stream_encoder_asm.obj new file mode 100644 index 0000000..aebec11 Binary files /dev/null and b/flac/src/libFLAC/ia32/stream_encoder_asm.obj differ diff --git a/flac/src/libFLAC/include/Makefile.am b/flac/src/libFLAC/include/Makefile.am new file mode 100644 index 0000000..b131696 --- /dev/null +++ b/flac/src/libFLAC/include/Makefile.am @@ -0,0 +1,31 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +SUBDIRS = private protected diff --git a/flac/src/libFLAC/include/private/Makefile.am b/flac/src/libFLAC/include/private/Makefile.am new file mode 100644 index 0000000..59805b2 --- /dev/null +++ b/flac/src/libFLAC/include/private/Makefile.am @@ -0,0 +1,50 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +noinst_HEADERS = \ + all.h \ + bitmath.h \ + bitreader.h \ + bitwriter.h \ + cpu.h \ + crc.h \ + fixed.h \ + float.h \ + format.h \ + lpc.h \ + md5.h \ + memory.h \ + metadata.h \ + ogg_decoder_aspect.h \ + ogg_encoder_aspect.h \ + ogg_helper.h \ + ogg_mapping.h \ + stream_encoder_framing.h \ + window.h diff --git a/flac/src/libFLAC/include/private/all.h b/flac/src/libFLAC/include/private/all.h new file mode 100644 index 0000000..e938a6a --- /dev/null +++ b/flac/src/libFLAC/include/private/all.h @@ -0,0 +1,49 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__ALL_H +#define FLAC__PRIVATE__ALL_H + +#include "bitmath.h" +#include "bitreader.h" +#include "bitwriter.h" +#include "cpu.h" +#include "crc.h" +#include "fixed.h" +#include "float.h" +#include "format.h" +#include "lpc.h" +#include "md5.h" +#include "memory.h" +#include "metadata.h" +#include "stream_encoder_framing.h" + +#endif diff --git a/flac/src/libFLAC/include/private/bitmath.h b/flac/src/libFLAC/include/private/bitmath.h new file mode 100644 index 0000000..5aebd0f --- /dev/null +++ b/flac/src/libFLAC/include/private/bitmath.h @@ -0,0 +1,42 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__BITMATH_H +#define FLAC__PRIVATE__BITMATH_H + +#include "FLAC/ordinals.h" + +unsigned FLAC__bitmath_ilog2(FLAC__uint32 v); +unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v); +unsigned FLAC__bitmath_silog2(int v); +unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v); + +#endif diff --git a/flac/src/libFLAC/include/private/bitreader.h b/flac/src/libFLAC/include/private/bitreader.h new file mode 100644 index 0000000..96b41a7 --- /dev/null +++ b/flac/src/libFLAC/include/private/bitreader.h @@ -0,0 +1,99 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__BITREADER_H +#define FLAC__PRIVATE__BITREADER_H + +#include /* for FILE */ +#include "FLAC/ordinals.h" +#include "cpu.h" + +/* + * opaque structure definition + */ +struct FLAC__BitReader; +typedef struct FLAC__BitReader FLAC__BitReader; + +typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data); + +/* + * construction, deletion, initialization, etc functions + */ +FLAC__BitReader *FLAC__bitreader_new(void); +void FLAC__bitreader_delete(FLAC__BitReader *br); +FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd); +void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */ +FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br); +void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out); + +/* + * CRC functions + */ +void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed); +FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br); + +/* + * info functions + */ +FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br); +unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br); +unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br); + +/* + * read functions + */ + +FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits); +FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits); +FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits); +FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/ +FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */ +FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */ +FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */ +FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val); +FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter); +FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter); +#ifndef FLAC__NO_ASM +# ifdef FLAC__CPU_IA32 +# ifdef FLAC__HAS_NASM +FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter); +# endif +# endif +#endif +#if 0 /* UNUSED */ +FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter); +FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter); +#endif +FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen); +FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen); + +FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br); +#endif diff --git a/flac/src/libFLAC/include/private/bitwriter.h b/flac/src/libFLAC/include/private/bitwriter.h new file mode 100644 index 0000000..6e93cdb --- /dev/null +++ b/flac/src/libFLAC/include/private/bitwriter.h @@ -0,0 +1,103 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__BITWRITER_H +#define FLAC__PRIVATE__BITWRITER_H + +#include /* for FILE */ +#include "FLAC/ordinals.h" + +/* + * opaque structure definition + */ +struct FLAC__BitWriter; +typedef struct FLAC__BitWriter FLAC__BitWriter; + +/* + * construction, deletion, initialization, etc functions + */ +FLAC__BitWriter *FLAC__bitwriter_new(void); +void FLAC__bitwriter_delete(FLAC__BitWriter *bw); +FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw); +void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */ +void FLAC__bitwriter_clear(FLAC__BitWriter *bw); +void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out); + +/* + * CRC functions + * + * non-const *bw because they have to cal FLAC__bitwriter_get_buffer() + */ +FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc); +FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc); + +/* + * info functions + */ +FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw); +unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */ + +/* + * direct buffer access + * + * there may be no calls on the bitwriter between get and release. + * the bitwriter continues to own the returned buffer. + * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned() + */ +FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes); +void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw); + +/* + * write functions + */ +FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits); +FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits); +FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits); +FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits); +FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/ +FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals); +FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val); +unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter); +#if 0 /* UNUSED */ +unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter); +unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter); +#endif +FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter); +FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter); +#if 0 /* UNUSED */ +FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter); +FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter); +#endif +FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val); +FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val); +FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw); + +#endif diff --git a/flac/src/libFLAC/include/private/cpu.h b/flac/src/libFLAC/include/private/cpu.h new file mode 100644 index 0000000..91fcb9c --- /dev/null +++ b/flac/src/libFLAC/include/private/cpu.h @@ -0,0 +1,88 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__CPU_H +#define FLAC__PRIVATE__CPU_H + +#include "FLAC/ordinals.h" + +#ifdef HAVE_CONFIG_H +#include +#endif + +typedef enum { + FLAC__CPUINFO_TYPE_IA32, + FLAC__CPUINFO_TYPE_PPC, + FLAC__CPUINFO_TYPE_UNKNOWN +} FLAC__CPUInfo_Type; + +typedef struct { + FLAC__bool cpuid; + FLAC__bool bswap; + FLAC__bool cmov; + FLAC__bool mmx; + FLAC__bool fxsr; + FLAC__bool sse; + FLAC__bool sse2; + FLAC__bool sse3; + FLAC__bool ssse3; + FLAC__bool _3dnow; + FLAC__bool ext3dnow; + FLAC__bool extmmx; +} FLAC__CPUInfo_IA32; + +typedef struct { + FLAC__bool altivec; + FLAC__bool ppc64; +} FLAC__CPUInfo_PPC; + +typedef struct { + FLAC__bool use_asm; + FLAC__CPUInfo_Type type; + union { + FLAC__CPUInfo_IA32 ia32; + FLAC__CPUInfo_PPC ppc; + } data; +} FLAC__CPUInfo; + +void FLAC__cpu_info(FLAC__CPUInfo *info); + +#ifndef FLAC__NO_ASM +#ifdef FLAC__CPU_IA32 +#ifdef FLAC__HAS_NASM +FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void); +void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx); +FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void); +#endif +#endif +#endif + +#endif diff --git a/flac/src/libFLAC/include/private/crc.h b/flac/src/libFLAC/include/private/crc.h new file mode 100644 index 0000000..bb765ae --- /dev/null +++ b/flac/src/libFLAC/include/private/crc.h @@ -0,0 +1,61 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__CRC_H +#define FLAC__PRIVATE__CRC_H + +#include "FLAC/ordinals.h" + +/* 8 bit CRC generator, MSB shifted first +** polynomial = x^8 + x^2 + x^1 + x^0 +** init = 0 +*/ +extern FLAC__byte const FLAC__crc8_table[256]; +#define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)]; +void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc); +void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc); +FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len); + +/* 16 bit CRC generator, MSB shifted first +** polynomial = x^16 + x^15 + x^2 + x^0 +** init = 0 +*/ +extern unsigned const FLAC__crc16_table[256]; + +#define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)])) +/* this alternate may be faster on some systems/compilers */ +#if 0 +#define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff) +#endif + +unsigned FLAC__crc16(const FLAC__byte *data, unsigned len); + +#endif diff --git a/flac/src/libFLAC/include/private/fixed.h b/flac/src/libFLAC/include/private/fixed.h new file mode 100644 index 0000000..fe123f3 --- /dev/null +++ b/flac/src/libFLAC/include/private/fixed.h @@ -0,0 +1,97 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__FIXED_H +#define FLAC__PRIVATE__FIXED_H + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "private/float.h" +#include "FLAC/format.h" + +/* + * FLAC__fixed_compute_best_predictor() + * -------------------------------------------------------------------- + * Compute the best fixed predictor and the expected bits-per-sample + * of the residual signal for each order. The _wide() version uses + * 64-bit integers which is statistically necessary when bits-per- + * sample + log2(blocksize) > 30 + * + * IN data[0,data_len-1] + * IN data_len + * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER] + */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY +unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +# ifndef FLAC__NO_ASM +# ifdef FLAC__CPU_IA32 +# ifdef FLAC__HAS_NASM +unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +# endif +# endif +# endif +unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +#else +unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +#endif + +/* + * FLAC__fixed_compute_residual() + * -------------------------------------------------------------------- + * Compute the residual signal obtained from sutracting the predicted + * signal from the original. + * + * IN data[-order,data_len-1] original signal (NOTE THE INDICES!) + * IN data_len length of original signal + * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order + * OUT residual[0,data_len-1] residual signal + */ +void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]); + +/* + * FLAC__fixed_restore_signal() + * -------------------------------------------------------------------- + * Restore the original signal by summing the residual and the + * predictor. + * + * IN residual[0,data_len-1] residual signal + * IN data_len length of original signal + * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order + * *** IMPORTANT: the caller must pass in the historical samples: + * IN data[-order,-1] previously-reconstructed historical samples + * OUT data[0,data_len-1] original signal + */ +void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]); + +#endif diff --git a/flac/src/libFLAC/include/private/float.h b/flac/src/libFLAC/include/private/float.h new file mode 100644 index 0000000..da8d4ff --- /dev/null +++ b/flac/src/libFLAC/include/private/float.h @@ -0,0 +1,97 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__FLOAT_H +#define FLAC__PRIVATE__FLOAT_H + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "FLAC/ordinals.h" + +/* + * These typedefs make it easier to ensure that integer versions of + * the library really only contain integer operations. All the code + * in libFLAC should use FLAC__float and FLAC__double in place of + * float and double, and be protected by checks of the macro + * FLAC__INTEGER_ONLY_LIBRARY. + * + * FLAC__real is the basic floating point type used in LPC analysis. + */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY +typedef double FLAC__double; +typedef float FLAC__float; +/* + * WATCHOUT: changing FLAC__real will change the signatures of many + * functions that have assembly language equivalents and break them. + */ +typedef float FLAC__real; +#else +/* + * The convention for FLAC__fixedpoint is to use the upper 16 bits + * for the integer part and lower 16 bits for the fractional part. + */ +typedef FLAC__int32 FLAC__fixedpoint; +extern const FLAC__fixedpoint FLAC__FP_ZERO; +extern const FLAC__fixedpoint FLAC__FP_ONE_HALF; +extern const FLAC__fixedpoint FLAC__FP_ONE; +extern const FLAC__fixedpoint FLAC__FP_LN2; +extern const FLAC__fixedpoint FLAC__FP_E; + +#define FLAC__fixedpoint_trunc(x) ((x)>>16) + +#define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) ) + +#define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) ) + +/* + * FLAC__fixedpoint_log2() + * -------------------------------------------------------------------- + * Returns the base-2 logarithm of the fixed-point number 'x' using an + * algorithm by Knuth for x >= 1.0 + * + * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must + * be < 32 and evenly divisible by 4 (0 is OK but not very precise). + * + * 'precision' roughly limits the number of iterations that are done; + * use (unsigned)(-1) for maximum precision. + * + * If 'x' is less than one -- that is, x < (1< +#endif + +#include "private/float.h" +#include "FLAC/format.h" + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +/* + * FLAC__lpc_window_data() + * -------------------------------------------------------------------- + * Applies the given window to the data. + * OPT: asm implementation + * + * IN in[0,data_len-1] + * IN window[0,data_len-1] + * OUT out[0,lag-1] + * IN data_len + */ +void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len); + +/* + * FLAC__lpc_compute_autocorrelation() + * -------------------------------------------------------------------- + * Compute the autocorrelation for lags between 0 and lag-1. + * Assumes data[] outside of [0,data_len-1] == 0. + * Asserts that lag > 0. + * + * IN data[0,data_len-1] + * IN data_len + * IN 0 < lag <= data_len + * OUT autoc[0,lag-1] + */ +void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +#ifndef FLAC__NO_ASM +# ifdef FLAC__CPU_IA32 +# ifdef FLAC__HAS_NASM +void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); +# endif +# endif +#endif + +/* + * FLAC__lpc_compute_lp_coefficients() + * -------------------------------------------------------------------- + * Computes LP coefficients for orders 1..max_order. + * Do not call if autoc[0] == 0.0. This means the signal is zero + * and there is no point in calculating a predictor. + * + * IN autoc[0,max_order] autocorrelation values + * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute + * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order + * *** IMPORTANT: + * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched + * OUT error[0,max_order-1] error for each order (more + * specifically, the variance of + * the error signal times # of + * samples in the signal) + * + * Example: if max_order is 9, the LP coefficients for order 9 will be + * in lp_coeff[8][0,8], the LP coefficients for order 8 will be + * in lp_coeff[7][0,7], etc. + */ +void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]); + +/* + * FLAC__lpc_quantize_coefficients() + * -------------------------------------------------------------------- + * Quantizes the LP coefficients. NOTE: precision + bits_per_sample + * must be less than 32 (sizeof(FLAC__int32)*8). + * + * IN lp_coeff[0,order-1] LP coefficients + * IN order LP order + * IN FLAC__MIN_QLP_COEFF_PRECISION < precision + * desired precision (in bits, including sign + * bit) of largest coefficient + * OUT qlp_coeff[0,order-1] quantized coefficients + * OUT shift # of bits to shift right to get approximated + * LP coefficients. NOTE: could be negative. + * RETURN 0 => quantization OK + * 1 => coefficients require too much shifting for *shift to + * fit in the LPC subframe header. 'shift' is unset. + * 2 => coefficients are all zero, which is bad. 'shift' is + * unset. + */ +int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift); + +/* + * FLAC__lpc_compute_residual_from_qlp_coefficients() + * -------------------------------------------------------------------- + * Compute the residual signal obtained from sutracting the predicted + * signal from the original. + * + * IN data[-order,data_len-1] original signal (NOTE THE INDICES!) + * IN data_len length of original signal + * IN qlp_coeff[0,order-1] quantized LP coefficients + * IN order > 0 LP order + * IN lp_quantization quantization of LP coefficients in bits + * OUT residual[0,data_len-1] residual signal + */ +void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); +void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); +#ifndef FLAC__NO_ASM +# ifdef FLAC__CPU_IA32 +# ifdef FLAC__HAS_NASM +void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); +void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); +# endif +# endif +#endif + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ + +/* + * FLAC__lpc_restore_signal() + * -------------------------------------------------------------------- + * Restore the original signal by summing the residual and the + * predictor. + * + * IN residual[0,data_len-1] residual signal + * IN data_len length of original signal + * IN qlp_coeff[0,order-1] quantized LP coefficients + * IN order > 0 LP order + * IN lp_quantization quantization of LP coefficients in bits + * *** IMPORTANT: the caller must pass in the historical samples: + * IN data[-order,-1] previously-reconstructed historical samples + * OUT data[0,data_len-1] original signal + */ +void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +#ifndef FLAC__NO_ASM +# ifdef FLAC__CPU_IA32 +# ifdef FLAC__HAS_NASM +void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +# endif /* FLAC__HAS_NASM */ +# elif defined FLAC__CPU_PPC +void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); +# endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */ +#endif /* FLAC__NO_ASM */ + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +/* + * FLAC__lpc_compute_expected_bits_per_residual_sample() + * -------------------------------------------------------------------- + * Compute the expected number of bits per residual signal sample + * based on the LP error (which is related to the residual variance). + * + * IN lpc_error >= 0.0 error returned from calculating LP coefficients + * IN total_samples > 0 # of samples in residual signal + * RETURN expected bits per sample + */ +FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples); +FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale); + +/* + * FLAC__lpc_compute_best_order() + * -------------------------------------------------------------------- + * Compute the best order from the array of signal errors returned + * during coefficient computation. + * + * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients + * IN max_order > 0 max LP order + * IN total_samples > 0 # of samples in residual signal + * IN overhead_bits_per_order # of bits overhead for each increased LP order + * (includes warmup sample size and quantized LP coefficient) + * RETURN [1,max_order] best order + */ +unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order); + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ + +#endif diff --git a/flac/src/libFLAC/include/private/md5.h b/flac/src/libFLAC/include/private/md5.h new file mode 100644 index 0000000..33c2eda --- /dev/null +++ b/flac/src/libFLAC/include/private/md5.h @@ -0,0 +1,44 @@ +#ifndef FLAC__PRIVATE__MD5_H +#define FLAC__PRIVATE__MD5_H + +/* + * This is the header file for the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + * + * Changed so as no longer to depend on Colin Plumb's `usual.h' + * header definitions; now uses stuff from dpkg's config.h + * - Ian Jackson . + * Still in the public domain. + * + * Josh Coalson: made some changes to integrate with libFLAC. + * Still in the public domain, with no warranty. + */ + +#include "FLAC/ordinals.h" + +typedef struct { + FLAC__uint32 in[16]; + FLAC__uint32 buf[4]; + FLAC__uint32 bytes[2]; + FLAC__byte *internal_buf; + size_t capacity; +} FLAC__MD5Context; + +void FLAC__MD5Init(FLAC__MD5Context *context); +void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context); + +FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample); + +#endif diff --git a/flac/src/libFLAC/include/private/memory.h b/flac/src/libFLAC/include/private/memory.h new file mode 100644 index 0000000..8a5e07e --- /dev/null +++ b/flac/src/libFLAC/include/private/memory.h @@ -0,0 +1,56 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__MEMORY_H +#define FLAC__PRIVATE__MEMORY_H + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include /* for size_t */ + +#include "private/float.h" +#include "FLAC/ordinals.h" /* for FLAC__bool */ + +/* Returns the unaligned address returned by malloc. + * Use free() on this address to deallocate. + */ +void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address); +FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer); +FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer); +FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer); +FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer); +#ifndef FLAC__INTEGER_ONLY_LIBRARY +FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer); +#endif + +#endif diff --git a/flac/src/libFLAC/include/private/metadata.h b/flac/src/libFLAC/include/private/metadata.h new file mode 100644 index 0000000..b4791cf --- /dev/null +++ b/flac/src/libFLAC/include/private/metadata.h @@ -0,0 +1,45 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__METADATA_H +#define FLAC__PRIVATE__METADATA_H + +#include "FLAC/metadata.h" + +/* WATCHOUT: all malloc()ed data in the block is free()ed; this may not + * be a consistent state (e.g. PICTURE) or equivalent to the initial + * state after FLAC__metadata_object_new() + */ +void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object); + +void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object); + +#endif diff --git a/flac/src/libFLAC/include/private/ogg_decoder_aspect.h b/flac/src/libFLAC/include/private/ogg_decoder_aspect.h new file mode 100644 index 0000000..77666d9 --- /dev/null +++ b/flac/src/libFLAC/include/private/ogg_decoder_aspect.h @@ -0,0 +1,79 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__OGG_DECODER_ASPECT_H +#define FLAC__PRIVATE__OGG_DECODER_ASPECT_H + +#include + +#include "FLAC/ordinals.h" +#include "FLAC/stream_decoder.h" /* for FLAC__StreamDecoderReadStatus */ + +typedef struct FLAC__OggDecoderAspect { + /* these are storage for values that can be set through the API */ + FLAC__bool use_first_serial_number; + long serial_number; + + /* these are for internal state related to Ogg decoding */ + ogg_stream_state stream_state; + ogg_sync_state sync_state; + unsigned version_major, version_minor; + FLAC__bool need_serial_number; + FLAC__bool end_of_stream; + FLAC__bool have_working_page; /* only if true will the following vars be valid */ + ogg_page working_page; + FLAC__bool have_working_packet; /* only if true will the following vars be valid */ + ogg_packet working_packet; /* as we work through the packet we will move working_packet.packet forward and working_packet.bytes down */ +} FLAC__OggDecoderAspect; + +void FLAC__ogg_decoder_aspect_set_serial_number(FLAC__OggDecoderAspect *aspect, long value); +void FLAC__ogg_decoder_aspect_set_defaults(FLAC__OggDecoderAspect *aspect); +FLAC__bool FLAC__ogg_decoder_aspect_init(FLAC__OggDecoderAspect *aspect); +void FLAC__ogg_decoder_aspect_finish(FLAC__OggDecoderAspect *aspect); +void FLAC__ogg_decoder_aspect_flush(FLAC__OggDecoderAspect *aspect); +void FLAC__ogg_decoder_aspect_reset(FLAC__OggDecoderAspect *aspect); + +typedef enum { + FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK = 0, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR, + FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR +} FLAC__OggDecoderAspectReadStatus; + +typedef FLAC__OggDecoderAspectReadStatus (*FLAC__OggDecoderAspectReadCallbackProxy)(const void *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); + +FLAC__OggDecoderAspectReadStatus FLAC__ogg_decoder_aspect_read_callback_wrapper(FLAC__OggDecoderAspect *aspect, FLAC__byte buffer[], size_t *bytes, FLAC__OggDecoderAspectReadCallbackProxy read_callback, const FLAC__StreamDecoder *decoder, void *client_data); + +#endif diff --git a/flac/src/libFLAC/include/private/ogg_encoder_aspect.h b/flac/src/libFLAC/include/private/ogg_encoder_aspect.h new file mode 100644 index 0000000..f4a9c2e --- /dev/null +++ b/flac/src/libFLAC/include/private/ogg_encoder_aspect.h @@ -0,0 +1,62 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__OGG_ENCODER_ASPECT_H +#define FLAC__PRIVATE__OGG_ENCODER_ASPECT_H + +#include + +#include "FLAC/ordinals.h" +#include "FLAC/stream_encoder.h" /* for FLAC__StreamEncoderWriteStatus */ + +typedef struct FLAC__OggEncoderAspect { + /* these are storage for values that can be set through the API */ + long serial_number; + unsigned num_metadata; + + /* these are for internal state related to Ogg encoding */ + ogg_stream_state stream_state; + ogg_page page; + FLAC__bool seen_magic; /* true if we've seen the fLaC magic in the write callback yet */ + FLAC__bool is_first_packet; + FLAC__uint64 samples_written; +} FLAC__OggEncoderAspect; + +void FLAC__ogg_encoder_aspect_set_serial_number(FLAC__OggEncoderAspect *aspect, long value); +FLAC__bool FLAC__ogg_encoder_aspect_set_num_metadata(FLAC__OggEncoderAspect *aspect, unsigned value); +void FLAC__ogg_encoder_aspect_set_defaults(FLAC__OggEncoderAspect *aspect); +FLAC__bool FLAC__ogg_encoder_aspect_init(FLAC__OggEncoderAspect *aspect); +void FLAC__ogg_encoder_aspect_finish(FLAC__OggEncoderAspect *aspect); + +typedef FLAC__StreamEncoderWriteStatus (*FLAC__OggEncoderAspectWriteCallbackProxy)(const void *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data); + +FLAC__StreamEncoderWriteStatus FLAC__ogg_encoder_aspect_write_callback_wrapper(FLAC__OggEncoderAspect *aspect, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, FLAC__bool is_last_block, FLAC__OggEncoderAspectWriteCallbackProxy write_callback, void *encoder, void *client_data); +#endif diff --git a/flac/src/libFLAC/include/private/ogg_helper.h b/flac/src/libFLAC/include/private/ogg_helper.h new file mode 100644 index 0000000..c3ee503 --- /dev/null +++ b/flac/src/libFLAC/include/private/ogg_helper.h @@ -0,0 +1,43 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__OGG_HELPER_H +#define FLAC__PRIVATE__OGG_HELPER_H + +#include +#include "FLAC/stream_encoder.h" /* for FLAC__StreamEncoder */ + +void simple_ogg_page__init(ogg_page *page); +void simple_ogg_page__clear(ogg_page *page); +FLAC__bool simple_ogg_page__get_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderReadCallback read_callback, void *client_data); +FLAC__bool simple_ogg_page__set_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderWriteCallback write_callback, void *client_data); + +#endif diff --git a/flac/src/libFLAC/include/private/ogg_mapping.h b/flac/src/libFLAC/include/private/ogg_mapping.h new file mode 100644 index 0000000..76bcbed --- /dev/null +++ b/flac/src/libFLAC/include/private/ogg_mapping.h @@ -0,0 +1,63 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__OGG_MAPPING_H +#define FLAC__PRIVATE__OGG_MAPPING_H + +#include "FLAC/ordinals.h" + +/** The length of the 'FLAC' magic in bytes. */ +#define FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH (1u) + +extern const unsigned FLAC__OGG_MAPPING_PACKET_TYPE_LEN; /* = 8 bits */ + +extern const FLAC__byte FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE; /* = 0x7f */ + +/** The length of the 'FLAC' magic in bytes. */ +#define FLAC__OGG_MAPPING_MAGIC_LENGTH (4u) + +extern const FLAC__byte * const FLAC__OGG_MAPPING_MAGIC; /* = "FLAC" */ + +extern const unsigned FLAC__OGG_MAPPING_VERSION_MAJOR_LEN; /* = 8 bits */ +extern const unsigned FLAC__OGG_MAPPING_VERSION_MINOR_LEN; /* = 8 bits */ + +/** The length of the Ogg FLAC mapping major version number in bytes. */ +#define FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH (1u) + +/** The length of the Ogg FLAC mapping minor version number in bytes. */ +#define FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH (1u) + +extern const unsigned FLAC__OGG_MAPPING_NUM_HEADERS_LEN; /* = 16 bits */ + +/** The length of the #-of-header-packets number bytes. */ +#define FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH (2u) + +#endif diff --git a/flac/src/libFLAC/include/private/stream_encoder_framing.h b/flac/src/libFLAC/include/private/stream_encoder_framing.h new file mode 100644 index 0000000..4500ac7 --- /dev/null +++ b/flac/src/libFLAC/include/private/stream_encoder_framing.h @@ -0,0 +1,45 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H +#define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H + +#include "FLAC/format.h" +#include "bitwriter.h" + +FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw); +FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw); +FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw); +FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw); +FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw); +FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw); + +#endif diff --git a/flac/src/libFLAC/include/private/window.h b/flac/src/libFLAC/include/private/window.h new file mode 100644 index 0000000..7b43639 --- /dev/null +++ b/flac/src/libFLAC/include/private/window.h @@ -0,0 +1,71 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PRIVATE__WINDOW_H +#define FLAC__PRIVATE__WINDOW_H + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "private/float.h" +#include "FLAC/format.h" + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +/* + * FLAC__window_*() + * -------------------------------------------------------------------- + * Calculates window coefficients according to different apodization + * functions. + * + * OUT window[0,L-1] + * IN L (number of points in window) + */ +void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */ +void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L); +void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p); +void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L); + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ + +#endif diff --git a/flac/src/libFLAC/include/protected/Makefile.am b/flac/src/libFLAC/include/protected/Makefile.am new file mode 100644 index 0000000..50b780c --- /dev/null +++ b/flac/src/libFLAC/include/protected/Makefile.am @@ -0,0 +1,34 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +noinst_HEADERS = \ + all.h \ + stream_decoder.h \ + stream_encoder.h diff --git a/flac/src/libFLAC/include/protected/all.h b/flac/src/libFLAC/include/protected/all.h new file mode 100644 index 0000000..52c12ef --- /dev/null +++ b/flac/src/libFLAC/include/protected/all.h @@ -0,0 +1,38 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PROTECTED__ALL_H +#define FLAC__PROTECTED__ALL_H + +#include "stream_decoder.h" +#include "stream_encoder.h" + +#endif diff --git a/flac/src/libFLAC/include/protected/stream_decoder.h b/flac/src/libFLAC/include/protected/stream_decoder.h new file mode 100644 index 0000000..1f08d9d --- /dev/null +++ b/flac/src/libFLAC/include/protected/stream_decoder.h @@ -0,0 +1,58 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PROTECTED__STREAM_DECODER_H +#define FLAC__PROTECTED__STREAM_DECODER_H + +#include "FLAC/stream_decoder.h" +#if FLAC__HAS_OGG +#include "private/ogg_decoder_aspect.h" +#endif + +typedef struct FLAC__StreamDecoderProtected { + FLAC__StreamDecoderState state; + unsigned channels; + FLAC__ChannelAssignment channel_assignment; + unsigned bits_per_sample; + unsigned sample_rate; /* in Hz */ + unsigned blocksize; /* in samples (per channel) */ + FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */ +#if FLAC__HAS_OGG + FLAC__OggDecoderAspect ogg_decoder_aspect; +#endif +} FLAC__StreamDecoderProtected; + +/* + * return the number of input bytes consumed + */ +unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder); + +#endif diff --git a/flac/src/libFLAC/include/protected/stream_encoder.h b/flac/src/libFLAC/include/protected/stream_encoder.h new file mode 100644 index 0000000..3d0d3fd --- /dev/null +++ b/flac/src/libFLAC/include/protected/stream_encoder.h @@ -0,0 +1,110 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#ifndef FLAC__PROTECTED__STREAM_ENCODER_H +#define FLAC__PROTECTED__STREAM_ENCODER_H + +#include "FLAC/stream_encoder.h" +#if FLAC__HAS_OGG +#include "private/ogg_encoder_aspect.h" +#endif + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +#include "private/float.h" + +#define FLAC__MAX_APODIZATION_FUNCTIONS 32 + +typedef enum { + FLAC__APODIZATION_BARTLETT, + FLAC__APODIZATION_BARTLETT_HANN, + FLAC__APODIZATION_BLACKMAN, + FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE, + FLAC__APODIZATION_CONNES, + FLAC__APODIZATION_FLATTOP, + FLAC__APODIZATION_GAUSS, + FLAC__APODIZATION_HAMMING, + FLAC__APODIZATION_HANN, + FLAC__APODIZATION_KAISER_BESSEL, + FLAC__APODIZATION_NUTTALL, + FLAC__APODIZATION_RECTANGLE, + FLAC__APODIZATION_TRIANGLE, + FLAC__APODIZATION_TUKEY, + FLAC__APODIZATION_WELCH +} FLAC__ApodizationFunction; + +typedef struct { + FLAC__ApodizationFunction type; + union { + struct { + FLAC__real stddev; + } gauss; + struct { + FLAC__real p; + } tukey; + } parameters; +} FLAC__ApodizationSpecification; + +#endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY + +typedef struct FLAC__StreamEncoderProtected { + FLAC__StreamEncoderState state; + FLAC__bool verify; + FLAC__bool streamable_subset; + FLAC__bool do_md5; + FLAC__bool do_mid_side_stereo; + FLAC__bool loose_mid_side_stereo; + unsigned channels; + unsigned bits_per_sample; + unsigned sample_rate; + unsigned blocksize; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + unsigned num_apodizations; + FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS]; +#endif + unsigned max_lpc_order; + unsigned qlp_coeff_precision; + FLAC__bool do_qlp_coeff_prec_search; + FLAC__bool do_exhaustive_model_search; + FLAC__bool do_escape_coding; + unsigned min_residual_partition_order; + unsigned max_residual_partition_order; + unsigned rice_parameter_search_dist; + FLAC__uint64 total_samples_estimate; + FLAC__StreamMetadata **metadata; + unsigned num_metadata_blocks; + FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset; +#if FLAC__HAS_OGG + FLAC__OggEncoderAspect ogg_encoder_aspect; +#endif +} FLAC__StreamEncoderProtected; + +#endif diff --git a/flac/src/libFLAC/libFLAC.m4 b/flac/src/libFLAC/libFLAC.m4 new file mode 100644 index 0000000..9cf2f66 --- /dev/null +++ b/flac/src/libFLAC/libFLAC.m4 @@ -0,0 +1,114 @@ +# Configure paths for libFLAC +# "Inspired" by ogg.m4 + +dnl AM_PATH_LIBFLAC([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libFLAC, and define LIBFLAC_CFLAGS, LIBFLAC_LIBS, LIBFLAC_LIBDIR +dnl +AC_DEFUN([AM_PATH_LIBFLAC], +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(libFLAC,[ --with-libFLAC=PFX Prefix where libFLAC is installed (optional)], libFLAC_prefix="$withval", libFLAC_prefix="") +AC_ARG_WITH(libFLAC-libraries,[ --with-libFLAC-libraries=DIR Directory where libFLAC library is installed (optional)], libFLAC_libraries="$withval", libFLAC_libraries="") +AC_ARG_WITH(libFLAC-includes,[ --with-libFLAC-includes=DIR Directory where libFLAC header files are installed (optional)], libFLAC_includes="$withval", libFLAC_includes="") +AC_ARG_ENABLE(libFLACtest, [ --disable-libFLACtest Do not try to compile and run a test libFLAC program],, enable_libFLACtest=yes) + + if test "x$libFLAC_libraries" != "x" ; then + LIBFLAC_LIBDIR="$libFLAC_libraries" + elif test "x$libFLAC_prefix" != "x" ; then + LIBFLAC_LIBDIR="$libFLAC_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + LIBFLAC_LIBDIR="$libdir" + fi + + LIBFLAC_LIBS="-L$LIBFLAC_LIBDIR -lFLAC $OGG_LIBS -lm" + + if test "x$libFLAC_includes" != "x" ; then + LIBFLAC_CFLAGS="-I$libFLAC_includes" + elif test "x$libFLAC_prefix" != "x" ; then + LIBFLAC_CFLAGS="-I$libFLAC_prefix/include" + elif test "$prefix" != "xNONE"; then + LIBFLAC_CFLAGS="" + fi + + AC_MSG_CHECKING(for libFLAC) + no_libFLAC="" + + + if test "x$enable_libFLACtest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_CXXFLAGS="$CXXFLAGS" + ac_save_LIBS="$LIBS" + ac_save_LD_LIBRARY_PATH="$LD_LIBRARY_PATH" + CFLAGS="$CFLAGS $LIBFLAC_CFLAGS" + CXXFLAGS="$CXXFLAGS $LIBFLAC_CFLAGS" + LIBS="$LIBS $LIBFLAC_LIBS" + LD_LIBRARY_PATH="$LIBFLAC_LIBDIR:$LD_LIBRARY_PATH" +dnl +dnl Now check if the installed libFLAC is sufficiently new. +dnl + rm -f conf.libFLACtest + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.libFLACtest"); + return 0; +} + +],, no_libFLAC=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + CXXFLAGS="$ac_save_CXXFLAGS" + LIBS="$ac_save_LIBS" + LD_LIBRARY_PATH="$ac_save_LD_LIBRARY_PATH" + fi + + if test "x$no_libFLAC" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.libFLACtest ; then + : + else + echo "*** Could not run libFLAC test program, checking why..." + CFLAGS="$CFLAGS $LIBFLAC_CFLAGS" + CXXFLAGS="$CXXFLAGS $LIBFLAC_CFLAGS" + LIBS="$LIBS $LIBFLAC_LIBS" + LD_LIBRARY_PATH="$LIBFLAC_LIBDIR:$LD_LIBRARY_PATH" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding libFLAC or finding the wrong" + echo "*** version of libFLAC. If it is not finding libFLAC, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means libFLAC was incorrectly installed" + echo "*** or that you have moved libFLAC since it was installed. In the latter case, you" + echo "*** may want to edit the libFLAC-config script: $LIBFLAC_CONFIG" ]) + CFLAGS="$ac_save_CFLAGS" + CXXFLAGS="$ac_save_CXXFLAGS" + LIBS="$ac_save_LIBS" + LD_LIBRARY_PATH="$ac_save_LD_LIBRARY_PATH" + fi + LIBFLAC_CFLAGS="" + LIBFLAC_LIBDIR="" + LIBFLAC_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(LIBFLAC_CFLAGS) + AC_SUBST(LIBFLAC_LIBDIR) + AC_SUBST(LIBFLAC_LIBS) + rm -f conf.libFLACtest +]) diff --git a/flac/src/libFLAC/libFLAC_dynamic.dsp b/flac/src/libFLAC/libFLAC_dynamic.dsp new file mode 100644 index 0000000..0f96feb --- /dev/null +++ b/flac/src/libFLAC/libFLAC_dynamic.dsp @@ -0,0 +1,464 @@ +# Microsoft Developer Studio Project File - Name="libFLAC_dynamic" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=libFLAC_dynamic - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libFLAC_dynamic.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libFLAC_dynamic.mak" CFG="libFLAC_dynamic - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libFLAC_dynamic - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "libFLAC_dynamic - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "libFLAC" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_dynamic" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /I ".\include" /I "..\..\include" /D "NDEBUG" /D "FLAC_API_EXPORTS" /D "FLAC__HAS_OGG" /D VERSION=\"1.2.1\" /D "FLAC__CPU_IA32" /D "FLAC__HAS_NASM" /D "FLAC__USE_3DNOW" /D "_WINDOWS" /D "_WINDLL" /D "WIN32" /D "_USRDLL" /FR /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" /d "_USRDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:windows /dll /machine:I386 /out:"..\..\obj\release\bin/libFLAC.dll" + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_dynamic" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I ".\include" /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__OVERFLOW_DETECT" /D "FLAC_API_EXPORTS" /D "FLAC__HAS_OGG" /D VERSION=\"1.2.1\" /D "FLAC__CPU_IA32" /D "FLAC__HAS_NASM" /D "FLAC__USE_3DNOW" /D "_WINDOWS" /D "_WINDLL" /D "WIN32" /D "_USRDLL" /FR /FD /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" /d "_USRDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:windows /dll /debug /machine:I386 /out:"..\..\obj\debug\bin/libFLAC.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "libFLAC_dynamic - Win32 Release" +# Name "libFLAC_dynamic - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Group "Assembly Files (ia32)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\ia32\bitreader_asm.nasm + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +USERDEP__CPU_A="ia32/bitreader_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\bitreader_asm.nasm + +"ia32/bitreader_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/bitreader_asm.nasm -o ia32/bitreader_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +USERDEP__CPU_A="ia32/bitreader_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\bitreader_asm.nasm + +"ia32/bitreader_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/bitreader_asm.nasm -o ia32/bitreader_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\cpu_asm.nasm + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +USERDEP__CPU_A="ia32/cpu_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\cpu_asm.nasm + +"ia32/cpu_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/cpu_asm.nasm -o ia32/cpu_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +USERDEP__CPU_A="ia32/cpu_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\cpu_asm.nasm + +"ia32/cpu_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/cpu_asm.nasm -o ia32/cpu_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\fixed_asm.nasm + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +USERDEP__FIXED="ia32/fixed_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\fixed_asm.nasm + +"ia32/fixed_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/fixed_asm.nasm -o ia32/fixed_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +USERDEP__FIXED="ia32/fixed_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\fixed_asm.nasm + +"ia32/fixed_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/fixed_asm.nasm -o ia32/fixed_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\lpc_asm.nasm + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +USERDEP__LPC_A="ia32/lpc_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\lpc_asm.nasm + +"ia32/lpc_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/lpc_asm.nasm -o ia32/lpc_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +USERDEP__LPC_A="ia32/lpc_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\lpc_asm.nasm + +"ia32/lpc_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/lpc_asm.nasm -o ia32/lpc_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\stream_encoder_asm.nasm + +!IF "$(CFG)" == "libFLAC_dynamic - Win32 Release" + +USERDEP__CPU_A="ia32/stream_encoder_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\stream_encoder_asm.nasm + +"ia32/stream_encoder_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/stream_encoder_asm.nasm -o ia32/stream_encoder_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_dynamic - Win32 Debug" + +USERDEP__CPU_A="ia32/stream_encoder_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\stream_encoder_asm.nasm + +"ia32/stream_encoder_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/stream_encoder_asm.nasm -o ia32/stream_encoder_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\nasm.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\bitmath.c +# End Source File +# Begin Source File + +SOURCE=.\bitreader.c +# End Source File +# Begin Source File + +SOURCE=.\bitwriter.c +# End Source File +# Begin Source File + +SOURCE=.\cpu.c +# End Source File +# Begin Source File + +SOURCE=.\crc.c +# End Source File +# Begin Source File + +SOURCE=.\fixed.c +# End Source File +# Begin Source File + +SOURCE=.\float.c +# End Source File +# Begin Source File + +SOURCE=.\format.c +# End Source File +# Begin Source File + +SOURCE=.\lpc.c +# End Source File +# Begin Source File + +SOURCE=.\md5.c +# End Source File +# Begin Source File + +SOURCE=.\memory.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_iterators.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_object.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_decoder_aspect.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_encoder_aspect.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_helper.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_mapping.c +# End Source File +# Begin Source File + +SOURCE=.\stream_decoder.c +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder.c +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder_framing.c +# End Source File +# Begin Source File + +SOURCE=.\window.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\private\all.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitmath.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitreader.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitwriter.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\cpu.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\crc.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\fixed.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\float.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\format.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\lpc.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\md5.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\memory.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\metadata.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_decoder_aspect.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_encoder_aspect.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_helper.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_mapping.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\stream_encoder_framing.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\window.h +# End Source File +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\protected\all.h +# End Source File +# Begin Source File + +SOURCE=.\include\protected\stream_decoder.h +# End Source File +# Begin Source File + +SOURCE=.\include\protected\stream_encoder.h +# End Source File +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\include\FLAC\all.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\assert.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\export.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\format.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\metadata.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\ordinals.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\stream_decoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\stream_encoder.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/libFLAC/libFLAC_dynamic.vcproj b/flac/src/libFLAC/libFLAC_dynamic.vcproj new file mode 100644 index 0000000..566907b --- /dev/null +++ b/flac/src/libFLAC/libFLAC_dynamic.vcproj @@ -0,0 +1,836 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/libFLAC/libFLAC_static.dsp b/flac/src/libFLAC/libFLAC_static.dsp new file mode 100644 index 0000000..e6a1217 --- /dev/null +++ b/flac/src/libFLAC/libFLAC_static.dsp @@ -0,0 +1,457 @@ +# Microsoft Developer Studio Project File - Name="libFLAC_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=libFLAC_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libFLAC_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libFLAC_static.mak" CFG="libFLAC_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libFLAC_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "libFLAC_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "libFLAC" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /Op /I ".\include" /I "..\..\include" /D VERSION=\"1.2.1\" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "FLAC__CPU_IA32" /D "FLAC__HAS_NASM" /D "FLAC__USE_3DNOW" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\include" /D VERSION=\"1.2.1\" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "FLAC__CPU_IA32" /D "FLAC__HAS_NASM" /D "FLAC__USE_3DNOW" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "FLAC__OVERFLOW_DETECT" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "libFLAC_static - Win32 Release" +# Name "libFLAC_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Group "Assembly Files (ia32)" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\ia32\bitreader_asm.nasm + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +USERDEP__CPU_A="ia32/bitreader_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\bitreader_asm.nasm + +"ia32/bitreader_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/bitreader_asm.nasm -o ia32/bitreader_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +USERDEP__CPU_A="ia32/bitreader_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\bitreader_asm.nasm + +"ia32/bitreader_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/bitreader_asm.nasm -o ia32/bitreader_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\cpu_asm.nasm + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +USERDEP__CPU_A="ia32/cpu_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\cpu_asm.nasm + +"ia32/cpu_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/cpu_asm.nasm -o ia32/cpu_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +USERDEP__CPU_A="ia32/cpu_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\cpu_asm.nasm + +"ia32/cpu_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/cpu_asm.nasm -o ia32/cpu_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\fixed_asm.nasm + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +USERDEP__FIXED="ia32/fixed_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\fixed_asm.nasm + +"ia32/fixed_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/fixed_asm.nasm -o ia32/fixed_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +USERDEP__FIXED="ia32/fixed_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\fixed_asm.nasm + +"ia32/fixed_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/fixed_asm.nasm -o ia32/fixed_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\lpc_asm.nasm + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +USERDEP__LPC_A="ia32/lpc_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\lpc_asm.nasm + +"ia32/lpc_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/lpc_asm.nasm -o ia32/lpc_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +USERDEP__LPC_A="ia32/lpc_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\lpc_asm.nasm + +"ia32/lpc_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/lpc_asm.nasm -o ia32/lpc_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\stream_encoder_asm.nasm + +!IF "$(CFG)" == "libFLAC_static - Win32 Release" + +USERDEP__CPU_A="ia32/stream_encoder_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\stream_encoder_asm.nasm + +"ia32/stream_encoder_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/stream_encoder_asm.nasm -o ia32/stream_encoder_asm.obj + +# End Custom Build + +!ELSEIF "$(CFG)" == "libFLAC_static - Win32 Debug" + +USERDEP__CPU_A="ia32/stream_encoder_asm.nasm" +# Begin Custom Build +InputPath=.\ia32\stream_encoder_asm.nasm + +"ia32/stream_encoder_asm.obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + nasmw.exe -f win32 -d OBJ_FORMAT_win32 -i ia32/ ia32/stream_encoder_asm.nasm -o ia32/stream_encoder_asm.obj + +# End Custom Build + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=.\ia32\nasm.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\bitmath.c +# End Source File +# Begin Source File + +SOURCE=.\bitreader.c +# End Source File +# Begin Source File + +SOURCE=.\bitwriter.c +# End Source File +# Begin Source File + +SOURCE=.\cpu.c +# End Source File +# Begin Source File + +SOURCE=.\crc.c +# End Source File +# Begin Source File + +SOURCE=.\fixed.c +# End Source File +# Begin Source File + +SOURCE=.\float.c +# End Source File +# Begin Source File + +SOURCE=.\format.c +# End Source File +# Begin Source File + +SOURCE=.\lpc.c +# End Source File +# Begin Source File + +SOURCE=.\md5.c +# End Source File +# Begin Source File + +SOURCE=.\memory.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_iterators.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_object.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_decoder_aspect.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_encoder_aspect.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_helper.c +# End Source File +# Begin Source File + +SOURCE=.\ogg_mapping.c +# End Source File +# Begin Source File + +SOURCE=.\stream_decoder.c +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder.c +# End Source File +# Begin Source File + +SOURCE=.\stream_encoder_framing.c +# End Source File +# Begin Source File + +SOURCE=.\window.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\private\all.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitmath.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitreader.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\bitwriter.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\cpu.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\crc.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\fixed.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\float.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\format.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\lpc.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\md5.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\memory.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\metadata.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_decoder_aspect.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_encoder_aspect.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_helper.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\ogg_mapping.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\stream_encoder_framing.h +# End Source File +# Begin Source File + +SOURCE=.\include\private\window.h +# End Source File +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\protected\all.h +# End Source File +# Begin Source File + +SOURCE=.\include\protected\stream_decoder.h +# End Source File +# Begin Source File + +SOURCE=.\include\protected\stream_encoder.h +# End Source File +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\include\FLAC\all.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\assert.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\export.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\format.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\metadata.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\ordinals.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\stream_decoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\FLAC\stream_encoder.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/libFLAC/libFLAC_static.vcproj b/flac/src/libFLAC/libFLAC_static.vcproj new file mode 100644 index 0000000..9739873 --- /dev/null +++ b/flac/src/libFLAC/libFLAC_static.vcproj @@ -0,0 +1,839 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/libFLAC/lpc.c b/flac/src/libFLAC/lpc.c new file mode 100644 index 0000000..918c104 --- /dev/null +++ b/flac/src/libFLAC/lpc.c @@ -0,0 +1,1377 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include "FLAC/assert.h" +#include "FLAC/format.h" +#include "private/bitmath.h" +#include "private/lpc.h" +#if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE +#include +#endif + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +#ifndef M_LN2 +/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */ +#define M_LN2 0.69314718055994530942 +#endif + +/* OPT: #undef'ing this may improve the speed on some architectures */ +#define FLAC__LPC_UNROLLED_FILTER_LOOPS + + +void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len) +{ + unsigned i; + for(i = 0; i < data_len; i++) + out[i] = in[i] * window[i]; +} + +void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]) +{ + /* a readable, but slower, version */ +#if 0 + FLAC__real d; + unsigned i; + + FLAC__ASSERT(lag > 0); + FLAC__ASSERT(lag <= data_len); + + /* + * Technically we should subtract the mean first like so: + * for(i = 0; i < data_len; i++) + * data[i] -= mean; + * but it appears not to make enough of a difference to matter, and + * most signals are already closely centered around zero + */ + while(lag--) { + for(i = lag, d = 0.0; i < data_len; i++) + d += data[i] * data[i - lag]; + autoc[lag] = d; + } +#endif + + /* + * this version tends to run faster because of better data locality + * ('data_len' is usually much larger than 'lag') + */ + FLAC__real d; + unsigned sample, coeff; + const unsigned limit = data_len - lag; + + FLAC__ASSERT(lag > 0); + FLAC__ASSERT(lag <= data_len); + + for(coeff = 0; coeff < lag; coeff++) + autoc[coeff] = 0.0; + for(sample = 0; sample <= limit; sample++) { + d = data[sample]; + for(coeff = 0; coeff < lag; coeff++) + autoc[coeff] += d * data[sample+coeff]; + } + for(; sample < data_len; sample++) { + d = data[sample]; + for(coeff = 0; coeff < data_len - sample; coeff++) + autoc[coeff] += d * data[sample+coeff]; + } +} + +void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]) +{ + unsigned i, j; + FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER]; + + FLAC__ASSERT(0 != max_order); + FLAC__ASSERT(0 < *max_order); + FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER); + FLAC__ASSERT(autoc[0] != 0.0); + + err = autoc[0]; + + for(i = 0; i < *max_order; i++) { + /* Sum up this iteration's reflection coefficient. */ + r = -autoc[i+1]; + for(j = 0; j < i; j++) + r -= lpc[j] * autoc[i-j]; + ref[i] = (r/=err); + + /* Update LPC coefficients and total error. */ + lpc[i]=r; + for(j = 0; j < (i>>1); j++) { + FLAC__double tmp = lpc[j]; + lpc[j] += r * lpc[i-1-j]; + lpc[i-1-j] += r * tmp; + } + if(i & 1) + lpc[j] += lpc[j] * r; + + err *= (1.0 - r * r); + + /* save this order */ + for(j = 0; j <= i; j++) + lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */ + error[i] = err; + + /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */ + if(err == 0.0) { + *max_order = i+1; + return; + } + } +} + +int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift) +{ + unsigned i; + FLAC__double cmax; + FLAC__int32 qmax, qmin; + + FLAC__ASSERT(precision > 0); + FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION); + + /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */ + precision--; + qmax = 1 << precision; + qmin = -qmax; + qmax--; + + /* calc cmax = max( |lp_coeff[i]| ) */ + cmax = 0.0; + for(i = 0; i < order; i++) { + const FLAC__double d = fabs(lp_coeff[i]); + if(d > cmax) + cmax = d; + } + + if(cmax <= 0.0) { + /* => coefficients are all 0, which means our constant-detect didn't work */ + return 2; + } + else { + const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1; + const int min_shiftlimit = -max_shiftlimit - 1; + int log2cmax; + + (void)frexp(cmax, &log2cmax); + log2cmax--; + *shift = (int)precision - log2cmax - 1; + + if(*shift > max_shiftlimit) + *shift = max_shiftlimit; + else if(*shift < min_shiftlimit) + return 1; + } + + if(*shift >= 0) { + FLAC__double error = 0.0; + FLAC__int32 q; + for(i = 0; i < order; i++) { + error += lp_coeff[i] * (1 << *shift); +#if 1 /* unfortunately lround() is C99 */ + if(error >= 0.0) + q = (FLAC__int32)(error + 0.5); + else + q = (FLAC__int32)(error - 0.5); +#else + q = lround(error); +#endif +#ifdef FLAC__OVERFLOW_DETECT + if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */ + fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]); + else if(q < qmin) + fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q qmax) + q = qmax; + else if(q < qmin) + q = qmin; + error -= q; + qlp_coeff[i] = q; + } + } + /* negative shift is very rare but due to design flaw, negative shift is + * a NOP in the decoder, so it must be handled specially by scaling down + * coeffs + */ + else { + const int nshift = -(*shift); + FLAC__double error = 0.0; + FLAC__int32 q; +#ifdef DEBUG + fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax); +#endif + for(i = 0; i < order; i++) { + error += lp_coeff[i] / (1 << nshift); +#if 1 /* unfortunately lround() is C99 */ + if(error >= 0.0) + q = (FLAC__int32)(error + 0.5); + else + q = (FLAC__int32)(error - 0.5); +#else + q = lround(error); +#endif +#ifdef FLAC__OVERFLOW_DETECT + if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */ + fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]); + else if(q < qmin) + fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q qmax) + q = qmax; + else if(q < qmin) + q = qmin; + error -= q; + qlp_coeff[i] = q; + } + *shift = 0; + } + + return 0; +} + +void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]) +#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS) +{ + FLAC__int64 sumo; + unsigned i, j; + FLAC__int32 sum; + const FLAC__int32 *history; + +#ifdef FLAC__OVERFLOW_DETECT_VERBOSE + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization); + for(i=0;i 0); + + for(i = 0; i < data_len; i++) { + sumo = 0; + sum = 0; + history = data; + for(j = 0; j < order; j++) { + sum += qlp_coeff[j] * (*(--history)); + sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history); +#if defined _MSC_VER + if(sumo > 2147483647I64 || sumo < -2147483648I64) + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo); +#else + if(sumo > 2147483647ll || sumo < -2147483648ll) + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo); +#endif + } + *(residual++) = *(data++) - (sum >> lp_quantization); + } + + /* Here's a slower but clearer version: + for(i = 0; i < data_len; i++) { + sum = 0; + for(j = 0; j < order; j++) + sum += qlp_coeff[j] * data[i-j-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + */ +} +#else /* fully unrolled version for normal use */ +{ + int i; + FLAC__int32 sum; + + FLAC__ASSERT(order > 0); + FLAC__ASSERT(order <= 32); + + /* + * We do unique versions up to 12th order since that's the subset limit. + * Also they are roughly ordered to match frequency of occurrence to + * minimize branching. + */ + if(order <= 12) { + if(order > 8) { + if(order > 10) { + if(order == 12) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[11] * data[i-12]; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 11 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + } + else { + if(order == 10) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 9 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + } + } + else if(order > 4) { + if(order > 6) { + if(order == 8) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 7 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + } + else { + if(order == 6) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 5 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + } + } + else { + if(order > 2) { + if(order == 4) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 3 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + } + else { + if(order == 2) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + residual[i] = data[i] - (sum >> lp_quantization); + } + } + else { /* order == 1 */ + for(i = 0; i < (int)data_len; i++) + residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization); + } + } + } + } + else { /* order > 12 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + switch(order) { + case 32: sum += qlp_coeff[31] * data[i-32]; + case 31: sum += qlp_coeff[30] * data[i-31]; + case 30: sum += qlp_coeff[29] * data[i-30]; + case 29: sum += qlp_coeff[28] * data[i-29]; + case 28: sum += qlp_coeff[27] * data[i-28]; + case 27: sum += qlp_coeff[26] * data[i-27]; + case 26: sum += qlp_coeff[25] * data[i-26]; + case 25: sum += qlp_coeff[24] * data[i-25]; + case 24: sum += qlp_coeff[23] * data[i-24]; + case 23: sum += qlp_coeff[22] * data[i-23]; + case 22: sum += qlp_coeff[21] * data[i-22]; + case 21: sum += qlp_coeff[20] * data[i-21]; + case 20: sum += qlp_coeff[19] * data[i-20]; + case 19: sum += qlp_coeff[18] * data[i-19]; + case 18: sum += qlp_coeff[17] * data[i-18]; + case 17: sum += qlp_coeff[16] * data[i-17]; + case 16: sum += qlp_coeff[15] * data[i-16]; + case 15: sum += qlp_coeff[14] * data[i-15]; + case 14: sum += qlp_coeff[13] * data[i-14]; + case 13: sum += qlp_coeff[12] * data[i-13]; + sum += qlp_coeff[11] * data[i-12]; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[ 9] * data[i-10]; + sum += qlp_coeff[ 8] * data[i- 9]; + sum += qlp_coeff[ 7] * data[i- 8]; + sum += qlp_coeff[ 6] * data[i- 7]; + sum += qlp_coeff[ 5] * data[i- 6]; + sum += qlp_coeff[ 4] * data[i- 5]; + sum += qlp_coeff[ 3] * data[i- 4]; + sum += qlp_coeff[ 2] * data[i- 3]; + sum += qlp_coeff[ 1] * data[i- 2]; + sum += qlp_coeff[ 0] * data[i- 1]; + } + residual[i] = data[i] - (sum >> lp_quantization); + } + } +} +#endif + +void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]) +#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS) +{ + unsigned i, j; + FLAC__int64 sum; + const FLAC__int32 *history; + +#ifdef FLAC__OVERFLOW_DETECT_VERBOSE + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization); + for(i=0;i 0); + + for(i = 0; i < data_len; i++) { + sum = 0; + history = data; + for(j = 0; j < order; j++) + sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history)); + if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) { +#if defined _MSC_VER + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization); +#else + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization)); +#endif + break; + } + if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) { +#if defined _MSC_VER + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization)); +#else + fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization))); +#endif + break; + } + *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization); + } +} +#else /* fully unrolled version for normal use */ +{ + int i; + FLAC__int64 sum; + + FLAC__ASSERT(order > 0); + FLAC__ASSERT(order <= 32); + + /* + * We do unique versions up to 12th order since that's the subset limit. + * Also they are roughly ordered to match frequency of occurrence to + * minimize branching. + */ + if(order <= 12) { + if(order > 8) { + if(order > 10) { + if(order == 12) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[11] * (FLAC__int64)data[i-12]; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 11 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 10) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 9 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + } + } + else if(order > 4) { + if(order > 6) { + if(order == 8) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 7 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 6) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 5 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + } + } + else { + if(order > 2) { + if(order == 4) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 3 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 2) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 1 */ + for(i = 0; i < (int)data_len; i++) + residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization); + } + } + } + } + else { /* order > 12 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + switch(order) { + case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32]; + case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31]; + case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30]; + case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29]; + case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28]; + case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27]; + case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26]; + case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25]; + case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24]; + case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23]; + case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22]; + case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21]; + case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20]; + case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19]; + case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18]; + case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17]; + case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16]; + case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15]; + case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14]; + case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13]; + sum += qlp_coeff[11] * (FLAC__int64)data[i-12]; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9]; + sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8]; + sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7]; + sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6]; + sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5]; + sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4]; + sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3]; + sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2]; + sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1]; + } + residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization); + } + } +} +#endif + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ + +void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]) +#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS) +{ + FLAC__int64 sumo; + unsigned i, j; + FLAC__int32 sum; + const FLAC__int32 *r = residual, *history; + +#ifdef FLAC__OVERFLOW_DETECT_VERBOSE + fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization); + for(i=0;i 0); + + for(i = 0; i < data_len; i++) { + sumo = 0; + sum = 0; + history = data; + for(j = 0; j < order; j++) { + sum += qlp_coeff[j] * (*(--history)); + sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history); +#if defined _MSC_VER + if(sumo > 2147483647I64 || sumo < -2147483648I64) + fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo); +#else + if(sumo > 2147483647ll || sumo < -2147483648ll) + fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo); +#endif + } + *(data++) = *(r++) + (sum >> lp_quantization); + } + + /* Here's a slower but clearer version: + for(i = 0; i < data_len; i++) { + sum = 0; + for(j = 0; j < order; j++) + sum += qlp_coeff[j] * data[i-j-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + */ +} +#else /* fully unrolled version for normal use */ +{ + int i; + FLAC__int32 sum; + + FLAC__ASSERT(order > 0); + FLAC__ASSERT(order <= 32); + + /* + * We do unique versions up to 12th order since that's the subset limit. + * Also they are roughly ordered to match frequency of occurrence to + * minimize branching. + */ + if(order <= 12) { + if(order > 8) { + if(order > 10) { + if(order == 12) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[11] * data[i-12]; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 11 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + } + else { + if(order == 10) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[9] * data[i-10]; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 9 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[8] * data[i-9]; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + } + } + else if(order > 4) { + if(order > 6) { + if(order == 8) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[7] * data[i-8]; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 7 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[6] * data[i-7]; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + } + else { + if(order == 6) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[5] * data[i-6]; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 5 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[4] * data[i-5]; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + } + } + else { + if(order > 2) { + if(order == 4) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[3] * data[i-4]; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 3 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[2] * data[i-3]; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + } + else { + if(order == 2) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[1] * data[i-2]; + sum += qlp_coeff[0] * data[i-1]; + data[i] = residual[i] + (sum >> lp_quantization); + } + } + else { /* order == 1 */ + for(i = 0; i < (int)data_len; i++) + data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization); + } + } + } + } + else { /* order > 12 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + switch(order) { + case 32: sum += qlp_coeff[31] * data[i-32]; + case 31: sum += qlp_coeff[30] * data[i-31]; + case 30: sum += qlp_coeff[29] * data[i-30]; + case 29: sum += qlp_coeff[28] * data[i-29]; + case 28: sum += qlp_coeff[27] * data[i-28]; + case 27: sum += qlp_coeff[26] * data[i-27]; + case 26: sum += qlp_coeff[25] * data[i-26]; + case 25: sum += qlp_coeff[24] * data[i-25]; + case 24: sum += qlp_coeff[23] * data[i-24]; + case 23: sum += qlp_coeff[22] * data[i-23]; + case 22: sum += qlp_coeff[21] * data[i-22]; + case 21: sum += qlp_coeff[20] * data[i-21]; + case 20: sum += qlp_coeff[19] * data[i-20]; + case 19: sum += qlp_coeff[18] * data[i-19]; + case 18: sum += qlp_coeff[17] * data[i-18]; + case 17: sum += qlp_coeff[16] * data[i-17]; + case 16: sum += qlp_coeff[15] * data[i-16]; + case 15: sum += qlp_coeff[14] * data[i-15]; + case 14: sum += qlp_coeff[13] * data[i-14]; + case 13: sum += qlp_coeff[12] * data[i-13]; + sum += qlp_coeff[11] * data[i-12]; + sum += qlp_coeff[10] * data[i-11]; + sum += qlp_coeff[ 9] * data[i-10]; + sum += qlp_coeff[ 8] * data[i- 9]; + sum += qlp_coeff[ 7] * data[i- 8]; + sum += qlp_coeff[ 6] * data[i- 7]; + sum += qlp_coeff[ 5] * data[i- 6]; + sum += qlp_coeff[ 4] * data[i- 5]; + sum += qlp_coeff[ 3] * data[i- 4]; + sum += qlp_coeff[ 2] * data[i- 3]; + sum += qlp_coeff[ 1] * data[i- 2]; + sum += qlp_coeff[ 0] * data[i- 1]; + } + data[i] = residual[i] + (sum >> lp_quantization); + } + } +} +#endif + +void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]) +#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS) +{ + unsigned i, j; + FLAC__int64 sum; + const FLAC__int32 *r = residual, *history; + +#ifdef FLAC__OVERFLOW_DETECT_VERBOSE + fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization); + for(i=0;i 0); + + for(i = 0; i < data_len; i++) { + sum = 0; + history = data; + for(j = 0; j < order; j++) + sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history)); + if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) { +#ifdef _MSC_VER + fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization); +#else + fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization)); +#endif + break; + } + if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) { +#ifdef _MSC_VER + fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization)); +#else + fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization))); +#endif + break; + } + *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization); + } +} +#else /* fully unrolled version for normal use */ +{ + int i; + FLAC__int64 sum; + + FLAC__ASSERT(order > 0); + FLAC__ASSERT(order <= 32); + + /* + * We do unique versions up to 12th order since that's the subset limit. + * Also they are roughly ordered to match frequency of occurrence to + * minimize branching. + */ + if(order <= 12) { + if(order > 8) { + if(order > 10) { + if(order == 12) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[11] * (FLAC__int64)data[i-12]; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 11 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 10) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 9 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[8] * (FLAC__int64)data[i-9]; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + } + } + else if(order > 4) { + if(order > 6) { + if(order == 8) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[7] * (FLAC__int64)data[i-8]; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 7 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[6] * (FLAC__int64)data[i-7]; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 6) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[5] * (FLAC__int64)data[i-6]; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 5 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[4] * (FLAC__int64)data[i-5]; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + } + } + else { + if(order > 2) { + if(order == 4) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[3] * (FLAC__int64)data[i-4]; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 3 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[2] * (FLAC__int64)data[i-3]; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + } + else { + if(order == 2) { + for(i = 0; i < (int)data_len; i++) { + sum = 0; + sum += qlp_coeff[1] * (FLAC__int64)data[i-2]; + sum += qlp_coeff[0] * (FLAC__int64)data[i-1]; + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } + else { /* order == 1 */ + for(i = 0; i < (int)data_len; i++) + data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization); + } + } + } + } + else { /* order > 12 */ + for(i = 0; i < (int)data_len; i++) { + sum = 0; + switch(order) { + case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32]; + case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31]; + case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30]; + case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29]; + case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28]; + case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27]; + case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26]; + case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25]; + case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24]; + case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23]; + case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22]; + case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21]; + case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20]; + case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19]; + case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18]; + case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17]; + case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16]; + case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15]; + case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14]; + case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13]; + sum += qlp_coeff[11] * (FLAC__int64)data[i-12]; + sum += qlp_coeff[10] * (FLAC__int64)data[i-11]; + sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10]; + sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9]; + sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8]; + sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7]; + sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6]; + sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5]; + sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4]; + sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3]; + sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2]; + sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1]; + } + data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization); + } + } +} +#endif + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples) +{ + FLAC__double error_scale; + + FLAC__ASSERT(total_samples > 0); + + error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples; + + return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale); +} + +FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale) +{ + if(lpc_error > 0.0) { + FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2; + if(bps >= 0.0) + return bps; + else + return 0.0; + } + else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */ + return 1e32; + } + else { + return 0.0; + } +} + +unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order) +{ + unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */ + FLAC__double bits, best_bits, error_scale; + + FLAC__ASSERT(max_order > 0); + FLAC__ASSERT(total_samples > 0); + + error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples; + + best_index = 0; + best_bits = (unsigned)(-1); + + for(index = 0, order = 1; index < max_order; index++, order++) { + bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order); + if(bits < best_bits) { + best_index = index; + best_bits = bits; + } + } + + return best_index+1; /* +1 since index of lpc_error[] is order-1 */ +} + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ diff --git a/flac/src/libFLAC/md5.c b/flac/src/libFLAC/md5.c new file mode 100644 index 0000000..ee100f5 --- /dev/null +++ b/flac/src/libFLAC/md5.c @@ -0,0 +1,424 @@ +#if HAVE_CONFIG_H +# include +#endif + +#include /* for malloc() */ +#include /* for memcpy() */ + +#include "private/md5.h" +#include "share/alloc.h" + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + * + * Changed so as no longer to depend on Colin Plumb's `usual.h' header + * definitions; now uses stuff from dpkg's config.h. + * - Ian Jackson . + * Still in the public domain. + * + * Josh Coalson: made some changes to integrate with libFLAC. + * Still in the public domain. + */ + +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f,w,x,y,z,in,s) \ + (w += f(x,y,z) + in, w = (w<>(32-s)) + x) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16]) +{ + register FLAC__uint32 a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +#if WORDS_BIGENDIAN +//@@@@@@ OPT: use bswap/intrinsics +static void byteSwap(FLAC__uint32 *buf, unsigned words) +{ + register FLAC__uint32 x; + do { + x = *buf; + x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); + *buf++ = (x >> 16) | (x << 16); + } while (--words); +} +static void byteSwapX16(FLAC__uint32 *buf) +{ + register FLAC__uint32 x; + + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16); + x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16); +} +#else +#define byteSwap(buf, words) +#define byteSwapX16(buf) +#endif + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len) +{ + FLAC__uint32 t; + + /* Update byte count */ + + t = ctx->bytes[0]; + if ((ctx->bytes[0] = t + len) < t) + ctx->bytes[1]++; /* Carry from low to high */ + + t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ + if (t > len) { + memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len); + return; + } + /* First chunk is an odd size */ + memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t); + byteSwapX16(ctx->in); + FLAC__MD5Transform(ctx->buf, ctx->in); + buf += t; + len -= t; + + /* Process data in 64-byte chunks */ + while (len >= 64) { + memcpy(ctx->in, buf, 64); + byteSwapX16(ctx->in); + FLAC__MD5Transform(ctx->buf, ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + memcpy(ctx->in, buf, len); +} + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +void FLAC__MD5Init(FLAC__MD5Context *ctx) +{ + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bytes[0] = 0; + ctx->bytes[1] = 0; + + ctx->internal_buf = 0; + ctx->capacity = 0; +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx) +{ + int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */ + FLAC__byte *p = (FLAC__byte *)ctx->in + count; + + /* Set the first char of padding to 0x80. There is always room. */ + *p++ = 0x80; + + /* Bytes of padding needed to make 56 bytes (-8..55) */ + count = 56 - 1 - count; + + if (count < 0) { /* Padding forces an extra block */ + memset(p, 0, count + 8); + byteSwapX16(ctx->in); + FLAC__MD5Transform(ctx->buf, ctx->in); + p = (FLAC__byte *)ctx->in; + count = 56; + } + memset(p, 0, count); + byteSwap(ctx->in, 14); + + /* Append length in bits and transform */ + ctx->in[14] = ctx->bytes[0] << 3; + ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29; + FLAC__MD5Transform(ctx->buf, ctx->in); + + byteSwap(ctx->buf, 4); + memcpy(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ + if(0 != ctx->internal_buf) { + free(ctx->internal_buf); + ctx->internal_buf = 0; + ctx->capacity = 0; + } +} + +/* + * Convert the incoming audio signal to a byte stream + */ +static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample) +{ + unsigned channel, sample; + register FLAC__int32 a_word; + register FLAC__byte *buf_ = buf; + +#if WORDS_BIGENDIAN +#else + if(channels == 2 && bytes_per_sample == 2) { + FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1; + memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples); + for(sample = 0; sample < samples; sample++, buf1_+=2) + *buf1_ = (FLAC__int16)signal[1][sample]; + } + else if(channels == 1 && bytes_per_sample == 2) { + FLAC__int16 *buf1_ = (FLAC__int16*)buf_; + for(sample = 0; sample < samples; sample++) + *buf1_++ = (FLAC__int16)signal[0][sample]; + } + else +#endif + if(bytes_per_sample == 2) { + if(channels == 2) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + a_word = signal[1][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + else if(channels == 1) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + else { + for(sample = 0; sample < samples; sample++) { + for(channel = 0; channel < channels; channel++) { + a_word = signal[channel][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + } + } + else if(bytes_per_sample == 3) { + if(channels == 2) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + a_word = signal[1][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + else if(channels == 1) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + else { + for(sample = 0; sample < samples; sample++) { + for(channel = 0; channel < channels; channel++) { + a_word = signal[channel][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + } + } + else if(bytes_per_sample == 1) { + if(channels == 2) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; + a_word = signal[1][sample]; + *buf_++ = (FLAC__byte)a_word; + } + } + else if(channels == 1) { + for(sample = 0; sample < samples; sample++) { + a_word = signal[0][sample]; + *buf_++ = (FLAC__byte)a_word; + } + } + else { + for(sample = 0; sample < samples; sample++) { + for(channel = 0; channel < channels; channel++) { + a_word = signal[channel][sample]; + *buf_++ = (FLAC__byte)a_word; + } + } + } + } + else { /* bytes_per_sample == 4, maybe optimize more later */ + for(sample = 0; sample < samples; sample++) { + for(channel = 0; channel < channels; channel++) { + a_word = signal[channel][sample]; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; a_word >>= 8; + *buf_++ = (FLAC__byte)a_word; + } + } + } +} + +/* + * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it. + */ +FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample) +{ + const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample; + + /* overflow check */ + if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample) + return false; + if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples) + return false; + + if(ctx->capacity < bytes_needed) { + FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed); + if(0 == tmp) { + free(ctx->internal_buf); + if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed))) + return false; + } + ctx->internal_buf = tmp; + ctx->capacity = bytes_needed; + } + + format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample); + + FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed); + + return true; +} diff --git a/flac/src/libFLAC/memory.c b/flac/src/libFLAC/memory.c new file mode 100644 index 0000000..476c23b --- /dev/null +++ b/flac/src/libFLAC/memory.c @@ -0,0 +1,221 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "private/memory.h" +#include "FLAC/assert.h" +#include "share/alloc.h" + +void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address) +{ + void *x; + + FLAC__ASSERT(0 != aligned_address); + +#ifdef FLAC__ALIGN_MALLOC_DATA + /* align on 32-byte (256-bit) boundary */ + x = safe_malloc_add_2op_(bytes, /*+*/31); +#ifdef SIZEOF_VOIDP +#if SIZEOF_VOIDP == 4 + /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */ + *aligned_address = (void*)(((unsigned)x + 31) & -32); +#elif SIZEOF_VOIDP == 8 + *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32))); +#else +# error Unsupported sizeof(void*) +#endif +#else + /* there's got to be a better way to do this right for all archs */ + if(sizeof(void*) == sizeof(unsigned)) + *aligned_address = (void*)(((unsigned)x + 31) & -32); + else if(sizeof(void*) == sizeof(FLAC__uint64)) + *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32))); + else + return 0; +#endif +#else + x = safe_malloc_(bytes); + *aligned_address = x; +#endif + return x; +} + +FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer) +{ + FLAC__int32 *pu; /* unaligned pointer */ + union { /* union needed to comply with C99 pointer aliasing rules */ + FLAC__int32 *pa; /* aligned pointer */ + void *pv; /* aligned pointer alias */ + } u; + + FLAC__ASSERT(elements > 0); + FLAC__ASSERT(0 != unaligned_pointer); + FLAC__ASSERT(0 != aligned_pointer); + FLAC__ASSERT(unaligned_pointer != aligned_pointer); + + if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */ + return false; + + pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv); + if(0 == pu) { + return false; + } + else { + if(*unaligned_pointer != 0) + free(*unaligned_pointer); + *unaligned_pointer = pu; + *aligned_pointer = u.pa; + return true; + } +} + +FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer) +{ + FLAC__uint32 *pu; /* unaligned pointer */ + union { /* union needed to comply with C99 pointer aliasing rules */ + FLAC__uint32 *pa; /* aligned pointer */ + void *pv; /* aligned pointer alias */ + } u; + + FLAC__ASSERT(elements > 0); + FLAC__ASSERT(0 != unaligned_pointer); + FLAC__ASSERT(0 != aligned_pointer); + FLAC__ASSERT(unaligned_pointer != aligned_pointer); + + if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */ + return false; + + pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv); + if(0 == pu) { + return false; + } + else { + if(*unaligned_pointer != 0) + free(*unaligned_pointer); + *unaligned_pointer = pu; + *aligned_pointer = u.pa; + return true; + } +} + +FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer) +{ + FLAC__uint64 *pu; /* unaligned pointer */ + union { /* union needed to comply with C99 pointer aliasing rules */ + FLAC__uint64 *pa; /* aligned pointer */ + void *pv; /* aligned pointer alias */ + } u; + + FLAC__ASSERT(elements > 0); + FLAC__ASSERT(0 != unaligned_pointer); + FLAC__ASSERT(0 != aligned_pointer); + FLAC__ASSERT(unaligned_pointer != aligned_pointer); + + if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */ + return false; + + pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv); + if(0 == pu) { + return false; + } + else { + if(*unaligned_pointer != 0) + free(*unaligned_pointer); + *unaligned_pointer = pu; + *aligned_pointer = u.pa; + return true; + } +} + +FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer) +{ + unsigned *pu; /* unaligned pointer */ + union { /* union needed to comply with C99 pointer aliasing rules */ + unsigned *pa; /* aligned pointer */ + void *pv; /* aligned pointer alias */ + } u; + + FLAC__ASSERT(elements > 0); + FLAC__ASSERT(0 != unaligned_pointer); + FLAC__ASSERT(0 != aligned_pointer); + FLAC__ASSERT(unaligned_pointer != aligned_pointer); + + if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */ + return false; + + pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv); + if(0 == pu) { + return false; + } + else { + if(*unaligned_pointer != 0) + free(*unaligned_pointer); + *unaligned_pointer = pu; + *aligned_pointer = u.pa; + return true; + } +} + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer) +{ + FLAC__real *pu; /* unaligned pointer */ + union { /* union needed to comply with C99 pointer aliasing rules */ + FLAC__real *pa; /* aligned pointer */ + void *pv; /* aligned pointer alias */ + } u; + + FLAC__ASSERT(elements > 0); + FLAC__ASSERT(0 != unaligned_pointer); + FLAC__ASSERT(0 != aligned_pointer); + FLAC__ASSERT(unaligned_pointer != aligned_pointer); + + if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */ + return false; + + pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv); + if(0 == pu) { + return false; + } + else { + if(*unaligned_pointer != 0) + free(*unaligned_pointer); + *unaligned_pointer = pu; + *aligned_pointer = u.pa; + return true; + } +} + +#endif diff --git a/flac/src/libFLAC/metadata_iterators.c b/flac/src/libFLAC/metadata_iterators.c new file mode 100644 index 0000000..f740cc4 --- /dev/null +++ b/flac/src/libFLAC/metadata_iterators.c @@ -0,0 +1,3363 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ +#if defined __BORLANDC__ +#include /* for utime() */ +#else +#include /* for utime() */ +#endif +#include /* for chmod() */ +#include /* for off_t */ +#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#else +#include /* some flavors of BSD (like OS X) require this to get time_t */ +#include /* for utime() */ +#include /* for chown(), unlink() */ +#endif +#include /* for stat(), maybe chmod() */ + +#include "private/metadata.h" + +#include "FLAC/assert.h" +#include "FLAC/stream_decoder.h" +#include "share/alloc.h" + +#ifdef max +#undef max +#endif +#define max(a,b) ((a)>(b)?(a):(b)) +#ifdef min +#undef min +#endif +#define min(a,b) ((a)<(b)?(a):(b)) + + +/**************************************************************************** + * + * Local function declarations + * + ***************************************************************************/ + +static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes); +static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes); +static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes); +static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes); +static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes); +static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes); + +static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator); +static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block); +static FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block); +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length); + +static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block); +static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block); +static FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block); +static FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block); +static FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block); +static FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length); +static FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length); +static FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block); +static FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block); +static FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block); +static FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block); +static FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length); + +static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block); +static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last); +static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append); + +static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator); +static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator); + +static unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb); +static unsigned seek_to_first_metadata_block_(FILE *f); + +static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append); +static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup); + +static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status); +static FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status); +static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status); +static FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status); + +static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status); +static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status); +static void cleanup_tempfile_(FILE **tempfile, char **tempfilename); + +static FLAC__bool get_file_stats_(const char *filename, struct stat *stats); +static void set_file_stats_(const char *filename, struct stat *stats); + +static int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence); +static FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle); + +static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status); + + +#ifdef FLAC__VALGRIND_TESTING +static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#else +#define local__fwrite fwrite +#endif + +/**************************************************************************** + * + * Level 0 implementation + * + ***************************************************************************/ + +static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + +typedef struct { + FLAC__bool got_error; + FLAC__StreamMetadata *object; +} level0_client_data; + +static FLAC__StreamMetadata *get_one_metadata_block_(const char *filename, FLAC__MetadataType type) +{ + level0_client_data cd; + FLAC__StreamDecoder *decoder; + + FLAC__ASSERT(0 != filename); + + cd.got_error = false; + cd.object = 0; + + decoder = FLAC__stream_decoder_new(); + + if(0 == decoder) + return 0; + + FLAC__stream_decoder_set_md5_checking(decoder, false); + FLAC__stream_decoder_set_metadata_ignore_all(decoder); + FLAC__stream_decoder_set_metadata_respond(decoder, type); + + if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &cd) != FLAC__STREAM_DECODER_INIT_STATUS_OK || cd.got_error) { + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + return 0; + } + + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || cd.got_error) { + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + if(0 != cd.object) + FLAC__metadata_object_delete(cd.object); + return 0; + } + + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + + return cd.object; +} + +FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo) +{ + FLAC__StreamMetadata *object; + + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != streaminfo); + + object = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_STREAMINFO); + + if (object) { + /* can just copy the contents since STREAMINFO has no internal structure */ + *streaminfo = *object; + FLAC__metadata_object_delete(object); + return true; + } + else { + return false; + } +} + +FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != tags); + + *tags = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_VORBIS_COMMENT); + + return 0 != *tags; +} + +FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != cuesheet); + + *cuesheet = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_CUESHEET); + + return 0 != *cuesheet; +} + +FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + (void)decoder, (void)frame, (void)buffer, (void)client_data; + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + level0_client_data *cd = (level0_client_data *)client_data; + (void)decoder; + + /* + * we assume we only get here when the one metadata block we were + * looking for was passed to us + */ + if(!cd->got_error && 0 == cd->object) { + if(0 == (cd->object = FLAC__metadata_object_clone(metadata))) + cd->got_error = true; + } +} + +void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + level0_client_data *cd = (level0_client_data *)client_data; + (void)decoder; + + if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC) + cd->got_error = true; +} + +FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors) +{ + FLAC__Metadata_SimpleIterator *it; + FLAC__uint64 max_area_seen = 0; + FLAC__uint64 max_depth_seen = 0; + + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != picture); + + *picture = 0; + + it = FLAC__metadata_simple_iterator_new(); + if(0 == it) + return false; + if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) { + FLAC__metadata_simple_iterator_delete(it); + return false; + } + do { + if(FLAC__metadata_simple_iterator_get_block_type(it) == FLAC__METADATA_TYPE_PICTURE) { + FLAC__StreamMetadata *obj = FLAC__metadata_simple_iterator_get_block(it); + FLAC__uint64 area = (FLAC__uint64)obj->data.picture.width * (FLAC__uint64)obj->data.picture.height; + /* check constraints */ + if( + (type == (FLAC__StreamMetadata_Picture_Type)(-1) || type == obj->data.picture.type) && + (mime_type == 0 || !strcmp(mime_type, obj->data.picture.mime_type)) && + (description == 0 || !strcmp((const char *)description, (const char *)obj->data.picture.description)) && + obj->data.picture.width <= max_width && + obj->data.picture.height <= max_height && + obj->data.picture.depth <= max_depth && + obj->data.picture.colors <= max_colors && + (area > max_area_seen || (area == max_area_seen && obj->data.picture.depth > max_depth_seen)) + ) { + if(*picture) + FLAC__metadata_object_delete(*picture); + *picture = obj; + max_area_seen = area; + max_depth_seen = obj->data.picture.depth; + } + else { + FLAC__metadata_object_delete(obj); + } + } + } while(FLAC__metadata_simple_iterator_next(it)); + + FLAC__metadata_simple_iterator_delete(it); + + return (0 != *picture); +} + + +/**************************************************************************** + * + * Level 1 implementation + * + ***************************************************************************/ + +#define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4) +/* 1 for initial offset, +4 for our own personal use */ + +struct FLAC__Metadata_SimpleIterator { + FILE *file; + char *filename, *tempfile_path_prefix; + struct stat stats; + FLAC__bool has_stats; + FLAC__bool is_writable; + FLAC__Metadata_SimpleIteratorStatus status; + off_t offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH]; + off_t first_offset; /* this is the offset to the STREAMINFO block */ + unsigned depth; + /* this is the metadata block header of the current block we are pointing to: */ + FLAC__bool is_last; + FLAC__MetadataType type; + unsigned length; +}; + +FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = { + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR", + "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR" +}; + + +FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void) +{ + FLAC__Metadata_SimpleIterator *iterator = (FLAC__Metadata_SimpleIterator*)calloc(1, sizeof(FLAC__Metadata_SimpleIterator)); + + if(0 != iterator) { + iterator->file = 0; + iterator->filename = 0; + iterator->tempfile_path_prefix = 0; + iterator->has_stats = false; + iterator->is_writable = false; + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; + iterator->first_offset = iterator->offset[0] = -1; + iterator->depth = 0; + } + + return iterator; +} + +static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + + if(0 != iterator->file) { + fclose(iterator->file); + iterator->file = 0; + if(iterator->has_stats) + set_file_stats_(iterator->filename, &iterator->stats); + } + if(0 != iterator->filename) { + free(iterator->filename); + iterator->filename = 0; + } + if(0 != iterator->tempfile_path_prefix) { + free(iterator->tempfile_path_prefix); + iterator->tempfile_path_prefix = 0; + } +} + +FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + + simple_iterator_free_guts_(iterator); + free(iterator); +} + +FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__Metadata_SimpleIteratorStatus status; + + FLAC__ASSERT(0 != iterator); + + status = iterator->status; + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; + return status; +} + +static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only) +{ + unsigned ret; + + FLAC__ASSERT(0 != iterator); + + if(read_only || 0 == (iterator->file = fopen(iterator->filename, "r+b"))) { + iterator->is_writable = false; + if(read_only || errno == EACCES) { + if(0 == (iterator->file = fopen(iterator->filename, "rb"))) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE; + return false; + } + } + else { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE; + return false; + } + } + else { + iterator->is_writable = true; + } + + ret = seek_to_first_metadata_block_(iterator->file); + switch(ret) { + case 0: + iterator->depth = 0; + iterator->first_offset = iterator->offset[iterator->depth] = ftello(iterator->file); + return read_metadata_block_header_(iterator); + case 1: + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + case 2: + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + case 3: + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE; + return false; + default: + FLAC__ASSERT(0); + return false; + } +} + +#if 0 +@@@ If we decide to finish implementing this, put this comment back in metadata.h +/* + * The 'tempfile_path_prefix' allows you to specify a directory where + * tempfiles should go. Remember that if your metadata edits cause the + * FLAC file to grow, the entire file will have to be rewritten. If + * 'tempfile_path_prefix' is NULL, the temp file will be written in the + * same directory as the original FLAC file. This makes replacing the + * original with the tempfile fast but requires extra space in the same + * partition for the tempfile. If space is a problem, you can pass a + * directory name belonging to a different partition in + * 'tempfile_path_prefix'. Note that you should use the forward slash + * '/' as the directory separator. A trailing slash is not needed; it + * will be added automatically. + */ +FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool preserve_file_stats, const char *tempfile_path_prefix); +#endif + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats) +{ + const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'rename(...)' for what it will take to finish implementing this */ + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != filename); + + simple_iterator_free_guts_(iterator); + + if(!read_only && preserve_file_stats) + iterator->has_stats = get_file_stats_(filename, &iterator->stats); + + if(0 == (iterator->filename = strdup(filename))) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + + return simple_iterator_prime_input_(iterator, read_only); +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + return iterator->is_writable; +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + if(iterator->is_last) + return false; + + if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + iterator->offset[iterator->depth] = ftello(iterator->file); + + return read_metadata_block_header_(iterator); +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator) +{ + off_t this_offset; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + if(iterator->offset[iterator->depth] == iterator->first_offset) + return false; + + if(0 != fseeko(iterator->file, iterator->first_offset, SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + this_offset = iterator->first_offset; + if(!read_metadata_block_header_(iterator)) + return false; + + /* we ignore any error from ftello() and catch it in fseeko() */ + while(ftello(iterator->file) + (off_t)iterator->length < iterator->offset[iterator->depth]) { + if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + this_offset = ftello(iterator->file); + if(!read_metadata_block_header_(iterator)) + return false; + } + + iterator->offset[iterator->depth] = this_offset; + + return true; +} + +/*@@@@add to tests*/ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + return iterator->is_last; +} + +/*@@@@add to tests*/ +FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + return iterator->offset[iterator->depth]; +} + +FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + return iterator->type; +} + +/*@@@@add to tests*/ +FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + return iterator->length; +} + +/*@@@@add to tests*/ +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id) +{ + const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + FLAC__ASSERT(0 != id); + + if(iterator->type != FLAC__METADATA_TYPE_APPLICATION) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT; + return false; + } + + if(fread(id, 1, id_bytes, iterator->file) != id_bytes) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + + /* back up */ + if(0 != fseeko(iterator->file, -((int)id_bytes), SEEK_CUR)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + return true; +} + +FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type); + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + if(0 != block) { + block->is_last = iterator->is_last; + block->length = iterator->length; + + if(!read_metadata_block_data_(iterator, block)) { + FLAC__metadata_object_delete(block); + return 0; + } + + /* back up to the beginning of the block data to stay consistent */ + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + FLAC__metadata_object_delete(block); + return 0; + } + } + else + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + return block; +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding) +{ + FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];) + FLAC__bool ret; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + FLAC__ASSERT(0 != block); + + if(!iterator->is_writable) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE; + return false; + } + + if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) { + if(iterator->type != block->type) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT; + return false; + } + } + + block->is_last = iterator->is_last; + + if(iterator->length == block->length) + return write_metadata_block_stationary_(iterator, block); + else if(iterator->length > block->length) { + if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) { + ret = write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last); + FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + else { + ret = rewrite_whole_file_(iterator, block, /*append=*/false); + FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + } + else /* iterator->length < block->length */ { + unsigned padding_leftover = 0; + FLAC__bool padding_is_last = false; + if(use_padding) { + /* first see if we can even use padding */ + if(iterator->is_last) { + use_padding = false; + } + else { + const unsigned extra_padding_bytes_required = block->length - iterator->length; + simple_iterator_push_(iterator); + if(!FLAC__metadata_simple_iterator_next(iterator)) { + (void)simple_iterator_pop_(iterator); + return false; + } + if(iterator->type != FLAC__METADATA_TYPE_PADDING) { + use_padding = false; + } + else { + if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) { + padding_leftover = 0; + block->is_last = iterator->is_last; + } + else if(iterator->length < extra_padding_bytes_required) + use_padding = false; + else { + padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required; + padding_is_last = iterator->is_last; + block->is_last = false; + } + } + if(!simple_iterator_pop_(iterator)) + return false; + } + } + if(use_padding) { + if(padding_leftover == 0) { + ret = write_metadata_block_stationary_(iterator, block); + FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + else { + FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH); + ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last); + FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + } + else { + ret = rewrite_whole_file_(iterator, block, /*append=*/false); + FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + } +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding) +{ + unsigned padding_leftover = 0; + FLAC__bool padding_is_last = false; + + FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;) + FLAC__bool ret; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + FLAC__ASSERT(0 != block); + + if(!iterator->is_writable) + return false; + + if(block->type == FLAC__METADATA_TYPE_STREAMINFO) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT; + return false; + } + + block->is_last = iterator->is_last; + + if(use_padding) { + /* first see if we can even use padding */ + if(iterator->is_last) { + use_padding = false; + } + else { + simple_iterator_push_(iterator); + if(!FLAC__metadata_simple_iterator_next(iterator)) { + (void)simple_iterator_pop_(iterator); + return false; + } + if(iterator->type != FLAC__METADATA_TYPE_PADDING) { + use_padding = false; + } + else { + if(iterator->length == block->length) { + padding_leftover = 0; + block->is_last = iterator->is_last; + } + else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) + use_padding = false; + else { + padding_leftover = iterator->length - block->length; + padding_is_last = iterator->is_last; + block->is_last = false; + } + } + if(!simple_iterator_pop_(iterator)) + return false; + } + } + if(use_padding) { + /* move to the next block, which is suitable padding */ + if(!FLAC__metadata_simple_iterator_next(iterator)) + return false; + if(padding_leftover == 0) { + ret = write_metadata_block_stationary_(iterator, block); + FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + else { + FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH); + ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last); + FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } + } + else { + ret = rewrite_whole_file_(iterator, block, /*append=*/true); + FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset); + FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH); + return ret; + } +} + +FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding) +{ + FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];) + FLAC__bool ret; + + if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT; + return false; + } + + if(use_padding) { + FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + if(0 == padding) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + padding->length = iterator->length; + if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) { + FLAC__metadata_object_delete(padding); + return false; + } + FLAC__metadata_object_delete(padding); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return false; + FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset); + FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset); + return true; + } + else { + ret = rewrite_whole_file_(iterator, 0, /*append=*/false); + FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset); + FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset); + return ret; + } +} + + + +/**************************************************************************** + * + * Level 2 implementation + * + ***************************************************************************/ + + +typedef struct FLAC__Metadata_Node { + FLAC__StreamMetadata *data; + struct FLAC__Metadata_Node *prev, *next; +} FLAC__Metadata_Node; + +struct FLAC__Metadata_Chain { + char *filename; /* will be NULL if using callbacks */ + FLAC__bool is_ogg; + FLAC__Metadata_Node *head; + FLAC__Metadata_Node *tail; + unsigned nodes; + FLAC__Metadata_ChainStatus status; + off_t first_offset, last_offset; + /* + * This is the length of the chain initially read from the FLAC file. + * it is used to compare against the current length to decide whether + * or not the whole file has to be rewritten. + */ + off_t initial_length; + /* @@@ hacky, these are currently only needed by ogg reader */ + FLAC__IOHandle handle; + FLAC__IOCallback_Read read_cb; +}; + +struct FLAC__Metadata_Iterator { + FLAC__Metadata_Chain *chain; + FLAC__Metadata_Node *current; +}; + +FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = { + "FLAC__METADATA_CHAIN_STATUS_OK", + "FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT", + "FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE", + "FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE", + "FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE", + "FLAC__METADATA_CHAIN_STATUS_BAD_METADATA", + "FLAC__METADATA_CHAIN_STATUS_READ_ERROR", + "FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR", + "FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR", + "FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR", + "FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR", + "FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR", + "FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR", + "FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS", + "FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", + "FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL" +}; + + +static FLAC__Metadata_Node *node_new_(void) +{ + return (FLAC__Metadata_Node*)calloc(1, sizeof(FLAC__Metadata_Node)); +} + +static void node_delete_(FLAC__Metadata_Node *node) +{ + FLAC__ASSERT(0 != node); + if(0 != node->data) + FLAC__metadata_object_delete(node->data); + free(node); +} + +static void chain_init_(FLAC__Metadata_Chain *chain) +{ + FLAC__ASSERT(0 != chain); + + chain->filename = 0; + chain->is_ogg = false; + chain->head = chain->tail = 0; + chain->nodes = 0; + chain->status = FLAC__METADATA_CHAIN_STATUS_OK; + chain->initial_length = 0; + chain->read_cb = 0; +} + +static void chain_clear_(FLAC__Metadata_Chain *chain) +{ + FLAC__Metadata_Node *node, *next; + + FLAC__ASSERT(0 != chain); + + for(node = chain->head; node; ) { + next = node->next; + node_delete_(node); + node = next; + } + + if(0 != chain->filename) + free(chain->filename); + + chain_init_(chain); +} + +static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node) +{ + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != node); + FLAC__ASSERT(0 != node->data); + + node->next = node->prev = 0; + node->data->is_last = true; + if(0 != chain->tail) + chain->tail->data->is_last = false; + + if(0 == chain->head) + chain->head = node; + else { + FLAC__ASSERT(0 != chain->tail); + chain->tail->next = node; + node->prev = chain->tail; + } + chain->tail = node; + chain->nodes++; +} + +static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node) +{ + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != node); + + if(node == chain->head) + chain->head = node->next; + else + node->prev->next = node->next; + + if(node == chain->tail) + chain->tail = node->prev; + else + node->next->prev = node->prev; + + if(0 != chain->tail) + chain->tail->data->is_last = true; + + chain->nodes--; +} + +static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node) +{ + chain_remove_node_(chain, node); + node_delete_(node); +} + +static off_t chain_calculate_length_(FLAC__Metadata_Chain *chain) +{ + const FLAC__Metadata_Node *node; + off_t length = 0; + for(node = chain->head; node; node = node->next) + length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length); + return length; +} + +static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node) +{ + FLAC__ASSERT(0 != node); + FLAC__ASSERT(0 != node->data); + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + FLAC__ASSERT(0 != iterator->chain); + FLAC__ASSERT(0 != iterator->chain->head); + FLAC__ASSERT(0 != iterator->chain->tail); + + node->data->is_last = false; + + node->prev = iterator->current->prev; + node->next = iterator->current; + + if(0 == node->prev) + iterator->chain->head = node; + else + node->prev->next = node; + + iterator->current->prev = node; + + iterator->chain->nodes++; +} + +static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node) +{ + FLAC__ASSERT(0 != node); + FLAC__ASSERT(0 != node->data); + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + FLAC__ASSERT(0 != iterator->chain); + FLAC__ASSERT(0 != iterator->chain->head); + FLAC__ASSERT(0 != iterator->chain->tail); + + iterator->current->data->is_last = false; + + node->prev = iterator->current; + node->next = iterator->current->next; + + if(0 == node->next) + iterator->chain->tail = node; + else + node->next->prev = node; + + node->prev->next = node; + + iterator->chain->tail->data->is_last = true; + + iterator->chain->nodes++; +} + +/* return true iff node and node->next are both padding */ +static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node) +{ + if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) { + const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length; + node->data->length += growth; + + chain_delete_node_(chain, node->next); + return true; + } + else + return false; +} + +/* Returns the new length of the chain, or 0 if there was an error. */ +/* WATCHOUT: This can get called multiple times before a write, so + * it should still work when this happens. + */ +/* WATCHOUT: Make sure to also update the logic in + * FLAC__metadata_chain_check_if_tempfile_needed() if the logic here changes. + */ +static off_t chain_prepare_for_write_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding) +{ + off_t current_length = chain_calculate_length_(chain); + + if(use_padding) { + /* if the metadata shrank and the last block is padding, we just extend the last padding block */ + if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) { + const off_t delta = chain->initial_length - current_length; + chain->tail->data->length += delta; + current_length += delta; + FLAC__ASSERT(current_length == chain->initial_length); + } + /* if the metadata shrank more than 4 bytes then there's room to add another padding block */ + else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) { + FLAC__StreamMetadata *padding; + FLAC__Metadata_Node *node; + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) { + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return 0; + } + padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length); + if(0 == (node = node_new_())) { + FLAC__metadata_object_delete(padding); + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return 0; + } + node->data = padding; + chain_append_node_(chain, node); + current_length = chain_calculate_length_(chain); + FLAC__ASSERT(current_length == chain->initial_length); + } + /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */ + else if(current_length > chain->initial_length) { + const off_t delta = current_length - chain->initial_length; + if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) { + /* if the delta is exactly the size of the last padding block, remove the padding block */ + if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) { + chain_delete_node_(chain, chain->tail); + current_length = chain_calculate_length_(chain); + FLAC__ASSERT(current_length == chain->initial_length); + } + /* if there is at least 'delta' bytes of padding, trim the padding down */ + else if((off_t)chain->tail->data->length >= delta) { + chain->tail->data->length -= delta; + current_length -= delta; + FLAC__ASSERT(current_length == chain->initial_length); + } + } + } + } + + return current_length; +} + +static FLAC__bool chain_read_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Tell tell_cb) +{ + FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != chain); + + /* we assume we're already at the beginning of the file */ + + switch(seek_to_first_metadata_block_cb_(handle, read_cb, seek_cb)) { + case 0: + break; + case 1: + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR; + return false; + case 2: + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + case 3: + chain->status = FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE; + return false; + default: + FLAC__ASSERT(0); + return false; + } + + { + FLAC__int64 pos = tell_cb(handle); + if(pos < 0) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR; + return false; + } + chain->first_offset = (off_t)pos; + } + + { + FLAC__bool is_last; + FLAC__MetadataType type; + unsigned length; + + do { + node = node_new_(); + if(0 == node) { + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + + if(!read_metadata_block_header_cb_(handle, read_cb, &is_last, &type, &length)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR; + return false; + } + + node->data = FLAC__metadata_object_new(type); + if(0 == node->data) { + node_delete_(node); + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + + node->data->is_last = is_last; + node->data->length = length; + + chain->status = get_equivalent_status_(read_metadata_block_data_cb_(handle, read_cb, seek_cb, node->data)); + if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) { + node_delete_(node); + return false; + } + chain_append_node_(chain, node); + } while(!is_last); + } + + { + FLAC__int64 pos = tell_cb(handle); + if(pos < 0) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR; + return false; + } + chain->last_offset = (off_t)pos; + } + + chain->initial_length = chain_calculate_length_(chain); + + return true; +} + +static FLAC__StreamDecoderReadStatus chain_read_ogg_read_cb_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data; + (void)decoder; + if(*bytes > 0 && chain->status == FLAC__METADATA_CHAIN_STATUS_OK) { + *bytes = chain->read_cb(buffer, sizeof(FLAC__byte), *bytes, chain->handle); + if(*bytes == 0) + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + else + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; +} + +static FLAC__StreamDecoderWriteStatus chain_read_ogg_write_cb_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + (void)decoder, (void)frame, (void)buffer, (void)client_data; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; +} + +static void chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data; + FLAC__Metadata_Node *node; + + (void)decoder; + + node = node_new_(); + if(0 == node) { + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return; + } + + node->data = FLAC__metadata_object_clone(metadata); + if(0 == node->data) { + node_delete_(node); + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return; + } + + chain_append_node_(chain, node); +} + +static void chain_read_ogg_error_cb_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data; + (void)decoder, (void)status; + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */ +} + +static FLAC__bool chain_read_ogg_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb) +{ + FLAC__StreamDecoder *decoder; + + FLAC__ASSERT(0 != chain); + + /* we assume we're already at the beginning of the file */ + + chain->handle = handle; + chain->read_cb = read_cb; + if(0 == (decoder = FLAC__stream_decoder_new())) { + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + FLAC__stream_decoder_set_metadata_respond_all(decoder); + if(FLAC__stream_decoder_init_ogg_stream(decoder, chain_read_ogg_read_cb_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, chain_read_ogg_write_cb_, chain_read_ogg_metadata_cb_, chain_read_ogg_error_cb_, chain) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + FLAC__stream_decoder_delete(decoder); + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */ + return false; + } + + chain->first_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */ + + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */ + if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) { + FLAC__stream_decoder_delete(decoder); + return false; + } + + FLAC__stream_decoder_delete(decoder); + + chain->last_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */ + + chain->initial_length = chain_calculate_length_(chain); + + return true; +} + +static FLAC__bool chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, FLAC__IOCallback_Seek seek_cb) +{ + FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != chain->head); + + if(0 != seek_cb(handle, chain->first_offset, SEEK_SET)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + } + + for(node = chain->head; node; node = node->next) { + if(!write_metadata_block_header_cb_(handle, write_cb, node->data)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR; + return false; + } + if(!write_metadata_block_data_cb_(handle, write_cb, node->data)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR; + return false; + } + } + + /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/ + + chain->status = FLAC__METADATA_CHAIN_STATUS_OK; + return true; +} + +static FLAC__bool chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain *chain) +{ + FILE *file; + FLAC__bool ret; + + FLAC__ASSERT(0 != chain->filename); + + if(0 == (file = fopen(chain->filename, "r+b"))) { + chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE; + return false; + } + + /* chain_rewrite_metadata_in_place_cb_() sets chain->status for us */ + ret = chain_rewrite_metadata_in_place_cb_(chain, (FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, fseek_wrapper_); + + fclose(file); + + return ret; +} + +static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix) +{ + FILE *f, *tempfile; + char *tempfilename; + FLAC__Metadata_SimpleIteratorStatus status; + const FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != chain->filename); + FLAC__ASSERT(0 != chain->head); + + /* copy the file prefix (data up to first metadata block */ + if(0 == (f = fopen(chain->filename, "rb"))) { + chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE; + return false; + } + if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) { + chain->status = get_equivalent_status_(status); + cleanup_tempfile_(&tempfile, &tempfilename); + return false; + } + if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) { + chain->status = get_equivalent_status_(status); + cleanup_tempfile_(&tempfile, &tempfilename); + return false; + } + + /* write the metadata */ + for(node = chain->head; node; node = node->next) { + if(!write_metadata_block_header_(tempfile, &status, node->data)) { + chain->status = get_equivalent_status_(status); + return false; + } + if(!write_metadata_block_data_(tempfile, &status, node->data)) { + chain->status = get_equivalent_status_(status); + return false; + } + } + /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/ + + /* copy the file postfix (everything after the metadata) */ + if(0 != fseeko(f, chain->last_offset, SEEK_SET)) { + cleanup_tempfile_(&tempfile, &tempfilename); + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + } + if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) { + cleanup_tempfile_(&tempfile, &tempfilename); + chain->status = get_equivalent_status_(status); + return false; + } + + /* move the tempfile on top of the original */ + (void)fclose(f); + if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status)) + return false; + + return true; +} + +/* assumes 'handle' is already at beginning of file */ +static FLAC__bool chain_rewrite_file_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb) +{ + FLAC__Metadata_SimpleIteratorStatus status; + const FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 == chain->filename); + FLAC__ASSERT(0 != chain->head); + + /* copy the file prefix (data up to first metadata block */ + if(!copy_n_bytes_from_file_cb_(handle, read_cb, temp_handle, temp_write_cb, chain->first_offset, &status)) { + chain->status = get_equivalent_status_(status); + return false; + } + + /* write the metadata */ + for(node = chain->head; node; node = node->next) { + if(!write_metadata_block_header_cb_(temp_handle, temp_write_cb, node->data)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR; + return false; + } + if(!write_metadata_block_data_cb_(temp_handle, temp_write_cb, node->data)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR; + return false; + } + } + /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/ + + /* copy the file postfix (everything after the metadata) */ + if(0 != seek_cb(handle, chain->last_offset, SEEK_SET)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + } + if(!copy_remaining_bytes_from_file_cb_(handle, read_cb, eof_cb, temp_handle, temp_write_cb, &status)) { + chain->status = get_equivalent_status_(status); + return false; + } + + return true; +} + +FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void) +{ + FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)calloc(1, sizeof(FLAC__Metadata_Chain)); + + if(0 != chain) + chain_init_(chain); + + return chain; +} + +FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain) +{ + FLAC__ASSERT(0 != chain); + + chain_clear_(chain); + + free(chain); +} + +FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain) +{ + FLAC__Metadata_ChainStatus status; + + FLAC__ASSERT(0 != chain); + + status = chain->status; + chain->status = FLAC__METADATA_CHAIN_STATUS_OK; + return status; +} + +static FLAC__bool chain_read_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool is_ogg) +{ + FILE *file; + FLAC__bool ret; + + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != filename); + + chain_clear_(chain); + + if(0 == (chain->filename = strdup(filename))) { + chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + + chain->is_ogg = is_ogg; + + if(0 == (file = fopen(filename, "rb"))) { + chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE; + return false; + } + + /* the function also sets chain->status for us */ + ret = is_ogg? + chain_read_ogg_cb_(chain, file, (FLAC__IOCallback_Read)fread) : + chain_read_cb_(chain, file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, ftell_wrapper_) + ; + + fclose(file); + + return ret; +} + +FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename) +{ + return chain_read_(chain, filename, /*is_ogg=*/false); +} + +/*@@@@add to tests*/ +FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename) +{ + return chain_read_(chain, filename, /*is_ogg=*/true); +} + +static FLAC__bool chain_read_with_callbacks_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__bool is_ogg) +{ + FLAC__bool ret; + + FLAC__ASSERT(0 != chain); + + chain_clear_(chain); + + if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.tell) { + chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS; + return false; + } + + chain->is_ogg = is_ogg; + + /* rewind */ + if(0 != callbacks.seek(handle, 0, SEEK_SET)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + } + + /* the function also sets chain->status for us */ + ret = is_ogg? + chain_read_ogg_cb_(chain, handle, callbacks.read) : + chain_read_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.tell) + ; + + return ret; +} + +FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks) +{ + return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/false); +} + +/*@@@@add to tests*/ +FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks) +{ + return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/true); +} + +FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding) +{ + /* This does all the same checks that are in chain_prepare_for_write_() + * but doesn't actually alter the chain. Make sure to update the logic + * here if chain_prepare_for_write_() changes. + */ + const off_t current_length = chain_calculate_length_(chain); + + FLAC__ASSERT(0 != chain); + + if(use_padding) { + /* if the metadata shrank and the last block is padding, we just extend the last padding block */ + if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) + return false; + /* if the metadata shrank more than 4 bytes then there's room to add another padding block */ + else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) + return false; + /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */ + else if(current_length > chain->initial_length) { + const off_t delta = current_length - chain->initial_length; + if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) { + /* if the delta is exactly the size of the last padding block, remove the padding block */ + if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) + return false; + /* if there is at least 'delta' bytes of padding, trim the padding down */ + else if((off_t)chain->tail->data->length >= delta) + return false; + } + } + } + + return (current_length != chain->initial_length); +} + +FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats) +{ + struct stat stats; + const char *tempfile_path_prefix = 0; + off_t current_length; + + FLAC__ASSERT(0 != chain); + + if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */ + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; + return false; + } + + if (0 == chain->filename) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH; + return false; + } + + current_length = chain_prepare_for_write_(chain, use_padding); + + /* a return value of 0 means there was an error; chain->status is already set */ + if (0 == current_length) + return false; + + if(preserve_file_stats) + get_file_stats_(chain->filename, &stats); + + if(current_length == chain->initial_length) { + if(!chain_rewrite_metadata_in_place_(chain)) + return false; + } + else { + if(!chain_rewrite_file_(chain, tempfile_path_prefix)) + return false; + + /* recompute lengths and offsets */ + { + const FLAC__Metadata_Node *node; + chain->initial_length = current_length; + chain->last_offset = chain->first_offset; + for(node = chain->head; node; node = node->next) + chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length); + } + } + + if(preserve_file_stats) + set_file_stats_(chain->filename, &stats); + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks) +{ + off_t current_length; + + FLAC__ASSERT(0 != chain); + + if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */ + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; + return false; + } + + if (0 != chain->filename) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH; + return false; + } + + if (0 == callbacks.write || 0 == callbacks.seek) { + chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS; + return false; + } + + if (FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL; + return false; + } + + current_length = chain_prepare_for_write_(chain, use_padding); + + /* a return value of 0 means there was an error; chain->status is already set */ + if (0 == current_length) + return false; + + FLAC__ASSERT(current_length == chain->initial_length); + + return chain_rewrite_metadata_in_place_cb_(chain, handle, callbacks.write, callbacks.seek); +} + +FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks) +{ + off_t current_length; + + FLAC__ASSERT(0 != chain); + + if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */ + chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; + return false; + } + + if (0 != chain->filename) { + chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH; + return false; + } + + if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.eof) { + chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS; + return false; + } + if (0 == temp_callbacks.write) { + chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS; + return false; + } + + if (!FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL; + return false; + } + + current_length = chain_prepare_for_write_(chain, use_padding); + + /* a return value of 0 means there was an error; chain->status is already set */ + if (0 == current_length) + return false; + + FLAC__ASSERT(current_length != chain->initial_length); + + /* rewind */ + if(0 != callbacks.seek(handle, 0, SEEK_SET)) { + chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + return false; + } + + if(!chain_rewrite_file_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.eof, temp_handle, temp_callbacks.write)) + return false; + + /* recompute lengths and offsets */ + { + const FLAC__Metadata_Node *node; + chain->initial_length = current_length; + chain->last_offset = chain->first_offset; + for(node = chain->head; node; node = node->next) + chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length); + } + + return true; +} + +FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain) +{ + FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != chain); + + for(node = chain->head; node; ) { + if(!chain_merge_adjacent_padding_(chain, node)) + node = node->next; + } +} + +FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain) +{ + FLAC__Metadata_Node *node, *save; + unsigned i; + + FLAC__ASSERT(0 != chain); + + /* + * Don't try and be too smart... this simple algo is good enough for + * the small number of nodes that we deal with. + */ + for(i = 0, node = chain->head; i < chain->nodes; i++) { + if(node->data->type == FLAC__METADATA_TYPE_PADDING) { + save = node->next; + chain_remove_node_(chain, node); + chain_append_node_(chain, node); + node = save; + } + else { + node = node->next; + } + } + + FLAC__metadata_chain_merge_padding(chain); +} + + +FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void) +{ + FLAC__Metadata_Iterator *iterator = (FLAC__Metadata_Iterator*)calloc(1, sizeof(FLAC__Metadata_Iterator)); + + /* calloc() implies: + iterator->current = 0; + iterator->chain = 0; + */ + + return iterator; +} + +FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + + free(iterator); +} + +FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != chain); + FLAC__ASSERT(0 != chain->head); + + iterator->chain = chain; + iterator->current = chain->head; +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + + if(0 == iterator->current || 0 == iterator->current->next) + return false; + + iterator->current = iterator->current->next; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + + if(0 == iterator->current || 0 == iterator->current->prev) + return false; + + iterator->current = iterator->current->prev; + return true; +} + +FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + FLAC__ASSERT(0 != iterator->current->data); + + return iterator->current->data->type; +} + +FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + + return iterator->current->data; +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != block); + return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block); +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding) +{ + FLAC__Metadata_Node *save; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + + if(0 == iterator->current->prev) { + FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO); + return false; + } + + save = iterator->current->prev; + + if(replace_with_padding) { + FLAC__metadata_object_delete_data(iterator->current->data); + iterator->current->data->type = FLAC__METADATA_TYPE_PADDING; + } + else { + chain_delete_node_(iterator->chain, iterator->current); + } + + iterator->current = save; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block) +{ + FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + FLAC__ASSERT(0 != block); + + if(block->type == FLAC__METADATA_TYPE_STREAMINFO) + return false; + + if(0 == iterator->current->prev) { + FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO); + return false; + } + + if(0 == (node = node_new_())) + return false; + + node->data = block; + iterator_insert_node_(iterator, node); + iterator->current = node; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block) +{ + FLAC__Metadata_Node *node; + + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->current); + FLAC__ASSERT(0 != block); + + if(block->type == FLAC__METADATA_TYPE_STREAMINFO) + return false; + + if(0 == (node = node_new_())) + return false; + + node->data = block; + iterator_insert_node_after_(iterator, node); + iterator->current = node; + return true; +} + + +/**************************************************************************** + * + * Local function definitions + * + ***************************************************************************/ + +void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes) +{ + unsigned i; + + b += bytes; + + for(i = 0; i < bytes; i++) { + *(--b) = (FLAC__byte)(val & 0xff); + val >>= 8; + } +} + +void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes) +{ + unsigned i; + + for(i = 0; i < bytes; i++) { + *(b++) = (FLAC__byte)(val & 0xff); + val >>= 8; + } +} + +void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes) +{ + unsigned i; + + b += bytes; + + for(i = 0; i < bytes; i++) { + *(--b) = (FLAC__byte)(val & 0xff); + val >>= 8; + } +} + +FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes) +{ + FLAC__uint32 ret = 0; + unsigned i; + + for(i = 0; i < bytes; i++) + ret = (ret << 8) | (FLAC__uint32)(*b++); + + return ret; +} + +FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes) +{ + FLAC__uint32 ret = 0; + unsigned i; + + b += bytes; + + for(i = 0; i < bytes; i++) + ret = (ret << 8) | (FLAC__uint32)(*--b); + + return ret; +} + +FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes) +{ + FLAC__uint64 ret = 0; + unsigned i; + + for(i = 0; i < bytes; i++) + ret = (ret << 8) | (FLAC__uint64)(*b++); + + return ret; +} + +FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + if(!read_metadata_block_header_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, &iterator->is_last, &iterator->type, &iterator->length)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + + return true; +} + +FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != iterator); + FLAC__ASSERT(0 != iterator->file); + + iterator->status = read_metadata_block_data_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, block); + + return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK); +} + +FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length) +{ + FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH]; + + if(read_cb(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH) + return false; + + *is_last = raw_header[0] & 0x80? true : false; + *type = (FLAC__MetadataType)(raw_header[0] & 0x7f); + *length = unpack_uint32_(raw_header + 1, 3); + + /* Note that we don't check: + * if(iterator->type >= FLAC__METADATA_TYPE_UNDEFINED) + * we just will read in an opaque block + */ + + return true; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block) +{ + switch(block->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + return read_metadata_block_data_streaminfo_cb_(handle, read_cb, &block->data.stream_info); + case FLAC__METADATA_TYPE_PADDING: + return read_metadata_block_data_padding_cb_(handle, seek_cb, &block->data.padding, block->length); + case FLAC__METADATA_TYPE_APPLICATION: + return read_metadata_block_data_application_cb_(handle, read_cb, &block->data.application, block->length); + case FLAC__METADATA_TYPE_SEEKTABLE: + return read_metadata_block_data_seektable_cb_(handle, read_cb, &block->data.seek_table, block->length); + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + return read_metadata_block_data_vorbis_comment_cb_(handle, read_cb, &block->data.vorbis_comment); + case FLAC__METADATA_TYPE_CUESHEET: + return read_metadata_block_data_cuesheet_cb_(handle, read_cb, &block->data.cue_sheet); + case FLAC__METADATA_TYPE_PICTURE: + return read_metadata_block_data_picture_cb_(handle, read_cb, &block->data.picture); + default: + return read_metadata_block_data_unknown_cb_(handle, read_cb, &block->data.unknown, block->length); + } +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block) +{ + FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b; + + if(read_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + b = buffer; + + /* we are using hardcoded numbers for simplicity but we should + * probably eventually write a bit-level unpacker and use the + * _STREAMINFO_ constants. + */ + block->min_blocksize = unpack_uint32_(b, 2); b += 2; + block->max_blocksize = unpack_uint32_(b, 2); b += 2; + block->min_framesize = unpack_uint32_(b, 3); b += 3; + block->max_framesize = unpack_uint32_(b, 3); b += 3; + block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4); + block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1; + block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1; + block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4); + memcpy(block->md5sum, b+8, 16); + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length) +{ + (void)block; /* nothing to do; we don't care about reading the padding bytes */ + + if(0 != seek_cb(handle, block_length, SEEK_CUR)) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length) +{ + const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + + if(read_cb(block->id, 1, id_bytes, handle) != id_bytes) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + if(block_length < id_bytes) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + block_length -= id_bytes; + + if(block_length == 0) { + block->data = 0; + } + else { + if(0 == (block->data = (FLAC__byte*)malloc(block_length))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + if(read_cb(block->data, 1, block_length, handle) != block_length) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length) +{ + unsigned i; + FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH]; + + FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0); + + block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; + + if(block->num_points == 0) + block->points = 0; + else if(0 == (block->points = (FLAC__StreamMetadata_SeekPoint*)safe_malloc_mul_2op_(block->num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + for(i = 0; i < block->num_points; i++) { + if(read_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + /* some MAGIC NUMBERs here */ + block->points[i].sample_number = unpack_uint64_(buffer, 8); + block->points[i].stream_offset = unpack_uint64_(buffer+8, 8); + block->points[i].frame_samples = unpack_uint32_(buffer+16, 2); + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry) +{ + const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8; + FLAC__byte buffer[4]; /* magic number is asserted below */ + + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == sizeof(buffer)); + + if(read_cb(buffer, 1, entry_length_len, handle) != entry_length_len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + entry->length = unpack_uint32_little_endian_(buffer, entry_length_len); + + if(0 != entry->entry) + free(entry->entry); + + if(entry->length == 0) { + entry->entry = 0; + } + else { + if(0 == (entry->entry = (FLAC__byte*)safe_malloc_add_2op_(entry->length, /*+*/1))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + if(read_cb(entry->entry, 1, entry->length, handle) != entry->length) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + entry->entry[entry->length] = '\0'; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block) +{ + unsigned i; + FLAC__Metadata_SimpleIteratorStatus status; + const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8; + FLAC__byte buffer[4]; /* magic number is asserted below */ + + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == sizeof(buffer)); + + if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, &(block->vendor_string)))) + return status; + + if(read_cb(buffer, 1, num_comments_len, handle) != num_comments_len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len); + + if(block->num_comments == 0) { + block->comments = 0; + } + else if(0 == (block->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)calloc(block->num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + for(i = 0; i < block->num_comments; i++) { + if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, block->comments + i))) + return status; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track) +{ + unsigned i, len; + FLAC__byte buffer[32]; /* asserted below that this is big enough */ + + FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64)); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + track->offset = unpack_uint64_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + track->number = (FLAC__byte)unpack_uint32_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8; + if(read_cb(track->isrc, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0); + len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN == 1); + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN == 1); + track->type = buffer[0] >> 7; + track->pre_emphasis = (buffer[0] >> 6) & 1; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + track->num_indices = (FLAC__byte)unpack_uint32_(buffer, len); + + if(track->num_indices == 0) { + track->indices = 0; + } + else if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + for(i = 0; i < track->num_indices; i++) { + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + track->indices[i].offset = unpack_uint64_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + track->indices[i].number = (FLAC__byte)unpack_uint32_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block) +{ + unsigned i, len; + FLAC__Metadata_SimpleIteratorStatus status; + FLAC__byte buffer[1024]; /* MSVC needs a constant expression so we put a magic number and assert */ + + FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)/8 <= sizeof(buffer)); + FLAC__ASSERT(sizeof(FLAC__uint64) <= sizeof(buffer)); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8; + if(read_cb(block->media_catalog_number, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->lead_in = unpack_uint64_(buffer, len); + + FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0); + len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->is_cd = buffer[0]&0x80? true : false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->num_tracks = unpack_uint32_(buffer, len); + + if(block->num_tracks == 0) { + block->tracks = 0; + } + else if(0 == (block->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(block->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + for(i = 0; i < block->num_tracks; i++) { + if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_cuesheet_track_cb_(handle, read_cb, block->tracks + i))) + return status; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__byte **data, FLAC__uint32 *length, FLAC__uint32 length_len) +{ + FLAC__byte buffer[sizeof(FLAC__uint32)]; + + FLAC__ASSERT(0 != data); + FLAC__ASSERT(length_len%8 == 0); + + length_len /= 8; /* convert to bytes */ + + FLAC__ASSERT(sizeof(buffer) >= length_len); + + if(read_cb(buffer, 1, length_len, handle) != length_len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + *length = unpack_uint32_(buffer, length_len); + + if(0 != *data) + free(*data); + + if(0 == (*data = (FLAC__byte*)safe_malloc_add_2op_(*length, /*+*/1))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + if(*length > 0) { + if(read_cb(*data, 1, *length, handle) != *length) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + } + + (*data)[*length] = '\0'; + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block) +{ + FLAC__Metadata_SimpleIteratorStatus status; + FLAC__byte buffer[4]; /* asserted below that this is big enough */ + FLAC__uint32 len; + + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8); + + FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_TYPE_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->type = (FLAC__StreamMetadata_Picture_Type)unpack_uint32_(buffer, len); + + if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, (FLAC__byte**)(&(block->mime_type)), &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) + return status; + + if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->description), &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) + return status; + + FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->width = unpack_uint32_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->height = unpack_uint32_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->depth = unpack_uint32_(buffer, len); + + FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_COLORS_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN / 8; + if(read_cb(buffer, 1, len, handle) != len) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + block->colors = unpack_uint32_(buffer, len); + + /* for convenience we use read_metadata_block_data_picture_cstring_cb_() even though it adds an extra terminating NUL we don't use */ + if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->data), &(block->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) + return status; + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length) +{ + if(block_length == 0) { + block->data = 0; + } + else { + if(0 == (block->data = (FLAC__byte*)malloc(block_length))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + if(read_cb(block->data, 1, block_length, handle) != block_length) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + } + + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; +} + +FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != status); + + if(!write_metadata_block_header_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + + return true; +} + +FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != status); + + if (write_metadata_block_data_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK; + return true; + } + else { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } +} + +FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block) +{ + FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH]; + + FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN)); + + buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type; + pack_uint32_(block->length, buffer + 1, 3); + + if(write_cb(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH) + return false; + + return true; +} + +FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != block); + + switch(block->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + return write_metadata_block_data_streaminfo_cb_(handle, write_cb, &block->data.stream_info); + case FLAC__METADATA_TYPE_PADDING: + return write_metadata_block_data_padding_cb_(handle, write_cb, &block->data.padding, block->length); + case FLAC__METADATA_TYPE_APPLICATION: + return write_metadata_block_data_application_cb_(handle, write_cb, &block->data.application, block->length); + case FLAC__METADATA_TYPE_SEEKTABLE: + return write_metadata_block_data_seektable_cb_(handle, write_cb, &block->data.seek_table); + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + return write_metadata_block_data_vorbis_comment_cb_(handle, write_cb, &block->data.vorbis_comment); + case FLAC__METADATA_TYPE_CUESHEET: + return write_metadata_block_data_cuesheet_cb_(handle, write_cb, &block->data.cue_sheet); + case FLAC__METADATA_TYPE_PICTURE: + return write_metadata_block_data_picture_cb_(handle, write_cb, &block->data.picture); + default: + return write_metadata_block_data_unknown_cb_(handle, write_cb, &block->data.unknown, block->length); + } +} + +FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block) +{ + FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH]; + const unsigned channels1 = block->channels - 1; + const unsigned bps1 = block->bits_per_sample - 1; + + /* we are using hardcoded numbers for simplicity but we should + * probably eventually write a bit-level packer and use the + * _STREAMINFO_ constants. + */ + pack_uint32_(block->min_blocksize, buffer, 2); + pack_uint32_(block->max_blocksize, buffer+2, 2); + pack_uint32_(block->min_framesize, buffer+4, 3); + pack_uint32_(block->max_framesize, buffer+7, 3); + buffer[10] = (block->sample_rate >> 12) & 0xff; + buffer[11] = (block->sample_rate >> 4) & 0xff; + buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4); + buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f)); + pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4); + memcpy(buffer+18, block->md5sum, 16); + + if(write_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH) + return false; + + return true; +} + +FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length) +{ + unsigned i, n = block_length; + FLAC__byte buffer[1024]; + + (void)block; + + memset(buffer, 0, 1024); + + for(i = 0; i < n/1024; i++) + if(write_cb(buffer, 1, 1024, handle) != 1024) + return false; + + n %= 1024; + + if(write_cb(buffer, 1, n, handle) != n) + return false; + + return true; +} + +FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length) +{ + const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + + if(write_cb(block->id, 1, id_bytes, handle) != id_bytes) + return false; + + block_length -= id_bytes; + + if(write_cb(block->data, 1, block_length, handle) != block_length) + return false; + + return true; +} + +FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block) +{ + unsigned i; + FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH]; + + for(i = 0; i < block->num_points; i++) { + /* some MAGIC NUMBERs here */ + pack_uint64_(block->points[i].sample_number, buffer, 8); + pack_uint64_(block->points[i].stream_offset, buffer+8, 8); + pack_uint32_(block->points[i].frame_samples, buffer+16, 2); + if(write_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH) + return false; + } + + return true; +} + +FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block) +{ + unsigned i; + const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8; + const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8; + FLAC__byte buffer[4]; /* magic number is asserted below */ + + FLAC__ASSERT(max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == sizeof(buffer)); + + pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len); + if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len) + return false; + if(write_cb(block->vendor_string.entry, 1, block->vendor_string.length, handle) != block->vendor_string.length) + return false; + + pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len); + if(write_cb(buffer, 1, num_comments_len, handle) != num_comments_len) + return false; + + for(i = 0; i < block->num_comments; i++) { + pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len); + if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len) + return false; + if(write_cb(block->comments[i].entry, 1, block->comments[i].length, handle) != block->comments[i].length) + return false; + } + + return true; +} + +FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block) +{ + unsigned i, j, len; + FLAC__byte buffer[1024]; /* asserted below that this is big enough */ + + FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64)); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8; + if(write_cb(block->media_catalog_number, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8; + pack_uint64_(block->lead_in, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0); + len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8; + memset(buffer, 0, len); + if(block->is_cd) + buffer[0] |= 0x80; + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8; + pack_uint32_(block->num_tracks, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + for(i = 0; i < block->num_tracks; i++) { + FLAC__StreamMetadata_CueSheet_Track *track = block->tracks + i; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8; + pack_uint64_(track->offset, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8; + pack_uint32_(track->number, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8; + if(write_cb(track->isrc, 1, len, handle) != len) + return false; + + FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0); + len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8; + memset(buffer, 0, len); + buffer[0] = (track->type << 7) | (track->pre_emphasis << 6); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8; + pack_uint32_(track->num_indices, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + for(j = 0; j < track->num_indices; j++) { + FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8; + pack_uint64_(index->offset, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8; + pack_uint32_(index->number, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0); + len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8; + memset(buffer, 0, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + } + } + + return true; +} + +FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block) +{ + unsigned len; + size_t slen; + FLAC__byte buffer[4]; /* magic number is asserted below */ + + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_TYPE_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_COLORS_LEN%8); + FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN%8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8); + FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8); + + len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8; + pack_uint32_(block->type, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8; + slen = strlen(block->mime_type); + pack_uint32_(slen, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + if(write_cb(block->mime_type, 1, slen, handle) != slen) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8; + slen = strlen((const char *)block->description); + pack_uint32_(slen, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + if(write_cb(block->description, 1, slen, handle) != slen) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8; + pack_uint32_(block->width, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8; + pack_uint32_(block->height, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8; + pack_uint32_(block->depth, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8; + pack_uint32_(block->colors, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + + len = FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8; + pack_uint32_(block->data_length, buffer, len); + if(write_cb(buffer, 1, len, handle) != len) + return false; + if(write_cb(block->data, 1, block->data_length, handle) != block->data_length) + return false; + + return true; +} + +FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length) +{ + if(write_cb(block->data, 1, block_length, handle) != block_length) + return false; + + return true; +} + +FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block) +{ + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + if(!write_metadata_block_header_(iterator->file, &iterator->status, block)) + return false; + + if(!write_metadata_block_data_(iterator->file, &iterator->status, block)) + return false; + + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + return read_metadata_block_header_(iterator); +} + +FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last) +{ + FLAC__StreamMetadata *padding; + + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + block->is_last = false; + + if(!write_metadata_block_header_(iterator->file, &iterator->status, block)) + return false; + + if(!write_metadata_block_data_(iterator->file, &iterator->status, block)) + return false; + + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + + padding->is_last = padding_is_last; + padding->length = padding_length; + + if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) { + FLAC__metadata_object_delete(padding); + return false; + } + + if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) { + FLAC__metadata_object_delete(padding); + return false; + } + + FLAC__metadata_object_delete(padding); + + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + return read_metadata_block_header_(iterator); +} + +FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append) +{ + FILE *tempfile; + char *tempfilename; + int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */ + off_t fixup_is_last_flag_offset = -1; + + FLAC__ASSERT(0 != block || append == false); + + if(iterator->is_last) { + if(append) { + fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */ + fixup_is_last_flag_offset = iterator->offset[iterator->depth]; + } + else if(0 == block) { + simple_iterator_push_(iterator); + if(!FLAC__metadata_simple_iterator_prev(iterator)) { + (void)simple_iterator_pop_(iterator); + return false; + } + fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */ + fixup_is_last_flag_offset = iterator->offset[iterator->depth]; + if(!simple_iterator_pop_(iterator)) + return false; + } + } + + if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append)) + return false; + + if(0 != block) { + if(!write_metadata_block_header_(tempfile, &iterator->status, block)) { + cleanup_tempfile_(&tempfile, &tempfilename); + return false; + } + + if(!write_metadata_block_data_(tempfile, &iterator->status, block)) { + cleanup_tempfile_(&tempfile, &tempfilename); + return false; + } + } + + if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0)) + return false; + + if(append) + return FLAC__metadata_simple_iterator_next(iterator); + + return true; +} + +void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH); + iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth]; + iterator->depth++; +} + +FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator) +{ + FLAC__ASSERT(iterator->depth > 0); + iterator->depth--; + if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + + return read_metadata_block_header_(iterator); +} + +/* return meanings: + * 0: ok + * 1: read error + * 2: seek error + * 3: not a FLAC file + */ +unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb) +{ + FLAC__byte buffer[4]; + size_t n; + unsigned i; + + FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == sizeof(buffer)); + + /* skip any id3v2 tag */ + errno = 0; + n = read_cb(buffer, 1, 4, handle); + if(errno) + return 1; + else if(n != 4) + return 3; + else if(0 == memcmp(buffer, "ID3", 3)) { + unsigned tag_length = 0; + + /* skip to the tag length */ + if(seek_cb(handle, 2, SEEK_CUR) < 0) + return 2; + + /* read the length */ + for(i = 0; i < 4; i++) { + if(read_cb(buffer, 1, 1, handle) < 1 || buffer[0] & 0x80) + return 1; + tag_length <<= 7; + tag_length |= (buffer[0] & 0x7f); + } + + /* skip the rest of the tag */ + if(seek_cb(handle, tag_length, SEEK_CUR) < 0) + return 2; + + /* read the stream sync code */ + errno = 0; + n = read_cb(buffer, 1, 4, handle); + if(errno) + return 1; + else if(n != 4) + return 3; + } + + /* check for the fLaC signature */ + if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH)) + return 0; + else + return 3; +} + +unsigned seek_to_first_metadata_block_(FILE *f) +{ + return seek_to_first_metadata_block_cb_((FLAC__IOHandle)f, (FLAC__IOCallback_Read)fread, fseek_wrapper_); +} + +FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append) +{ + const off_t offset_end = append? iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length : iterator->offset[iterator->depth]; + + if(0 != fseeko(iterator->file, 0, SEEK_SET)) { + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } + if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } + + return true; +} + +FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup) +{ + off_t save_offset = iterator->offset[iterator->depth]; + FLAC__ASSERT(0 != *tempfile); + + if(0 != fseeko(iterator->file, save_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length, SEEK_SET)) { + cleanup_tempfile_(tempfile, tempfilename); + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } + + if(fixup_is_last_code != 0) { + /* + * if code == 1, it means a block was appended to the end so + * we have to clear the is_last flag of the previous block + * if code == -1, it means the last block was deleted so + * we have to set the is_last flag of the previous block + */ + /* MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */ + FLAC__byte x; + if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) { + cleanup_tempfile_(tempfile, tempfilename); + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + if(fread(&x, 1, 1, *tempfile) != 1) { + cleanup_tempfile_(tempfile, tempfilename); + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + if(fixup_is_last_code > 0) { + FLAC__ASSERT(x & 0x80); + x &= 0x7f; + } + else { + FLAC__ASSERT(!(x & 0x80)); + x |= 0x80; + } + if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) { + cleanup_tempfile_(tempfile, tempfilename); + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR; + return false; + } + if(local__fwrite(&x, 1, 1, *tempfile) != 1) { + cleanup_tempfile_(tempfile, tempfilename); + iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + } + + (void)fclose(iterator->file); + + if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status)) + return false; + + if(iterator->has_stats) + set_file_stats_(iterator->filename, &iterator->stats); + + if(!simple_iterator_prime_input_(iterator, !iterator->is_writable)) + return false; + if(backup) { + while(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length < save_offset) + if(!FLAC__metadata_simple_iterator_next(iterator)) + return false; + return true; + } + else { + /* move the iterator to it's original block faster by faking a push, then doing a pop_ */ + FLAC__ASSERT(iterator->depth == 0); + iterator->offset[0] = save_offset; + iterator->depth++; + return simple_iterator_pop_(iterator); + } +} + +FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status) +{ + FLAC__byte buffer[8192]; + size_t n; + + FLAC__ASSERT(bytes >= 0); + while(bytes > 0) { + n = min(sizeof(buffer), (size_t)bytes); + if(fread(buffer, 1, n, file) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + if(local__fwrite(buffer, 1, n, tempfile) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + bytes -= n; + } + + return true; +} + +FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status) +{ + FLAC__byte buffer[8192]; + size_t n; + + FLAC__ASSERT(bytes >= 0); + while(bytes > 0) { + n = min(sizeof(buffer), (size_t)bytes); + if(read_cb(buffer, 1, n, handle) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + if(temp_write_cb(buffer, 1, n, temp_handle) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + bytes -= n; + } + + return true; +} + +FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status) +{ + FLAC__byte buffer[8192]; + size_t n; + + while(!feof(file)) { + n = fread(buffer, 1, sizeof(buffer), file); + if(n == 0 && !feof(file)) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + if(n > 0 && local__fwrite(buffer, 1, n, tempfile) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + } + + return true; +} + +FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status) +{ + FLAC__byte buffer[8192]; + size_t n; + + while(!eof_cb(handle)) { + n = read_cb(buffer, 1, sizeof(buffer), handle); + if(n == 0 && !eof_cb(handle)) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR; + return false; + } + if(n > 0 && temp_write_cb(buffer, 1, n, temp_handle) != n) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR; + return false; + } + } + + return true; +} + +FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status) +{ + static const char *tempfile_suffix = ".metadata_edit"; + if(0 == tempfile_path_prefix) { + if(0 == (*tempfilename = (char*)safe_malloc_add_3op_(strlen(filename), /*+*/strlen(tempfile_suffix), /*+*/1))) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + strcpy(*tempfilename, filename); + strcat(*tempfilename, tempfile_suffix); + } + else { + const char *p = strrchr(filename, '/'); + if(0 == p) + p = filename; + else + p++; + + if(0 == (*tempfilename = (char*)safe_malloc_add_4op_(strlen(tempfile_path_prefix), /*+*/strlen(p), /*+*/strlen(tempfile_suffix), /*+*/2))) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR; + return false; + } + strcpy(*tempfilename, tempfile_path_prefix); + strcat(*tempfilename, "/"); + strcat(*tempfilename, p); + strcat(*tempfilename, tempfile_suffix); + } + + if(0 == (*tempfile = fopen(*tempfilename, "w+b"))) { + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE; + return false; + } + + return true; +} + +FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != tempfile); + FLAC__ASSERT(0 != *tempfile); + FLAC__ASSERT(0 != tempfilename); + FLAC__ASSERT(0 != *tempfilename); + FLAC__ASSERT(0 != status); + + (void)fclose(*tempfile); + *tempfile = 0; + +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__ + /* on some flavors of windows, rename() will fail if the destination already exists */ + if(unlink(filename) < 0) { + cleanup_tempfile_(tempfile, tempfilename); + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR; + return false; + } +#endif + + /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just rename(): */ + if(0 != rename(*tempfilename, filename)) { + cleanup_tempfile_(tempfile, tempfilename); + *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR; + return false; + } + + cleanup_tempfile_(tempfile, tempfilename); + + return true; +} + +void cleanup_tempfile_(FILE **tempfile, char **tempfilename) +{ + if(0 != *tempfile) { + (void)fclose(*tempfile); + *tempfile = 0; + } + + if(0 != *tempfilename) { + (void)unlink(*tempfilename); + free(*tempfilename); + *tempfilename = 0; + } +} + +FLAC__bool get_file_stats_(const char *filename, struct stat *stats) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + return (0 == stat(filename, stats)); +} + +void set_file_stats_(const char *filename, struct stat *stats) +{ + struct utimbuf srctime; + + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + + srctime.actime = stats->st_atime; + srctime.modtime = stats->st_mtime; + (void)chmod(filename, stats->st_mode); + (void)utime(filename, &srctime); +#if !defined _MSC_VER && !defined __BORLANDC__ && !defined __MINGW32__ && !defined __EMX__ + (void)chown(filename, stats->st_uid, -1); + (void)chown(filename, -1, stats->st_gid); +#endif +} + +int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence) +{ + return fseeko((FILE*)handle, (off_t)offset, whence); +} + +FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle) +{ + return ftello((FILE*)handle); +} + +FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status) +{ + switch(status) { + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK: + return FLAC__METADATA_CHAIN_STATUS_OK; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT: + return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE: + return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE: + return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE: + return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA: + return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR: + return FLAC__METADATA_CHAIN_STATUS_READ_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR: + return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR: + return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR: + return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR: + return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR: + return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR; + case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR: + default: + return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; + } +} diff --git a/flac/src/libFLAC/metadata_object.c b/flac/src/libFLAC/metadata_object.c new file mode 100644 index 0000000..65976a8 --- /dev/null +++ b/flac/src/libFLAC/metadata_object.c @@ -0,0 +1,1824 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include + +#include "private/metadata.h" + +#include "FLAC/assert.h" +#include "share/alloc.h" + + +/**************************************************************************** + * + * Local routines + * + ***************************************************************************/ + +/* copy bytes: + * from = NULL && bytes = 0 + * to <- NULL + * from != NULL && bytes > 0 + * to <- copy of from + * else ASSERT + * malloc error leaves 'to' unchanged + */ +static FLAC__bool copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes) +{ + FLAC__ASSERT(0 != to); + if(bytes > 0 && 0 != from) { + FLAC__byte *x; + if(0 == (x = (FLAC__byte*)safe_malloc_(bytes))) + return false; + memcpy(x, from, bytes); + *to = x; + } + else { + FLAC__ASSERT(0 == from); + FLAC__ASSERT(bytes == 0); + *to = 0; + } + return true; +} + +#if 0 /* UNUSED */ +/* like copy_bytes_(), but free()s the original '*to' if the copy succeeds and the original '*to' is non-NULL */ +static FLAC__bool free_copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes) +{ + FLAC__byte *copy; + FLAC__ASSERT(0 != to); + if(copy_bytes_(©, from, bytes)) { + if(*to) + free(*to); + *to = copy; + return true; + } + else + return false; +} +#endif + +/* reallocate entry to 1 byte larger and add a terminating NUL */ +/* realloc() failure leaves entry unchanged */ +static FLAC__bool ensure_null_terminated_(FLAC__byte **entry, unsigned length) +{ + FLAC__byte *x = (FLAC__byte*)safe_realloc_add_2op_(*entry, length, /*+*/1); + if(0 != x) { + x[length] = '\0'; + *entry = x; + return true; + } + else + return false; +} + +/* copies the NUL-terminated C-string 'from' to '*to', leaving '*to' + * unchanged if malloc fails, free()ing the original '*to' if it + * succeeds and the original '*to' was not NULL + */ +static FLAC__bool copy_cstring_(char **to, const char *from) +{ + char *copy = strdup(from); + FLAC__ASSERT(to); + if(copy) { + if(*to) + free(*to); + *to = copy; + return true; + } + else + return false; +} + +static FLAC__bool copy_vcentry_(FLAC__StreamMetadata_VorbisComment_Entry *to, const FLAC__StreamMetadata_VorbisComment_Entry *from) +{ + to->length = from->length; + if(0 == from->entry) { + FLAC__ASSERT(from->length == 0); + to->entry = 0; + } + else { + FLAC__byte *x; + FLAC__ASSERT(from->length > 0); + if(0 == (x = (FLAC__byte*)safe_malloc_add_2op_(from->length, /*+*/1))) + return false; + memcpy(x, from->entry, from->length); + x[from->length] = '\0'; + to->entry = x; + } + return true; +} + +static FLAC__bool copy_track_(FLAC__StreamMetadata_CueSheet_Track *to, const FLAC__StreamMetadata_CueSheet_Track *from) +{ + memcpy(to, from, sizeof(FLAC__StreamMetadata_CueSheet_Track)); + if(0 == from->indices) { + FLAC__ASSERT(from->num_indices == 0); + } + else { + FLAC__StreamMetadata_CueSheet_Index *x; + FLAC__ASSERT(from->num_indices > 0); + if(0 == (x = (FLAC__StreamMetadata_CueSheet_Index*)safe_malloc_mul_2op_(from->num_indices, /*times*/sizeof(FLAC__StreamMetadata_CueSheet_Index)))) + return false; + memcpy(x, from->indices, from->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index)); + to->indices = x; + } + return true; +} + +static void seektable_calculate_length_(FLAC__StreamMetadata *object) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + object->length = object->data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; +} + +static FLAC__StreamMetadata_SeekPoint *seekpoint_array_new_(unsigned num_points) +{ + FLAC__StreamMetadata_SeekPoint *object_array; + + FLAC__ASSERT(num_points > 0); + + object_array = (FLAC__StreamMetadata_SeekPoint*)safe_malloc_mul_2op_(num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)); + + if(0 != object_array) { + unsigned i; + for(i = 0; i < num_points; i++) { + object_array[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + object_array[i].stream_offset = 0; + object_array[i].frame_samples = 0; + } + } + + return object_array; +} + +static void vorbiscomment_calculate_length_(FLAC__StreamMetadata *object) +{ + unsigned i; + + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + object->length = (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN) / 8; + object->length += object->data.vorbis_comment.vendor_string.length; + object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8; + for(i = 0; i < object->data.vorbis_comment.num_comments; i++) { + object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8); + object->length += object->data.vorbis_comment.comments[i].length; + } +} + +static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_new_(unsigned num_comments) +{ + FLAC__ASSERT(num_comments > 0); + + return (FLAC__StreamMetadata_VorbisComment_Entry*)safe_calloc_(num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)); +} + +static void vorbiscomment_entry_array_delete_(FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments) +{ + unsigned i; + + FLAC__ASSERT(0 != object_array && num_comments > 0); + + for(i = 0; i < num_comments; i++) + if(0 != object_array[i].entry) + free(object_array[i].entry); + + if(0 != object_array) + free(object_array); +} + +static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_copy_(const FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments) +{ + FLAC__StreamMetadata_VorbisComment_Entry *return_array; + + FLAC__ASSERT(0 != object_array); + FLAC__ASSERT(num_comments > 0); + + return_array = vorbiscomment_entry_array_new_(num_comments); + + if(0 != return_array) { + unsigned i; + + for(i = 0; i < num_comments; i++) { + if(!copy_vcentry_(return_array+i, object_array+i)) { + vorbiscomment_entry_array_delete_(return_array, num_comments); + return 0; + } + } + } + + return return_array; +} + +static FLAC__bool vorbiscomment_set_entry_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry *dest, const FLAC__StreamMetadata_VorbisComment_Entry *src, FLAC__bool copy) +{ + FLAC__byte *save; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(0 != dest); + FLAC__ASSERT(0 != src); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT((0 != src->entry && src->length > 0) || (0 == src->entry && src->length == 0)); + + save = dest->entry; + + if(0 != src->entry && src->length > 0) { + if(copy) { + /* do the copy first so that if we fail we leave the dest object untouched */ + if(!copy_vcentry_(dest, src)) + return false; + } + else { + /* we have to make sure that the string we're taking over is null-terminated */ + + /* + * Stripping the const from src->entry is OK since we're taking + * ownership of the pointer. This is a hack around a deficiency + * in the API where the same function is used for 'copy' and + * 'own', but the source entry is a const pointer. If we were + * precise, the 'own' flavor would be a separate function with a + * non-const source pointer. But it's not, so we hack away. + */ + if(!ensure_null_terminated_((FLAC__byte**)(&src->entry), src->length)) + return false; + *dest = *src; + } + } + else { + /* the src is null */ + *dest = *src; + } + + if(0 != save) + free(save); + + vorbiscomment_calculate_length_(object); + return true; +} + +static int vorbiscomment_find_entry_from_(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name, unsigned field_name_length) +{ + unsigned i; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != field_name); + + for(i = offset; i < object->data.vorbis_comment.num_comments; i++) { + if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) + return (int)i; + } + + return -1; +} + +static void cuesheet_calculate_length_(FLAC__StreamMetadata *object) +{ + unsigned i; + + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + + object->length = ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8; + + object->length += object->data.cue_sheet.num_tracks * ( + FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN + ) / 8; + + for(i = 0; i < object->data.cue_sheet.num_tracks; i++) { + object->length += object->data.cue_sheet.tracks[i].num_indices * ( + FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN + ) / 8; + } +} + +static FLAC__StreamMetadata_CueSheet_Index *cuesheet_track_index_array_new_(unsigned num_indices) +{ + FLAC__ASSERT(num_indices > 0); + + return (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)); +} + +static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_new_(unsigned num_tracks) +{ + FLAC__ASSERT(num_tracks > 0); + + return (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)); +} + +static void cuesheet_track_array_delete_(FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks) +{ + unsigned i; + + FLAC__ASSERT(0 != object_array && num_tracks > 0); + + for(i = 0; i < num_tracks; i++) { + if(0 != object_array[i].indices) { + FLAC__ASSERT(object_array[i].num_indices > 0); + free(object_array[i].indices); + } + } + + if(0 != object_array) + free(object_array); +} + +static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_copy_(const FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks) +{ + FLAC__StreamMetadata_CueSheet_Track *return_array; + + FLAC__ASSERT(0 != object_array); + FLAC__ASSERT(num_tracks > 0); + + return_array = cuesheet_track_array_new_(num_tracks); + + if(0 != return_array) { + unsigned i; + + for(i = 0; i < num_tracks; i++) { + if(!copy_track_(return_array+i, object_array+i)) { + cuesheet_track_array_delete_(return_array, num_tracks); + return 0; + } + } + } + + return return_array; +} + +static FLAC__bool cuesheet_set_track_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_CueSheet_Track *dest, const FLAC__StreamMetadata_CueSheet_Track *src, FLAC__bool copy) +{ + FLAC__StreamMetadata_CueSheet_Index *save; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(0 != dest); + FLAC__ASSERT(0 != src); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT((0 != src->indices && src->num_indices > 0) || (0 == src->indices && src->num_indices == 0)); + + save = dest->indices; + + /* do the copy first so that if we fail we leave the object untouched */ + if(copy) { + if(!copy_track_(dest, src)) + return false; + } + else { + *dest = *src; + } + + if(0 != save) + free(save); + + cuesheet_calculate_length_(object); + return true; +} + + +/**************************************************************************** + * + * Metadata object routines + * + ***************************************************************************/ + +FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type) +{ + FLAC__StreamMetadata *object; + + if(type > FLAC__MAX_METADATA_TYPE_CODE) + return 0; + + object = (FLAC__StreamMetadata*)calloc(1, sizeof(FLAC__StreamMetadata)); + if(0 != object) { + object->is_last = false; + object->type = type; + switch(type) { + case FLAC__METADATA_TYPE_STREAMINFO: + object->length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + break; + case FLAC__METADATA_TYPE_PADDING: + /* calloc() took care of this for us: + object->length = 0; + */ + break; + case FLAC__METADATA_TYPE_APPLICATION: + object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + /* calloc() took care of this for us: + object->data.application.data = 0; + */ + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + /* calloc() took care of this for us: + object->length = 0; + object->data.seek_table.num_points = 0; + object->data.seek_table.points = 0; + */ + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + object->data.vorbis_comment.vendor_string.length = (unsigned)strlen(FLAC__VENDOR_STRING); + if(!copy_bytes_(&object->data.vorbis_comment.vendor_string.entry, (const FLAC__byte*)FLAC__VENDOR_STRING, object->data.vorbis_comment.vendor_string.length+1)) { + free(object); + return 0; + } + vorbiscomment_calculate_length_(object); + break; + case FLAC__METADATA_TYPE_CUESHEET: + cuesheet_calculate_length_(object); + break; + case FLAC__METADATA_TYPE_PICTURE: + object->length = ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* empty mime_type string */ + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* empty description string */ + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN + + 0 /* no data */ + ) / 8; + object->data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER; + object->data.picture.mime_type = 0; + object->data.picture.description = 0; + /* calloc() took care of this for us: + object->data.picture.width = 0; + object->data.picture.height = 0; + object->data.picture.depth = 0; + object->data.picture.colors = 0; + object->data.picture.data_length = 0; + object->data.picture.data = 0; + */ + /* now initialize mime_type and description with empty strings to make things easier on the client */ + if(!copy_cstring_(&object->data.picture.mime_type, "")) { + free(object); + return 0; + } + if(!copy_cstring_((char**)(&object->data.picture.description), "")) { + if(object->data.picture.mime_type) + free(object->data.picture.mime_type); + free(object); + return 0; + } + break; + default: + /* calloc() took care of this for us: + object->length = 0; + object->data.unknown.data = 0; + */ + break; + } + } + + return object; +} + +FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object) +{ + FLAC__StreamMetadata *to; + + FLAC__ASSERT(0 != object); + + if(0 != (to = FLAC__metadata_object_new(object->type))) { + to->is_last = object->is_last; + to->type = object->type; + to->length = object->length; + switch(to->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + memcpy(&to->data.stream_info, &object->data.stream_info, sizeof(FLAC__StreamMetadata_StreamInfo)); + break; + case FLAC__METADATA_TYPE_PADDING: + break; + case FLAC__METADATA_TYPE_APPLICATION: + if(to->length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8) { /* underflow check */ + FLAC__metadata_object_delete(to); + return 0; + } + memcpy(&to->data.application.id, &object->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8); + if(!copy_bytes_(&to->data.application.data, object->data.application.data, object->length - FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)) { + FLAC__metadata_object_delete(to); + return 0; + } + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + to->data.seek_table.num_points = object->data.seek_table.num_points; + if(to->data.seek_table.num_points > SIZE_MAX / sizeof(FLAC__StreamMetadata_SeekPoint)) { /* overflow check */ + FLAC__metadata_object_delete(to); + return 0; + } + if(!copy_bytes_((FLAC__byte**)&to->data.seek_table.points, (FLAC__byte*)object->data.seek_table.points, object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint))) { + FLAC__metadata_object_delete(to); + return 0; + } + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + if(0 != to->data.vorbis_comment.vendor_string.entry) { + free(to->data.vorbis_comment.vendor_string.entry); + to->data.vorbis_comment.vendor_string.entry = 0; + } + if(!copy_vcentry_(&to->data.vorbis_comment.vendor_string, &object->data.vorbis_comment.vendor_string)) { + FLAC__metadata_object_delete(to); + return 0; + } + if(object->data.vorbis_comment.num_comments == 0) { + FLAC__ASSERT(0 == object->data.vorbis_comment.comments); + to->data.vorbis_comment.comments = 0; + } + else { + FLAC__ASSERT(0 != object->data.vorbis_comment.comments); + to->data.vorbis_comment.comments = vorbiscomment_entry_array_copy_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments); + if(0 == to->data.vorbis_comment.comments) { + FLAC__metadata_object_delete(to); + return 0; + } + } + to->data.vorbis_comment.num_comments = object->data.vorbis_comment.num_comments; + break; + case FLAC__METADATA_TYPE_CUESHEET: + memcpy(&to->data.cue_sheet, &object->data.cue_sheet, sizeof(FLAC__StreamMetadata_CueSheet)); + if(object->data.cue_sheet.num_tracks == 0) { + FLAC__ASSERT(0 == object->data.cue_sheet.tracks); + } + else { + FLAC__ASSERT(0 != object->data.cue_sheet.tracks); + to->data.cue_sheet.tracks = cuesheet_track_array_copy_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks); + if(0 == to->data.cue_sheet.tracks) { + FLAC__metadata_object_delete(to); + return 0; + } + } + break; + case FLAC__METADATA_TYPE_PICTURE: + to->data.picture.type = object->data.picture.type; + if(!copy_cstring_(&to->data.picture.mime_type, object->data.picture.mime_type)) { + FLAC__metadata_object_delete(to); + return 0; + } + if(!copy_cstring_((char**)(&to->data.picture.description), (const char*)object->data.picture.description)) { + FLAC__metadata_object_delete(to); + return 0; + } + to->data.picture.width = object->data.picture.width; + to->data.picture.height = object->data.picture.height; + to->data.picture.depth = object->data.picture.depth; + to->data.picture.colors = object->data.picture.colors; + to->data.picture.data_length = object->data.picture.data_length; + if(!copy_bytes_((&to->data.picture.data), object->data.picture.data, object->data.picture.data_length)) { + FLAC__metadata_object_delete(to); + return 0; + } + break; + default: + if(!copy_bytes_(&to->data.unknown.data, object->data.unknown.data, object->length)) { + FLAC__metadata_object_delete(to); + return 0; + } + break; + } + } + + return to; +} + +void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object) +{ + FLAC__ASSERT(0 != object); + + switch(object->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + case FLAC__METADATA_TYPE_PADDING: + break; + case FLAC__METADATA_TYPE_APPLICATION: + if(0 != object->data.application.data) { + free(object->data.application.data); + object->data.application.data = 0; + } + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + if(0 != object->data.seek_table.points) { + free(object->data.seek_table.points); + object->data.seek_table.points = 0; + } + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + if(0 != object->data.vorbis_comment.vendor_string.entry) { + free(object->data.vorbis_comment.vendor_string.entry); + object->data.vorbis_comment.vendor_string.entry = 0; + } + if(0 != object->data.vorbis_comment.comments) { + FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0); + vorbiscomment_entry_array_delete_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments); + } + break; + case FLAC__METADATA_TYPE_CUESHEET: + if(0 != object->data.cue_sheet.tracks) { + FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0); + cuesheet_track_array_delete_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks); + } + break; + case FLAC__METADATA_TYPE_PICTURE: + if(0 != object->data.picture.mime_type) { + free(object->data.picture.mime_type); + object->data.picture.mime_type = 0; + } + if(0 != object->data.picture.description) { + free(object->data.picture.description); + object->data.picture.description = 0; + } + if(0 != object->data.picture.data) { + free(object->data.picture.data); + object->data.picture.data = 0; + } + break; + default: + if(0 != object->data.unknown.data) { + free(object->data.unknown.data); + object->data.unknown.data = 0; + } + break; + } +} + +FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object) +{ + FLAC__metadata_object_delete_data(object); + free(object); +} + +static FLAC__bool compare_block_data_streaminfo_(const FLAC__StreamMetadata_StreamInfo *block1, const FLAC__StreamMetadata_StreamInfo *block2) +{ + if(block1->min_blocksize != block2->min_blocksize) + return false; + if(block1->max_blocksize != block2->max_blocksize) + return false; + if(block1->min_framesize != block2->min_framesize) + return false; + if(block1->max_framesize != block2->max_framesize) + return false; + if(block1->sample_rate != block2->sample_rate) + return false; + if(block1->channels != block2->channels) + return false; + if(block1->bits_per_sample != block2->bits_per_sample) + return false; + if(block1->total_samples != block2->total_samples) + return false; + if(0 != memcmp(block1->md5sum, block2->md5sum, 16)) + return false; + return true; +} + +static FLAC__bool compare_block_data_application_(const FLAC__StreamMetadata_Application *block1, const FLAC__StreamMetadata_Application *block2, unsigned block_length) +{ + FLAC__ASSERT(0 != block1); + FLAC__ASSERT(0 != block2); + FLAC__ASSERT(block_length >= sizeof(block1->id)); + + if(0 != memcmp(block1->id, block2->id, sizeof(block1->id))) + return false; + if(0 != block1->data && 0 != block2->data) + return 0 == memcmp(block1->data, block2->data, block_length - sizeof(block1->id)); + else + return block1->data == block2->data; +} + +static FLAC__bool compare_block_data_seektable_(const FLAC__StreamMetadata_SeekTable *block1, const FLAC__StreamMetadata_SeekTable *block2) +{ + unsigned i; + + FLAC__ASSERT(0 != block1); + FLAC__ASSERT(0 != block2); + + if(block1->num_points != block2->num_points) + return false; + + if(0 != block1->points && 0 != block2->points) { + for(i = 0; i < block1->num_points; i++) { + if(block1->points[i].sample_number != block2->points[i].sample_number) + return false; + if(block1->points[i].stream_offset != block2->points[i].stream_offset) + return false; + if(block1->points[i].frame_samples != block2->points[i].frame_samples) + return false; + } + return true; + } + else + return block1->points == block2->points; +} + +static FLAC__bool compare_block_data_vorbiscomment_(const FLAC__StreamMetadata_VorbisComment *block1, const FLAC__StreamMetadata_VorbisComment *block2) +{ + unsigned i; + + if(block1->vendor_string.length != block2->vendor_string.length) + return false; + + if(0 != block1->vendor_string.entry && 0 != block2->vendor_string.entry) { + if(0 != memcmp(block1->vendor_string.entry, block2->vendor_string.entry, block1->vendor_string.length)) + return false; + } + else if(block1->vendor_string.entry != block2->vendor_string.entry) + return false; + + if(block1->num_comments != block2->num_comments) + return false; + + for(i = 0; i < block1->num_comments; i++) { + if(0 != block1->comments[i].entry && 0 != block2->comments[i].entry) { + if(0 != memcmp(block1->comments[i].entry, block2->comments[i].entry, block1->comments[i].length)) + return false; + } + else if(block1->comments[i].entry != block2->comments[i].entry) + return false; + } + return true; +} + +static FLAC__bool compare_block_data_cuesheet_(const FLAC__StreamMetadata_CueSheet *block1, const FLAC__StreamMetadata_CueSheet *block2) +{ + unsigned i, j; + + if(0 != strcmp(block1->media_catalog_number, block2->media_catalog_number)) + return false; + + if(block1->lead_in != block2->lead_in) + return false; + + if(block1->is_cd != block2->is_cd) + return false; + + if(block1->num_tracks != block2->num_tracks) + return false; + + if(0 != block1->tracks && 0 != block2->tracks) { + FLAC__ASSERT(block1->num_tracks > 0); + for(i = 0; i < block1->num_tracks; i++) { + if(block1->tracks[i].offset != block2->tracks[i].offset) + return false; + if(block1->tracks[i].number != block2->tracks[i].number) + return false; + if(0 != memcmp(block1->tracks[i].isrc, block2->tracks[i].isrc, sizeof(block1->tracks[i].isrc))) + return false; + if(block1->tracks[i].type != block2->tracks[i].type) + return false; + if(block1->tracks[i].pre_emphasis != block2->tracks[i].pre_emphasis) + return false; + if(block1->tracks[i].num_indices != block2->tracks[i].num_indices) + return false; + if(0 != block1->tracks[i].indices && 0 != block2->tracks[i].indices) { + FLAC__ASSERT(block1->tracks[i].num_indices > 0); + for(j = 0; j < block1->tracks[i].num_indices; j++) { + if(block1->tracks[i].indices[j].offset != block2->tracks[i].indices[j].offset) + return false; + if(block1->tracks[i].indices[j].number != block2->tracks[i].indices[j].number) + return false; + } + } + else if(block1->tracks[i].indices != block2->tracks[i].indices) + return false; + } + } + else if(block1->tracks != block2->tracks) + return false; + return true; +} + +static FLAC__bool compare_block_data_picture_(const FLAC__StreamMetadata_Picture *block1, const FLAC__StreamMetadata_Picture *block2) +{ + if(block1->type != block2->type) + return false; + if(block1->mime_type != block2->mime_type && (0 == block1->mime_type || 0 == block2->mime_type || strcmp(block1->mime_type, block2->mime_type))) + return false; + if(block1->description != block2->description && (0 == block1->description || 0 == block2->description || strcmp((const char *)block1->description, (const char *)block2->description))) + return false; + if(block1->width != block2->width) + return false; + if(block1->height != block2->height) + return false; + if(block1->depth != block2->depth) + return false; + if(block1->colors != block2->colors) + return false; + if(block1->data_length != block2->data_length) + return false; + if(block1->data != block2->data && (0 == block1->data || 0 == block2->data || memcmp(block1->data, block2->data, block1->data_length))) + return false; + return true; +} + +static FLAC__bool compare_block_data_unknown_(const FLAC__StreamMetadata_Unknown *block1, const FLAC__StreamMetadata_Unknown *block2, unsigned block_length) +{ + FLAC__ASSERT(0 != block1); + FLAC__ASSERT(0 != block2); + + if(0 != block1->data && 0 != block2->data) + return 0 == memcmp(block1->data, block2->data, block_length); + else + return block1->data == block2->data; +} + +FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2) +{ + FLAC__ASSERT(0 != block1); + FLAC__ASSERT(0 != block2); + + if(block1->type != block2->type) { + return false; + } + if(block1->is_last != block2->is_last) { + return false; + } + if(block1->length != block2->length) { + return false; + } + switch(block1->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + return compare_block_data_streaminfo_(&block1->data.stream_info, &block2->data.stream_info); + case FLAC__METADATA_TYPE_PADDING: + return true; /* we don't compare the padding guts */ + case FLAC__METADATA_TYPE_APPLICATION: + return compare_block_data_application_(&block1->data.application, &block2->data.application, block1->length); + case FLAC__METADATA_TYPE_SEEKTABLE: + return compare_block_data_seektable_(&block1->data.seek_table, &block2->data.seek_table); + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + return compare_block_data_vorbiscomment_(&block1->data.vorbis_comment, &block2->data.vorbis_comment); + case FLAC__METADATA_TYPE_CUESHEET: + return compare_block_data_cuesheet_(&block1->data.cue_sheet, &block2->data.cue_sheet); + case FLAC__METADATA_TYPE_PICTURE: + return compare_block_data_picture_(&block1->data.picture, &block2->data.picture); + default: + return compare_block_data_unknown_(&block1->data.unknown, &block2->data.unknown, block1->length); + } +} + +FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy) +{ + FLAC__byte *save; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_APPLICATION); + FLAC__ASSERT((0 != data && length > 0) || (0 == data && length == 0 && copy == false)); + + save = object->data.application.data; + + /* do the copy first so that if we fail we leave the object untouched */ + if(copy) { + if(!copy_bytes_(&object->data.application.data, data, length)) + return false; + } + else { + object->data.application.data = data; + } + + if(0 != save) + free(save); + + object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8 + length; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + if(0 == object->data.seek_table.points) { + FLAC__ASSERT(object->data.seek_table.num_points == 0); + if(0 == new_num_points) + return true; + else if(0 == (object->data.seek_table.points = seekpoint_array_new_(new_num_points))) + return false; + } + else { + const size_t old_size = object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint); + const size_t new_size = new_num_points * sizeof(FLAC__StreamMetadata_SeekPoint); + + /* overflow check */ + if((size_t)new_num_points > SIZE_MAX / sizeof(FLAC__StreamMetadata_SeekPoint)) + return false; + + FLAC__ASSERT(object->data.seek_table.num_points > 0); + + if(new_size == 0) { + free(object->data.seek_table.points); + object->data.seek_table.points = 0; + } + else if(0 == (object->data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(object->data.seek_table.points, new_size))) + return false; + + /* if growing, set new elements to placeholders */ + if(new_size > old_size) { + unsigned i; + for(i = object->data.seek_table.num_points; i < new_num_points; i++) { + object->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + object->data.seek_table.points[i].stream_offset = 0; + object->data.seek_table.points[i].frame_samples = 0; + } + } + } + + object->data.seek_table.num_points = new_num_points; + + seektable_calculate_length_(object); + return true; +} + +FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(point_num < object->data.seek_table.num_points); + + object->data.seek_table.points[point_num] = point; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point) +{ + int i; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(point_num <= object->data.seek_table.num_points); + + if(!FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points+1)) + return false; + + /* move all points >= point_num forward one space */ + for(i = (int)object->data.seek_table.num_points-1; i > (int)point_num; i--) + object->data.seek_table.points[i] = object->data.seek_table.points[i-1]; + + FLAC__metadata_object_seektable_set_point(object, point_num, point); + seektable_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num) +{ + unsigned i; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(point_num < object->data.seek_table.num_points); + + /* move all points > point_num backward one space */ + for(i = point_num; i < object->data.seek_table.num_points-1; i++) + object->data.seek_table.points[i] = object->data.seek_table.points[i+1]; + + return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points-1); +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + return FLAC__format_seektable_is_legal(&object->data.seek_table); +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + if(num > 0) + /* WATCHOUT: we rely on the fact that growing the array adds PLACEHOLDERS at the end */ + return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points + num); + else + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number) +{ + FLAC__StreamMetadata_SeekTable *seek_table; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + seek_table = &object->data.seek_table; + + if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + 1)) + return false; + + seek_table->points[seek_table->num_points - 1].sample_number = sample_number; + seek_table->points[seek_table->num_points - 1].stream_offset = 0; + seek_table->points[seek_table->num_points - 1].frame_samples = 0; + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(0 != sample_numbers || num == 0); + + if(num > 0) { + FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table; + unsigned i, j; + + i = seek_table->num_points; + + if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num)) + return false; + + for(j = 0; j < num; i++, j++) { + seek_table->points[i].sample_number = sample_numbers[j]; + seek_table->points[i].stream_offset = 0; + seek_table->points[i].frame_samples = 0; + } + } + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(total_samples > 0); + + if(num > 0 && total_samples > 0) { + FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table; + unsigned i, j; + + i = seek_table->num_points; + + if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num)) + return false; + + for(j = 0; j < num; i++, j++) { + seek_table->points[i].sample_number = total_samples * (FLAC__uint64)j / (FLAC__uint64)num; + seek_table->points[i].stream_offset = 0; + seek_table->points[i].frame_samples = 0; + } + } + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + FLAC__ASSERT(samples > 0); + FLAC__ASSERT(total_samples > 0); + + if(samples > 0 && total_samples > 0) { + FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table; + unsigned i, j; + FLAC__uint64 num, sample; + + num = 1 + total_samples / samples; /* 1+ for the first sample at 0 */ + /* now account for the fact that we don't place a seekpoint at "total_samples" since samples are number from 0: */ + if(total_samples % samples == 0) + num--; + + i = seek_table->num_points; + + if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + (unsigned)num)) + return false; + + sample = 0; + for(j = 0; j < num; i++, j++, sample += samples) { + seek_table->points[i].sample_number = sample; + seek_table->points[i].stream_offset = 0; + seek_table->points[i].frame_samples = 0; + } + } + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact) +{ + unsigned unique; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE); + + unique = FLAC__format_seektable_sort(&object->data.seek_table); + + return !compact || FLAC__metadata_object_seektable_resize_points(object, unique); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy) +{ + if(!FLAC__format_vorbiscomment_entry_value_is_legal(entry.entry, entry.length)) + return false; + return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.vendor_string, &entry, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + if(0 == object->data.vorbis_comment.comments) { + FLAC__ASSERT(object->data.vorbis_comment.num_comments == 0); + if(0 == new_num_comments) + return true; + else if(0 == (object->data.vorbis_comment.comments = vorbiscomment_entry_array_new_(new_num_comments))) + return false; + } + else { + const size_t old_size = object->data.vorbis_comment.num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry); + const size_t new_size = new_num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry); + + /* overflow check */ + if((size_t)new_num_comments > SIZE_MAX / sizeof(FLAC__StreamMetadata_VorbisComment_Entry)) + return false; + + FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0); + + /* if shrinking, free the truncated entries */ + if(new_num_comments < object->data.vorbis_comment.num_comments) { + unsigned i; + for(i = new_num_comments; i < object->data.vorbis_comment.num_comments; i++) + if(0 != object->data.vorbis_comment.comments[i].entry) + free(object->data.vorbis_comment.comments[i].entry); + } + + if(new_size == 0) { + free(object->data.vorbis_comment.comments); + object->data.vorbis_comment.comments = 0; + } + else if(0 == (object->data.vorbis_comment.comments = (FLAC__StreamMetadata_VorbisComment_Entry*)realloc(object->data.vorbis_comment.comments, new_size))) + return false; + + /* if growing, zero all the length/pointers of new elements */ + if(new_size > old_size) + memset(object->data.vorbis_comment.comments + object->data.vorbis_comment.num_comments, 0, new_size - old_size); + } + + object->data.vorbis_comment.num_comments = new_num_comments; + + vorbiscomment_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments); + + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) + return false; + return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.comments[comment_num], &entry, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy) +{ + FLAC__StreamMetadata_VorbisComment *vc; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(comment_num <= object->data.vorbis_comment.num_comments); + + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) + return false; + + vc = &object->data.vorbis_comment; + + if(!FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments+1)) + return false; + + /* move all comments >= comment_num forward one space */ + memmove(&vc->comments[comment_num+1], &vc->comments[comment_num], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-1-comment_num)); + vc->comments[comment_num].length = 0; + vc->comments[comment_num].entry = 0; + + return FLAC__metadata_object_vorbiscomment_set_comment(object, comment_num, entry, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + return FLAC__metadata_object_vorbiscomment_insert_comment(object, object->data.vorbis_comment.num_comments, entry, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy) +{ + FLAC__ASSERT(0 != entry.entry && entry.length > 0); + + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) + return false; + + { + int i; + size_t field_name_length; + const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length); + + FLAC__ASSERT(0 != eq); + + if(0 == eq) + return false; /* double protection */ + + field_name_length = eq-entry.entry; + + i = vorbiscomment_find_entry_from_(object, 0, (const char *)entry.entry, field_name_length); + if(i >= 0) { + unsigned index = (unsigned)i; + if(!FLAC__metadata_object_vorbiscomment_set_comment(object, index, entry, copy)) + return false; + entry = object->data.vorbis_comment.comments[index]; + index++; /* skip over replaced comment */ + if(all && index < object->data.vorbis_comment.num_comments) { + i = vorbiscomment_find_entry_from_(object, index, (const char *)entry.entry, field_name_length); + while(i >= 0) { + index = (unsigned)i; + if(!FLAC__metadata_object_vorbiscomment_delete_comment(object, index)) + return false; + if(index < object->data.vorbis_comment.num_comments) + i = vorbiscomment_find_entry_from_(object, index, (const char *)entry.entry, field_name_length); + else + i = -1; + } + } + return true; + } + else + return FLAC__metadata_object_vorbiscomment_append_comment(object, entry, copy); + } +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num) +{ + FLAC__StreamMetadata_VorbisComment *vc; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments); + + vc = &object->data.vorbis_comment; + + /* free the comment at comment_num */ + if(0 != vc->comments[comment_num].entry) + free(vc->comments[comment_num].entry); + + /* move all comments > comment_num backward one space */ + memmove(&vc->comments[comment_num], &vc->comments[comment_num+1], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-comment_num-1)); + vc->comments[vc->num_comments-1].length = 0; + vc->comments[vc->num_comments-1].entry = 0; + + return FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments-1); +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value) +{ + FLAC__ASSERT(0 != entry); + FLAC__ASSERT(0 != field_name); + FLAC__ASSERT(0 != field_value); + + if(!FLAC__format_vorbiscomment_entry_name_is_legal(field_name)) + return false; + if(!FLAC__format_vorbiscomment_entry_value_is_legal((const FLAC__byte *)field_value, (unsigned)(-1))) + return false; + + { + const size_t nn = strlen(field_name); + const size_t nv = strlen(field_value); + entry->length = nn + 1 /*=*/ + nv; + if(0 == (entry->entry = (FLAC__byte*)safe_malloc_add_4op_(nn, /*+*/1, /*+*/nv, /*+*/1))) + return false; + memcpy(entry->entry, field_name, nn); + entry->entry[nn] = '='; + memcpy(entry->entry+nn+1, field_value, nv); + entry->entry[entry->length] = '\0'; + } + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value) +{ + FLAC__ASSERT(0 != entry.entry && entry.length > 0); + FLAC__ASSERT(0 != field_name); + FLAC__ASSERT(0 != field_value); + + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) + return false; + + { + const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length); + const size_t nn = eq-entry.entry; + const size_t nv = entry.length-nn-1; /* -1 for the '=' */ + FLAC__ASSERT(0 != eq); + if(0 == eq) + return false; /* double protection */ + if(0 == (*field_name = (char*)safe_malloc_add_2op_(nn, /*+*/1))) + return false; + if(0 == (*field_value = (char*)safe_malloc_add_2op_(nv, /*+*/1))) { + free(*field_name); + return false; + } + memcpy(*field_name, entry.entry, nn); + memcpy(*field_value, entry.entry+nn+1, nv); + (*field_name)[nn] = '\0'; + (*field_value)[nv] = '\0'; + } + + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length) +{ + FLAC__ASSERT(0 != entry.entry && entry.length > 0); + { + const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length); +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__ +#define FLAC__STRNCASECMP strnicmp +#else +#define FLAC__STRNCASECMP strncasecmp +#endif + return (0 != eq && (unsigned)(eq-entry.entry) == field_name_length && 0 == FLAC__STRNCASECMP(field_name, (const char *)entry.entry, field_name_length)); +#undef FLAC__STRNCASECMP + } +} + +FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name) +{ + FLAC__ASSERT(0 != field_name); + + return vorbiscomment_find_entry_from_(object, offset, field_name, strlen(field_name)); +} + +FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name) +{ + const unsigned field_name_length = strlen(field_name); + unsigned i; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + for(i = 0; i < object->data.vorbis_comment.num_comments; i++) { + if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) { + if(!FLAC__metadata_object_vorbiscomment_delete_comment(object, i)) + return -1; + else + return 1; + } + } + + return 0; +} + +FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name) +{ + FLAC__bool ok = true; + unsigned matching = 0; + const unsigned field_name_length = strlen(field_name); + int i; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + /* must delete from end to start otherwise it will interfere with our iteration */ + for(i = (int)object->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) { + if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) { + matching++; + ok &= FLAC__metadata_object_vorbiscomment_delete_comment(object, (unsigned)i); + } + } + + return ok? (int)matching : -1; +} + +FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void) +{ + return (FLAC__StreamMetadata_CueSheet_Track*)calloc(1, sizeof(FLAC__StreamMetadata_CueSheet_Track)); +} + +FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object) +{ + FLAC__StreamMetadata_CueSheet_Track *to; + + FLAC__ASSERT(0 != object); + + if(0 != (to = FLAC__metadata_object_cuesheet_track_new())) { + if(!copy_track_(to, object)) { + FLAC__metadata_object_cuesheet_track_delete(to); + return 0; + } + } + + return to; +} + +void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object) +{ + FLAC__ASSERT(0 != object); + + if(0 != object->indices) { + FLAC__ASSERT(object->num_indices > 0); + free(object->indices); + } +} + +FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object) +{ + FLAC__metadata_object_cuesheet_track_delete_data(object); + free(object); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices) +{ + FLAC__StreamMetadata_CueSheet_Track *track; + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks); + + track = &object->data.cue_sheet.tracks[track_num]; + + if(0 == track->indices) { + FLAC__ASSERT(track->num_indices == 0); + if(0 == new_num_indices) + return true; + else if(0 == (track->indices = cuesheet_track_index_array_new_(new_num_indices))) + return false; + } + else { + const size_t old_size = track->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index); + const size_t new_size = new_num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index); + + /* overflow check */ + if((size_t)new_num_indices > SIZE_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Index)) + return false; + + FLAC__ASSERT(track->num_indices > 0); + + if(new_size == 0) { + free(track->indices); + track->indices = 0; + } + else if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)realloc(track->indices, new_size))) + return false; + + /* if growing, zero all the lengths/pointers of new elements */ + if(new_size > old_size) + memset(track->indices + track->num_indices, 0, new_size - old_size); + } + + track->num_indices = new_num_indices; + + cuesheet_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index) +{ + FLAC__StreamMetadata_CueSheet_Track *track; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks); + FLAC__ASSERT(index_num <= object->data.cue_sheet.tracks[track_num].num_indices); + + track = &object->data.cue_sheet.tracks[track_num]; + + if(!FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices+1)) + return false; + + /* move all indices >= index_num forward one space */ + memmove(&track->indices[index_num+1], &track->indices[index_num], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-1-index_num)); + + track->indices[index_num] = index; + cuesheet_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num) +{ + FLAC__StreamMetadata_CueSheet_Index index; + memset(&index, 0, sizeof(index)); + return FLAC__metadata_object_cuesheet_track_insert_index(object, track_num, index_num, index); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num) +{ + FLAC__StreamMetadata_CueSheet_Track *track; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks); + FLAC__ASSERT(index_num < object->data.cue_sheet.tracks[track_num].num_indices); + + track = &object->data.cue_sheet.tracks[track_num]; + + /* move all indices > index_num backward one space */ + memmove(&track->indices[index_num], &track->indices[index_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-index_num-1)); + + FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices-1); + cuesheet_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + + if(0 == object->data.cue_sheet.tracks) { + FLAC__ASSERT(object->data.cue_sheet.num_tracks == 0); + if(0 == new_num_tracks) + return true; + else if(0 == (object->data.cue_sheet.tracks = cuesheet_track_array_new_(new_num_tracks))) + return false; + } + else { + const size_t old_size = object->data.cue_sheet.num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track); + const size_t new_size = new_num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track); + + /* overflow check */ + if((size_t)new_num_tracks > SIZE_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Track)) + return false; + + FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0); + + /* if shrinking, free the truncated entries */ + if(new_num_tracks < object->data.cue_sheet.num_tracks) { + unsigned i; + for(i = new_num_tracks; i < object->data.cue_sheet.num_tracks; i++) + if(0 != object->data.cue_sheet.tracks[i].indices) + free(object->data.cue_sheet.tracks[i].indices); + } + + if(new_size == 0) { + free(object->data.cue_sheet.tracks); + object->data.cue_sheet.tracks = 0; + } + else if(0 == (object->data.cue_sheet.tracks = (FLAC__StreamMetadata_CueSheet_Track*)realloc(object->data.cue_sheet.tracks, new_size))) + return false; + + /* if growing, zero all the lengths/pointers of new elements */ + if(new_size > old_size) + memset(object->data.cue_sheet.tracks + object->data.cue_sheet.num_tracks, 0, new_size - old_size); + } + + object->data.cue_sheet.num_tracks = new_num_tracks; + + cuesheet_calculate_length_(object); + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks); + + return cuesheet_set_track_(object, object->data.cue_sheet.tracks + track_num, track, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy) +{ + FLAC__StreamMetadata_CueSheet *cs; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT(track_num <= object->data.cue_sheet.num_tracks); + + cs = &object->data.cue_sheet; + + if(!FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks+1)) + return false; + + /* move all tracks >= track_num forward one space */ + memmove(&cs->tracks[track_num+1], &cs->tracks[track_num], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-1-track_num)); + cs->tracks[track_num].num_indices = 0; + cs->tracks[track_num].indices = 0; + + return FLAC__metadata_object_cuesheet_set_track(object, track_num, track, copy); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num) +{ + FLAC__StreamMetadata_CueSheet_Track track; + memset(&track, 0, sizeof(track)); + return FLAC__metadata_object_cuesheet_insert_track(object, track_num, &track, /*copy=*/false); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num) +{ + FLAC__StreamMetadata_CueSheet *cs; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks); + + cs = &object->data.cue_sheet; + + /* free the track at track_num */ + if(0 != cs->tracks[track_num].indices) + free(cs->tracks[track_num].indices); + + /* move all tracks > track_num backward one space */ + memmove(&cs->tracks[track_num], &cs->tracks[track_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-track_num-1)); + cs->tracks[cs->num_tracks-1].num_indices = 0; + cs->tracks[cs->num_tracks-1].indices = 0; + + return FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks-1); +} + +FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + + return FLAC__format_cuesheet_is_legal(&object->data.cue_sheet, check_cd_da_subset, violation); +} + +static FLAC__uint64 get_index_01_offset_(const FLAC__StreamMetadata_CueSheet *cs, unsigned track) +{ + if (track >= (cs->num_tracks-1) || cs->tracks[track].num_indices < 1) + return 0; + else if (cs->tracks[track].indices[0].number == 1) + return cs->tracks[track].indices[0].offset + cs->tracks[track].offset + cs->lead_in; + else if (cs->tracks[track].num_indices < 2) + return 0; + else if (cs->tracks[track].indices[1].number == 1) + return cs->tracks[track].indices[1].offset + cs->tracks[track].offset + cs->lead_in; + else + return 0; +} + +static FLAC__uint32 cddb_add_digits_(FLAC__uint32 x) +{ + FLAC__uint32 n = 0; + while (x) { + n += (x%10); + x /= 10; + } + return n; +} + +/*@@@@add to tests*/ +FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object) +{ + const FLAC__StreamMetadata_CueSheet *cs; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET); + + cs = &object->data.cue_sheet; + + if (cs->num_tracks < 2) /* need at least one real track and the lead-out track */ + return 0; + + { + FLAC__uint32 i, length, sum = 0; + for (i = 0; i < (cs->num_tracks-1); i++) /* -1 to avoid counting the lead-out */ + sum += cddb_add_digits_((FLAC__uint32)(get_index_01_offset_(cs, i) / 44100)); + length = (FLAC__uint32)((cs->tracks[cs->num_tracks-1].offset+cs->lead_in) / 44100) - (FLAC__uint32)(get_index_01_offset_(cs, 0) / 44100); + + return (sum % 0xFF) << 24 | length << 8 | (FLAC__uint32)(cs->num_tracks-1); + } +} + +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy) +{ + char *old; + size_t old_length, new_length; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE); + FLAC__ASSERT(0 != mime_type); + + old = object->data.picture.mime_type; + old_length = old? strlen(old) : 0; + new_length = strlen(mime_type); + + /* do the copy first so that if we fail we leave the object untouched */ + if(copy) { + if(new_length >= SIZE_MAX) /* overflow check */ + return false; + if(!copy_bytes_((FLAC__byte**)(&object->data.picture.mime_type), (FLAC__byte*)mime_type, new_length+1)) + return false; + } + else { + object->data.picture.mime_type = mime_type; + } + + if(0 != old) + free(old); + + object->length -= old_length; + object->length += new_length; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy) +{ + FLAC__byte *old; + size_t old_length, new_length; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE); + FLAC__ASSERT(0 != description); + + old = object->data.picture.description; + old_length = old? strlen((const char *)old) : 0; + new_length = strlen((const char *)description); + + /* do the copy first so that if we fail we leave the object untouched */ + if(copy) { + if(new_length >= SIZE_MAX) /* overflow check */ + return false; + if(!copy_bytes_(&object->data.picture.description, description, new_length+1)) + return false; + } + else { + object->data.picture.description = description; + } + + if(0 != old) + free(old); + + object->length -= old_length; + object->length += new_length; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy) +{ + FLAC__byte *old; + + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE); + FLAC__ASSERT((0 != data && length > 0) || (0 == data && length == 0 && copy == false)); + + old = object->data.picture.data; + + /* do the copy first so that if we fail we leave the object untouched */ + if(copy) { + if(!copy_bytes_(&object->data.picture.data, data, length)) + return false; + } + else { + object->data.picture.data = data; + } + + if(0 != old) + free(old); + + object->length -= object->data.picture.data_length; + object->data.picture.data_length = length; + object->length += length; + return true; +} + +FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation) +{ + FLAC__ASSERT(0 != object); + FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE); + + return FLAC__format_picture_is_legal(&object->data.picture, violation); +} diff --git a/flac/src/libFLAC/ogg_decoder_aspect.c b/flac/src/libFLAC/ogg_decoder_aspect.c new file mode 100644 index 0000000..d009400 --- /dev/null +++ b/flac/src/libFLAC/ogg_decoder_aspect.c @@ -0,0 +1,253 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for memcpy() */ +#include "FLAC/assert.h" +#include "private/ogg_decoder_aspect.h" +#include "private/ogg_mapping.h" + +#ifdef max +#undef max +#endif +#define max(x,y) ((x)>(y)?(x):(y)) + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +FLAC__bool FLAC__ogg_decoder_aspect_init(FLAC__OggDecoderAspect *aspect) +{ + /* we will determine the serial number later if necessary */ + if(ogg_stream_init(&aspect->stream_state, aspect->serial_number) != 0) + return false; + + if(ogg_sync_init(&aspect->sync_state) != 0) + return false; + + aspect->version_major = ~(0u); + aspect->version_minor = ~(0u); + + aspect->need_serial_number = aspect->use_first_serial_number; + + aspect->end_of_stream = false; + aspect->have_working_page = false; + + return true; +} + +void FLAC__ogg_decoder_aspect_finish(FLAC__OggDecoderAspect *aspect) +{ + (void)ogg_sync_clear(&aspect->sync_state); + (void)ogg_stream_clear(&aspect->stream_state); +} + +void FLAC__ogg_decoder_aspect_set_serial_number(FLAC__OggDecoderAspect *aspect, long value) +{ + aspect->use_first_serial_number = false; + aspect->serial_number = value; +} + +void FLAC__ogg_decoder_aspect_set_defaults(FLAC__OggDecoderAspect *aspect) +{ + aspect->use_first_serial_number = true; +} + +void FLAC__ogg_decoder_aspect_flush(FLAC__OggDecoderAspect *aspect) +{ + (void)ogg_stream_reset(&aspect->stream_state); + (void)ogg_sync_reset(&aspect->sync_state); + aspect->end_of_stream = false; + aspect->have_working_page = false; +} + +void FLAC__ogg_decoder_aspect_reset(FLAC__OggDecoderAspect *aspect) +{ + FLAC__ogg_decoder_aspect_flush(aspect); + + if(aspect->use_first_serial_number) + aspect->need_serial_number = true; +} + +FLAC__OggDecoderAspectReadStatus FLAC__ogg_decoder_aspect_read_callback_wrapper(FLAC__OggDecoderAspect *aspect, FLAC__byte buffer[], size_t *bytes, FLAC__OggDecoderAspectReadCallbackProxy read_callback, const FLAC__StreamDecoder *decoder, void *client_data) +{ + static const size_t OGG_BYTES_CHUNK = 8192; + const size_t bytes_requested = *bytes; + + /* + * The FLAC decoding API uses pull-based reads, whereas Ogg decoding + * is push-based. In libFLAC, when you ask to decode a frame, the + * decoder will eventually call the read callback to supply some data, + * but how much it asks for depends on how much free space it has in + * its internal buffer. It does not try to grow its internal buffer + * to accomodate a whole frame because then the internal buffer size + * could not be limited, which is necessary in embedded applications. + * + * Ogg however grows its internal buffer until a whole page is present; + * only then can you get decoded data out. So we can't just ask for + * the same number of bytes from Ogg, then pass what's decoded down to + * libFLAC. If what libFLAC is asking for will not contain a whole + * page, then we will get no data from ogg_sync_pageout(), and at the + * same time cannot just read more data from the client for the purpose + * of getting a whole decoded page because the decoded size might be + * larger than libFLAC's internal buffer. + * + * Instead, whenever this read callback wrapper is called, we will + * continually request data from the client until we have at least one + * page, and manage pages internally so that we can send pieces of + * pages down to libFLAC in such a way that we obey its size + * requirement. To limit the amount of callbacks, we will always try + * to read in enough pages to return the full number of bytes + * requested. + */ + *bytes = 0; + while (*bytes < bytes_requested && !aspect->end_of_stream) { + if (aspect->have_working_page) { + if (aspect->have_working_packet) { + size_t n = bytes_requested - *bytes; + if ((size_t)aspect->working_packet.bytes <= n) { + /* the rest of the packet will fit in the buffer */ + n = aspect->working_packet.bytes; + memcpy(buffer, aspect->working_packet.packet, n); + *bytes += n; + buffer += n; + aspect->have_working_packet = false; + } + else { + /* only n bytes of the packet will fit in the buffer */ + memcpy(buffer, aspect->working_packet.packet, n); + *bytes += n; + buffer += n; + aspect->working_packet.packet += n; + aspect->working_packet.bytes -= n; + } + } + else { + /* try and get another packet */ + const int ret = ogg_stream_packetout(&aspect->stream_state, &aspect->working_packet); + if (ret > 0) { + aspect->have_working_packet = true; + /* if it is the first header packet, check for magic and a supported Ogg FLAC mapping version */ + if (aspect->working_packet.bytes > 0 && aspect->working_packet.packet[0] == FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE) { + const FLAC__byte *b = aspect->working_packet.packet; + const unsigned header_length = + FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH + + FLAC__OGG_MAPPING_MAGIC_LENGTH + + FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH + + FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH + + FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH; + if (aspect->working_packet.bytes < (long)header_length) + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC; + b += FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH; + if (memcmp(b, FLAC__OGG_MAPPING_MAGIC, FLAC__OGG_MAPPING_MAGIC_LENGTH)) + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC; + b += FLAC__OGG_MAPPING_MAGIC_LENGTH; + aspect->version_major = (unsigned)(*b); + b += FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH; + aspect->version_minor = (unsigned)(*b); + if (aspect->version_major != 1) + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION; + aspect->working_packet.packet += header_length; + aspect->working_packet.bytes -= header_length; + } + } + else if (ret == 0) { + aspect->have_working_page = false; + } + else { /* ret < 0 */ + /* lost sync, we'll leave the working page for the next call */ + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC; + } + } + } + else { + /* try and get another page */ + const int ret = ogg_sync_pageout(&aspect->sync_state, &aspect->working_page); + if (ret > 0) { + /* got a page, grab the serial number if necessary */ + if(aspect->need_serial_number) { + aspect->stream_state.serialno = aspect->serial_number = ogg_page_serialno(&aspect->working_page); + aspect->need_serial_number = false; + } + if(ogg_stream_pagein(&aspect->stream_state, &aspect->working_page) == 0) { + aspect->have_working_page = true; + aspect->have_working_packet = false; + } + /* else do nothing, could be a page from another stream */ + } + else if (ret == 0) { + /* need more data */ + const size_t ogg_bytes_to_read = max(bytes_requested - *bytes, OGG_BYTES_CHUNK); + char *oggbuf = ogg_sync_buffer(&aspect->sync_state, ogg_bytes_to_read); + + if(0 == oggbuf) { + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR; + } + else { + size_t ogg_bytes_read = ogg_bytes_to_read; + + switch(read_callback(decoder, (FLAC__byte*)oggbuf, &ogg_bytes_read, client_data)) { + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK: + break; + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM: + aspect->end_of_stream = true; + break; + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT: + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT; + default: + FLAC__ASSERT(0); + } + + if(ogg_sync_wrote(&aspect->sync_state, ogg_bytes_read) < 0) { + /* double protection; this will happen if the read callback returns more bytes than the max requested, which would overflow Ogg's internal buffer */ + FLAC__ASSERT(0); + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR; + } + } + } + else { /* ret < 0 */ + /* lost sync, bail out */ + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC; + } + } + } + + if (aspect->end_of_stream && *bytes == 0) { + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM; + } + + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK; +} diff --git a/flac/src/libFLAC/ogg_encoder_aspect.c b/flac/src/libFLAC/ogg_encoder_aspect.c new file mode 100644 index 0000000..a9b8080 --- /dev/null +++ b/flac/src/libFLAC/ogg_encoder_aspect.c @@ -0,0 +1,227 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for memset() */ +#include "FLAC/assert.h" +#include "private/ogg_encoder_aspect.h" +#include "private/ogg_mapping.h" + +static const FLAC__byte FLAC__OGG_MAPPING_VERSION_MAJOR = 1; +static const FLAC__byte FLAC__OGG_MAPPING_VERSION_MINOR = 0; + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +FLAC__bool FLAC__ogg_encoder_aspect_init(FLAC__OggEncoderAspect *aspect) +{ + /* we will determine the serial number later if necessary */ + if(ogg_stream_init(&aspect->stream_state, aspect->serial_number) != 0) + return false; + + aspect->seen_magic = false; + aspect->is_first_packet = true; + aspect->samples_written = 0; + + return true; +} + +void FLAC__ogg_encoder_aspect_finish(FLAC__OggEncoderAspect *aspect) +{ + (void)ogg_stream_clear(&aspect->stream_state); + /*@@@ what about the page? */ +} + +void FLAC__ogg_encoder_aspect_set_serial_number(FLAC__OggEncoderAspect *aspect, long value) +{ + aspect->serial_number = value; +} + +FLAC__bool FLAC__ogg_encoder_aspect_set_num_metadata(FLAC__OggEncoderAspect *aspect, unsigned value) +{ + if(value < (1u << FLAC__OGG_MAPPING_NUM_HEADERS_LEN)) { + aspect->num_metadata = value; + return true; + } + else + return false; +} + +void FLAC__ogg_encoder_aspect_set_defaults(FLAC__OggEncoderAspect *aspect) +{ + aspect->serial_number = 0; + aspect->num_metadata = 0; +} + +/* + * The basic FLAC -> Ogg mapping goes like this: + * + * - 'fLaC' magic and STREAMINFO block get combined into the first + * packet. The packet is prefixed with + * + the one-byte packet type 0x7F + * + 'FLAC' magic + * + the 2 byte Ogg FLAC mapping version number + * + tne 2 byte big-endian # of header packets + * - The first packet is flushed to the first page. + * - Each subsequent metadata block goes into its own packet. + * - Each metadata packet is flushed to page (this is not required, + * the mapping only requires that a flush must occur after all + * metadata is written). + * - Each subsequent FLAC audio frame goes into its own packet. + * + * WATCHOUT: + * This depends on the behavior of FLAC__StreamEncoder that we get a + * separate write callback for the fLaC magic, and then separate write + * callbacks for each metadata block and audio frame. + */ +FLAC__StreamEncoderWriteStatus FLAC__ogg_encoder_aspect_write_callback_wrapper(FLAC__OggEncoderAspect *aspect, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, FLAC__bool is_last_block, FLAC__OggEncoderAspectWriteCallbackProxy write_callback, void *encoder, void *client_data) +{ + /* WATCHOUT: + * This depends on the behavior of FLAC__StreamEncoder that 'samples' + * will be 0 for metadata writes. + */ + const FLAC__bool is_metadata = (samples == 0); + + /* + * Treat fLaC magic packet specially. We will note when we see it, then + * wait until we get the STREAMINFO and prepend it in that packet + */ + if(aspect->seen_magic) { + ogg_packet packet; + FLAC__byte synthetic_first_packet_body[ + FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH + + FLAC__OGG_MAPPING_MAGIC_LENGTH + + FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH + + FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH + + FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH + + FLAC__STREAM_SYNC_LENGTH + + FLAC__STREAM_METADATA_HEADER_LENGTH + + FLAC__STREAM_METADATA_STREAMINFO_LENGTH + ]; + + memset(&packet, 0, sizeof(packet)); + packet.granulepos = aspect->samples_written + samples; + + if(aspect->is_first_packet) { + FLAC__byte *b = synthetic_first_packet_body; + if(bytes != FLAC__STREAM_METADATA_HEADER_LENGTH + FLAC__STREAM_METADATA_STREAMINFO_LENGTH) { + /* + * If we get here, our assumption about the way write callbacks happen + * (explained above) is wrong + */ + FLAC__ASSERT(0); + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + } + /* add first header packet type */ + *b = FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE; + b += FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH; + /* add 'FLAC' mapping magic */ + memcpy(b, FLAC__OGG_MAPPING_MAGIC, FLAC__OGG_MAPPING_MAGIC_LENGTH); + b += FLAC__OGG_MAPPING_MAGIC_LENGTH; + /* add Ogg FLAC mapping major version number */ + memcpy(b, &FLAC__OGG_MAPPING_VERSION_MAJOR, FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH); + b += FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH; + /* add Ogg FLAC mapping minor version number */ + memcpy(b, &FLAC__OGG_MAPPING_VERSION_MINOR, FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH); + b += FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH; + /* add number of header packets */ + *b = (FLAC__byte)(aspect->num_metadata >> 8); + b++; + *b = (FLAC__byte)(aspect->num_metadata); + b++; + /* add native FLAC 'fLaC' magic */ + memcpy(b, FLAC__STREAM_SYNC_STRING, FLAC__STREAM_SYNC_LENGTH); + b += FLAC__STREAM_SYNC_LENGTH; + /* add STREAMINFO */ + memcpy(b, buffer, bytes); + FLAC__ASSERT(b + bytes - synthetic_first_packet_body == sizeof(synthetic_first_packet_body)); + packet.packet = (unsigned char *)synthetic_first_packet_body; + packet.bytes = sizeof(synthetic_first_packet_body); + + packet.b_o_s = 1; + aspect->is_first_packet = false; + } + else { + packet.packet = (unsigned char *)buffer; + packet.bytes = bytes; + } + + if(is_last_block) { + /* we used to check: + * FLAC__ASSERT(total_samples_estimate == 0 || total_samples_estimate == aspect->samples_written + samples); + * but it's really not useful since total_samples_estimate is an estimate and can be inexact + */ + packet.e_o_s = 1; + } + + if(ogg_stream_packetin(&aspect->stream_state, &packet) != 0) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + + /*@@@ can't figure out a way to pass a useful number for 'samples' to the write_callback, so we'll just pass 0 */ + if(is_metadata) { + while(ogg_stream_flush(&aspect->stream_state, &aspect->page) != 0) { + if(write_callback(encoder, aspect->page.header, aspect->page.header_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + if(write_callback(encoder, aspect->page.body, aspect->page.body_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + } + } + else { + while(ogg_stream_pageout(&aspect->stream_state, &aspect->page) != 0) { + if(write_callback(encoder, aspect->page.header, aspect->page.header_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + if(write_callback(encoder, aspect->page.body, aspect->page.body_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + } + } + } + else if(is_metadata && current_frame == 0 && samples == 0 && bytes == 4 && 0 == memcmp(buffer, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING))) { + aspect->seen_magic = true; + } + else { + /* + * If we get here, our assumption about the way write callbacks happen + * explained above is wrong + */ + FLAC__ASSERT(0); + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + } + + aspect->samples_written += samples; + + return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; +} diff --git a/flac/src/libFLAC/ogg_helper.c b/flac/src/libFLAC/ogg_helper.c new file mode 100644 index 0000000..9896dc5 --- /dev/null +++ b/flac/src/libFLAC/ogg_helper.c @@ -0,0 +1,209 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for malloc() */ +#include /* for memcmp(), memcpy() */ +#include "FLAC/assert.h" +#include "share/alloc.h" +#include "private/ogg_helper.h" +#include "protected/stream_encoder.h" + + +static FLAC__bool full_read_(FLAC__StreamEncoder *encoder, FLAC__byte *buffer, size_t bytes, FLAC__StreamEncoderReadCallback read_callback, void *client_data) +{ + while(bytes > 0) { + size_t bytes_read = bytes; + switch(read_callback(encoder, buffer, &bytes_read, client_data)) { + case FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE: + bytes -= bytes_read; + buffer += bytes_read; + break; + case FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM: + if(bytes_read == 0) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + return false; + } + bytes -= bytes_read; + buffer += bytes_read; + break; + case FLAC__STREAM_ENCODER_READ_STATUS_ABORT: + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + case FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED: + return false; + default: + /* double protection: */ + FLAC__ASSERT(0); + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + } + + return true; +} + +void simple_ogg_page__init(ogg_page *page) +{ + page->header = 0; + page->header_len = 0; + page->body = 0; + page->body_len = 0; +} + +void simple_ogg_page__clear(ogg_page *page) +{ + if(page->header) + free(page->header); + if(page->body) + free(page->body); + simple_ogg_page__init(page); +} + +FLAC__bool simple_ogg_page__get_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderReadCallback read_callback, void *client_data) +{ + static const unsigned OGG_HEADER_FIXED_PORTION_LEN = 27; + static const unsigned OGG_MAX_HEADER_LEN = 27/*OGG_HEADER_FIXED_PORTION_LEN*/ + 255; + FLAC__byte crc[4]; + FLAC__StreamEncoderSeekStatus seek_status; + + FLAC__ASSERT(page->header == 0); + FLAC__ASSERT(page->header_len == 0); + FLAC__ASSERT(page->body == 0); + FLAC__ASSERT(page->body_len == 0); + + /* move the stream pointer to the supposed beginning of the page */ + if(0 == seek_callback) + return false; + if((seek_status = seek_callback((FLAC__StreamEncoder*)encoder, position, client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + + /* allocate space for the page header */ + if(0 == (page->header = (unsigned char *)safe_malloc_(OGG_MAX_HEADER_LEN))) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + /* read in the fixed part of the page header (up to but not including + * the segment table */ + if(!full_read_(encoder, page->header, OGG_HEADER_FIXED_PORTION_LEN, read_callback, client_data)) + return false; + + page->header_len = OGG_HEADER_FIXED_PORTION_LEN + page->header[26]; + + /* check to see if it's a correct, "simple" page (one packet only) */ + if( + memcmp(page->header, "OggS", 4) || /* doesn't start with OggS */ + (page->header[5] & 0x01) || /* continued packet */ + memcmp(page->header+6, "\0\0\0\0\0\0\0\0", 8) || /* granulepos is non-zero */ + page->header[26] == 0 /* packet is 0-size */ + ) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + return false; + } + + /* read in the segment table */ + if(!full_read_(encoder, page->header + OGG_HEADER_FIXED_PORTION_LEN, page->header[26], read_callback, client_data)) + return false; + + { + unsigned i; + + /* check to see that it specifies a single packet */ + for(i = 0; i < (unsigned)page->header[26] - 1; i++) { + if(page->header[i + OGG_HEADER_FIXED_PORTION_LEN] != 255) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + return false; + } + } + + page->body_len = 255 * i + page->header[i + OGG_HEADER_FIXED_PORTION_LEN]; + } + + /* allocate space for the page body */ + if(0 == (page->body = (unsigned char *)safe_malloc_(page->body_len))) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + /* read in the page body */ + if(!full_read_(encoder, page->body, page->body_len, read_callback, client_data)) + return false; + + /* check the CRC */ + memcpy(crc, page->header+22, 4); + ogg_page_checksum_set(page); + if(memcmp(crc, page->header+22, 4)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + return false; + } + + return true; +} + +FLAC__bool simple_ogg_page__set_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderWriteCallback write_callback, void *client_data) +{ + FLAC__StreamEncoderSeekStatus seek_status; + + FLAC__ASSERT(page->header != 0); + FLAC__ASSERT(page->header_len != 0); + FLAC__ASSERT(page->body != 0); + FLAC__ASSERT(page->body_len != 0); + + /* move the stream pointer to the supposed beginning of the page */ + if(0 == seek_callback) + return false; + if((seek_status = seek_callback((FLAC__StreamEncoder*)encoder, position, client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + + ogg_page_checksum_set(page); + + /* re-write the page */ + if(write_callback((FLAC__StreamEncoder*)encoder, page->header, page->header_len, 0, 0, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + if(write_callback((FLAC__StreamEncoder*)encoder, page->body, page->body_len, 0, 0, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + + return true; +} diff --git a/flac/src/libFLAC/ogg_mapping.c b/flac/src/libFLAC/ogg_mapping.c new file mode 100644 index 0000000..ec37ce9 --- /dev/null +++ b/flac/src/libFLAC/ogg_mapping.c @@ -0,0 +1,47 @@ +/* libFLAC - Free Lossless Audio Codec + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "private/ogg_mapping.h" + +const unsigned FLAC__OGG_MAPPING_PACKET_TYPE_LEN = 8; /* bits */ + +const FLAC__byte FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE = 0x7f; + +const FLAC__byte * const FLAC__OGG_MAPPING_MAGIC = (const FLAC__byte * const)"FLAC"; + +const unsigned FLAC__OGG_MAPPING_VERSION_MAJOR_LEN = 8; /* bits */ +const unsigned FLAC__OGG_MAPPING_VERSION_MINOR_LEN = 8; /* bits */ + +const unsigned FLAC__OGG_MAPPING_NUM_HEADERS_LEN = 16; /* bits */ diff --git a/flac/src/libFLAC/ppc/Makefile.am b/flac/src/libFLAC/ppc/Makefile.am new file mode 100644 index 0000000..370cd9f --- /dev/null +++ b/flac/src/libFLAC/ppc/Makefile.am @@ -0,0 +1,31 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +SUBDIRS = as gas diff --git a/flac/src/libFLAC/ppc/as/Makefile.am b/flac/src/libFLAC/ppc/as/Makefile.am new file mode 100644 index 0000000..24f4457 --- /dev/null +++ b/flac/src/libFLAC/ppc/as/Makefile.am @@ -0,0 +1,52 @@ +# libFLAC - Free Lossless Audio Codec library +# Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - 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. +# +# - Neither the name of the Xiph.org Foundation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``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 FOUNDATION OR +# CONTRIBUTORS 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. + +#@@@ +if FLaC__HAS_AS__TEMPORARILY_DISABLED + +SUFFIXES = .s .lo + +STRIP_NON_ASM = sh $(top_srcdir)/strip_non_asm_libtool_args.sh + +# For some unknown reason libtool can't figure out the tag for 'as', so +# we fake it with --tag=CC and strip out unwanted options. +.s.lo: + $(LIBTOOL) --tag=CC --mode=compile $(STRIP_NON_ASM) as -force_cpusubtype_ALL -o $@ $< + +noinst_LTLIBRARIES = libFLAC-asm.la +libFLAC_asm_la_SOURCES = \ + lpc_asm.s + +else + +EXTRA_DIST = \ + lpc_asm.s + +endif diff --git a/flac/src/libFLAC/ppc/as/lpc_asm.s b/flac/src/libFLAC/ppc/as/lpc_asm.s new file mode 100644 index 0000000..58b8955 --- /dev/null +++ b/flac/src/libFLAC/ppc/as/lpc_asm.s @@ -0,0 +1,429 @@ +; libFLAC - Free Lossless Audio Codec library +; Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions +; are met: +; +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; +; - 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. +; +; - Neither the name of the Xiph.org Foundation nor the names of its +; contributors may be used to endorse or promote products derived from +; this software without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +; ``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 FOUNDATION OR +; CONTRIBUTORS 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. + +.text + .align 2 +.globl _FLAC__lpc_restore_signal_asm_ppc_altivec_16 + +.globl _FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8 + +_FLAC__lpc_restore_signal_asm_ppc_altivec_16: +; r3: residual[] +; r4: data_len +; r5: qlp_coeff[] +; r6: order +; r7: lp_quantization +; r8: data[] + +; see src/libFLAC/lpc.c:FLAC__lpc_restore_signal() +; these is a PowerPC/Altivec assembly version which requires bps<=16 (or actual +; bps<=15 for mid-side coding, since that uses an extra bit) + +; these should be fast; the inner loop is unrolled (it takes no more than +; 3*(order%4) instructions, all of which are arithmetic), and all of the +; coefficients and all relevant history stay in registers, so the outer loop +; has only one load from memory (the residual) + +; I have not yet run this through simg4, so there may be some avoidable stalls, +; and there may be a somewhat more clever way to do the outer loop + +; the branch mechanism may prevent dynamic loading; I still need to examine +; this issue, and there may be a more elegant method + + stmw r31,-4(r1) + + addi r9,r1,-28 + li r31,0xf + andc r9,r9,r31 ; for quadword-aligned stack data + + slwi r6,r6,2 ; adjust for word size + slwi r4,r4,2 + add r4,r4,r8 ; r4 = data+data_len + + mfspr r0,256 ; cache old vrsave + addis r31,0,hi16(0xfffffc00) + ori r31,r31,lo16(0xfffffc00) + mtspr 256,r31 ; declare VRs in vrsave + + cmplw cr0,r8,r4 ; i> lp_quantization + + lvewx v21,0,r3 ; v21[n]: *residual + vperm v21,v21,v21,v18 ; v21[3]: *residual + vaddsws v20,v21,v20 ; v20[3]: *residual + (sum >> lp_quantization) + vsldoi v18,v18,v18,4 ; increment shift vector + + vperm v21,v20,v20,v17 ; v21[n]: shift for storage + vsldoi v17,v17,v17,12 ; increment shift vector + stvewx v21,0,r8 + + vsldoi v20,v20,v20,12 + vsldoi v8,v8,v20,4 ; insert value onto history + + addi r3,r3,4 + addi r8,r8,4 + cmplw cr0,r8,r4 ; i> lp_quantization + + lvewx v9,0,r3 ; v9[n]: *residual + vperm v9,v9,v9,v6 ; v9[3]: *residual + vaddsws v8,v9,v8 ; v8[3]: *residual + (sum >> lp_quantization) + vsldoi v6,v6,v6,4 ; increment shift vector + + vperm v9,v8,v8,v5 ; v9[n]: shift for storage + vsldoi v5,v5,v5,12 ; increment shift vector + stvewx v9,0,r8 + + vsldoi v8,v8,v8,12 + vsldoi v2,v2,v8,4 ; insert value onto history + + addi r3,r3,4 + addi r8,r8,4 + cmplw cr0,r8,r4 ; i> lp_quantization + + lvewx v21,0,r3 # v21[n]: *residual + vperm v21,v21,v21,v18 # v21[3]: *residual + vaddsws v20,v21,v20 # v20[3]: *residual + (sum >> lp_quantization) + vsldoi v18,v18,v18,4 # increment shift vector + + vperm v21,v20,v20,v17 # v21[n]: shift for storage + vsldoi v17,v17,v17,12 # increment shift vector + stvewx v21,0,r8 + + vsldoi v20,v20,v20,12 + vsldoi v8,v8,v20,4 # insert value onto history + + addi r3,r3,4 + addi r8,r8,4 + cmplw cr0,r8,r4 # i> lp_quantization + + lvewx v9,0,r3 # v9[n]: *residual + vperm v9,v9,v9,v6 # v9[3]: *residual + vaddsws v8,v9,v8 # v8[3]: *residual + (sum >> lp_quantization) + vsldoi v6,v6,v6,4 # increment shift vector + + vperm v9,v8,v8,v5 # v9[n]: shift for storage + vsldoi v5,v5,v5,12 # increment shift vector + stvewx v9,0,r8 + + vsldoi v8,v8,v8,12 + vsldoi v2,v2,v8,4 # insert value onto history + + addi r3,r3,4 + addi r8,r8,4 + cmplw cr0,r8,r4 # i +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#include /* for _setmode() */ +#include /* for _O_BINARY */ +#endif +#if defined __CYGWIN__ || defined __EMX__ +#include /* for setmode(), O_BINARY */ +#include /* for _O_BINARY */ +#endif +#include +#include /* for malloc() */ +#include /* for memset/memcpy() */ +#include /* for stat() */ +#include /* for off_t */ +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ +#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include "FLAC/assert.h" +#include "share/alloc.h" +#include "protected/stream_decoder.h" +#include "private/bitreader.h" +#include "private/bitmath.h" +#include "private/cpu.h" +#include "private/crc.h" +#include "private/fixed.h" +#include "private/format.h" +#include "private/lpc.h" +#include "private/md5.h" +#include "private/memory.h" + +#ifdef max +#undef max +#endif +#define max(a,b) ((a)>(b)?(a):(b)) + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + + +/* technically this should be in an "export.c" but this is convenient enough */ +FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC = +#if FLAC__HAS_OGG + 1 +#else + 0 +#endif +; + + +/*********************************************************************** + * + * Private static data + * + ***********************************************************************/ + +static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' }; + +/*********************************************************************** + * + * Private class method prototypes + * + ***********************************************************************/ + +static void set_defaults_(FLAC__StreamDecoder *decoder); +static FILE *get_binary_stdin_(void); +static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels); +static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id); +static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder); +static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder); +static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length); +static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length); +static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj); +static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj); +static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj); +static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder); +static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder); +static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode); +static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder); +static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode); +static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode); +static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode); +static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode); +static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode); +static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended); +static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder); +static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data); +#if FLAC__HAS_OGG +static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes); +static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +#endif +static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]); +static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status); +static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample); +#if FLAC__HAS_OGG +static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample); +#endif +static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data); +static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data); +static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data); +static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data); + +/*********************************************************************** + * + * Private class data + * + ***********************************************************************/ + +typedef struct FLAC__StreamDecoderPrivate { +#if FLAC__HAS_OGG + FLAC__bool is_ogg; +#endif + FLAC__StreamDecoderReadCallback read_callback; + FLAC__StreamDecoderSeekCallback seek_callback; + FLAC__StreamDecoderTellCallback tell_callback; + FLAC__StreamDecoderLengthCallback length_callback; + FLAC__StreamDecoderEofCallback eof_callback; + FLAC__StreamDecoderWriteCallback write_callback; + FLAC__StreamDecoderMetadataCallback metadata_callback; + FLAC__StreamDecoderErrorCallback error_callback; + /* generic 32-bit datapath: */ + void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); + /* generic 64-bit datapath: */ + void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); + /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */ + void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); + /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */ + void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]); + FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter); + void *client_data; + FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */ + FLAC__BitReader *input; + FLAC__int32 *output[FLAC__MAX_CHANNELS]; + FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */ + FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS]; + unsigned output_capacity, output_channels; + FLAC__uint32 fixed_block_size, next_fixed_block_size; + FLAC__uint64 samples_decoded; + FLAC__bool has_stream_info, has_seek_table; + FLAC__StreamMetadata stream_info; + FLAC__StreamMetadata seek_table; + FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */ + FLAC__byte *metadata_filter_ids; + size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */ + FLAC__Frame frame; + FLAC__bool cached; /* true if there is a byte in lookahead */ + FLAC__CPUInfo cpuinfo; + FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */ + FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */ + /* unaligned (original) pointers to allocated data */ + FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS]; + FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */ + FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */ + FLAC__bool is_seeking; + FLAC__MD5Context md5context; + FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */ + /* (the rest of these are only used for seeking) */ + FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */ + FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */ + FLAC__uint64 target_sample; + unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */ +#if FLAC__HAS_OGG + FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */ +#endif +} FLAC__StreamDecoderPrivate; + +/*********************************************************************** + * + * Public static class data + * + ***********************************************************************/ + +FLAC_API const char * const FLAC__StreamDecoderStateString[] = { + "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA", + "FLAC__STREAM_DECODER_READ_METADATA", + "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC", + "FLAC__STREAM_DECODER_READ_FRAME", + "FLAC__STREAM_DECODER_END_OF_STREAM", + "FLAC__STREAM_DECODER_OGG_ERROR", + "FLAC__STREAM_DECODER_SEEK_ERROR", + "FLAC__STREAM_DECODER_ABORTED", + "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR", + "FLAC__STREAM_DECODER_UNINITIALIZED" +}; + +FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = { + "FLAC__STREAM_DECODER_INIT_STATUS_OK", + "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER", + "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS", + "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR", + "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE", + "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED" +}; + +FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = { + "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE", + "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM", + "FLAC__STREAM_DECODER_READ_STATUS_ABORT" +}; + +FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = { + "FLAC__STREAM_DECODER_SEEK_STATUS_OK", + "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR", + "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED" +}; + +FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = { + "FLAC__STREAM_DECODER_TELL_STATUS_OK", + "FLAC__STREAM_DECODER_TELL_STATUS_ERROR", + "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED" +}; + +FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = { + "FLAC__STREAM_DECODER_LENGTH_STATUS_OK", + "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR", + "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED" +}; + +FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = { + "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE", + "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT" +}; + +FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = { + "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC", + "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER", + "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH", + "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM" +}; + +/*********************************************************************** + * + * Class constructor/destructor + * + ***********************************************************************/ +FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void) +{ + FLAC__StreamDecoder *decoder; + unsigned i; + + FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */ + + decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder)); + if(decoder == 0) { + return 0; + } + + decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected)); + if(decoder->protected_ == 0) { + free(decoder); + return 0; + } + + decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate)); + if(decoder->private_ == 0) { + free(decoder->protected_); + free(decoder); + return 0; + } + + decoder->private_->input = FLAC__bitreader_new(); + if(decoder->private_->input == 0) { + free(decoder->private_); + free(decoder->protected_); + free(decoder); + return 0; + } + + decoder->private_->metadata_filter_ids_capacity = 16; + if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) { + FLAC__bitreader_delete(decoder->private_->input); + free(decoder->private_); + free(decoder->protected_); + free(decoder); + return 0; + } + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + decoder->private_->output[i] = 0; + decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0; + } + + decoder->private_->output_capacity = 0; + decoder->private_->output_channels = 0; + decoder->private_->has_seek_table = false; + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]); + + decoder->private_->file = 0; + + set_defaults_(decoder); + + decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED; + + return decoder; +} + +FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder) +{ + unsigned i; + + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->private_->input); + + (void)FLAC__stream_decoder_finish(decoder); + + if(0 != decoder->private_->metadata_filter_ids) + free(decoder->private_->metadata_filter_ids); + + FLAC__bitreader_delete(decoder->private_->input); + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]); + + free(decoder->private_); + free(decoder->protected_); + free(decoder); +} + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +static FLAC__StreamDecoderInitStatus init_stream_internal_( + FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderReadCallback read_callback, + FLAC__StreamDecoderSeekCallback seek_callback, + FLAC__StreamDecoderTellCallback tell_callback, + FLAC__StreamDecoderLengthCallback length_callback, + FLAC__StreamDecoderEofCallback eof_callback, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + FLAC__ASSERT(0 != decoder); + + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED; + +#if !FLAC__HAS_OGG + if(is_ogg) + return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER; +#endif + + if( + 0 == read_callback || + 0 == write_callback || + 0 == error_callback || + (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback)) + ) + return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS; + +#if FLAC__HAS_OGG + decoder->private_->is_ogg = is_ogg; + if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect)) + return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR; +#endif + + /* + * get the CPU info and set the function pointers + */ + FLAC__cpu_info(&decoder->private_->cpuinfo); + /* first default to the non-asm routines */ + decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal; + decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide; + decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal; + decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal; + decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block; + /* now override with asm where appropriate */ +#ifndef FLAC__NO_ASM + if(decoder->private_->cpuinfo.use_asm) { +#ifdef FLAC__CPU_IA32 + FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32); +#ifdef FLAC__HAS_NASM +#if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */ + if(decoder->private_->cpuinfo.data.ia32.bswap) + decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap; +#endif + if(decoder->private_->cpuinfo.data.ia32.mmx) { + decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32; + decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx; + decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx; + } + else { + decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32; + decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32; + decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32; + } +#endif +#elif defined FLAC__CPU_PPC + FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC); + if(decoder->private_->cpuinfo.data.ppc.altivec) { + decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16; + decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8; + } +#endif + } +#endif + + /* from here on, errors are fatal */ + + if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR; + } + + decoder->private_->read_callback = read_callback; + decoder->private_->seek_callback = seek_callback; + decoder->private_->tell_callback = tell_callback; + decoder->private_->length_callback = length_callback; + decoder->private_->eof_callback = eof_callback; + decoder->private_->write_callback = write_callback; + decoder->private_->metadata_callback = metadata_callback; + decoder->private_->error_callback = error_callback; + decoder->private_->client_data = client_data; + decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0; + decoder->private_->samples_decoded = 0; + decoder->private_->has_stream_info = false; + decoder->private_->cached = false; + + decoder->private_->do_md5_checking = decoder->protected_->md5_checking; + decoder->private_->is_seeking = false; + + decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */ + if(!FLAC__stream_decoder_reset(decoder)) { + /* above call sets the state for us */ + return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR; + } + + return FLAC__STREAM_DECODER_INIT_STATUS_OK; +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream( + FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderReadCallback read_callback, + FLAC__StreamDecoderSeekCallback seek_callback, + FLAC__StreamDecoderTellCallback tell_callback, + FLAC__StreamDecoderLengthCallback length_callback, + FLAC__StreamDecoderEofCallback eof_callback, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_stream_internal_( + decoder, + read_callback, + seek_callback, + tell_callback, + length_callback, + eof_callback, + write_callback, + metadata_callback, + error_callback, + client_data, + /*is_ogg=*/false + ); +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream( + FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderReadCallback read_callback, + FLAC__StreamDecoderSeekCallback seek_callback, + FLAC__StreamDecoderTellCallback tell_callback, + FLAC__StreamDecoderLengthCallback length_callback, + FLAC__StreamDecoderEofCallback eof_callback, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_stream_internal_( + decoder, + read_callback, + seek_callback, + tell_callback, + length_callback, + eof_callback, + write_callback, + metadata_callback, + error_callback, + client_data, + /*is_ogg=*/true + ); +} + +static FLAC__StreamDecoderInitStatus init_FILE_internal_( + FLAC__StreamDecoder *decoder, + FILE *file, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != file); + + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED; + + if(0 == write_callback || 0 == error_callback) + return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS; + + /* + * To make sure that our file does not go unclosed after an error, we + * must assign the FILE pointer before any further error can occur in + * this routine. + */ + if(file == stdin) + file = get_binary_stdin_(); /* just to be safe */ + + decoder->private_->file = file; + + return init_stream_internal_( + decoder, + file_read_callback_, + decoder->private_->file == stdin? 0: file_seek_callback_, + decoder->private_->file == stdin? 0: file_tell_callback_, + decoder->private_->file == stdin? 0: file_length_callback_, + file_eof_callback_, + write_callback, + metadata_callback, + error_callback, + client_data, + is_ogg + ); +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE( + FLAC__StreamDecoder *decoder, + FILE *file, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false); +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE( + FLAC__StreamDecoder *decoder, + FILE *file, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true); +} + +static FLAC__StreamDecoderInitStatus init_file_internal_( + FLAC__StreamDecoder *decoder, + const char *filename, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + FILE *file; + + FLAC__ASSERT(0 != decoder); + + /* + * To make sure that our file does not go unclosed after an error, we + * have to do the same entrance checks here that are later performed + * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned. + */ + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED; + + if(0 == write_callback || 0 == error_callback) + return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS; + + file = filename? fopen(filename, "rb") : stdin; + + if(0 == file) + return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE; + + return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg); +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file( + FLAC__StreamDecoder *decoder, + const char *filename, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false); +} + +FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file( + FLAC__StreamDecoder *decoder, + const char *filename, + FLAC__StreamDecoderWriteCallback write_callback, + FLAC__StreamDecoderMetadataCallback metadata_callback, + FLAC__StreamDecoderErrorCallback error_callback, + void *client_data +) +{ + return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true); +} + +FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder) +{ + FLAC__bool md5_failed = false; + unsigned i; + + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + + if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED) + return true; + + /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we + * always call FLAC__MD5Final() + */ + FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context); + + if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) { + free(decoder->private_->seek_table.data.seek_table.points); + decoder->private_->seek_table.data.seek_table.points = 0; + decoder->private_->has_seek_table = false; + } + FLAC__bitreader_free(decoder->private_->input); + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + /* WATCHOUT: + * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the + * output arrays have a buffer of up to 3 zeroes in front + * (at negative indices) for alignment purposes; we use 4 + * to keep the data well-aligned. + */ + if(0 != decoder->private_->output[i]) { + free(decoder->private_->output[i]-4); + decoder->private_->output[i] = 0; + } + if(0 != decoder->private_->residual_unaligned[i]) { + free(decoder->private_->residual_unaligned[i]); + decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0; + } + } + decoder->private_->output_capacity = 0; + decoder->private_->output_channels = 0; + +#if FLAC__HAS_OGG + if(decoder->private_->is_ogg) + FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect); +#endif + + if(0 != decoder->private_->file) { + if(decoder->private_->file != stdin) + fclose(decoder->private_->file); + decoder->private_->file = 0; + } + + if(decoder->private_->do_md5_checking) { + if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16)) + md5_failed = true; + } + decoder->private_->is_seeking = false; + + set_defaults_(decoder); + + decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED; + + return !md5_failed; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; +#if FLAC__HAS_OGG + /* can't check decoder->private_->is_ogg since that's not set until init time */ + FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value); + return true; +#else + (void)value; + return false; +#endif +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + decoder->protected_->md5_checking = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE); + /* double protection */ + if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE) + return false; + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + decoder->private_->metadata_filter[type] = true; + if(type == FLAC__METADATA_TYPE_APPLICATION) + decoder->private_->metadata_filter_ids_count = 0; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + FLAC__ASSERT(0 != id); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + + if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION]) + return true; + + FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids); + + if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) { + if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + decoder->private_->metadata_filter_ids_capacity *= 2; + } + + memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)); + decoder->private_->metadata_filter_ids_count++; + + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder) +{ + unsigned i; + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++) + decoder->private_->metadata_filter[i] = true; + decoder->private_->metadata_filter_ids_count = 0; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE); + /* double protection */ + if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE) + return false; + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + decoder->private_->metadata_filter[type] = false; + if(type == FLAC__METADATA_TYPE_APPLICATION) + decoder->private_->metadata_filter_ids_count = 0; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + FLAC__ASSERT(0 != id); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + + if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION]) + return true; + + FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids); + + if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) { + if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + decoder->private_->metadata_filter_ids_capacity *= 2; + } + + memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)); + decoder->private_->metadata_filter_ids_count++; + + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED) + return false; + memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter)); + decoder->private_->metadata_filter_ids_count = 0; + return true; +} + +FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->state; +} + +FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder) +{ + return FLAC__StreamDecoderStateString[decoder->protected_->state]; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->md5_checking; +} + +FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0; +} + +FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->channels; +} + +FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->channel_assignment; +} + +FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->bits_per_sample; +} + +FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->sample_rate; +} + +FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + return decoder->protected_->blocksize; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != position); + +#if FLAC__HAS_OGG + if(decoder->private_->is_ogg) + return false; +#endif + if(0 == decoder->private_->tell_callback) + return false; + if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) + return false; + /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */ + if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) + return false; + FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder)); + *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder); + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + + decoder->private_->samples_decoded = 0; + decoder->private_->do_md5_checking = false; + +#if FLAC__HAS_OGG + if(decoder->private_->is_ogg) + FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect); +#endif + + if(!FLAC__bitreader_clear(decoder->private_->input)) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + FLAC__ASSERT(0 != decoder->protected_); + + if(!FLAC__stream_decoder_flush(decoder)) { + /* above call sets the state for us */ + return false; + } + +#if FLAC__HAS_OGG + /*@@@ could go in !internal_reset_hack block below */ + if(decoder->private_->is_ogg) + FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect); +#endif + + /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us, + * (internal_reset_hack) don't try to rewind since we are already at + * the beginning of the stream and don't want to fail if the input is + * not seekable. + */ + if(!decoder->private_->internal_reset_hack) { + if(decoder->private_->file == stdin) + return false; /* can't rewind stdin, reset fails */ + if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR) + return false; /* seekable and seek fails, reset fails */ + } + else + decoder->private_->internal_reset_hack = false; + + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA; + + decoder->private_->has_stream_info = false; + if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) { + free(decoder->private_->seek_table.data.seek_table.points); + decoder->private_->seek_table.data.seek_table.points = 0; + decoder->private_->has_seek_table = false; + } + decoder->private_->do_md5_checking = decoder->protected_->md5_checking; + /* + * This goes in reset() and not flush() because according to the spec, a + * fixed-blocksize stream must stay that way through the whole stream. + */ + decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0; + + /* We initialize the FLAC__MD5Context even though we may never use it. This + * is because md5 checking may be turned on to start and then turned off if + * a seek occurs. So we init the context here and finalize it in + * FLAC__stream_decoder_finish() to make sure things are always cleaned up + * properly. + */ + FLAC__MD5Init(&decoder->private_->md5context); + + decoder->private_->first_frame_offset = 0; + decoder->private_->unparseable_frame_count = 0; + + return true; +} + +FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder) +{ + FLAC__bool got_a_frame; + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + + while(1) { + switch(decoder->protected_->state) { + case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA: + if(!find_metadata_(decoder)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_METADATA: + if(!read_metadata_(decoder)) + return false; /* above function sets the status for us */ + else + return true; + case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC: + if(!frame_sync_(decoder)) + return true; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_FRAME: + if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true)) + return false; /* above function sets the status for us */ + if(got_a_frame) + return true; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_END_OF_STREAM: + case FLAC__STREAM_DECODER_ABORTED: + return true; + default: + FLAC__ASSERT(0); + return false; + } + } +} + +FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + + while(1) { + switch(decoder->protected_->state) { + case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA: + if(!find_metadata_(decoder)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_METADATA: + if(!read_metadata_(decoder)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC: + case FLAC__STREAM_DECODER_READ_FRAME: + case FLAC__STREAM_DECODER_END_OF_STREAM: + case FLAC__STREAM_DECODER_ABORTED: + return true; + default: + FLAC__ASSERT(0); + return false; + } + } +} + +FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder) +{ + FLAC__bool dummy; + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + + while(1) { + switch(decoder->protected_->state) { + case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA: + if(!find_metadata_(decoder)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_METADATA: + if(!read_metadata_(decoder)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC: + if(!frame_sync_(decoder)) + return true; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_FRAME: + if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true)) + return false; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_END_OF_STREAM: + case FLAC__STREAM_DECODER_ABORTED: + return true; + default: + FLAC__ASSERT(0); + return false; + } + } +} + +FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder) +{ + FLAC__bool got_a_frame; + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->protected_); + + while(1) { + switch(decoder->protected_->state) { + case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA: + case FLAC__STREAM_DECODER_READ_METADATA: + return false; /* above function sets the status for us */ + case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC: + if(!frame_sync_(decoder)) + return true; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_READ_FRAME: + if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false)) + return false; /* above function sets the status for us */ + if(got_a_frame) + return true; /* above function sets the status for us */ + break; + case FLAC__STREAM_DECODER_END_OF_STREAM: + case FLAC__STREAM_DECODER_ABORTED: + return true; + default: + FLAC__ASSERT(0); + return false; + } + } +} + +FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample) +{ + FLAC__uint64 length; + + FLAC__ASSERT(0 != decoder); + + if( + decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA && + decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA && + decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC && + decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME && + decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM + ) + return false; + + if(0 == decoder->private_->seek_callback) + return false; + + FLAC__ASSERT(decoder->private_->seek_callback); + FLAC__ASSERT(decoder->private_->tell_callback); + FLAC__ASSERT(decoder->private_->length_callback); + FLAC__ASSERT(decoder->private_->eof_callback); + + if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) + return false; + + decoder->private_->is_seeking = true; + + /* turn off md5 checking if a seek is attempted */ + decoder->private_->do_md5_checking = false; + + /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */ + if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) { + decoder->private_->is_seeking = false; + return false; + } + + /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */ + if( + decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA || + decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA + ) { + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) { + /* above call sets the state for us */ + decoder->private_->is_seeking = false; + return false; + } + /* check this again in case we didn't know total_samples the first time */ + if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) { + decoder->private_->is_seeking = false; + return false; + } + } + + { + const FLAC__bool ok = +#if FLAC__HAS_OGG + decoder->private_->is_ogg? + seek_to_absolute_sample_ogg_(decoder, length, sample) : +#endif + seek_to_absolute_sample_(decoder, length, sample) + ; + decoder->private_->is_seeking = false; + return ok; + } +} + +/*********************************************************************** + * + * Protected class methods + * + ***********************************************************************/ + +unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder) +{ + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7)); + return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8; +} + +/*********************************************************************** + * + * Private class methods + * + ***********************************************************************/ + +void set_defaults_(FLAC__StreamDecoder *decoder) +{ +#if FLAC__HAS_OGG + decoder->private_->is_ogg = false; +#endif + decoder->private_->read_callback = 0; + decoder->private_->seek_callback = 0; + decoder->private_->tell_callback = 0; + decoder->private_->length_callback = 0; + decoder->private_->eof_callback = 0; + decoder->private_->write_callback = 0; + decoder->private_->metadata_callback = 0; + decoder->private_->error_callback = 0; + decoder->private_->client_data = 0; + + memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter)); + decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true; + decoder->private_->metadata_filter_ids_count = 0; + + decoder->protected_->md5_checking = false; + +#if FLAC__HAS_OGG + FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect); +#endif +} + +/* + * This will forcibly set stdin to binary mode (for OSes that require it) + */ +FILE *get_binary_stdin_(void) +{ + /* if something breaks here it is probably due to the presence or + * absence of an underscore before the identifiers 'setmode', + * 'fileno', and/or 'O_BINARY'; check your system header files. + */ +#if defined _MSC_VER || defined __MINGW32__ + _setmode(_fileno(stdin), _O_BINARY); +#elif defined __CYGWIN__ + /* almost certainly not needed for any modern Cygwin, but let's be safe... */ + setmode(_fileno(stdin), _O_BINARY); +#elif defined __EMX__ + setmode(fileno(stdin), O_BINARY); +#endif + + return stdin; +} + +FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels) +{ + unsigned i; + FLAC__int32 *tmp; + + if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels) + return true; + + /* simply using realloc() is not practical because the number of channels may change mid-stream */ + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + if(0 != decoder->private_->output[i]) { + free(decoder->private_->output[i]-4); + decoder->private_->output[i] = 0; + } + if(0 != decoder->private_->residual_unaligned[i]) { + free(decoder->private_->residual_unaligned[i]); + decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0; + } + } + + for(i = 0; i < channels; i++) { + /* WATCHOUT: + * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the + * output arrays have a buffer of up to 3 zeroes in front + * (at negative indices) for alignment purposes; we use 4 + * to keep the data well-aligned. + */ + tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/); + if(tmp == 0) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + memset(tmp, 0, sizeof(FLAC__int32)*4); + decoder->private_->output[i] = tmp + 4; + + /* WATCHOUT: + * minimum of quadword alignment for PPC vector optimizations is REQUIRED: + */ + if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + } + + decoder->private_->output_capacity = size; + decoder->private_->output_channels = channels; + + return true; +} + +FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id) +{ + size_t i; + + FLAC__ASSERT(0 != decoder); + FLAC__ASSERT(0 != decoder->private_); + + for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++) + if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))) + return true; + + return false; +} + +FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder) +{ + FLAC__uint32 x; + unsigned i, id; + FLAC__bool first = true; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + for(i = id = 0; i < 4; ) { + if(decoder->private_->cached) { + x = (FLAC__uint32)decoder->private_->lookahead; + decoder->private_->cached = false; + } + else { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + } + if(x == FLAC__STREAM_SYNC_STRING[i]) { + first = true; + i++; + id = 0; + continue; + } + if(x == ID3V2_TAG_[id]) { + id++; + i = 0; + if(id == 3) { + if(!skip_id3v2_tag_(decoder)) + return false; /* skip_id3v2_tag_ sets the state for us */ + } + continue; + } + id = 0; + if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */ + decoder->private_->header_warmup[0] = (FLAC__byte)x; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + + /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */ + /* else we have to check if the second byte is the end of a sync code */ + if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */ + decoder->private_->lookahead = (FLAC__byte)x; + decoder->private_->cached = true; + } + else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */ + decoder->private_->header_warmup[1] = (FLAC__byte)x; + decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME; + return true; + } + } + i = 0; + if(first) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + first = false; + } + } + + decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA; + return true; +} + +FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder) +{ + FLAC__bool is_last; + FLAC__uint32 i, x, type, length; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN)) + return false; /* read_callback_ sets the state for us */ + is_last = x? true : false; + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(type == FLAC__METADATA_TYPE_STREAMINFO) { + if(!read_metadata_streaminfo_(decoder, is_last, length)) + return false; + + decoder->private_->has_stream_info = true; + if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) + decoder->private_->do_md5_checking = false; + if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback) + decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data); + } + else if(type == FLAC__METADATA_TYPE_SEEKTABLE) { + if(!read_metadata_seektable_(decoder, is_last, length)) + return false; + + decoder->private_->has_seek_table = true; + if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback) + decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data); + } + else { + FLAC__bool skip_it = !decoder->private_->metadata_filter[type]; + unsigned real_length = length; + FLAC__StreamMetadata block; + + block.is_last = is_last; + block.type = (FLAC__MetadataType)type; + block.length = length; + + if(type == FLAC__METADATA_TYPE_APPLICATION) { + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)) + return false; /* read_callback_ sets the state for us */ + + if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */ + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/ + return false; + } + + real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8; + + if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id)) + skip_it = !skip_it; + } + + if(skip_it) { + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length)) + return false; /* read_callback_ sets the state for us */ + } + else { + switch(type) { + case FLAC__METADATA_TYPE_PADDING: + /* skip the padding bytes */ + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length)) + return false; /* read_callback_ sets the state for us */ + break; + case FLAC__METADATA_TYPE_APPLICATION: + /* remember, we read the ID already */ + if(real_length > 0) { + if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length)) + return false; /* read_callback_ sets the state for us */ + } + else + block.data.application.data = 0; + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment)) + return false; + break; + case FLAC__METADATA_TYPE_CUESHEET: + if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet)) + return false; + break; + case FLAC__METADATA_TYPE_PICTURE: + if(!read_metadata_picture_(decoder, &block.data.picture)) + return false; + break; + case FLAC__METADATA_TYPE_STREAMINFO: + case FLAC__METADATA_TYPE_SEEKTABLE: + FLAC__ASSERT(0); + break; + default: + if(real_length > 0) { + if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length)) + return false; /* read_callback_ sets the state for us */ + } + else + block.data.unknown.data = 0; + break; + } + if(!decoder->private_->is_seeking && decoder->private_->metadata_callback) + decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data); + + /* now we have to free any malloc()ed data in the block */ + switch(type) { + case FLAC__METADATA_TYPE_PADDING: + break; + case FLAC__METADATA_TYPE_APPLICATION: + if(0 != block.data.application.data) + free(block.data.application.data); + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + if(0 != block.data.vorbis_comment.vendor_string.entry) + free(block.data.vorbis_comment.vendor_string.entry); + if(block.data.vorbis_comment.num_comments > 0) + for(i = 0; i < block.data.vorbis_comment.num_comments; i++) + if(0 != block.data.vorbis_comment.comments[i].entry) + free(block.data.vorbis_comment.comments[i].entry); + if(0 != block.data.vorbis_comment.comments) + free(block.data.vorbis_comment.comments); + break; + case FLAC__METADATA_TYPE_CUESHEET: + if(block.data.cue_sheet.num_tracks > 0) + for(i = 0; i < block.data.cue_sheet.num_tracks; i++) + if(0 != block.data.cue_sheet.tracks[i].indices) + free(block.data.cue_sheet.tracks[i].indices); + if(0 != block.data.cue_sheet.tracks) + free(block.data.cue_sheet.tracks); + break; + case FLAC__METADATA_TYPE_PICTURE: + if(0 != block.data.picture.mime_type) + free(block.data.picture.mime_type); + if(0 != block.data.picture.description) + free(block.data.picture.description); + if(0 != block.data.picture.data) + free(block.data.picture.data); + break; + case FLAC__METADATA_TYPE_STREAMINFO: + case FLAC__METADATA_TYPE_SEEKTABLE: + FLAC__ASSERT(0); + default: + if(0 != block.data.unknown.data) + free(block.data.unknown.data); + break; + } + } + } + + if(is_last) { + /* if this fails, it's OK, it's just a hint for the seek routine */ + if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset)) + decoder->private_->first_frame_offset = 0; + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + } + + return true; +} + +FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length) +{ + FLAC__uint32 x; + unsigned bits, used_bits = 0; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO; + decoder->private_->stream_info.is_last = is_last; + decoder->private_->stream_info.length = length; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.sample_rate = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.channels = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) + return false; /* read_callback_ sets the state for us */ + used_bits += bits; + + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16)) + return false; /* read_callback_ sets the state for us */ + used_bits += 16*8; + + /* skip the rest of the block */ + FLAC__ASSERT(used_bits % 8 == 0); + length -= (used_bits / 8); + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + + return true; +} + +FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length) +{ + FLAC__uint32 i, x; + FLAC__uint64 xx; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE; + decoder->private_->seek_table.is_last = is_last; + decoder->private_->seek_table.length = length; + + decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; + + /* use realloc since we may pass through here several times (e.g. after seeking) */ + if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) { + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx; + + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx; + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x; + } + length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH); + /* if there is a partial point left, skip over it */ + if(length > 0) { + /*@@@ do a send_error_to_client_() here? there's an argument for either way */ + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + } + + return true; +} + +FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj) +{ + FLAC__uint32 i; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + /* read vendor string */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + if(obj->vendor_string.length > 0) { + if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + obj->vendor_string.entry[obj->vendor_string.length] = '\0'; + } + else + obj->vendor_string.entry = 0; + + /* read num comments */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32); + if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments)) + return false; /* read_callback_ sets the state for us */ + + /* read comments */ + if(obj->num_comments > 0) { + if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + for(i = 0; i < obj->num_comments; i++) { + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length)) + return false; /* read_callback_ sets the state for us */ + if(obj->comments[i].length > 0) { + if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) + return false; /* read_callback_ sets the state for us */ + obj->comments[i].entry[obj->comments[i].length] = '\0'; + } + else + obj->comments[i].entry = 0; + } + } + else { + obj->comments = 0; + } + + return true; +} + +FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj) +{ + FLAC__uint32 i, j, x; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet)); + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0); + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN)) + return false; /* read_callback_ sets the state for us */ + obj->is_cd = x? true : false; + + if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN)) + return false; /* read_callback_ sets the state for us */ + obj->num_tracks = x; + + if(obj->num_tracks > 0) { + if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + for(i = 0; i < obj->num_tracks; i++) { + FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i]; + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN)) + return false; /* read_callback_ sets the state for us */ + track->number = (FLAC__byte)x; + + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0); + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + track->type = x; + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN)) + return false; /* read_callback_ sets the state for us */ + track->pre_emphasis = x; + + if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN)) + return false; /* read_callback_ sets the state for us */ + track->num_indices = (FLAC__byte)x; + + if(track->num_indices > 0) { + if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + for(j = 0; j < track->num_indices; j++) { + FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j]; + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN)) + return false; /* read_callback_ sets the state for us */ + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN)) + return false; /* read_callback_ sets the state for us */ + index->number = (FLAC__byte)x; + + if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN)) + return false; /* read_callback_ sets the state for us */ + } + } + } + } + + return true; +} + +FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj) +{ + FLAC__uint32 x; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + /* read type */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + obj->type = x; + + /* read MIME type */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) + return false; /* read_callback_ sets the state for us */ + if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(x > 0) { + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x)) + return false; /* read_callback_ sets the state for us */ + } + obj->mime_type[x] = '\0'; + + /* read description */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) + return false; /* read_callback_ sets the state for us */ + if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(x > 0) { + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x)) + return false; /* read_callback_ sets the state for us */ + } + obj->description[x] = '\0'; + + /* read width */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN)) + return false; /* read_callback_ sets the state for us */ + + /* read height */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN)) + return false; /* read_callback_ sets the state for us */ + + /* read depth */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN)) + return false; /* read_callback_ sets the state for us */ + + /* read colors */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN)) + return false; /* read_callback_ sets the state for us */ + + /* read data */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) + return false; /* read_callback_ sets the state for us */ + if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if(obj->data_length > 0) { + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length)) + return false; /* read_callback_ sets the state for us */ + } + + return true; +} + +FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder) +{ + FLAC__uint32 x; + unsigned i, skip; + + /* skip the version and flags bytes */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24)) + return false; /* read_callback_ sets the state for us */ + /* get the size (in bytes) to skip */ + skip = 0; + for(i = 0; i < 4; i++) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + skip <<= 7; + skip |= (x & 0x7f); + } + /* skip the rest of the tag */ + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip)) + return false; /* read_callback_ sets the state for us */ + return true; +} + +FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder) +{ + FLAC__uint32 x; + FLAC__bool first = true; + + /* If we know the total number of samples in the stream, stop if we've read that many. */ + /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */ + if(FLAC__stream_decoder_get_total_samples(decoder) > 0) { + if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) { + decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM; + return true; + } + } + + /* make sure we're byte aligned */ + if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input))) + return false; /* read_callback_ sets the state for us */ + } + + while(1) { + if(decoder->private_->cached) { + x = (FLAC__uint32)decoder->private_->lookahead; + decoder->private_->cached = false; + } + else { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + } + if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */ + decoder->private_->header_warmup[0] = (FLAC__byte)x; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + + /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */ + /* else we have to check if the second byte is the end of a sync code */ + if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */ + decoder->private_->lookahead = (FLAC__byte)x; + decoder->private_->cached = true; + } + else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */ + decoder->private_->header_warmup[1] = (FLAC__byte)x; + decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME; + return true; + } + } + if(first) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + first = false; + } + } + + return true; +} + +FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode) +{ + unsigned channel; + unsigned i; + FLAC__int32 mid, side; + unsigned frame_crc; /* the one we calculate from the input stream */ + FLAC__uint32 x; + + *got_a_frame = false; + + /* init the CRC */ + frame_crc = 0; + frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc); + frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc); + FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc); + + if(!read_frame_header_(decoder)) + return false; + if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */ + return true; + if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels)) + return false; + for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) { + /* + * first figure the correct bits-per-sample of the subframe + */ + unsigned bps = decoder->private_->frame.header.bits_per_sample; + switch(decoder->private_->frame.header.channel_assignment) { + case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT: + /* no adjustment needed */ + break; + case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + if(channel == 1) + bps++; + break; + case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + if(channel == 0) + bps++; + break; + case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + if(channel == 1) + bps++; + break; + default: + FLAC__ASSERT(0); + } + /* + * now read it + */ + if(!read_subframe_(decoder, channel, bps, do_full_decode)) + return false; + if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */ + return true; + } + if(!read_zero_padding_(decoder)) + return false; + if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */ + return true; + + /* + * Read the frame CRC-16 from the footer and check + */ + frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input); + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN)) + return false; /* read_callback_ sets the state for us */ + if(frame_crc == x) { + if(do_full_decode) { + /* Undo any special channel coding */ + switch(decoder->private_->frame.header.channel_assignment) { + case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT: + /* do nothing */ + break; + case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) + decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i]; + break; + case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) + decoder->private_->output[0][i] += decoder->private_->output[1][i]; + break; + case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE: + FLAC__ASSERT(decoder->private_->frame.header.channels == 2); + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) { +#if 1 + mid = decoder->private_->output[0][i]; + side = decoder->private_->output[1][i]; + mid <<= 1; + mid |= (side & 1); /* i.e. if 'side' is odd... */ + decoder->private_->output[0][i] = (mid + side) >> 1; + decoder->private_->output[1][i] = (mid - side) >> 1; +#else + /* OPT: without 'side' temp variable */ + mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */ + decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1; + decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1; +#endif + } + break; + default: + FLAC__ASSERT(0); + break; + } + } + } + else { + /* Bad frame, emit error and zero the output signal */ + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH); + if(do_full_decode) { + for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) { + memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize); + } + } + } + + *got_a_frame = true; + + /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */ + if(decoder->private_->next_fixed_block_size) + decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size; + + /* put the latest values into the public section of the decoder instance */ + decoder->protected_->channels = decoder->private_->frame.header.channels; + decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment; + decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample; + decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate; + decoder->protected_->blocksize = decoder->private_->frame.header.blocksize; + + FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); + decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize; + + /* write it */ + if(do_full_decode) { + if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE) + return false; + } + + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; +} + +FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder) +{ + FLAC__uint32 x; + FLAC__uint64 xx; + unsigned i, blocksize_hint = 0, sample_rate_hint = 0; + FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */ + unsigned raw_header_len; + FLAC__bool is_unparseable = false; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + /* init the raw header with the saved bits from synchronization */ + raw_header[0] = decoder->private_->header_warmup[0]; + raw_header[1] = decoder->private_->header_warmup[1]; + raw_header_len = 2; + + /* check to make sure that reserved bit is 0 */ + if(raw_header[1] & 0x02) /* MAGIC NUMBER */ + is_unparseable = true; + + /* + * Note that along the way as we read the header, we look for a sync + * code inside. If we find one it would indicate that our original + * sync was bad since there cannot be a sync code in a valid header. + * + * Three kinds of things can go wrong when reading the frame header: + * 1) We may have sync'ed incorrectly and not landed on a frame header. + * If we don't find a sync code, it can end up looking like we read + * a valid but unparseable header, until getting to the frame header + * CRC. Even then we could get a false positive on the CRC. + * 2) We may have sync'ed correctly but on an unparseable frame (from a + * future encoder). + * 3) We may be on a damaged frame which appears valid but unparseable. + * + * For all these reasons, we try and read a complete frame header as + * long as it seems valid, even if unparseable, up until the frame + * header CRC. + */ + + /* + * read in the raw header as bytes so we can CRC it, and parse it on the way + */ + for(i = 0; i < 2; i++) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */ + /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */ + decoder->private_->lookahead = (FLAC__byte)x; + decoder->private_->cached = true; + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + raw_header[raw_header_len++] = (FLAC__byte)x; + } + + switch(x = raw_header[2] >> 4) { + case 0: + is_unparseable = true; + break; + case 1: + decoder->private_->frame.header.blocksize = 192; + break; + case 2: + case 3: + case 4: + case 5: + decoder->private_->frame.header.blocksize = 576 << (x-2); + break; + case 6: + case 7: + blocksize_hint = x; + break; + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + decoder->private_->frame.header.blocksize = 256 << (x-8); + break; + default: + FLAC__ASSERT(0); + break; + } + + switch(x = raw_header[2] & 0x0f) { + case 0: + if(decoder->private_->has_stream_info) + decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate; + else + is_unparseable = true; + break; + case 1: + decoder->private_->frame.header.sample_rate = 88200; + break; + case 2: + decoder->private_->frame.header.sample_rate = 176400; + break; + case 3: + decoder->private_->frame.header.sample_rate = 192000; + break; + case 4: + decoder->private_->frame.header.sample_rate = 8000; + break; + case 5: + decoder->private_->frame.header.sample_rate = 16000; + break; + case 6: + decoder->private_->frame.header.sample_rate = 22050; + break; + case 7: + decoder->private_->frame.header.sample_rate = 24000; + break; + case 8: + decoder->private_->frame.header.sample_rate = 32000; + break; + case 9: + decoder->private_->frame.header.sample_rate = 44100; + break; + case 10: + decoder->private_->frame.header.sample_rate = 48000; + break; + case 11: + decoder->private_->frame.header.sample_rate = 96000; + break; + case 12: + case 13: + case 14: + sample_rate_hint = x; + break; + case 15: + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + default: + FLAC__ASSERT(0); + } + + x = (unsigned)(raw_header[3] >> 4); + if(x & 8) { + decoder->private_->frame.header.channels = 2; + switch(x & 7) { + case 0: + decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE; + break; + case 1: + decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE; + break; + case 2: + decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE; + break; + default: + is_unparseable = true; + break; + } + } + else { + decoder->private_->frame.header.channels = (unsigned)x + 1; + decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; + } + + switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) { + case 0: + if(decoder->private_->has_stream_info) + decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample; + else + is_unparseable = true; + break; + case 1: + decoder->private_->frame.header.bits_per_sample = 8; + break; + case 2: + decoder->private_->frame.header.bits_per_sample = 12; + break; + case 4: + decoder->private_->frame.header.bits_per_sample = 16; + break; + case 5: + decoder->private_->frame.header.bits_per_sample = 20; + break; + case 6: + decoder->private_->frame.header.bits_per_sample = 24; + break; + case 3: + case 7: + is_unparseable = true; + break; + default: + FLAC__ASSERT(0); + break; + } + + /* check to make sure that reserved bit is 0 */ + if(raw_header[3] & 0x01) /* MAGIC NUMBER */ + is_unparseable = true; + + /* read the frame's starting sample number (or frame number as the case may be) */ + if( + raw_header[1] & 0x01 || + /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */ + (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize) + ) { /* variable blocksize */ + if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len)) + return false; /* read_callback_ sets the state for us */ + if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */ + decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */ + decoder->private_->cached = true; + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER; + decoder->private_->frame.header.number.sample_number = xx; + } + else { /* fixed blocksize */ + if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len)) + return false; /* read_callback_ sets the state for us */ + if(x == 0xffffffff) { /* i.e. non-UTF8 code... */ + decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */ + decoder->private_->cached = true; + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER; + decoder->private_->frame.header.number.frame_number = x; + } + + if(blocksize_hint) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + raw_header[raw_header_len++] = (FLAC__byte)x; + if(blocksize_hint == 7) { + FLAC__uint32 _x; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8)) + return false; /* read_callback_ sets the state for us */ + raw_header[raw_header_len++] = (FLAC__byte)_x; + x = (x << 8) | _x; + } + decoder->private_->frame.header.blocksize = x+1; + } + + if(sample_rate_hint) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + raw_header[raw_header_len++] = (FLAC__byte)x; + if(sample_rate_hint != 12) { + FLAC__uint32 _x; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8)) + return false; /* read_callback_ sets the state for us */ + raw_header[raw_header_len++] = (FLAC__byte)_x; + x = (x << 8) | _x; + } + if(sample_rate_hint == 12) + decoder->private_->frame.header.sample_rate = x*1000; + else if(sample_rate_hint == 13) + decoder->private_->frame.header.sample_rate = x; + else + decoder->private_->frame.header.sample_rate = x*10; + } + + /* read the CRC-8 byte */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) + return false; /* read_callback_ sets the state for us */ + crc8 = (FLAC__byte)x; + + if(FLAC__crc8(raw_header, raw_header_len) != crc8) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + /* calculate the sample number from the frame number if needed */ + decoder->private_->next_fixed_block_size = 0; + if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) { + x = decoder->private_->frame.header.number.frame_number; + decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER; + if(decoder->private_->fixed_block_size) + decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x; + else if(decoder->private_->has_stream_info) { + if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) { + decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x; + decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize; + } + else + is_unparseable = true; + } + else if(x == 0) { + decoder->private_->frame.header.number.sample_number = 0; + decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize; + } + else { + /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */ + decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x; + } + } + + if(is_unparseable) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + return true; +} + +FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode) +{ + FLAC__uint32 x; + FLAC__bool wasted_bits; + unsigned i; + + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */ + return false; /* read_callback_ sets the state for us */ + + wasted_bits = (x & 1); + x &= 0xfe; + + if(wasted_bits) { + unsigned u; + if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->frame.subframes[channel].wasted_bits = u+1; + bps -= decoder->private_->frame.subframes[channel].wasted_bits; + } + else + decoder->private_->frame.subframes[channel].wasted_bits = 0; + + /* + * Lots of magic numbers here + */ + if(x & 0x80) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + else if(x == 0) { + if(!read_subframe_constant_(decoder, channel, bps, do_full_decode)) + return false; + } + else if(x == 2) { + if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode)) + return false; + } + else if(x < 16) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + else if(x <= 24) { + if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode)) + return false; + if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */ + return true; + } + else if(x < 64) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + else { + if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode)) + return false; + if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */ + return true; + } + + if(wasted_bits && do_full_decode) { + x = decoder->private_->frame.subframes[channel].wasted_bits; + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) + decoder->private_->output[channel][i] <<= x; + } + + return true; +} + +FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode) +{ + FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant; + FLAC__int32 x; + unsigned i; + FLAC__int32 *output = decoder->private_->output[channel]; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT; + + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps)) + return false; /* read_callback_ sets the state for us */ + + subframe->value = x; + + /* decode the subframe */ + if(do_full_decode) { + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) + output[i] = x; + } + + return true; +} + +FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode) +{ + FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed; + FLAC__int32 i32; + FLAC__uint32 u32; + unsigned u; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED; + + subframe->residual = decoder->private_->residual[channel]; + subframe->order = order; + + /* read warm-up samples */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps)) + return false; /* read_callback_ sets the state for us */ + subframe->warmup[u] = i32; + } + + /* read entropy coding method info */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.data.partitioned_rice.order = u32; + subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel]; + break; + default: + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + /* read residual */ + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2)) + return false; + break; + default: + FLAC__ASSERT(0); + } + + /* decode the subframe */ + if(do_full_decode) { + memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order); + FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order); + } + + return true; +} + +FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode) +{ + FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc; + FLAC__int32 i32; + FLAC__uint32 u32; + unsigned u; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC; + + subframe->residual = decoder->private_->residual[channel]; + subframe->order = order; + + /* read warm-up samples */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps)) + return false; /* read_callback_ sets the state for us */ + subframe->warmup[u] = i32; + } + + /* read qlp coeff precision */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)) + return false; /* read_callback_ sets the state for us */ + if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + subframe->qlp_coeff_precision = u32+1; + + /* read qlp shift */ + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->quantization_level = i32; + + /* read quantized lp coefficiencts */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision)) + return false; /* read_callback_ sets the state for us */ + subframe->qlp_coeff[u] = i32; + } + + /* read entropy coding method info */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.data.partitioned_rice.order = u32; + subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel]; + break; + default: + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + /* read residual */ + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2)) + return false; + break; + default: + FLAC__ASSERT(0); + } + + /* decode the subframe */ + if(do_full_decode) { + memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order); + /*@@@@@@ technically not pessimistic enough, should be more like + if( (FLAC__uint64)order * ((((FLAC__uint64)1)<qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) ) + */ + if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32) + if(bps <= 16 && subframe->qlp_coeff_precision <= 16) { + if(order <= 8) + decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + } + else + decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + } + + return true; +} + +FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode) +{ + FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim; + FLAC__int32 x, *residual = decoder->private_->residual[channel]; + unsigned i; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM; + + subframe->data = residual; + + for(i = 0; i < decoder->private_->frame.header.blocksize; i++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps)) + return false; /* read_callback_ sets the state for us */ + residual[i] = x; + } + + /* decode the subframe */ + if(do_full_decode) + memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize); + + return true; +} + +FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended) +{ + FLAC__uint32 rice_parameter; + int i; + unsigned partition, sample, u; + const unsigned partitions = 1u << partition_order; + const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order; + const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; + const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; + + /* sanity checks */ + if(partition_order == 0) { + if(decoder->private_->frame.header.blocksize < predictor_order) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + } + else { + if(partition_samples < predictor_order) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + } + + if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + sample = 0; + for(partition = 0; partition < partitions; partition++) { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen)) + return false; /* read_callback_ sets the state for us */ + partitioned_rice_contents->parameters[partition] = rice_parameter; + if(rice_parameter < pesc) { + partitioned_rice_contents->raw_bits[partition] = 0; + u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order; + if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter)) + return false; /* read_callback_ sets the state for us */ + sample += u; + } + else { + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN)) + return false; /* read_callback_ sets the state for us */ + partitioned_rice_contents->raw_bits[partition] = rice_parameter; + for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter)) + return false; /* read_callback_ sets the state for us */ + residual[sample] = i; + } + } + } + + return true; +} + +FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder) +{ + if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) { + FLAC__uint32 zero = 0; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input))) + return false; /* read_callback_ sets the state for us */ + if(zero != 0) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + } + } + return true; +} + +FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data; + + if( +#if FLAC__HAS_OGG + /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */ + !decoder->private_->is_ogg && +#endif + decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data) + ) { + *bytes = 0; + decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM; + return false; + } + else if(*bytes > 0) { + /* While seeking, it is possible for our seek to land in the + * middle of audio data that looks exactly like a frame header + * from a future version of an encoder. When that happens, our + * error callback will get an + * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its + * unparseable_frame_count. But there is a remote possibility + * that it is properly synced at such a "future-codec frame", + * so to make sure, we wait to see many "unparseable" errors in + * a row before bailing out. + */ + if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) { + decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED; + return false; + } + else { + const FLAC__StreamDecoderReadStatus status = +#if FLAC__HAS_OGG + decoder->private_->is_ogg? + read_callback_ogg_aspect_(decoder, buffer, bytes) : +#endif + decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data) + ; + if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) { + decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED; + return false; + } + else if(*bytes == 0) { + if( + status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM || + ( +#if FLAC__HAS_OGG + /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */ + !decoder->private_->is_ogg && +#endif + decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data) + ) + ) { + decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM; + return false; + } + else + return true; + } + else + return true; + } + } + else { + /* abort to avoid a deadlock */ + decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED; + return false; + } + /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around + * for Ogg FLAC. This is because the ogg decoder aspect can lose sync + * and at the same time hit the end of the stream (for example, seeking + * to a point that is after the beginning of the last Ogg page). There + * is no way to report an Ogg sync loss through the callbacks (see note + * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0. + * So to keep the decoder from stopping at this point we gate the call + * to the eof_callback and let the Ogg decoder aspect set the + * end-of-stream state when it is needed. + */ +} + +#if FLAC__HAS_OGG +FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes) +{ + switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) { + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK: + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + /* we don't really have a way to handle lost sync via read + * callback so we'll let it pass and let the underlying + * FLAC decoder catch the error + */ + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC: + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM: + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC: + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION: + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT: + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR: + case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR: + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + default: + FLAC__ASSERT(0); + /* double protection */ + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + } +} + +FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder; + + switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) { + case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE: + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK; + case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM: + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM; + case FLAC__STREAM_DECODER_READ_STATUS_ABORT: + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT; + default: + /* double protection: */ + FLAC__ASSERT(0); + return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT; + } +} +#endif + +FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]) +{ + if(decoder->private_->is_seeking) { + FLAC__uint64 this_frame_sample = frame->header.number.sample_number; + FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize; + FLAC__uint64 target_sample = decoder->private_->target_sample; + + FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); + +#if FLAC__HAS_OGG + decoder->private_->got_a_frame = true; +#endif + decoder->private_->last_frame = *frame; /* save the frame */ + if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */ + unsigned delta = (unsigned)(target_sample - this_frame_sample); + /* kick out of seek mode */ + decoder->private_->is_seeking = false; + /* shift out the samples before target_sample */ + if(delta > 0) { + unsigned channel; + const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS]; + for(channel = 0; channel < frame->header.channels; channel++) + newbuffer[channel] = buffer[channel] + delta; + decoder->private_->last_frame.header.blocksize -= delta; + decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta; + /* write the relevant samples */ + return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data); + } + else { + /* write the relevant samples */ + return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data); + } + } + else { + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; + } + } + else { + /* + * If we never got STREAMINFO, turn off MD5 checking to save + * cycles since we don't have a sum to compare to anyway + */ + if(!decoder->private_->has_stream_info) + decoder->private_->do_md5_checking = false; + if(decoder->private_->do_md5_checking) { + if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8)) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data); + } +} + +void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status) +{ + if(!decoder->private_->is_seeking) + decoder->private_->error_callback(decoder, status, decoder->private_->client_data); + else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM) + decoder->private_->unparseable_frame_count++; +} + +FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample) +{ + FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample; + FLAC__int64 pos = -1; + int i; + unsigned approx_bytes_per_frame; + FLAC__bool first_seek = true; + const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder); + const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize; + const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize; + const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize; + const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize; + /* take these from the current frame in case they've changed mid-stream */ + unsigned channels = FLAC__stream_decoder_get_channels(decoder); + unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder); + const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0; + + /* use values from stream info if we didn't decode a frame */ + if(channels == 0) + channels = decoder->private_->stream_info.data.stream_info.channels; + if(bps == 0) + bps = decoder->private_->stream_info.data.stream_info.bits_per_sample; + + /* we are just guessing here */ + if(max_framesize > 0) + approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1; + /* + * Check if it's a known fixed-blocksize stream. Note that though + * the spec doesn't allow zeroes in the STREAMINFO block, we may + * never get a STREAMINFO block when decoding so the value of + * min_blocksize might be zero. + */ + else if(min_blocksize == max_blocksize && min_blocksize > 0) { + /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */ + approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64; + } + else + approx_bytes_per_frame = 4096 * channels * bps/8 + 64; + + /* + * First, we set an upper and lower bound on where in the + * stream we will search. For now we assume the worst case + * scenario, which is our best guess at the beginning of + * the first frame and end of the stream. + */ + lower_bound = first_frame_offset; + lower_bound_sample = 0; + upper_bound = stream_length; + upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/; + + /* + * Now we refine the bounds if we have a seektable with + * suitable points. Note that according to the spec they + * must be ordered by ascending sample number. + * + * Note: to protect against invalid seek tables we will ignore points + * that have frame_samples==0 or sample_number>=total_samples + */ + if(seek_table) { + FLAC__uint64 new_lower_bound = lower_bound; + FLAC__uint64 new_upper_bound = upper_bound; + FLAC__uint64 new_lower_bound_sample = lower_bound_sample; + FLAC__uint64 new_upper_bound_sample = upper_bound_sample; + + /* find the closest seek point <= target_sample, if it exists */ + for(i = (int)seek_table->num_points - 1; i >= 0; i--) { + if( + seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && + seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */ + (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */ + seek_table->points[i].sample_number <= target_sample + ) + break; + } + if(i >= 0) { /* i.e. we found a suitable seek point... */ + new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset; + new_lower_bound_sample = seek_table->points[i].sample_number; + } + + /* find the closest seek point > target_sample, if it exists */ + for(i = 0; i < (int)seek_table->num_points; i++) { + if( + seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && + seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */ + (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */ + seek_table->points[i].sample_number > target_sample + ) + break; + } + if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */ + new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset; + new_upper_bound_sample = seek_table->points[i].sample_number; + } + /* final protection against unsorted seek tables; keep original values if bogus */ + if(new_upper_bound >= new_lower_bound) { + lower_bound = new_lower_bound; + upper_bound = new_upper_bound; + lower_bound_sample = new_lower_bound_sample; + upper_bound_sample = new_upper_bound_sample; + } + } + + FLAC__ASSERT(upper_bound_sample >= lower_bound_sample); + /* there are 2 insidious ways that the following equality occurs, which + * we need to fix: + * 1) total_samples is 0 (unknown) and target_sample is 0 + * 2) total_samples is 0 (unknown) and target_sample happens to be + * exactly equal to the last seek point in the seek table; this + * means there is no seek point above it, and upper_bound_samples + * remains equal to the estimate (of target_samples) we made above + * in either case it does not hurt to move upper_bound_sample up by 1 + */ + if(upper_bound_sample == lower_bound_sample) + upper_bound_sample++; + + decoder->private_->target_sample = target_sample; + while(1) { + /* check if the bounds are still ok */ + if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if defined _MSC_VER || defined __MINGW32__ + /* with VC++ you have to spoon feed it the casting */ + pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame; +#else + pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame; +#endif +#else + /* a little less accurate: */ + if(upper_bound - lower_bound < 0xffffffff) + pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame; + else /* @@@ WATCHOUT, ~2TB limit */ + pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame; +#endif + if(pos >= (FLAC__int64)upper_bound) + pos = (FLAC__int64)upper_bound - 1; + if(pos < (FLAC__int64)lower_bound) + pos = (FLAC__int64)lower_bound; + if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + if(!FLAC__stream_decoder_flush(decoder)) { + /* above call sets the state for us */ + return false; + } + /* Now we need to get a frame. First we need to reset our + * unparseable_frame_count; if we get too many unparseable + * frames in a row, the read callback will return + * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing + * FLAC__stream_decoder_process_single() to return false. + */ + decoder->private_->unparseable_frame_count = 0; + if(!FLAC__stream_decoder_process_single(decoder)) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + /* our write callback will change the state when it gets to the target frame */ + /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */ +#if 0 + /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */ + if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM) + break; +#endif + if(!decoder->private_->is_seeking) + break; + + FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); + this_frame_sample = decoder->private_->last_frame.header.number.sample_number; + + if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) { + if (pos == (FLAC__int64)lower_bound) { + /* can't move back any more than the first frame, something is fatally wrong */ + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + /* our last move backwards wasn't big enough, try again */ + approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16; + continue; + } + /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */ + first_seek = false; + + /* make sure we are not seeking in corrupted stream */ + if (this_frame_sample < lower_bound_sample) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + + /* we need to narrow the search */ + if(target_sample < this_frame_sample) { + upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize; +/*@@@@@@ what will decode position be if at end of stream? */ + if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16); + } + else { /* target_sample >= this_frame_sample + this frame's blocksize */ + lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize; + if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16); + } + } + + return true; +} + +#if FLAC__HAS_OGG +FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample) +{ + FLAC__uint64 left_pos = 0, right_pos = stream_length; + FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder); + FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1; + FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */ + FLAC__bool did_a_seek; + unsigned iteration = 0; + + /* In the first iterations, we will calculate the target byte position + * by the distance from the target sample to left_sample and + * right_sample (let's call it "proportional search"). After that, we + * will switch to binary search. + */ + unsigned BINARY_SEARCH_AFTER_ITERATION = 2; + + /* We will switch to a linear search once our current sample is less + * than this number of samples ahead of the target sample + */ + static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2; + + /* If the total number of samples is unknown, use a large value, and + * force binary search immediately. + */ + if(right_sample == 0) { + right_sample = (FLAC__uint64)(-1); + BINARY_SEARCH_AFTER_ITERATION = 0; + } + + decoder->private_->target_sample = target_sample; + for( ; ; iteration++) { + if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) { + if (iteration >= BINARY_SEARCH_AFTER_ITERATION) { + pos = (right_pos + left_pos) / 2; + } + else { +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if defined _MSC_VER || defined __MINGW32__ + /* with MSVC you have to spoon feed it the casting */ + pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos)); +#else + pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos)); +#endif +#else + /* a little less accurate: */ + if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff)) + pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample)); + else /* @@@ WATCHOUT, ~2TB limit */ + pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16)); +#endif + /* @@@ TODO: might want to limit pos to some distance + * before EOF, to make sure we land before the last frame, + * thereby getting a this_frame_sample and so having a better + * estimate. + */ + } + + /* physical seek */ + if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + if(!FLAC__stream_decoder_flush(decoder)) { + /* above call sets the state for us */ + return false; + } + did_a_seek = true; + } + else + did_a_seek = false; + + decoder->private_->got_a_frame = false; + if(!FLAC__stream_decoder_process_single(decoder)) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + if(!decoder->private_->got_a_frame) { + if(did_a_seek) { + /* this can happen if we seek to a point after the last frame; we drop + * to binary search right away in this case to avoid any wasted + * iterations of proportional search. + */ + right_pos = pos; + BINARY_SEARCH_AFTER_ITERATION = 0; + } + else { + /* this can probably only happen if total_samples is unknown and the + * target_sample is past the end of the stream + */ + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + } + /* our write callback will change the state when it gets to the target frame */ + else if(!decoder->private_->is_seeking) { + break; + } + else { + this_frame_sample = decoder->private_->last_frame.header.number.sample_number; + FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); + + if (did_a_seek) { + if (this_frame_sample <= target_sample) { + /* The 'equal' case should not happen, since + * FLAC__stream_decoder_process_single() + * should recognize that it has hit the + * target sample and we would exit through + * the 'break' above. + */ + FLAC__ASSERT(this_frame_sample != target_sample); + + left_sample = this_frame_sample; + /* sanity check to avoid infinite loop */ + if (left_pos == pos) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + left_pos = pos; + } + else if(this_frame_sample > target_sample) { + right_sample = this_frame_sample; + /* sanity check to avoid infinite loop */ + if (right_pos == pos) { + decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR; + return false; + } + right_pos = pos; + } + } + } + } + + return true; +} +#endif + +FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + (void)client_data; + + if(*bytes > 0) { + *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file); + if(ferror(decoder->private_->file)) + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + else if(*bytes == 0) + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + else + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */ +} + +FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) +{ + (void)client_data; + + if(decoder->private_->file == stdin) + return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; + else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0) + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + else + return FLAC__STREAM_DECODER_SEEK_STATUS_OK; +} + +FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) +{ + off_t pos; + (void)client_data; + + if(decoder->private_->file == stdin) + return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; + else if((pos = ftello(decoder->private_->file)) < 0) + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + else { + *absolute_byte_offset = (FLAC__uint64)pos; + return FLAC__STREAM_DECODER_TELL_STATUS_OK; + } +} + +FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) +{ + struct stat filestats; + (void)client_data; + + if(decoder->private_->file == stdin) + return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; + else if(fstat(fileno(decoder->private_->file), &filestats) != 0) + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + else { + *stream_length = (FLAC__uint64)filestats.st_size; + return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; + } +} + +FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data) +{ + (void)client_data; + + return feof(decoder->private_->file)? true : false; +} diff --git a/flac/src/libFLAC/stream_encoder.c b/flac/src/libFLAC/stream_encoder.c new file mode 100644 index 0000000..dc1ae9f --- /dev/null +++ b/flac/src/libFLAC/stream_encoder.c @@ -0,0 +1,4346 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#include /* for _setmode() */ +#include /* for _O_BINARY */ +#endif +#if defined __CYGWIN__ || defined __EMX__ +#include /* for setmode(), O_BINARY */ +#include /* for _O_BINARY */ +#endif +#include +#include +#include /* for malloc() */ +#include /* for memcpy() */ +#include /* for off_t */ +#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ +#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include "FLAC/assert.h" +#include "FLAC/stream_decoder.h" +#include "share/alloc.h" +#include "protected/stream_encoder.h" +#include "private/bitwriter.h" +#include "private/bitmath.h" +#include "private/crc.h" +#include "private/cpu.h" +#include "private/fixed.h" +#include "private/format.h" +#include "private/lpc.h" +#include "private/md5.h" +#include "private/memory.h" +#if FLAC__HAS_OGG +#include "private/ogg_helper.h" +#include "private/ogg_mapping.h" +#endif +#include "private/stream_encoder_framing.h" +#include "private/window.h" + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) + +#ifdef max +#undef max +#endif +#define max(x,y) ((x)>(y)?(x):(y)) + +/* Exact Rice codeword length calculation is off by default. The simple + * (and fast) estimation (of how many bits a residual value will be + * encoded with) in this encoder is very good, almost always yielding + * compression within 0.1% of exact calculation. + */ +#undef EXACT_RICE_BITS_CALCULATION +/* Rice parameter searching is off by default. The simple (and fast) + * parameter estimation in this encoder is very good, almost always + * yielding compression within 0.1% of the optimal parameters. + */ +#undef ENABLE_RICE_PARAMETER_SEARCH + + +typedef struct { + FLAC__int32 *data[FLAC__MAX_CHANNELS]; + unsigned size; /* of each data[] in samples */ + unsigned tail; +} verify_input_fifo; + +typedef struct { + const FLAC__byte *data; + unsigned capacity; + unsigned bytes; +} verify_output; + +typedef enum { + ENCODER_IN_MAGIC = 0, + ENCODER_IN_METADATA = 1, + ENCODER_IN_AUDIO = 2 +} EncoderStateHint; + +static struct CompressionLevels { + FLAC__bool do_mid_side_stereo; + FLAC__bool loose_mid_side_stereo; + unsigned max_lpc_order; + unsigned qlp_coeff_precision; + FLAC__bool do_qlp_coeff_prec_search; + FLAC__bool do_escape_coding; + FLAC__bool do_exhaustive_model_search; + unsigned min_residual_partition_order; + unsigned max_residual_partition_order; + unsigned rice_parameter_search_dist; +} compression_levels_[] = { + { false, false, 0, 0, false, false, false, 0, 3, 0 }, + { true , true , 0, 0, false, false, false, 0, 3, 0 }, + { true , false, 0, 0, false, false, false, 0, 3, 0 }, + { false, false, 6, 0, false, false, false, 0, 4, 0 }, + { true , true , 8, 0, false, false, false, 0, 4, 0 }, + { true , false, 8, 0, false, false, false, 0, 5, 0 }, + { true , false, 8, 0, false, false, false, 0, 6, 0 }, + { true , false, 8, 0, false, false, true , 0, 6, 0 }, + { true , false, 12, 0, false, false, true , 0, 6, 0 } +}; + + +/*********************************************************************** + * + * Private class method prototypes + * + ***********************************************************************/ + +static void set_defaults_(FLAC__StreamEncoder *encoder); +static void free_(FLAC__StreamEncoder *encoder); +static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize); +static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block); +static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block); +static void update_metadata_(const FLAC__StreamEncoder *encoder); +#if FLAC__HAS_OGG +static void update_ogg_metadata_(FLAC__StreamEncoder *encoder); +#endif +static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block); +static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block); + +static FLAC__bool process_subframe_( + FLAC__StreamEncoder *encoder, + unsigned min_partition_order, + unsigned max_partition_order, + const FLAC__FrameHeader *frame_header, + unsigned subframe_bps, + const FLAC__int32 integer_signal[], + FLAC__Subframe *subframe[2], + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2], + FLAC__int32 *residual[2], + unsigned *best_subframe, + unsigned *best_bits +); + +static FLAC__bool add_subframe_( + FLAC__StreamEncoder *encoder, + unsigned blocksize, + unsigned subframe_bps, + const FLAC__Subframe *subframe, + FLAC__BitWriter *frame +); + +static unsigned evaluate_constant_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal, + unsigned blocksize, + unsigned subframe_bps, + FLAC__Subframe *subframe +); + +static unsigned evaluate_fixed_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + unsigned blocksize, + unsigned subframe_bps, + unsigned order, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__Subframe *subframe, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents +); + +#ifndef FLAC__INTEGER_ONLY_LIBRARY +static unsigned evaluate_lpc_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + const FLAC__real lp_coeff[], + unsigned blocksize, + unsigned subframe_bps, + unsigned order, + unsigned qlp_coeff_precision, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__Subframe *subframe, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents +); +#endif + +static unsigned evaluate_verbatim_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + unsigned blocksize, + unsigned subframe_bps, + FLAC__Subframe *subframe +); + +static unsigned find_best_partition_order_( + struct FLAC__StreamEncoderPrivate *private_, + const FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + unsigned residual_samples, + unsigned predictor_order, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + unsigned bps, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__EntropyCodingMethod *best_ecm +); + +static void precompute_partition_info_sums_( + const FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned residual_samples, + unsigned predictor_order, + unsigned min_partition_order, + unsigned max_partition_order, + unsigned bps +); + +static void precompute_partition_info_escapes_( + const FLAC__int32 residual[], + unsigned raw_bits_per_partition[], + unsigned residual_samples, + unsigned predictor_order, + unsigned min_partition_order, + unsigned max_partition_order +); + +static FLAC__bool set_partitioned_rice_( +#ifdef EXACT_RICE_BITS_CALCULATION + const FLAC__int32 residual[], +#endif + const FLAC__uint64 abs_residual_partition_sums[], + const unsigned raw_bits_per_partition[], + const unsigned residual_samples, + const unsigned predictor_order, + const unsigned suggested_rice_parameter, + const unsigned rice_parameter_limit, + const unsigned rice_parameter_search_dist, + const unsigned partition_order, + const FLAC__bool search_for_escapes, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, + unsigned *bits +); + +static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples); + +/* verify-related routines: */ +static void append_to_verify_fifo_( + verify_input_fifo *fifo, + const FLAC__int32 * const input[], + unsigned input_offset, + unsigned channels, + unsigned wide_samples +); + +static void append_to_verify_fifo_interleaved_( + verify_input_fifo *fifo, + const FLAC__int32 input[], + unsigned input_offset, + unsigned channels, + unsigned wide_samples +); + +static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + +static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data); +static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data); +static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data); +static FILE *get_binary_stdout_(void); + + +/*********************************************************************** + * + * Private class data + * + ***********************************************************************/ + +typedef struct FLAC__StreamEncoderPrivate { + unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */ + FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */ + FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY + FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */ + FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */ + FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */ + FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */ +#endif + unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */ + unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */ + FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */ + FLAC__int32 *residual_workspace_mid_side[2][2]; + FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2]; + FLAC__Subframe subframe_workspace_mid_side[2][2]; + FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2]; + FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2]; + FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2]; + FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2]; + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2]; + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2]; + unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */ + unsigned best_subframe_mid_side[2]; + unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */ + unsigned best_subframe_bits_mid_side[2]; + FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */ + unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */ + FLAC__BitWriter *frame; /* the current frame being worked on */ + unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */ + unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */ + FLAC__ChannelAssignment last_channel_assignment; + FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */ + FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */ + unsigned current_sample_number; + unsigned current_frame_number; + FLAC__MD5Context md5context; + FLAC__CPUInfo cpuinfo; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +#else + unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]); +#endif +#ifndef FLAC__INTEGER_ONLY_LIBRARY + void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]); + void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); + void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); + void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]); +#endif + FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */ + FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */ + FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */ + FLAC__bool disable_constant_subframes; + FLAC__bool disable_fixed_subframes; + FLAC__bool disable_verbatim_subframes; +#if FLAC__HAS_OGG + FLAC__bool is_ogg; +#endif + FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */ + FLAC__StreamEncoderSeekCallback seek_callback; + FLAC__StreamEncoderTellCallback tell_callback; + FLAC__StreamEncoderWriteCallback write_callback; + FLAC__StreamEncoderMetadataCallback metadata_callback; + FLAC__StreamEncoderProgressCallback progress_callback; + void *client_data; + unsigned first_seekpoint_to_check; + FILE *file; /* only used when encoding to a file */ + FLAC__uint64 bytes_written; + FLAC__uint64 samples_written; + unsigned frames_written; + unsigned total_frames_estimate; + /* unaligned (original) pointers to allocated data */ + FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS]; + FLAC__int32 *integer_signal_mid_side_unaligned[2]; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */ + FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */ + FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS]; + FLAC__real *windowed_signal_unaligned; +#endif + FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2]; + FLAC__int32 *residual_workspace_mid_side_unaligned[2][2]; + FLAC__uint64 *abs_residual_partition_sums_unaligned; + unsigned *raw_bits_per_partition_unaligned; + /* + * These fields have been moved here from private function local + * declarations merely to save stack space during encoding. + */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY + FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */ +#endif + FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */ + /* + * The data for the verify section + */ + struct { + FLAC__StreamDecoder *decoder; + EncoderStateHint state_hint; + FLAC__bool needs_magic_hack; + verify_input_fifo input_fifo; + verify_output output; + struct { + FLAC__uint64 absolute_sample; + unsigned frame_number; + unsigned channel; + unsigned sample; + FLAC__int32 expected; + FLAC__int32 got; + } error_stats; + } verify; + FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */ +} FLAC__StreamEncoderPrivate; + +/*********************************************************************** + * + * Public static class data + * + ***********************************************************************/ + +FLAC_API const char * const FLAC__StreamEncoderStateString[] = { + "FLAC__STREAM_ENCODER_OK", + "FLAC__STREAM_ENCODER_UNINITIALIZED", + "FLAC__STREAM_ENCODER_OGG_ERROR", + "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR", + "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA", + "FLAC__STREAM_ENCODER_CLIENT_ERROR", + "FLAC__STREAM_ENCODER_IO_ERROR", + "FLAC__STREAM_ENCODER_FRAMING_ERROR", + "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR" +}; + +FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = { + "FLAC__STREAM_ENCODER_INIT_STATUS_OK", + "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR", + "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION", + "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER", + "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE", + "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA", + "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED" +}; + +FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = { + "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE", + "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM", + "FLAC__STREAM_ENCODER_READ_STATUS_ABORT", + "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED" +}; + +FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = { + "FLAC__STREAM_ENCODER_WRITE_STATUS_OK", + "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR" +}; + +FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = { + "FLAC__STREAM_ENCODER_SEEK_STATUS_OK", + "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR", + "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED" +}; + +FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = { + "FLAC__STREAM_ENCODER_TELL_STATUS_OK", + "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR", + "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED" +}; + +/* Number of samples that will be overread to watch for end of stream. By + * 'overread', we mean that the FLAC__stream_encoder_process*() calls will + * always try to read blocksize+1 samples before encoding a block, so that + * even if the stream has a total sample count that is an integral multiple + * of the blocksize, we will still notice when we are encoding the last + * block. This is needed, for example, to correctly set the end-of-stream + * marker in Ogg FLAC. + * + * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's + * not really any reason to change it. + */ +static const unsigned OVERREAD_ = 1; + +/*********************************************************************** + * + * Class constructor/destructor + * + */ +FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void) +{ + FLAC__StreamEncoder *encoder; + unsigned i; + + FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */ + + encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder)); + if(encoder == 0) { + return 0; + } + + encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected)); + if(encoder->protected_ == 0) { + free(encoder); + return 0; + } + + encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate)); + if(encoder->private_ == 0) { + free(encoder->protected_); + free(encoder); + return 0; + } + + encoder->private_->frame = FLAC__bitwriter_new(); + if(encoder->private_->frame == 0) { + free(encoder->private_); + free(encoder->protected_); + free(encoder); + return 0; + } + + encoder->private_->file = 0; + + set_defaults_(encoder); + + encoder->private_->is_being_deleted = false; + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0]; + encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1]; + } + for(i = 0; i < 2; i++) { + encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0]; + encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1]; + } + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0]; + encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1]; + } + for(i = 0; i < 2; i++) { + encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]; + encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]; + } + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]); + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]); + } + for(i = 0; i < 2; i++) { + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]); + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]); + } + for(i = 0; i < 2; i++) + FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]); + + encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED; + + return encoder; +} + +FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder) +{ + unsigned i; + + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->protected_); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->private_->frame); + + encoder->private_->is_being_deleted = true; + + (void)FLAC__stream_encoder_finish(encoder); + + if(0 != encoder->private_->verify.decoder) + FLAC__stream_decoder_delete(encoder->private_->verify.decoder); + + for(i = 0; i < FLAC__MAX_CHANNELS; i++) { + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]); + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]); + } + for(i = 0; i < 2; i++) { + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]); + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]); + } + for(i = 0; i < 2; i++) + FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]); + + FLAC__bitwriter_delete(encoder->private_->frame); + free(encoder->private_); + free(encoder->protected_); + free(encoder); +} + +/*********************************************************************** + * + * Public class methods + * + ***********************************************************************/ + +static FLAC__StreamEncoderInitStatus init_stream_internal_( + FLAC__StreamEncoder *encoder, + FLAC__StreamEncoderReadCallback read_callback, + FLAC__StreamEncoderWriteCallback write_callback, + FLAC__StreamEncoderSeekCallback seek_callback, + FLAC__StreamEncoderTellCallback tell_callback, + FLAC__StreamEncoderMetadataCallback metadata_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + unsigned i; + FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2; + + FLAC__ASSERT(0 != encoder); + + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED; + +#if !FLAC__HAS_OGG + if(is_ogg) + return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER; +#endif + + if(0 == write_callback || (seek_callback && 0 == tell_callback)) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS; + + if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS; + + if(encoder->protected_->channels != 2) { + encoder->protected_->do_mid_side_stereo = false; + encoder->protected_->loose_mid_side_stereo = false; + } + else if(!encoder->protected_->do_mid_side_stereo) + encoder->protected_->loose_mid_side_stereo = false; + + if(encoder->protected_->bits_per_sample >= 32) + encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */ + + if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE; + + if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate)) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE; + + if(encoder->protected_->blocksize == 0) { + if(encoder->protected_->max_lpc_order == 0) + encoder->protected_->blocksize = 1152; + else + encoder->protected_->blocksize = 4096; + } + + if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE; + + if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER; + + if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order) + return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER; + + if(encoder->protected_->qlp_coeff_precision == 0) { + if(encoder->protected_->bits_per_sample < 16) { + /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */ + /* @@@ until then we'll make a guess */ + encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2); + } + else if(encoder->protected_->bits_per_sample == 16) { + if(encoder->protected_->blocksize <= 192) + encoder->protected_->qlp_coeff_precision = 7; + else if(encoder->protected_->blocksize <= 384) + encoder->protected_->qlp_coeff_precision = 8; + else if(encoder->protected_->blocksize <= 576) + encoder->protected_->qlp_coeff_precision = 9; + else if(encoder->protected_->blocksize <= 1152) + encoder->protected_->qlp_coeff_precision = 10; + else if(encoder->protected_->blocksize <= 2304) + encoder->protected_->qlp_coeff_precision = 11; + else if(encoder->protected_->blocksize <= 4608) + encoder->protected_->qlp_coeff_precision = 12; + else + encoder->protected_->qlp_coeff_precision = 13; + } + else { + if(encoder->protected_->blocksize <= 384) + encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2; + else if(encoder->protected_->blocksize <= 1152) + encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1; + else + encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION; + } + FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION); + } + else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION; + + if(encoder->protected_->streamable_subset) { + if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate)) + return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE; + if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate)) + return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE; + if( + encoder->protected_->bits_per_sample != 8 && + encoder->protected_->bits_per_sample != 12 && + encoder->protected_->bits_per_sample != 16 && + encoder->protected_->bits_per_sample != 20 && + encoder->protected_->bits_per_sample != 24 + ) + return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE; + if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER) + return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE; + if( + encoder->protected_->sample_rate <= 48000 && + ( + encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ || + encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ + ) + ) { + return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE; + } + } + + if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1; + if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order) + encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order; + +#if FLAC__HAS_OGG + /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */ + if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) { + unsigned i; + for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) { + if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + FLAC__StreamMetadata *vc = encoder->protected_->metadata[i]; + for( ; i > 0; i--) + encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1]; + encoder->protected_->metadata[0] = vc; + break; + } + } + } +#endif + /* keep track of any SEEKTABLE block */ + if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) { + unsigned i; + for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) { + if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) { + encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table; + break; /* take only the first one */ + } + } + } + + /* validate metadata */ + if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + metadata_has_seektable = false; + metadata_has_vorbis_comment = false; + metadata_picture_has_type1 = false; + metadata_picture_has_type2 = false; + for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) { + const FLAC__StreamMetadata *m = encoder->protected_->metadata[i]; + if(m->type == FLAC__METADATA_TYPE_STREAMINFO) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) { + if(metadata_has_seektable) /* only one is allowed */ + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + metadata_has_seektable = true; + if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + } + else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + if(metadata_has_vorbis_comment) /* only one is allowed */ + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + metadata_has_vorbis_comment = true; + } + else if(m->type == FLAC__METADATA_TYPE_CUESHEET) { + if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + } + else if(m->type == FLAC__METADATA_TYPE_PICTURE) { + if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0)) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) { + if(metadata_picture_has_type1) /* there should only be 1 per stream */ + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + metadata_picture_has_type1 = true; + /* standard icon must be 32x32 pixel PNG */ + if( + m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD && + ( + (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) || + m->data.picture.width != 32 || + m->data.picture.height != 32 + ) + ) + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + } + else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) { + if(metadata_picture_has_type2) /* there should only be 1 per stream */ + return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA; + metadata_picture_has_type2 = true; + } + } + } + + encoder->private_->input_capacity = 0; + for(i = 0; i < encoder->protected_->channels; i++) { + encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0; +#endif + } + for(i = 0; i < 2; i++) { + encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0; +#endif + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY + for(i = 0; i < encoder->protected_->num_apodizations; i++) + encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0; + encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0; +#endif + for(i = 0; i < encoder->protected_->channels; i++) { + encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0; + encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0; + encoder->private_->best_subframe[i] = 0; + } + for(i = 0; i < 2; i++) { + encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0; + encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0; + encoder->private_->best_subframe_mid_side[i] = 0; + } + encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0; + encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5); +#else + /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */ + /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */ + FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350); + FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535); + FLAC__ASSERT(encoder->protected_->sample_rate <= 655350); + FLAC__ASSERT(encoder->protected_->blocksize <= 65535); + encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF); +#endif + if(encoder->private_->loose_mid_side_stereo_frames == 0) + encoder->private_->loose_mid_side_stereo_frames = 1; + encoder->private_->loose_mid_side_stereo_frame_count = 0; + encoder->private_->current_sample_number = 0; + encoder->private_->current_frame_number = 0; + + encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30); + encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */ + encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */ + + /* + * get the CPU info and set the function pointers + */ + FLAC__cpu_info(&encoder->private_->cpuinfo); + /* first default to the non-asm routines */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation; +#endif + encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients; + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide; + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients; +#endif + /* now override with asm where appropriate */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY +# ifndef FLAC__NO_ASM + if(encoder->private_->cpuinfo.use_asm) { +# ifdef FLAC__CPU_IA32 + FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32); +# ifdef FLAC__HAS_NASM + if(encoder->private_->cpuinfo.data.ia32.sse) { + if(encoder->protected_->max_lpc_order < 4) + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4; + else if(encoder->protected_->max_lpc_order < 8) + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8; + else if(encoder->protected_->max_lpc_order < 12) + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12; + else + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32; + } + else if(encoder->private_->cpuinfo.data.ia32._3dnow) + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow; + else + encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32; + if(encoder->private_->cpuinfo.data.ia32.mmx) { + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32; + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx; + } + else { + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32; + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32; + } + if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov) + encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov; +# endif /* FLAC__HAS_NASM */ +# endif /* FLAC__CPU_IA32 */ + } +# endif /* !FLAC__NO_ASM */ +#endif /* !FLAC__INTEGER_ONLY_LIBRARY */ + /* finally override based on wide-ness if necessary */ + if(encoder->private_->use_wide_by_block) { + encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide; + } + + /* set state to OK; from here on, errors are fatal and we'll override the state then */ + encoder->protected_->state = FLAC__STREAM_ENCODER_OK; + +#if FLAC__HAS_OGG + encoder->private_->is_ogg = is_ogg; + if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } +#endif + + encoder->private_->read_callback = read_callback; + encoder->private_->write_callback = write_callback; + encoder->private_->seek_callback = seek_callback; + encoder->private_->tell_callback = tell_callback; + encoder->private_->metadata_callback = metadata_callback; + encoder->private_->client_data = client_data; + + if(!resize_buffers_(encoder, encoder->protected_->blocksize)) { + /* the above function sets the state for us in case of an error */ + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + if(!FLAC__bitwriter_init(encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + /* + * Set up the verify stuff if necessary + */ + if(encoder->protected_->verify) { + /* + * First, set up the fifo which will hold the + * original signal to compare against + */ + encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_; + for(i = 0; i < encoder->protected_->channels; i++) { + if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + } + encoder->private_->verify.input_fifo.tail = 0; + + /* + * Now set up a stream decoder for verification + */ + encoder->private_->verify.decoder = FLAC__stream_decoder_new(); + if(0 == encoder->private_->verify.decoder) { + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + } + encoder->private_->verify.error_stats.absolute_sample = 0; + encoder->private_->verify.error_stats.frame_number = 0; + encoder->private_->verify.error_stats.channel = 0; + encoder->private_->verify.error_stats.sample = 0; + encoder->private_->verify.error_stats.expected = 0; + encoder->private_->verify.error_stats.got = 0; + + /* + * These must be done before we write any metadata, because that + * calls the write_callback, which uses these values. + */ + encoder->private_->first_seekpoint_to_check = 0; + encoder->private_->samples_written = 0; + encoder->protected_->streaminfo_offset = 0; + encoder->protected_->seektable_offset = 0; + encoder->protected_->audio_offset = 0; + + /* + * write the stream header + */ + if(encoder->protected_->verify) + encoder->private_->verify.state_hint = ENCODER_IN_MAGIC; + if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) { + /* the above function sets the state for us in case of an error */ + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + /* + * write the STREAMINFO metadata block + */ + if(encoder->protected_->verify) + encoder->private_->verify.state_hint = ENCODER_IN_METADATA; + encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO; + encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */ + encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */ + encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize; + encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */ + encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */ + encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate; + encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels; + encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample; + encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */ + memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */ + if(encoder->protected_->do_md5) + FLAC__MD5Init(&encoder->private_->md5context); + if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) { + /* the above function sets the state for us in case of an error */ + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + /* + * Now that the STREAMINFO block is written, we can init this to an + * absurdly-high value... + */ + encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1; + /* ... and clear this to 0 */ + encoder->private_->streaminfo.data.stream_info.total_samples = 0; + + /* + * Check to see if the supplied metadata contains a VORBIS_COMMENT; + * if not, we will write an empty one (FLAC__add_metadata_block() + * automatically supplies the vendor string). + * + * WATCHOUT: the Ogg FLAC mapping requires us to write this block after + * the STREAMINFO. (In the case that metadata_has_vorbis_comment is + * true it will have already insured that the metadata list is properly + * ordered.) + */ + if(!metadata_has_vorbis_comment) { + FLAC__StreamMetadata vorbis_comment; + vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT; + vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0); + vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */ + vorbis_comment.data.vorbis_comment.vendor_string.length = 0; + vorbis_comment.data.vorbis_comment.vendor_string.entry = 0; + vorbis_comment.data.vorbis_comment.num_comments = 0; + vorbis_comment.data.vorbis_comment.comments = 0; + if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) { + /* the above function sets the state for us in case of an error */ + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + } + + /* + * write the user's metadata blocks + */ + for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) { + encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1); + if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) { + /* the above function sets the state for us in case of an error */ + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + } + + /* now that all the metadata is written, we save the stream offset */ + if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */ + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + if(encoder->protected_->verify) + encoder->private_->verify.state_hint = ENCODER_IN_AUDIO; + + return FLAC__STREAM_ENCODER_INIT_STATUS_OK; +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream( + FLAC__StreamEncoder *encoder, + FLAC__StreamEncoderWriteCallback write_callback, + FLAC__StreamEncoderSeekCallback seek_callback, + FLAC__StreamEncoderTellCallback tell_callback, + FLAC__StreamEncoderMetadataCallback metadata_callback, + void *client_data +) +{ + return init_stream_internal_( + encoder, + /*read_callback=*/0, + write_callback, + seek_callback, + tell_callback, + metadata_callback, + client_data, + /*is_ogg=*/false + ); +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream( + FLAC__StreamEncoder *encoder, + FLAC__StreamEncoderReadCallback read_callback, + FLAC__StreamEncoderWriteCallback write_callback, + FLAC__StreamEncoderSeekCallback seek_callback, + FLAC__StreamEncoderTellCallback tell_callback, + FLAC__StreamEncoderMetadataCallback metadata_callback, + void *client_data +) +{ + return init_stream_internal_( + encoder, + read_callback, + write_callback, + seek_callback, + tell_callback, + metadata_callback, + client_data, + /*is_ogg=*/true + ); +} + +static FLAC__StreamEncoderInitStatus init_FILE_internal_( + FLAC__StreamEncoder *encoder, + FILE *file, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + FLAC__StreamEncoderInitStatus init_status; + + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != file); + + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED; + + /* double protection */ + if(file == 0) { + encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + /* + * To make sure that our file does not go unclosed after an error, we + * must assign the FILE pointer before any further error can occur in + * this routine. + */ + if(file == stdout) + file = get_binary_stdout_(); /* just to be safe */ + + encoder->private_->file = file; + + encoder->private_->progress_callback = progress_callback; + encoder->private_->bytes_written = 0; + encoder->private_->samples_written = 0; + encoder->private_->frames_written = 0; + + init_status = init_stream_internal_( + encoder, + encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0, + file_write_callback_, + encoder->private_->file == stdout? 0 : file_seek_callback_, + encoder->private_->file == stdout? 0 : file_tell_callback_, + /*metadata_callback=*/0, + client_data, + is_ogg + ); + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + /* the above function sets the state for us in case of an error */ + return init_status; + } + + { + unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder); + + FLAC__ASSERT(blocksize != 0); + encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize); + } + + return init_status; +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE( + FLAC__StreamEncoder *encoder, + FILE *file, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data +) +{ + return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false); +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE( + FLAC__StreamEncoder *encoder, + FILE *file, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data +) +{ + return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true); +} + +static FLAC__StreamEncoderInitStatus init_file_internal_( + FLAC__StreamEncoder *encoder, + const char *filename, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data, + FLAC__bool is_ogg +) +{ + FILE *file; + + FLAC__ASSERT(0 != encoder); + + /* + * To make sure that our file does not go unclosed after an error, we + * have to do the same entrance checks here that are later performed + * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned. + */ + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED; + + file = filename? fopen(filename, "w+b") : stdout; + + if(file == 0) { + encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR; + return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR; + } + + return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg); +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file( + FLAC__StreamEncoder *encoder, + const char *filename, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data +) +{ + return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false); +} + +FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file( + FLAC__StreamEncoder *encoder, + const char *filename, + FLAC__StreamEncoderProgressCallback progress_callback, + void *client_data +) +{ + return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true); +} + +FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder) +{ + FLAC__bool error = false; + + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + + if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED) + return true; + + if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) { + if(encoder->private_->current_sample_number != 0) { + const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number; + encoder->protected_->blocksize = encoder->private_->current_sample_number; + if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true)) + error = true; + } + } + + if(encoder->protected_->do_md5) + FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context); + + if(!encoder->private_->is_being_deleted) { + if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) { + if(encoder->private_->seek_callback) { +#if FLAC__HAS_OGG + if(encoder->private_->is_ogg) + update_ogg_metadata_(encoder); + else +#endif + update_metadata_(encoder); + + /* check if an error occurred while updating metadata */ + if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK) + error = true; + } + if(encoder->private_->metadata_callback) + encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data); + } + + if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) { + if(!error) + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA; + error = true; + } + } + + if(0 != encoder->private_->file) { + if(encoder->private_->file != stdout) + fclose(encoder->private_->file); + encoder->private_->file = 0; + } + +#if FLAC__HAS_OGG + if(encoder->private_->is_ogg) + FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect); +#endif + + free_(encoder); + set_defaults_(encoder); + + if(!error) + encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED; + + return !error; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; +#if FLAC__HAS_OGG + /* can't check encoder->private_->is_ogg since that's not set until init time */ + FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value); + return true; +#else + (void)value; + return false; +#endif +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; +#ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING + encoder->protected_->verify = value; +#endif + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->streamable_subset = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->do_md5 = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->channels = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->bits_per_sample = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->sample_rate = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__bool ok = true; + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0])) + value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1; + ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo); + ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo); +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if 0 + /* was: */ + ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization); + /* but it's too hard to specify the string in a locale-specific way */ +#else + encoder->protected_->num_apodizations = 1; + encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY; + encoder->protected_->apodizations[0].parameters.tukey.p = 0.5; +#endif +#endif + ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order); + ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision); + ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search); + ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding); + ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search); + ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order); + ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order); + ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist); + return ok; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->blocksize = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->do_mid_side_stereo = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->loose_mid_side_stereo = value; + return true; +} + +/*@@@@add to tests*/ +FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + FLAC__ASSERT(0 != specification); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; +#ifdef FLAC__INTEGER_ONLY_LIBRARY + (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */ +#else + encoder->protected_->num_apodizations = 0; + while(1) { + const char *s = strchr(specification, ';'); + const size_t n = s? (size_t)(s - specification) : strlen(specification); + if (n==8 && 0 == strncmp("bartlett" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT; + else if(n==13 && 0 == strncmp("bartlett_hann", specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN; + else if(n==8 && 0 == strncmp("blackman" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN; + else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE; + else if(n==6 && 0 == strncmp("connes" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES; + else if(n==7 && 0 == strncmp("flattop" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP; + else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) { + FLAC__real stddev = (FLAC__real)strtod(specification+6, 0); + if (stddev > 0.0 && stddev <= 0.5) { + encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev; + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS; + } + } + else if(n==7 && 0 == strncmp("hamming" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING; + else if(n==4 && 0 == strncmp("hann" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN; + else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL; + else if(n==7 && 0 == strncmp("nuttall" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL; + else if(n==9 && 0 == strncmp("rectangle" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE; + else if(n==8 && 0 == strncmp("triangle" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE; + else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) { + FLAC__real p = (FLAC__real)strtod(specification+6, 0); + if (p >= 0.0 && p <= 1.0) { + encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p; + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY; + } + } + else if(n==5 && 0 == strncmp("welch" , specification, n)) + encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH; + if (encoder->protected_->num_apodizations == 32) + break; + if (s) + specification = s+1; + else + break; + } + if(encoder->protected_->num_apodizations == 0) { + encoder->protected_->num_apodizations = 1; + encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY; + encoder->protected_->apodizations[0].parameters.tukey.p = 0.5; + } +#endif + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->max_lpc_order = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->qlp_coeff_precision = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->do_qlp_coeff_prec_search = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; +#if 0 + /*@@@ deprecated: */ + encoder->protected_->do_escape_coding = value; +#else + (void)value; +#endif + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->do_exhaustive_model_search = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->min_residual_partition_order = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->max_residual_partition_order = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; +#if 0 + /*@@@ deprecated: */ + encoder->protected_->rice_parameter_search_dist = value; +#else + (void)value; +#endif + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->protected_->total_samples_estimate = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + if(0 == metadata) + num_blocks = 0; + if(0 == num_blocks) + metadata = 0; + /* realloc() does not do exactly what we want so... */ + if(encoder->protected_->metadata) { + free(encoder->protected_->metadata); + encoder->protected_->metadata = 0; + encoder->protected_->num_metadata_blocks = 0; + } + if(num_blocks) { + FLAC__StreamMetadata **m; + if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks))) + return false; + memcpy(m, metadata, sizeof(m[0]) * num_blocks); + encoder->protected_->metadata = m; + encoder->protected_->num_metadata_blocks = num_blocks; + } +#if FLAC__HAS_OGG + if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks)) + return false; +#endif + return true; +} + +/* + * These three functions are not static, but not publically exposed in + * include/FLAC/ either. They are used by the test suite. + */ +FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->private_->disable_constant_subframes = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->private_->disable_fixed_subframes = value; + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED) + return false; + encoder->private_->disable_verbatim_subframes = value; + return true; +} + +FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->state; +} + +FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->verify) + return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder); + else + return FLAC__STREAM_DECODER_UNINITIALIZED; +} + +FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) + return FLAC__StreamEncoderStateString[encoder->protected_->state]; + else + return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder); +} + +FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + if(0 != absolute_sample) + *absolute_sample = encoder->private_->verify.error_stats.absolute_sample; + if(0 != frame_number) + *frame_number = encoder->private_->verify.error_stats.frame_number; + if(0 != channel) + *channel = encoder->private_->verify.error_stats.channel; + if(0 != sample) + *sample = encoder->private_->verify.error_stats.sample; + if(0 != expected) + *expected = encoder->private_->verify.error_stats.expected; + if(0 != got) + *got = encoder->private_->verify.error_stats.got; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->verify; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->streamable_subset; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->do_md5; +} + +FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->channels; +} + +FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->bits_per_sample; +} + +FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->sample_rate; +} + +FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->blocksize; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->do_mid_side_stereo; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->loose_mid_side_stereo; +} + +FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->max_lpc_order; +} + +FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->qlp_coeff_precision; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->do_qlp_coeff_prec_search; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->do_escape_coding; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->do_exhaustive_model_search; +} + +FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->min_residual_partition_order; +} + +FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->max_residual_partition_order; +} + +FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->rice_parameter_search_dist; +} + +FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + return encoder->protected_->total_samples_estimate; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples) +{ + unsigned i, j = 0, channel; + const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize; + + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK); + + do { + const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j); + + if(encoder->protected_->verify) + append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n); + + for(channel = 0; channel < channels; channel++) + memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n); + + if(encoder->protected_->do_mid_side_stereo) { + FLAC__ASSERT(channels == 2); + /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */ + for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) { + encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j]; + encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */ + } + } + else + j += n; + + encoder->private_->current_sample_number += n; + + /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */ + if(encoder->private_->current_sample_number > blocksize) { + FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_); + FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */ + if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false)) + return false; + /* move unprocessed overread samples to beginnings of arrays */ + for(channel = 0; channel < channels; channel++) + encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize]; + if(encoder->protected_->do_mid_side_stereo) { + encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize]; + encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize]; + } + encoder->private_->current_sample_number = 1; + } + } while(j < samples); + + return true; +} + +FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples) +{ + unsigned i, j, k, channel; + FLAC__int32 x, mid, side; + const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize; + + FLAC__ASSERT(0 != encoder); + FLAC__ASSERT(0 != encoder->private_); + FLAC__ASSERT(0 != encoder->protected_); + FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK); + + j = k = 0; + /* + * we have several flavors of the same basic loop, optimized for + * different conditions: + */ + if(encoder->protected_->do_mid_side_stereo && channels == 2) { + /* + * stereo coding: unroll channel loop + */ + do { + if(encoder->protected_->verify) + append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j)); + + /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */ + for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) { + encoder->private_->integer_signal[0][i] = mid = side = buffer[k++]; + x = buffer[k++]; + encoder->private_->integer_signal[1][i] = x; + mid += x; + side -= x; + mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */ + encoder->private_->integer_signal_mid_side[1][i] = side; + encoder->private_->integer_signal_mid_side[0][i] = mid; + } + encoder->private_->current_sample_number = i; + /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */ + if(i > blocksize) { + if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false)) + return false; + /* move unprocessed overread samples to beginnings of arrays */ + FLAC__ASSERT(i == blocksize+OVERREAD_); + FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */ + encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize]; + encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize]; + encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize]; + encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize]; + encoder->private_->current_sample_number = 1; + } + } while(j < samples); + } + else { + /* + * independent channel coding: buffer each channel in inner loop + */ + do { + if(encoder->protected_->verify) + append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j)); + + /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */ + for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) { + for(channel = 0; channel < channels; channel++) + encoder->private_->integer_signal[channel][i] = buffer[k++]; + } + encoder->private_->current_sample_number = i; + /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */ + if(i > blocksize) { + if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false)) + return false; + /* move unprocessed overread samples to beginnings of arrays */ + FLAC__ASSERT(i == blocksize+OVERREAD_); + FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */ + for(channel = 0; channel < channels; channel++) + encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize]; + encoder->private_->current_sample_number = 1; + } + } while(j < samples); + } + + return true; +} + +/*********************************************************************** + * + * Private class methods + * + ***********************************************************************/ + +void set_defaults_(FLAC__StreamEncoder *encoder) +{ + FLAC__ASSERT(0 != encoder); + +#ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING + encoder->protected_->verify = true; +#else + encoder->protected_->verify = false; +#endif + encoder->protected_->streamable_subset = true; + encoder->protected_->do_md5 = true; + encoder->protected_->do_mid_side_stereo = false; + encoder->protected_->loose_mid_side_stereo = false; + encoder->protected_->channels = 2; + encoder->protected_->bits_per_sample = 16; + encoder->protected_->sample_rate = 44100; + encoder->protected_->blocksize = 0; +#ifndef FLAC__INTEGER_ONLY_LIBRARY + encoder->protected_->num_apodizations = 1; + encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY; + encoder->protected_->apodizations[0].parameters.tukey.p = 0.5; +#endif + encoder->protected_->max_lpc_order = 0; + encoder->protected_->qlp_coeff_precision = 0; + encoder->protected_->do_qlp_coeff_prec_search = false; + encoder->protected_->do_exhaustive_model_search = false; + encoder->protected_->do_escape_coding = false; + encoder->protected_->min_residual_partition_order = 0; + encoder->protected_->max_residual_partition_order = 0; + encoder->protected_->rice_parameter_search_dist = 0; + encoder->protected_->total_samples_estimate = 0; + encoder->protected_->metadata = 0; + encoder->protected_->num_metadata_blocks = 0; + + encoder->private_->seek_table = 0; + encoder->private_->disable_constant_subframes = false; + encoder->private_->disable_fixed_subframes = false; + encoder->private_->disable_verbatim_subframes = false; +#if FLAC__HAS_OGG + encoder->private_->is_ogg = false; +#endif + encoder->private_->read_callback = 0; + encoder->private_->write_callback = 0; + encoder->private_->seek_callback = 0; + encoder->private_->tell_callback = 0; + encoder->private_->metadata_callback = 0; + encoder->private_->progress_callback = 0; + encoder->private_->client_data = 0; + +#if FLAC__HAS_OGG + FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect); +#endif +} + +void free_(FLAC__StreamEncoder *encoder) +{ + unsigned i, channel; + + FLAC__ASSERT(0 != encoder); + if(encoder->protected_->metadata) { + free(encoder->protected_->metadata); + encoder->protected_->metadata = 0; + encoder->protected_->num_metadata_blocks = 0; + } + for(i = 0; i < encoder->protected_->channels; i++) { + if(0 != encoder->private_->integer_signal_unaligned[i]) { + free(encoder->private_->integer_signal_unaligned[i]); + encoder->private_->integer_signal_unaligned[i] = 0; + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY + if(0 != encoder->private_->real_signal_unaligned[i]) { + free(encoder->private_->real_signal_unaligned[i]); + encoder->private_->real_signal_unaligned[i] = 0; + } +#endif + } + for(i = 0; i < 2; i++) { + if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) { + free(encoder->private_->integer_signal_mid_side_unaligned[i]); + encoder->private_->integer_signal_mid_side_unaligned[i] = 0; + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY + if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) { + free(encoder->private_->real_signal_mid_side_unaligned[i]); + encoder->private_->real_signal_mid_side_unaligned[i] = 0; + } +#endif + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY + for(i = 0; i < encoder->protected_->num_apodizations; i++) { + if(0 != encoder->private_->window_unaligned[i]) { + free(encoder->private_->window_unaligned[i]); + encoder->private_->window_unaligned[i] = 0; + } + } + if(0 != encoder->private_->windowed_signal_unaligned) { + free(encoder->private_->windowed_signal_unaligned); + encoder->private_->windowed_signal_unaligned = 0; + } +#endif + for(channel = 0; channel < encoder->protected_->channels; channel++) { + for(i = 0; i < 2; i++) { + if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) { + free(encoder->private_->residual_workspace_unaligned[channel][i]); + encoder->private_->residual_workspace_unaligned[channel][i] = 0; + } + } + } + for(channel = 0; channel < 2; channel++) { + for(i = 0; i < 2; i++) { + if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) { + free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]); + encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0; + } + } + } + if(0 != encoder->private_->abs_residual_partition_sums_unaligned) { + free(encoder->private_->abs_residual_partition_sums_unaligned); + encoder->private_->abs_residual_partition_sums_unaligned = 0; + } + if(0 != encoder->private_->raw_bits_per_partition_unaligned) { + free(encoder->private_->raw_bits_per_partition_unaligned); + encoder->private_->raw_bits_per_partition_unaligned = 0; + } + if(encoder->protected_->verify) { + for(i = 0; i < encoder->protected_->channels; i++) { + if(0 != encoder->private_->verify.input_fifo.data[i]) { + free(encoder->private_->verify.input_fifo.data[i]); + encoder->private_->verify.input_fifo.data[i] = 0; + } + } + } + FLAC__bitwriter_free(encoder->private_->frame); +} + +FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize) +{ + FLAC__bool ok; + unsigned i, channel; + + FLAC__ASSERT(new_blocksize > 0); + FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK); + FLAC__ASSERT(encoder->private_->current_sample_number == 0); + + /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */ + if(new_blocksize <= encoder->private_->input_capacity) + return true; + + ok = true; + + /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() + * requires that the input arrays (in our case the integer signals) + * have a buffer of up to 3 zeroes in front (at negative indices) for + * alignment purposes; we use 4 in front to keep the data well-aligned. + */ + + for(i = 0; ok && i < encoder->protected_->channels; i++) { + ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]); + memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4); + encoder->private_->integer_signal[i] += 4; +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if 0 /* @@@ currently unused */ + if(encoder->protected_->max_lpc_order > 0) + ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]); +#endif +#endif + } + for(i = 0; ok && i < 2; i++) { + ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]); + memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4); + encoder->private_->integer_signal_mid_side[i] += 4; +#ifndef FLAC__INTEGER_ONLY_LIBRARY +#if 0 /* @@@ currently unused */ + if(encoder->protected_->max_lpc_order > 0) + ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]); +#endif +#endif + } +#ifndef FLAC__INTEGER_ONLY_LIBRARY + if(ok && encoder->protected_->max_lpc_order > 0) { + for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) + ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]); + ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal); + } +#endif + for(channel = 0; ok && channel < encoder->protected_->channels; channel++) { + for(i = 0; ok && i < 2; i++) { + ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]); + } + } + for(channel = 0; ok && channel < 2; channel++) { + for(i = 0; ok && i < 2; i++) { + ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]); + } + } + /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */ + /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */ + ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums); + if(encoder->protected_->do_escape_coding) + ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition); + + /* now adjust the windows if the blocksize has changed */ +#ifndef FLAC__INTEGER_ONLY_LIBRARY + if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) { + for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) { + switch(encoder->protected_->apodizations[i].type) { + case FLAC__APODIZATION_BARTLETT: + FLAC__window_bartlett(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_BARTLETT_HANN: + FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_BLACKMAN: + FLAC__window_blackman(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE: + FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_CONNES: + FLAC__window_connes(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_FLATTOP: + FLAC__window_flattop(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_GAUSS: + FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev); + break; + case FLAC__APODIZATION_HAMMING: + FLAC__window_hamming(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_HANN: + FLAC__window_hann(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_KAISER_BESSEL: + FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_NUTTALL: + FLAC__window_nuttall(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_RECTANGLE: + FLAC__window_rectangle(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_TRIANGLE: + FLAC__window_triangle(encoder->private_->window[i], new_blocksize); + break; + case FLAC__APODIZATION_TUKEY: + FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p); + break; + case FLAC__APODIZATION_WELCH: + FLAC__window_welch(encoder->private_->window[i], new_blocksize); + break; + default: + FLAC__ASSERT(0); + /* double protection */ + FLAC__window_hann(encoder->private_->window[i], new_blocksize); + break; + } + } + } +#endif + + if(ok) + encoder->private_->input_capacity = new_blocksize; + else + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + + return ok; +} + +FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block) +{ + const FLAC__byte *buffer; + size_t bytes; + + FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame)); + + if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + if(encoder->protected_->verify) { + encoder->private_->verify.output.data = buffer; + encoder->private_->verify.output.bytes = bytes; + if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) { + encoder->private_->verify.needs_magic_hack = true; + } + else { + if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) { + FLAC__bitwriter_release_buffer(encoder->private_->frame); + FLAC__bitwriter_clear(encoder->private_->frame); + if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR; + return false; + } + } + } + + if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + FLAC__bitwriter_release_buffer(encoder->private_->frame); + FLAC__bitwriter_clear(encoder->private_->frame); + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return false; + } + + FLAC__bitwriter_release_buffer(encoder->private_->frame); + FLAC__bitwriter_clear(encoder->private_->frame); + + if(samples > 0) { + encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize); + encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize); + } + + return true; +} + +FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block) +{ + FLAC__StreamEncoderWriteStatus status; + FLAC__uint64 output_position = 0; + + /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */ + if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + } + + /* + * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets. + */ + if(samples == 0) { + FLAC__MetadataType type = (buffer[0] & 0x7f); + if(type == FLAC__METADATA_TYPE_STREAMINFO) + encoder->protected_->streaminfo_offset = output_position; + else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0) + encoder->protected_->seektable_offset = output_position; + } + + /* + * Mark the current seek point if hit (if audio_offset == 0 that + * means we're still writing metadata and haven't hit the first + * frame yet) + */ + if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) { + const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder); + const FLAC__uint64 frame_first_sample = encoder->private_->samples_written; + const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1; + FLAC__uint64 test_sample; + unsigned i; + for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) { + test_sample = encoder->private_->seek_table->points[i].sample_number; + if(test_sample > frame_last_sample) { + break; + } + else if(test_sample >= frame_first_sample) { + encoder->private_->seek_table->points[i].sample_number = frame_first_sample; + encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset; + encoder->private_->seek_table->points[i].frame_samples = blocksize; + encoder->private_->first_seekpoint_to_check++; + /* DO NOT: "break;" and here's why: + * The seektable template may contain more than one target + * sample for any given frame; we will keep looping, generating + * duplicate seekpoints for them, and we'll clean it up later, + * just before writing the seektable back to the metadata. + */ + } + else { + encoder->private_->first_seekpoint_to_check++; + } + } + } + +#if FLAC__HAS_OGG + if(encoder->private_->is_ogg) { + status = FLAC__ogg_encoder_aspect_write_callback_wrapper( + &encoder->protected_->ogg_encoder_aspect, + buffer, + bytes, + samples, + encoder->private_->current_frame_number, + is_last_block, + (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback, + encoder, + encoder->private_->client_data + ); + } + else +#endif + status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data); + + if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->private_->bytes_written += bytes; + encoder->private_->samples_written += samples; + /* we keep a high watermark on the number of frames written because + * when the encoder goes back to write metadata, 'current_frame' + * will drop back to 0. + */ + encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1); + } + else + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + + return status; +} + +/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */ +void update_metadata_(const FLAC__StreamEncoder *encoder) +{ + FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)]; + const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo; + const FLAC__uint64 samples = metadata->data.stream_info.total_samples; + const unsigned min_framesize = metadata->data.stream_info.min_framesize; + const unsigned max_framesize = metadata->data.stream_info.max_framesize; + const unsigned bps = metadata->data.stream_info.bits_per_sample; + FLAC__StreamEncoderSeekStatus seek_status; + + FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO); + + /* All this is based on intimate knowledge of the stream header + * layout, but a change to the header format that would break this + * would also break all streams encoded in the previous format. + */ + + /* + * Write MD5 signature + */ + { + const unsigned md5_offset = + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN + + FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN + ) / 8; + + if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + } + + /* + * Write total samples + */ + { + const unsigned total_samples_byte_offset = + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN + + FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN + - 4 + ) / 8; + + b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F); + b[1] = (FLAC__byte)((samples >> 24) & 0xFF); + b[2] = (FLAC__byte)((samples >> 16) & 0xFF); + b[3] = (FLAC__byte)((samples >> 8) & 0xFF); + b[4] = (FLAC__byte)(samples & 0xFF); + if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + } + + /* + * Write min/max framesize + */ + { + const unsigned min_framesize_offset = + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + ) / 8; + + b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF); + b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF); + b[2] = (FLAC__byte)(min_framesize & 0xFF); + b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF); + b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF); + b[5] = (FLAC__byte)(max_framesize & 0xFF); + if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + } + + /* + * Write seektable + */ + if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) { + unsigned i; + + FLAC__format_seektable_sort(encoder->private_->seek_table); + + FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table)); + + if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) { + if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR) + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + + for(i = 0; i < encoder->private_->seek_table->num_points; i++) { + FLAC__uint64 xx; + unsigned x; + xx = encoder->private_->seek_table->points[i].sample_number; + b[7] = (FLAC__byte)xx; xx >>= 8; + b[6] = (FLAC__byte)xx; xx >>= 8; + b[5] = (FLAC__byte)xx; xx >>= 8; + b[4] = (FLAC__byte)xx; xx >>= 8; + b[3] = (FLAC__byte)xx; xx >>= 8; + b[2] = (FLAC__byte)xx; xx >>= 8; + b[1] = (FLAC__byte)xx; xx >>= 8; + b[0] = (FLAC__byte)xx; xx >>= 8; + xx = encoder->private_->seek_table->points[i].stream_offset; + b[15] = (FLAC__byte)xx; xx >>= 8; + b[14] = (FLAC__byte)xx; xx >>= 8; + b[13] = (FLAC__byte)xx; xx >>= 8; + b[12] = (FLAC__byte)xx; xx >>= 8; + b[11] = (FLAC__byte)xx; xx >>= 8; + b[10] = (FLAC__byte)xx; xx >>= 8; + b[9] = (FLAC__byte)xx; xx >>= 8; + b[8] = (FLAC__byte)xx; xx >>= 8; + x = encoder->private_->seek_table->points[i].frame_samples; + b[17] = (FLAC__byte)x; x >>= 8; + b[16] = (FLAC__byte)x; x >>= 8; + if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) { + encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR; + return; + } + } + } +} + +#if FLAC__HAS_OGG +/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */ +void update_ogg_metadata_(FLAC__StreamEncoder *encoder) +{ + /* the # of bytes in the 1st packet that precede the STREAMINFO */ + static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH = + FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH + + FLAC__OGG_MAPPING_MAGIC_LENGTH + + FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH + + FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH + + FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH + + FLAC__STREAM_SYNC_LENGTH + ; + FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)]; + const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo; + const FLAC__uint64 samples = metadata->data.stream_info.total_samples; + const unsigned min_framesize = metadata->data.stream_info.min_framesize; + const unsigned max_framesize = metadata->data.stream_info.max_framesize; + ogg_page page; + + FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO); + FLAC__ASSERT(0 != encoder->private_->seek_callback); + + /* Pre-check that client supports seeking, since we don't want the + * ogg_helper code to ever have to deal with this condition. + */ + if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED) + return; + + /* All this is based on intimate knowledge of the stream header + * layout, but a change to the header format that would break this + * would also break all streams encoded in the previous format. + */ + + /** + ** Write STREAMINFO stats + **/ + simple_ogg_page__init(&page); + if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) { + simple_ogg_page__clear(&page); + return; /* state already set */ + } + + /* + * Write MD5 signature + */ + { + const unsigned md5_offset = + FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH + + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN + + FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN + ) / 8; + + if(md5_offset + 16 > (unsigned)page.body_len) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + simple_ogg_page__clear(&page); + return; + } + memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16); + } + + /* + * Write total samples + */ + { + const unsigned total_samples_byte_offset = + FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH + + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN + + FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN + - 4 + ) / 8; + + if(total_samples_byte_offset + 5 > (unsigned)page.body_len) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + simple_ogg_page__clear(&page); + return; + } + b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0; + b[0] |= (FLAC__byte)((samples >> 32) & 0x0F); + b[1] = (FLAC__byte)((samples >> 24) & 0xFF); + b[2] = (FLAC__byte)((samples >> 16) & 0xFF); + b[3] = (FLAC__byte)((samples >> 8) & 0xFF); + b[4] = (FLAC__byte)(samples & 0xFF); + memcpy(page.body + total_samples_byte_offset, b, 5); + } + + /* + * Write min/max framesize + */ + { + const unsigned min_framesize_offset = + FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH + + FLAC__STREAM_METADATA_HEADER_LENGTH + + ( + FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN + + FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN + ) / 8; + + if(min_framesize_offset + 6 > (unsigned)page.body_len) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + simple_ogg_page__clear(&page); + return; + } + b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF); + b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF); + b[2] = (FLAC__byte)(min_framesize & 0xFF); + b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF); + b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF); + b[5] = (FLAC__byte)(max_framesize & 0xFF); + memcpy(page.body + min_framesize_offset, b, 6); + } + if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) { + simple_ogg_page__clear(&page); + return; /* state already set */ + } + simple_ogg_page__clear(&page); + + /* + * Write seektable + */ + if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) { + unsigned i; + FLAC__byte *p; + + FLAC__format_seektable_sort(encoder->private_->seek_table); + + FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table)); + + simple_ogg_page__init(&page); + if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) { + simple_ogg_page__clear(&page); + return; /* state already set */ + } + + if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) { + encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR; + simple_ogg_page__clear(&page); + return; + } + + for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) { + FLAC__uint64 xx; + unsigned x; + xx = encoder->private_->seek_table->points[i].sample_number; + b[7] = (FLAC__byte)xx; xx >>= 8; + b[6] = (FLAC__byte)xx; xx >>= 8; + b[5] = (FLAC__byte)xx; xx >>= 8; + b[4] = (FLAC__byte)xx; xx >>= 8; + b[3] = (FLAC__byte)xx; xx >>= 8; + b[2] = (FLAC__byte)xx; xx >>= 8; + b[1] = (FLAC__byte)xx; xx >>= 8; + b[0] = (FLAC__byte)xx; xx >>= 8; + xx = encoder->private_->seek_table->points[i].stream_offset; + b[15] = (FLAC__byte)xx; xx >>= 8; + b[14] = (FLAC__byte)xx; xx >>= 8; + b[13] = (FLAC__byte)xx; xx >>= 8; + b[12] = (FLAC__byte)xx; xx >>= 8; + b[11] = (FLAC__byte)xx; xx >>= 8; + b[10] = (FLAC__byte)xx; xx >>= 8; + b[9] = (FLAC__byte)xx; xx >>= 8; + b[8] = (FLAC__byte)xx; xx >>= 8; + x = encoder->private_->seek_table->points[i].frame_samples; + b[17] = (FLAC__byte)x; x >>= 8; + b[16] = (FLAC__byte)x; x >>= 8; + memcpy(p, b, 18); + } + + if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) { + simple_ogg_page__clear(&page); + return; /* state already set */ + } + simple_ogg_page__clear(&page); + } +} +#endif + +FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block) +{ + FLAC__uint16 crc; + FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK); + + /* + * Accumulate raw signal to the MD5 signature + */ + if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + /* + * Process the frame header and subframes into the frame bitbuffer + */ + if(!process_subframes_(encoder, is_fractional_block)) { + /* the above function sets the state for us in case of an error */ + return false; + } + + /* + * Zero-pad the frame to a byte_boundary + */ + if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + /* + * CRC-16 the whole thing + */ + FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame)); + if( + !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) || + !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN) + ) { + encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR; + return false; + } + + /* + * Write it + */ + if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) { + /* the above function sets the state for us in case of an error */ + return false; + } + + /* + * Get ready for the next frame + */ + encoder->private_->current_sample_number = 0; + encoder->private_->current_frame_number++; + encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize; + + return true; +} + +FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block) +{ + FLAC__FrameHeader frame_header; + unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order; + FLAC__bool do_independent, do_mid_side; + + /* + * Calculate the min,max Rice partition orders + */ + if(is_fractional_block) { + max_partition_order = 0; + } + else { + max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize); + max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order); + } + min_partition_order = min(min_partition_order, max_partition_order); + + /* + * Setup the frame + */ + frame_header.blocksize = encoder->protected_->blocksize; + frame_header.sample_rate = encoder->protected_->sample_rate; + frame_header.channels = encoder->protected_->channels; + frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */ + frame_header.bits_per_sample = encoder->protected_->bits_per_sample; + frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER; + frame_header.number.frame_number = encoder->private_->current_frame_number; + + /* + * Figure out what channel assignments to try + */ + if(encoder->protected_->do_mid_side_stereo) { + if(encoder->protected_->loose_mid_side_stereo) { + if(encoder->private_->loose_mid_side_stereo_frame_count == 0) { + do_independent = true; + do_mid_side = true; + } + else { + do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT); + do_mid_side = !do_independent; + } + } + else { + do_independent = true; + do_mid_side = true; + } + } + else { + do_independent = true; + do_mid_side = false; + } + + FLAC__ASSERT(do_independent || do_mid_side); + + /* + * Check for wasted bits; set effective bps for each subframe + */ + if(do_independent) { + for(channel = 0; channel < encoder->protected_->channels; channel++) { + const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize); + encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w; + encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w; + } + } + if(do_mid_side) { + FLAC__ASSERT(encoder->protected_->channels == 2); + for(channel = 0; channel < 2; channel++) { + const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize); + encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w; + encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1); + } + } + + /* + * First do a normal encoding pass of each independent channel + */ + if(do_independent) { + for(channel = 0; channel < encoder->protected_->channels; channel++) { + if(! + process_subframe_( + encoder, + min_partition_order, + max_partition_order, + &frame_header, + encoder->private_->subframe_bps[channel], + encoder->private_->integer_signal[channel], + encoder->private_->subframe_workspace_ptr[channel], + encoder->private_->partitioned_rice_contents_workspace_ptr[channel], + encoder->private_->residual_workspace[channel], + encoder->private_->best_subframe+channel, + encoder->private_->best_subframe_bits+channel + ) + ) + return false; + } + } + + /* + * Now do mid and side channels if requested + */ + if(do_mid_side) { + FLAC__ASSERT(encoder->protected_->channels == 2); + + for(channel = 0; channel < 2; channel++) { + if(! + process_subframe_( + encoder, + min_partition_order, + max_partition_order, + &frame_header, + encoder->private_->subframe_bps_mid_side[channel], + encoder->private_->integer_signal_mid_side[channel], + encoder->private_->subframe_workspace_ptr_mid_side[channel], + encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel], + encoder->private_->residual_workspace_mid_side[channel], + encoder->private_->best_subframe_mid_side+channel, + encoder->private_->best_subframe_bits_mid_side+channel + ) + ) + return false; + } + } + + /* + * Compose the frame bitbuffer + */ + if(do_mid_side) { + unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */ + FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */ + FLAC__ChannelAssignment channel_assignment; + + FLAC__ASSERT(encoder->protected_->channels == 2); + + if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) { + channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE); + } + else { + unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */ + unsigned min_bits; + int ca; + + FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0); + FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1); + FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2); + FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3); + FLAC__ASSERT(do_independent && do_mid_side); + + /* We have to figure out which channel assignent results in the smallest frame */ + bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1]; + bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1]; + bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1]; + bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1]; + + channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; + min_bits = bits[channel_assignment]; + for(ca = 1; ca <= 3; ca++) { + if(bits[ca] < min_bits) { + min_bits = bits[ca]; + channel_assignment = (FLAC__ChannelAssignment)ca; + } + } + } + + frame_header.channel_assignment = channel_assignment; + + if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + + switch(channel_assignment) { + case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT: + left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]]; + right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]]; + break; + case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE: + left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]]; + right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]]; + break; + case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE: + left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]]; + right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]]; + break; + case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE: + left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]]; + right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]]; + break; + default: + FLAC__ASSERT(0); + } + + switch(channel_assignment) { + case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT: + left_bps = encoder->private_->subframe_bps [0]; + right_bps = encoder->private_->subframe_bps [1]; + break; + case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE: + left_bps = encoder->private_->subframe_bps [0]; + right_bps = encoder->private_->subframe_bps_mid_side[1]; + break; + case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE: + left_bps = encoder->private_->subframe_bps_mid_side[1]; + right_bps = encoder->private_->subframe_bps [1]; + break; + case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE: + left_bps = encoder->private_->subframe_bps_mid_side[0]; + right_bps = encoder->private_->subframe_bps_mid_side[1]; + break; + default: + FLAC__ASSERT(0); + } + + /* note that encoder_add_subframe_ sets the state for us in case of an error */ + if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame)) + return false; + if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame)) + return false; + } + else { + if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + + for(channel = 0; channel < encoder->protected_->channels; channel++) { + if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) { + /* the above function sets the state for us in case of an error */ + return false; + } + } + } + + if(encoder->protected_->loose_mid_side_stereo) { + encoder->private_->loose_mid_side_stereo_frame_count++; + if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames) + encoder->private_->loose_mid_side_stereo_frame_count = 0; + } + + encoder->private_->last_channel_assignment = frame_header.channel_assignment; + + return true; +} + +FLAC__bool process_subframe_( + FLAC__StreamEncoder *encoder, + unsigned min_partition_order, + unsigned max_partition_order, + const FLAC__FrameHeader *frame_header, + unsigned subframe_bps, + const FLAC__int32 integer_signal[], + FLAC__Subframe *subframe[2], + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2], + FLAC__int32 *residual[2], + unsigned *best_subframe, + unsigned *best_bits +) +{ +#ifndef FLAC__INTEGER_ONLY_LIBRARY + FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]; +#else + FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]; +#endif +#ifndef FLAC__INTEGER_ONLY_LIBRARY + FLAC__double lpc_residual_bits_per_sample; + FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */ + FLAC__double lpc_error[FLAC__MAX_LPC_ORDER]; + unsigned min_lpc_order, max_lpc_order, lpc_order; + unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision; +#endif + unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order; + unsigned rice_parameter; + unsigned _candidate_bits, _best_bits; + unsigned _best_subframe; + /* only use RICE2 partitions if stream bps > 16 */ + const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; + + FLAC__ASSERT(frame_header->blocksize > 0); + + /* verbatim subframe is the baseline against which we measure other compressed subframes */ + _best_subframe = 0; + if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) + _best_bits = UINT_MAX; + else + _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]); + + if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) { + unsigned signal_is_constant = false; + guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample); + /* check for constant subframe */ + if( + !encoder->private_->disable_constant_subframes && +#ifndef FLAC__INTEGER_ONLY_LIBRARY + fixed_residual_bits_per_sample[1] == 0.0 +#else + fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO +#endif + ) { + /* the above means it's possible all samples are the same value; now double-check it: */ + unsigned i; + signal_is_constant = true; + for(i = 1; i < frame_header->blocksize; i++) { + if(integer_signal[0] != integer_signal[i]) { + signal_is_constant = false; + break; + } + } + } + if(signal_is_constant) { + _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]); + if(_candidate_bits < _best_bits) { + _best_subframe = !_best_subframe; + _best_bits = _candidate_bits; + } + } + else { + if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) { + /* encode fixed */ + if(encoder->protected_->do_exhaustive_model_search) { + min_fixed_order = 0; + max_fixed_order = FLAC__MAX_FIXED_ORDER; + } + else { + min_fixed_order = max_fixed_order = guess_fixed_order; + } + if(max_fixed_order >= frame_header->blocksize) + max_fixed_order = frame_header->blocksize - 1; + for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) { +#ifndef FLAC__INTEGER_ONLY_LIBRARY + if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps) + continue; /* don't even try */ + rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */ +#else + if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps) + continue; /* don't even try */ + rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */ +#endif + rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */ + if(rice_parameter >= rice_parameter_limit) { +#ifdef DEBUG_VERBOSE + fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1); +#endif + rice_parameter = rice_parameter_limit - 1; + } + _candidate_bits = + evaluate_fixed_subframe_( + encoder, + integer_signal, + residual[!_best_subframe], + encoder->private_->abs_residual_partition_sums, + encoder->private_->raw_bits_per_partition, + frame_header->blocksize, + subframe_bps, + fixed_order, + rice_parameter, + rice_parameter_limit, + min_partition_order, + max_partition_order, + encoder->protected_->do_escape_coding, + encoder->protected_->rice_parameter_search_dist, + subframe[!_best_subframe], + partitioned_rice_contents[!_best_subframe] + ); + if(_candidate_bits < _best_bits) { + _best_subframe = !_best_subframe; + _best_bits = _candidate_bits; + } + } + } + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + /* encode lpc */ + if(encoder->protected_->max_lpc_order > 0) { + if(encoder->protected_->max_lpc_order >= frame_header->blocksize) + max_lpc_order = frame_header->blocksize-1; + else + max_lpc_order = encoder->protected_->max_lpc_order; + if(max_lpc_order > 0) { + unsigned a; + for (a = 0; a < encoder->protected_->num_apodizations; a++) { + FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize); + encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc); + /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */ + if(autoc[0] != 0.0) { + FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error); + if(encoder->protected_->do_exhaustive_model_search) { + min_lpc_order = 1; + } + else { + const unsigned guess_lpc_order = + FLAC__lpc_compute_best_order( + lpc_error, + max_lpc_order, + frame_header->blocksize, + subframe_bps + ( + encoder->protected_->do_qlp_coeff_prec_search? + FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */ + encoder->protected_->qlp_coeff_precision + ) + ); + min_lpc_order = max_lpc_order = guess_lpc_order; + } + if(max_lpc_order >= frame_header->blocksize) + max_lpc_order = frame_header->blocksize - 1; + for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) { + lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order); + if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps) + continue; /* don't even try */ + rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */ + rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */ + if(rice_parameter >= rice_parameter_limit) { +#ifdef DEBUG_VERBOSE + fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1); +#endif + rice_parameter = rice_parameter_limit - 1; + } + if(encoder->protected_->do_qlp_coeff_prec_search) { + min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION; + /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */ + if(subframe_bps <= 17) { + max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION); + max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision); + } + else + max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION; + } + else { + min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision; + } + for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) { + _candidate_bits = + evaluate_lpc_subframe_( + encoder, + integer_signal, + residual[!_best_subframe], + encoder->private_->abs_residual_partition_sums, + encoder->private_->raw_bits_per_partition, + encoder->private_->lp_coeff[lpc_order-1], + frame_header->blocksize, + subframe_bps, + lpc_order, + qlp_coeff_precision, + rice_parameter, + rice_parameter_limit, + min_partition_order, + max_partition_order, + encoder->protected_->do_escape_coding, + encoder->protected_->rice_parameter_search_dist, + subframe[!_best_subframe], + partitioned_rice_contents[!_best_subframe] + ); + if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */ + if(_candidate_bits < _best_bits) { + _best_subframe = !_best_subframe; + _best_bits = _candidate_bits; + } + } + } + } + } + } + } + } +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ + } + } + + /* under rare circumstances this can happen when all but lpc subframe types are disabled: */ + if(_best_bits == UINT_MAX) { + FLAC__ASSERT(_best_subframe == 0); + _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]); + } + + *best_subframe = _best_subframe; + *best_bits = _best_bits; + + return true; +} + +FLAC__bool add_subframe_( + FLAC__StreamEncoder *encoder, + unsigned blocksize, + unsigned subframe_bps, + const FLAC__Subframe *subframe, + FLAC__BitWriter *frame +) +{ + switch(subframe->type) { + case FLAC__SUBFRAME_TYPE_CONSTANT: + if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + break; + case FLAC__SUBFRAME_TYPE_FIXED: + if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + break; + case FLAC__SUBFRAME_TYPE_LPC: + if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + break; + case FLAC__SUBFRAME_TYPE_VERBATIM: + if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) { + encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR; + return false; + } + break; + default: + FLAC__ASSERT(0); + } + + return true; +} + +#define SPOTCHECK_ESTIMATE 0 +#if SPOTCHECK_ESTIMATE +static void spotcheck_subframe_estimate_( + FLAC__StreamEncoder *encoder, + unsigned blocksize, + unsigned subframe_bps, + const FLAC__Subframe *subframe, + unsigned estimate +) +{ + FLAC__bool ret; + FLAC__BitWriter *frame = FLAC__bitwriter_new(); + if(frame == 0) { + fprintf(stderr, "EST: can't allocate frame\n"); + return; + } + if(!FLAC__bitwriter_init(frame)) { + fprintf(stderr, "EST: can't init frame\n"); + return; + } + ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame); + FLAC__ASSERT(ret); + { + const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame); + if(estimate != actual) + fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate); + } + FLAC__bitwriter_delete(frame); +} +#endif + +unsigned evaluate_constant_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal, + unsigned blocksize, + unsigned subframe_bps, + FLAC__Subframe *subframe +) +{ + unsigned estimate; + subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT; + subframe->data.constant.value = signal; + + estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps; + +#if SPOTCHECK_ESTIMATE + spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate); +#else + (void)encoder, (void)blocksize; +#endif + + return estimate; +} + +unsigned evaluate_fixed_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + unsigned blocksize, + unsigned subframe_bps, + unsigned order, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__Subframe *subframe, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents +) +{ + unsigned i, residual_bits, estimate; + const unsigned residual_samples = blocksize - order; + + FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual); + + subframe->type = FLAC__SUBFRAME_TYPE_FIXED; + + subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE; + subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents; + subframe->data.fixed.residual = residual; + + residual_bits = + find_best_partition_order_( + encoder->private_, + residual, + abs_residual_partition_sums, + raw_bits_per_partition, + residual_samples, + order, + rice_parameter, + rice_parameter_limit, + min_partition_order, + max_partition_order, + subframe_bps, + do_escape_coding, + rice_parameter_search_dist, + &subframe->data.fixed.entropy_coding_method + ); + + subframe->data.fixed.order = order; + for(i = 0; i < order; i++) + subframe->data.fixed.warmup[i] = signal[i]; + + estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits; + +#if SPOTCHECK_ESTIMATE + spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate); +#endif + + return estimate; +} + +#ifndef FLAC__INTEGER_ONLY_LIBRARY +unsigned evaluate_lpc_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + const FLAC__real lp_coeff[], + unsigned blocksize, + unsigned subframe_bps, + unsigned order, + unsigned qlp_coeff_precision, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__Subframe *subframe, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents +) +{ + FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; + unsigned i, residual_bits, estimate; + int quantization, ret; + const unsigned residual_samples = blocksize - order; + + /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */ + if(subframe_bps <= 16) { + FLAC__ASSERT(order > 0); + FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER); + qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order)); + } + + ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization); + if(ret != 0) + return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */ + + if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32) + if(subframe_bps <= 16 && qlp_coeff_precision <= 16) + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual); + else + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual); + else + encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual); + + subframe->type = FLAC__SUBFRAME_TYPE_LPC; + + subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE; + subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents; + subframe->data.lpc.residual = residual; + + residual_bits = + find_best_partition_order_( + encoder->private_, + residual, + abs_residual_partition_sums, + raw_bits_per_partition, + residual_samples, + order, + rice_parameter, + rice_parameter_limit, + min_partition_order, + max_partition_order, + subframe_bps, + do_escape_coding, + rice_parameter_search_dist, + &subframe->data.lpc.entropy_coding_method + ); + + subframe->data.lpc.order = order; + subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision; + subframe->data.lpc.quantization_level = quantization; + memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER); + for(i = 0; i < order; i++) + subframe->data.lpc.warmup[i] = signal[i]; + + estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits; + +#if SPOTCHECK_ESTIMATE + spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate); +#endif + + return estimate; +} +#endif + +unsigned evaluate_verbatim_subframe_( + FLAC__StreamEncoder *encoder, + const FLAC__int32 signal[], + unsigned blocksize, + unsigned subframe_bps, + FLAC__Subframe *subframe +) +{ + unsigned estimate; + + subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM; + + subframe->data.verbatim.data = signal; + + estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps); + +#if SPOTCHECK_ESTIMATE + spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate); +#else + (void)encoder; +#endif + + return estimate; +} + +unsigned find_best_partition_order_( + FLAC__StreamEncoderPrivate *private_, + const FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned raw_bits_per_partition[], + unsigned residual_samples, + unsigned predictor_order, + unsigned rice_parameter, + unsigned rice_parameter_limit, + unsigned min_partition_order, + unsigned max_partition_order, + unsigned bps, + FLAC__bool do_escape_coding, + unsigned rice_parameter_search_dist, + FLAC__EntropyCodingMethod *best_ecm +) +{ + unsigned residual_bits, best_residual_bits = 0; + unsigned best_parameters_index = 0; + unsigned best_partition_order = 0; + const unsigned blocksize = residual_samples + predictor_order; + + max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order); + min_partition_order = min(min_partition_order, max_partition_order); + + precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps); + + if(do_escape_coding) + precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order); + + { + int partition_order; + unsigned sum; + + for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) { + if(! + set_partitioned_rice_( +#ifdef EXACT_RICE_BITS_CALCULATION + residual, +#endif + abs_residual_partition_sums+sum, + raw_bits_per_partition+sum, + residual_samples, + predictor_order, + rice_parameter, + rice_parameter_limit, + rice_parameter_search_dist, + (unsigned)partition_order, + do_escape_coding, + &private_->partitioned_rice_contents_extra[!best_parameters_index], + &residual_bits + ) + ) + { + FLAC__ASSERT(best_residual_bits != 0); + break; + } + sum += 1u << partition_order; + if(best_residual_bits == 0 || residual_bits < best_residual_bits) { + best_residual_bits = residual_bits; + best_parameters_index = !best_parameters_index; + best_partition_order = partition_order; + } + } + } + + best_ecm->data.partitioned_rice.order = best_partition_order; + + { + /* + * We are allowed to de-const the pointer based on our special + * knowledge; it is const to the outside world. + */ + FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents; + unsigned partition; + + /* save best parameters and raw_bits */ + FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order)); + memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order))); + if(do_escape_coding) + memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order))); + /* + * Now need to check if the type should be changed to + * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the + * size of the rice parameters. + */ + for(partition = 0; partition < (1u<parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) { + best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2; + break; + } + } + } + + return best_residual_bits; +} + +#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM +extern void precompute_partition_info_sums_32bit_asm_ia32_( + const FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned blocksize, + unsigned predictor_order, + unsigned min_partition_order, + unsigned max_partition_order +); +#endif + +void precompute_partition_info_sums_( + const FLAC__int32 residual[], + FLAC__uint64 abs_residual_partition_sums[], + unsigned residual_samples, + unsigned predictor_order, + unsigned min_partition_order, + unsigned max_partition_order, + unsigned bps +) +{ + const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order; + unsigned partitions = 1u << max_partition_order; + + FLAC__ASSERT(default_partition_samples > predictor_order); + +#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM + /* slightly pessimistic but still catches all common cases */ + /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */ + if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) { + precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order); + return; + } +#endif + + /* first do max_partition_order */ + { + unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order); + /* slightly pessimistic but still catches all common cases */ + /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */ + if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) { + FLAC__uint32 abs_residual_partition_sum; + + for(partition = residual_sample = 0; partition < partitions; partition++) { + end += default_partition_samples; + abs_residual_partition_sum = 0; + for( ; residual_sample < end; residual_sample++) + abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */ + abs_residual_partition_sums[partition] = abs_residual_partition_sum; + } + } + else { /* have to pessimistically use 64 bits for accumulator */ + FLAC__uint64 abs_residual_partition_sum; + + for(partition = residual_sample = 0; partition < partitions; partition++) { + end += default_partition_samples; + abs_residual_partition_sum = 0; + for( ; residual_sample < end; residual_sample++) + abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */ + abs_residual_partition_sums[partition] = abs_residual_partition_sum; + } + } + } + + /* now merge partitions for lower orders */ + { + unsigned from_partition = 0, to_partition = partitions; + int partition_order; + for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) { + unsigned i; + partitions >>= 1; + for(i = 0; i < partitions; i++) { + abs_residual_partition_sums[to_partition++] = + abs_residual_partition_sums[from_partition ] + + abs_residual_partition_sums[from_partition+1]; + from_partition += 2; + } + } + } +} + +void precompute_partition_info_escapes_( + const FLAC__int32 residual[], + unsigned raw_bits_per_partition[], + unsigned residual_samples, + unsigned predictor_order, + unsigned min_partition_order, + unsigned max_partition_order +) +{ + int partition_order; + unsigned from_partition, to_partition = 0; + const unsigned blocksize = residual_samples + predictor_order; + + /* first do max_partition_order */ + for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) { + FLAC__int32 r; + FLAC__uint32 rmax; + unsigned partition, partition_sample, partition_samples, residual_sample; + const unsigned partitions = 1u << partition_order; + const unsigned default_partition_samples = blocksize >> partition_order; + + FLAC__ASSERT(default_partition_samples > predictor_order); + + for(partition = residual_sample = 0; partition < partitions; partition++) { + partition_samples = default_partition_samples; + if(partition == 0) + partition_samples -= predictor_order; + rmax = 0; + for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) { + r = residual[residual_sample++]; + /* OPT: maybe faster: rmax |= r ^ (r>>31) */ + if(r < 0) + rmax |= ~r; + else + rmax |= r; + } + /* now we know all residual values are in the range [-rmax-1,rmax] */ + raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1; + } + to_partition = partitions; + break; /*@@@ yuck, should remove the 'for' loop instead */ + } + + /* now merge partitions for lower orders */ + for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) { + unsigned m; + unsigned i; + const unsigned partitions = 1u << partition_order; + for(i = 0; i < partitions; i++) { + m = raw_bits_per_partition[from_partition]; + from_partition++; + raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]); + from_partition++; + to_partition++; + } + } +} + +#ifdef EXACT_RICE_BITS_CALCULATION +static FLaC__INLINE unsigned count_rice_bits_in_partition_( + const unsigned rice_parameter, + const unsigned partition_samples, + const FLAC__int32 *residual +) +{ + unsigned i, partition_bits = + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */ + (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */ + ; + for(i = 0; i < partition_samples; i++) + partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter ); + return partition_bits; +} +#else +static FLaC__INLINE unsigned count_rice_bits_in_partition_( + const unsigned rice_parameter, + const unsigned partition_samples, + const FLAC__uint64 abs_residual_partition_sum +) +{ + return + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */ + (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */ + ( + rice_parameter? + (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */ + : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */ + ) + - (partition_samples >> 1) + /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum. + * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1) + * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out. + * So the subtraction term tries to guess how many extra bits were contributed. + * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample. + */ + ; +} +#endif + +FLAC__bool set_partitioned_rice_( +#ifdef EXACT_RICE_BITS_CALCULATION + const FLAC__int32 residual[], +#endif + const FLAC__uint64 abs_residual_partition_sums[], + const unsigned raw_bits_per_partition[], + const unsigned residual_samples, + const unsigned predictor_order, + const unsigned suggested_rice_parameter, + const unsigned rice_parameter_limit, + const unsigned rice_parameter_search_dist, + const unsigned partition_order, + const FLAC__bool search_for_escapes, + FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, + unsigned *bits +) +{ + unsigned rice_parameter, partition_bits; + unsigned best_partition_bits, best_rice_parameter = 0; + unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; + unsigned *parameters, *raw_bits; +#ifdef ENABLE_RICE_PARAMETER_SEARCH + unsigned min_rice_parameter, max_rice_parameter; +#else + (void)rice_parameter_search_dist; +#endif + + FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER); + FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER); + + FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order)); + parameters = partitioned_rice_contents->parameters; + raw_bits = partitioned_rice_contents->raw_bits; + + if(partition_order == 0) { + best_partition_bits = (unsigned)(-1); +#ifdef ENABLE_RICE_PARAMETER_SEARCH + if(rice_parameter_search_dist) { + if(suggested_rice_parameter < rice_parameter_search_dist) + min_rice_parameter = 0; + else + min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist; + max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist; + if(max_rice_parameter >= rice_parameter_limit) { +#ifdef DEBUG_VERBOSE + fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1); +#endif + max_rice_parameter = rice_parameter_limit - 1; + } + } + else + min_rice_parameter = max_rice_parameter = suggested_rice_parameter; + + for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) { +#else + rice_parameter = suggested_rice_parameter; +#endif +#ifdef EXACT_RICE_BITS_CALCULATION + partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual); +#else + partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]); +#endif + if(partition_bits < best_partition_bits) { + best_rice_parameter = rice_parameter; + best_partition_bits = partition_bits; + } +#ifdef ENABLE_RICE_PARAMETER_SEARCH + } +#endif + if(search_for_escapes) { + partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples; + if(partition_bits <= best_partition_bits) { + raw_bits[0] = raw_bits_per_partition[0]; + best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */ + best_partition_bits = partition_bits; + } + else + raw_bits[0] = 0; + } + parameters[0] = best_rice_parameter; + bits_ += best_partition_bits; + } + else { + unsigned partition, residual_sample; + unsigned partition_samples; + FLAC__uint64 mean, k; + const unsigned partitions = 1u << partition_order; + for(partition = residual_sample = 0; partition < partitions; partition++) { + partition_samples = (residual_samples+predictor_order) >> partition_order; + if(partition == 0) { + if(partition_samples <= predictor_order) + return false; + else + partition_samples -= predictor_order; + } + mean = abs_residual_partition_sums[partition]; + /* we are basically calculating the size in bits of the + * average residual magnitude in the partition: + * rice_parameter = floor(log2(mean/partition_samples)) + * 'mean' is not a good name for the variable, it is + * actually the sum of magnitudes of all residual values + * in the partition, so the actual mean is + * mean/partition_samples + */ + for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1) + ; + if(rice_parameter >= rice_parameter_limit) { +#ifdef DEBUG_VERBOSE + fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1); +#endif + rice_parameter = rice_parameter_limit - 1; + } + + best_partition_bits = (unsigned)(-1); +#ifdef ENABLE_RICE_PARAMETER_SEARCH + if(rice_parameter_search_dist) { + if(rice_parameter < rice_parameter_search_dist) + min_rice_parameter = 0; + else + min_rice_parameter = rice_parameter - rice_parameter_search_dist; + max_rice_parameter = rice_parameter + rice_parameter_search_dist; + if(max_rice_parameter >= rice_parameter_limit) { +#ifdef DEBUG_VERBOSE + fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1); +#endif + max_rice_parameter = rice_parameter_limit - 1; + } + } + else + min_rice_parameter = max_rice_parameter = rice_parameter; + + for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) { +#endif +#ifdef EXACT_RICE_BITS_CALCULATION + partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample); +#else + partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]); +#endif + if(partition_bits < best_partition_bits) { + best_rice_parameter = rice_parameter; + best_partition_bits = partition_bits; + } +#ifdef ENABLE_RICE_PARAMETER_SEARCH + } +#endif + if(search_for_escapes) { + partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples; + if(partition_bits <= best_partition_bits) { + raw_bits[partition] = raw_bits_per_partition[partition]; + best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */ + best_partition_bits = partition_bits; + } + else + raw_bits[partition] = 0; + } + parameters[partition] = best_rice_parameter; + bits_ += best_partition_bits; + residual_sample += partition_samples; + } + } + + *bits = bits_; + return true; +} + +unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples) +{ + unsigned i, shift; + FLAC__int32 x = 0; + + for(i = 0; i < samples && !(x&1); i++) + x |= signal[i]; + + if(x == 0) { + shift = 0; + } + else { + for(shift = 0; !(x&1); shift++) + x >>= 1; + } + + if(shift > 0) { + for(i = 0; i < samples; i++) + signal[i] >>= shift; + } + + return shift; +} + +void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples) +{ + unsigned channel; + + for(channel = 0; channel < channels; channel++) + memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples); + + fifo->tail += wide_samples; + + FLAC__ASSERT(fifo->tail <= fifo->size); +} + +void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples) +{ + unsigned channel; + unsigned sample, wide_sample; + unsigned tail = fifo->tail; + + sample = input_offset * channels; + for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) { + for(channel = 0; channel < channels; channel++) + fifo->data[channel][tail] = input[sample++]; + tail++; + } + fifo->tail = tail; + + FLAC__ASSERT(fifo->tail <= fifo->size); +} + +FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data; + const size_t encoded_bytes = encoder->private_->verify.output.bytes; + (void)decoder; + + if(encoder->private_->verify.needs_magic_hack) { + FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH); + *bytes = FLAC__STREAM_SYNC_LENGTH; + memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes); + encoder->private_->verify.needs_magic_hack = false; + } + else { + if(encoded_bytes == 0) { + /* + * If we get here, a FIFO underflow has occurred, + * which means there is a bug somewhere. + */ + FLAC__ASSERT(0); + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + } + else if(encoded_bytes < *bytes) + *bytes = encoded_bytes; + memcpy(buffer, encoder->private_->verify.output.data, *bytes); + encoder->private_->verify.output.data += *bytes; + encoder->private_->verify.output.bytes -= *bytes; + } + + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; +} + +FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data; + unsigned channel; + const unsigned channels = frame->header.channels; + const unsigned blocksize = frame->header.blocksize; + const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize; + + (void)decoder; + + for(channel = 0; channel < channels; channel++) { + if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) { + unsigned i, sample = 0; + FLAC__int32 expect = 0, got = 0; + + for(i = 0; i < blocksize; i++) { + if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) { + sample = i; + expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i]; + got = (FLAC__int32)buffer[channel][i]; + break; + } + } + FLAC__ASSERT(i < blocksize); + FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); + encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample; + encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize); + encoder->private_->verify.error_stats.channel = channel; + encoder->private_->verify.error_stats.sample = sample; + encoder->private_->verify.error_stats.expected = expect; + encoder->private_->verify.error_stats.got = got; + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA; + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + /* dequeue the frame from the fifo */ + encoder->private_->verify.input_fifo.tail -= blocksize; + FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_); + for(channel = 0; channel < channels; channel++) + memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0])); + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + (void)decoder, (void)metadata, (void)client_data; +} + +void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data; + (void)decoder, (void)status; + encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR; +} + +FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + (void)client_data; + + *bytes = fread(buffer, 1, *bytes, encoder->private_->file); + if (*bytes == 0) { + if (feof(encoder->private_->file)) + return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM; + else if (ferror(encoder->private_->file)) + return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; + } + return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE; +} + +FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) +{ + (void)client_data; + + if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0) + return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; + else + return FLAC__STREAM_ENCODER_SEEK_STATUS_OK; +} + +FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) +{ + off_t offset; + + (void)client_data; + + offset = ftello(encoder->private_->file); + + if(offset < 0) { + return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR; + } + else { + *absolute_byte_offset = (FLAC__uint64)offset; + return FLAC__STREAM_ENCODER_TELL_STATUS_OK; + } +} + +#ifdef FLAC__VALGRIND_TESTING +static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#else +#define local__fwrite fwrite +#endif + +FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) +{ + (void)client_data, (void)current_frame; + + if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) { + FLAC__bool call_it = 0 != encoder->private_->progress_callback && ( +#if FLAC__HAS_OGG + /* We would like to be able to use 'samples > 0' in the + * clause here but currently because of the nature of our + * Ogg writing implementation, 'samples' is always 0 (see + * ogg_encoder_aspect.c). The downside is extra progress + * callbacks. + */ + encoder->private_->is_ogg? true : +#endif + samples > 0 + ); + if(call_it) { + /* NOTE: We have to add +bytes, +samples, and +1 to the stats + * because at this point in the callback chain, the stats + * have not been updated. Only after we return and control + * gets back to write_frame_() are the stats updated + */ + encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data); + } + return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; + } + else + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; +} + +/* + * This will forcibly set stdout to binary mode (for OSes that require it) + */ +FILE *get_binary_stdout_(void) +{ + /* if something breaks here it is probably due to the presence or + * absence of an underscore before the identifiers 'setmode', + * 'fileno', and/or 'O_BINARY'; check your system header files. + */ +#if defined _MSC_VER || defined __MINGW32__ + _setmode(_fileno(stdout), _O_BINARY); +#elif defined __CYGWIN__ + /* almost certainly not needed for any modern Cygwin, but let's be safe... */ + setmode(_fileno(stdout), _O_BINARY); +#elif defined __EMX__ + setmode(fileno(stdout), O_BINARY); +#endif + + return stdout; +} diff --git a/flac/src/libFLAC/stream_encoder_framing.c b/flac/src/libFLAC/stream_encoder_framing.c new file mode 100644 index 0000000..4fc6118 --- /dev/null +++ b/flac/src/libFLAC/stream_encoder_framing.c @@ -0,0 +1,553 @@ +/* libFLAC - Free Lossless Audio Codec library + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the Xiph.org Foundation nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``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 FOUNDATION OR + * CONTRIBUTORS 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. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for strlen() */ +#include "private/stream_encoder_framing.h" +#include "private/crc.h" +#include "FLAC/assert.h" + +#ifdef max +#undef max +#endif +#define max(x,y) ((x)>(y)?(x):(y)) + +static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method); +static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended); + +FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw) +{ + unsigned i, j; + const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING); + + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN)) + return false; + + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN)) + return false; + + /* + * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string + */ + i = metadata->length; + if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry); + i -= metadata->data.vorbis_comment.vendor_string.length; + i += vendor_string_length; + } + FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN)) + return false; + + switch(metadata->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN)) + return false; + FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)) + return false; + FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) + return false; + FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) + return false; + FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN)) + return false; + FLAC__ASSERT(metadata->data.stream_info.channels > 0); + FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)) + return false; + FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0); + FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)); + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16)) + return false; + break; + case FLAC__METADATA_TYPE_PADDING: + if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8)) + return false; + break; + case FLAC__METADATA_TYPE_APPLICATION: + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))) + return false; + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + for(i = 0; i < metadata->data.seek_table.num_points; i++) { + if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN)) + return false; + } + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length)) + return false; + if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments)) + return false; + for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) { + if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length)) + return false; + } + break; + case FLAC__METADATA_TYPE_CUESHEET: + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0); + if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8)) + return false; + if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN)) + return false; + if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN)) + return false; + for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) { + const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i; + + if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN)) + return false; + FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0); + if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN)) + return false; + if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN)) + return false; + for(j = 0; j < track->num_indices; j++) { + const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j; + + if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN)) + return false; + if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN)) + return false; + } + } + break; + case FLAC__METADATA_TYPE_PICTURE: + { + size_t len; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN)) + return false; + len = strlen(metadata->data.picture.mime_type); + if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len)) + return false; + len = strlen((const char *)metadata->data.picture.description); + if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) + return false; + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length)) + return false; + } + break; + default: + if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length)) + return false; + break; + } + + FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw)); + return true; +} + +FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw) +{ + unsigned u, blocksize_hint, sample_rate_hint; + FLAC__byte crc; + + FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw)); + + if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN)) + return false; + + if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN)) + return false; + + if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN)) + return false; + + FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE); + /* when this assertion holds true, any legal blocksize can be expressed in the frame header */ + FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u); + blocksize_hint = 0; + switch(header->blocksize) { + case 192: u = 1; break; + case 576: u = 2; break; + case 1152: u = 3; break; + case 2304: u = 4; break; + case 4608: u = 5; break; + case 256: u = 8; break; + case 512: u = 9; break; + case 1024: u = 10; break; + case 2048: u = 11; break; + case 4096: u = 12; break; + case 8192: u = 13; break; + case 16384: u = 14; break; + case 32768: u = 15; break; + default: + if(header->blocksize <= 0x100) + blocksize_hint = u = 6; + else + blocksize_hint = u = 7; + break; + } + if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN)) + return false; + + FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate)); + sample_rate_hint = 0; + switch(header->sample_rate) { + case 88200: u = 1; break; + case 176400: u = 2; break; + case 192000: u = 3; break; + case 8000: u = 4; break; + case 16000: u = 5; break; + case 22050: u = 6; break; + case 24000: u = 7; break; + case 32000: u = 8; break; + case 44100: u = 9; break; + case 48000: u = 10; break; + case 96000: u = 11; break; + default: + if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0) + sample_rate_hint = u = 12; + else if(header->sample_rate % 10 == 0) + sample_rate_hint = u = 14; + else if(header->sample_rate <= 0xffff) + sample_rate_hint = u = 13; + else + u = 0; + break; + } + if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN)) + return false; + + FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS); + switch(header->channel_assignment) { + case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT: + u = header->channels - 1; + break; + case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE: + FLAC__ASSERT(header->channels == 2); + u = 8; + break; + case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE: + FLAC__ASSERT(header->channels == 2); + u = 9; + break; + case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE: + FLAC__ASSERT(header->channels == 2); + u = 10; + break; + default: + FLAC__ASSERT(0); + } + if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN)) + return false; + + FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)); + switch(header->bits_per_sample) { + case 8 : u = 1; break; + case 12: u = 2; break; + case 16: u = 4; break; + case 20: u = 5; break; + case 24: u = 6; break; + default: u = 0; break; + } + if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN)) + return false; + + if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN)) + return false; + + if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) { + if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number)) + return false; + } + else { + if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number)) + return false; + } + + if(blocksize_hint) + if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16)) + return false; + + switch(sample_rate_hint) { + case 12: + if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8)) + return false; + break; + case 13: + if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16)) + return false; + break; + case 14: + if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16)) + return false; + break; + } + + /* write the CRC */ + if(!FLAC__bitwriter_get_write_crc8(bw, &crc)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN)) + return false; + + return true; +} + +FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw) +{ + FLAC__bool ok; + + ok = + FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) && + (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) && + FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps) + ; + + return ok; +} + +FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw) +{ + unsigned i; + + if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN)) + return false; + if(wasted_bits) + if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1)) + return false; + + for(i = 0; i < subframe->order; i++) + if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps)) + return false; + + if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method)) + return false; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!add_residual_partitioned_rice_( + bw, + subframe->residual, + residual_samples, + subframe->order, + subframe->entropy_coding_method.data.partitioned_rice.contents->parameters, + subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits, + subframe->entropy_coding_method.data.partitioned_rice.order, + /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 + )) + return false; + break; + default: + FLAC__ASSERT(0); + } + + return true; +} + +FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw) +{ + unsigned i; + + if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN)) + return false; + if(wasted_bits) + if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1)) + return false; + + for(i = 0; i < subframe->order; i++) + if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps)) + return false; + + if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)) + return false; + if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN)) + return false; + for(i = 0; i < subframe->order; i++) + if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision)) + return false; + + if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method)) + return false; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!add_residual_partitioned_rice_( + bw, + subframe->residual, + residual_samples, + subframe->order, + subframe->entropy_coding_method.data.partitioned_rice.contents->parameters, + subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits, + subframe->entropy_coding_method.data.partitioned_rice.order, + /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 + )) + return false; + break; + default: + FLAC__ASSERT(0); + } + + return true; +} + +FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw) +{ + unsigned i; + const FLAC__int32 *signal = subframe->data; + + if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN)) + return false; + if(wasted_bits) + if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1)) + return false; + + for(i = 0; i < samples; i++) + if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps)) + return false; + + return true; +} + +FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method) +{ + if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN)) + return false; + switch(method->type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + return false; + break; + default: + FLAC__ASSERT(0); + } + return true; +} + +FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended) +{ + const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; + const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; + + if(partition_order == 0) { + unsigned i; + + if(raw_bits[0] == 0) { + if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen)) + return false; + if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0])) + return false; + } + else { + FLAC__ASSERT(rice_parameters[0] == 0); + if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen)) + return false; + if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN)) + return false; + for(i = 0; i < residual_samples; i++) { + if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0])) + return false; + } + } + return true; + } + else { + unsigned i, j, k = 0, k_last = 0; + unsigned partition_samples; + const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order; + for(i = 0; i < (1u< +#endif + +#include +#include "FLAC/assert.h" +#include "FLAC/format.h" +#include "private/window.h" + +#ifndef FLAC__INTEGER_ONLY_LIBRARY + +#ifndef M_PI +/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */ +#define M_PI 3.14159265358979323846 +#endif + + +void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + if (L & 1) { + for (n = 0; n <= N/2; n++) + window[n] = 2.0f * n / (float)N; + for (; n <= N; n++) + window[n] = 2.0f - 2.0f * n / (float)N; + } + else { + for (n = 0; n <= L/2-1; n++) + window[n] = 2.0f * n / (float)N; + for (; n <= N; n++) + window[n] = 2.0f - 2.0f * (N-n) / (float)N; + } +} + +void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f))); +} + +void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N)); +} + +/* 4-term -92dB side-lobe */ +void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n <= N; n++) + window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N)); +} + +void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + const double N2 = (double)N / 2.; + FLAC__int32 n; + + for (n = 0; n <= N; n++) { + double k = ((double)n - N2) / N2; + k = 1.0f - k * k; + window[n] = (FLAC__real)(k * k); + } +} + +void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N)); +} + +void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev) +{ + const FLAC__int32 N = L - 1; + const double N2 = (double)N / 2.; + FLAC__int32 n; + + for (n = 0; n <= N; n++) { + const double k = ((double)n - N2) / (stddev * N2); + window[n] = (FLAC__real)exp(-0.5f * k * k); + } +} + +void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N)); +} + +void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N)); +} + +void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N)); +} + +void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N)); +} + +void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L) +{ + FLAC__int32 n; + + for (n = 0; n < L; n++) + window[n] = 1.0f; +} + +void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L) +{ + FLAC__int32 n; + + if (L & 1) { + for (n = 1; n <= L+1/2; n++) + window[n-1] = 2.0f * n / ((float)L + 1.0f); + for (; n <= L; n++) + window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f); + } + else { + for (n = 1; n <= L/2; n++) + window[n-1] = 2.0f * n / (float)L; + for (; n <= L; n++) + window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L; + } +} + +void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p) +{ + if (p <= 0.0) + FLAC__window_rectangle(window, L); + else if (p >= 1.0) + FLAC__window_hann(window, L); + else { + const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1; + FLAC__int32 n; + /* start with rectangle... */ + FLAC__window_rectangle(window, L); + /* ...replace ends with hann */ + if (Np > 0) { + for (n = 0; n <= Np; n++) { + window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np)); + window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np)); + } + } + } +} + +void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L) +{ + const FLAC__int32 N = L - 1; + const double N2 = (double)N / 2.; + FLAC__int32 n; + + for (n = 0; n <= N; n++) { + const double k = ((double)n - N2) / N2; + window[n] = (FLAC__real)(1.0f - k * k); + } +} + +#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */ diff --git a/flac/src/metaflac/Makefile.am b/flac/src/metaflac/Makefile.am new file mode 100644 index 0000000..93413ef --- /dev/null +++ b/flac/src/metaflac/Makefile.am @@ -0,0 +1,54 @@ +# metaflac - Command-line FLAC metadata editor +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +bin_PROGRAMS = metaflac + +AM_CFLAGS = @OGG_CFLAGS@ + +EXTRA_DIST = \ + Makefile.lite \ + metaflac.dsp \ + metaflac.vcproj + +metaflac_SOURCES = \ + main.c \ + operations.c \ + operations_shorthand_cuesheet.c \ + operations_shorthand_picture.c \ + operations_shorthand_seektable.c \ + operations_shorthand_streaminfo.c \ + operations_shorthand_vorbiscomment.c \ + options.c \ + usage.c \ + utils.c \ + operations.h \ + operations_shorthand.h \ + options.h \ + usage.h \ + utils.h +metaflac_LDFLAGS = + +metaflac_LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/share/getopt/libgetopt.a \ + $(top_builddir)/src/share/utf8/libutf8.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @LIBICONV@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm diff --git a/flac/src/metaflac/Makefile.lite b/flac/src/metaflac/Makefile.lite new file mode 100644 index 0000000..cc322a3 --- /dev/null +++ b/flac/src/metaflac/Makefile.lite @@ -0,0 +1,49 @@ +# metaflac - Command-line FLAC metadata editor +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = metaflac + +INCLUDES = -I./include -I$(topdir)/include -I$(OGG_INCLUDE_DIR) + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libFLAC.a $(libdir)/libreplaygain_analysis.a $(libdir)/libgetopt.a $(libdir)/libutf8.a $(OGG_LIB_DIR)/libogg.a -liconv -lm +else +LIBS = -lgrabbag -lFLAC -lreplaygain_analysis -lgetopt -lutf8 -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + main.c \ + operations.c \ + operations_shorthand_cuesheet.c \ + operations_shorthand_picture.c \ + operations_shorthand_seektable.c \ + operations_shorthand_streaminfo.c \ + operations_shorthand_vorbiscomment.c \ + options.c \ + usage.c \ + utils.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/metaflac/main.c b/flac/src/metaflac/main.c new file mode 100644 index 0000000..42279e1 --- /dev/null +++ b/flac/src/metaflac/main.c @@ -0,0 +1,48 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "operations.h" +#include "options.h" +#include + +int main(int argc, char *argv[]) +{ + CommandLineOptions options; + int ret = 0; + +#ifdef __EMX__ + _response(&argc, &argv); + _wildcard(&argc, &argv); +#endif + + setlocale(LC_ALL, ""); + init_options(&options); + + if(parse_options(argc, argv, &options)) + ret = !do_operations(&options); + else + ret = 1; + + free_options(&options); + + return ret; +} diff --git a/flac/src/metaflac/metaflac.dsp b/flac/src/metaflac/metaflac.dsp new file mode 100644 index 0000000..d1ec51f --- /dev/null +++ b/flac/src/metaflac/metaflac.dsp @@ -0,0 +1,152 @@ +# Microsoft Developer Studio Project File - Name="metaflac" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=metaflac - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "metaflac.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "metaflac.mak" CFG="metaflac - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "metaflac - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "metaflac - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "metaflac - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "." /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\grabbag_static.lib ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\obj\release\lib\getopt_static.lib ..\..\obj\release\lib\utf8_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "metaflac - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "." /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\grabbag_static.lib ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\obj\debug\lib\getopt_static.lib ..\..\obj\debug\lib\utf8_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "metaflac - Win32 Release" +# Name "metaflac - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# Begin Source File + +SOURCE=.\operations.c +# End Source File +# Begin Source File + +SOURCE=.\operations_shorthand_cuesheet.c +# End Source File +# Begin Source File + +SOURCE=.\operations_shorthand_picture.c +# End Source File +# Begin Source File + +SOURCE=.\operations_shorthand_seektable.c +# End Source File +# Begin Source File + +SOURCE=.\operations_shorthand_streaminfo.c +# End Source File +# Begin Source File + +SOURCE=.\operations_shorthand_vorbiscomment.c +# End Source File +# Begin Source File + +SOURCE=.\options.c +# End Source File +# Begin Source File + +SOURCE=.\usage.c +# End Source File +# Begin Source File + +SOURCE=.\utils.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\operations.h +# End Source File +# Begin Source File + +SOURCE=.\options.h +# End Source File +# Begin Source File + +SOURCE=.\usage.h +# End Source File +# Begin Source File + +SOURCE=.\utils.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/metaflac/metaflac.vcproj b/flac/src/metaflac/metaflac.vcproj new file mode 100644 index 0000000..64b5424 --- /dev/null +++ b/flac/src/metaflac/metaflac.vcproj @@ -0,0 +1,424 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/metaflac/operations.c b/flac/src/metaflac/operations.c new file mode 100644 index 0000000..805ce08 --- /dev/null +++ b/flac/src/metaflac/operations.c @@ -0,0 +1,682 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "operations.h" +#include "usage.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "share/alloc.h" +#include "share/grabbag.h" +#include +#include +#include +#include "operations_shorthand.h" + +static void show_version(void); +static FLAC__bool do_major_operation(const CommandLineOptions *options); +static FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options); +static FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options); +static FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); +static FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); +static FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); +static FLAC__bool do_shorthand_operations(const CommandLineOptions *options); +static FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options); +static FLAC__bool do_shorthand_operation(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert); +static FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files, FLAC__bool preserve_modtime); +static FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write); + +static FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number); +static void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application); + +/* from operations_shorthand_seektable.c */ +extern FLAC__bool do_shorthand_operation__add_seekpoints(const char *filename, FLAC__Metadata_Chain *chain, const char *specification, FLAC__bool *needs_write); + +/* from operations_shorthand_streaminfo.c */ +extern FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); + +/* from operations_shorthand_vorbiscomment.c */ +extern FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw); + +/* from operations_shorthand_cuesheet.c */ +extern FLAC__bool do_shorthand_operation__cuesheet(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); + +/* from operations_shorthand_picture.c */ +extern FLAC__bool do_shorthand_operation__picture(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); + + +FLAC__bool do_operations(const CommandLineOptions *options) +{ + FLAC__bool ok = true; + + if(options->show_long_help) { + long_usage(0); + } + if(options->show_version) { + show_version(); + } + else if(options->args.checks.num_major_ops > 0) { + FLAC__ASSERT(options->args.checks.num_shorthand_ops == 0); + FLAC__ASSERT(options->args.checks.num_major_ops == 1); + FLAC__ASSERT(options->args.checks.num_major_ops == options->ops.num_operations); + ok = do_major_operation(options); + } + else if(options->args.checks.num_shorthand_ops > 0) { + FLAC__ASSERT(options->args.checks.num_shorthand_ops == options->ops.num_operations); + ok = do_shorthand_operations(options); + } + + return ok; +} + +/* + * local routines + */ + +void show_version(void) +{ + printf("metaflac %s\n", FLAC__VERSION_STRING); +} + +FLAC__bool do_major_operation(const CommandLineOptions *options) +{ + unsigned i; + FLAC__bool ok = true; + + /* to die after first error, v--- add '&& ok' here */ + for(i = 0; i < options->num_files; i++) + ok &= do_major_operation_on_file(options->filenames[i], options); + + return ok; +} + +FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options) +{ + FLAC__bool ok = true, needs_write = false, is_ogg = false; + FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new(); + + if(0 == chain) + die("out of memory allocating chain"); + + /*@@@@ lame way of guessing the file type */ + if(strlen(filename) >= 4 && (0 == strcmp(filename+strlen(filename)-4, ".oga") || 0 == strcmp(filename+strlen(filename)-4, ".ogg"))) + is_ogg = true; + + if(! (is_ogg? FLAC__metadata_chain_read_ogg(chain, filename) : FLAC__metadata_chain_read(chain, filename)) ) { + print_error_with_chain_status(chain, "%s: ERROR: reading metadata", filename); + FLAC__metadata_chain_delete(chain); + return false; + } + + switch(options->ops.operations[0].type) { + case OP__LIST: + ok = do_major_operation__list(options->prefix_with_filename? filename : 0, chain, options); + break; + case OP__APPEND: + ok = do_major_operation__append(chain, options); + needs_write = true; + break; + case OP__REMOVE: + ok = do_major_operation__remove(chain, options); + needs_write = true; + break; + case OP__REMOVE_ALL: + ok = do_major_operation__remove_all(chain, options); + needs_write = true; + break; + case OP__MERGE_PADDING: + FLAC__metadata_chain_merge_padding(chain); + needs_write = true; + break; + case OP__SORT_PADDING: + FLAC__metadata_chain_sort_padding(chain); + needs_write = true; + break; + default: + FLAC__ASSERT(0); + return false; + } + + if(ok && needs_write) { + if(options->use_padding) + FLAC__metadata_chain_sort_padding(chain); + ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime); + if(!ok) + print_error_with_chain_status(chain, "%s: ERROR: writing FLAC file", filename); + } + + FLAC__metadata_chain_delete(chain); + + return ok; +} + +FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options) +{ + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + FLAC__StreamMetadata *block; + FLAC__bool ok = true; + unsigned block_number; + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + block_number = 0; + do { + block = FLAC__metadata_iterator_get_block(iterator); + ok &= (0 != block); + if(!ok) + fprintf(stderr, "%s: ERROR: couldn't get block from chain\n", filename); + else if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) + write_metadata(filename, block, block_number, !options->utf8_convert, options->application_data_format_is_hexdump); + block_number++; + } while(ok && FLAC__metadata_iterator_next(iterator)); + + FLAC__metadata_iterator_delete(iterator); + + return ok; +} + +FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) +{ + (void) chain, (void) options; + fprintf(stderr, "ERROR: --append not implemented yet\n"); + return false; +} + +FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) +{ + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + FLAC__bool ok = true; + unsigned block_number; + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + block_number = 0; + while(ok && FLAC__metadata_iterator_next(iterator)) { + block_number++; + if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) { + ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding); + if(options->use_padding) + ok &= FLAC__metadata_iterator_next(iterator); + } + } + + FLAC__metadata_iterator_delete(iterator); + + return ok; +} + +FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) +{ + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + FLAC__bool ok = true; + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + while(ok && FLAC__metadata_iterator_next(iterator)) { + ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding); + if(options->use_padding) + ok &= FLAC__metadata_iterator_next(iterator); + } + + FLAC__metadata_iterator_delete(iterator); + + return ok; +} + +FLAC__bool do_shorthand_operations(const CommandLineOptions *options) +{ + unsigned i; + FLAC__bool ok = true; + + /* to die after first error, v--- add '&& ok' here */ + for(i = 0; i < options->num_files; i++) + ok &= do_shorthand_operations_on_file(options->filenames[i], options); + + /* check if OP__ADD_REPLAY_GAIN requested */ + if(ok && options->num_files > 0) { + for(i = 0; i < options->ops.num_operations; i++) { + if(options->ops.operations[i].type == OP__ADD_REPLAY_GAIN) + ok = do_shorthand_operation__add_replay_gain(options->filenames, options->num_files, options->preserve_modtime); + } + } + + return ok; +} + +FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options) +{ + unsigned i; + FLAC__bool ok = true, needs_write = false, use_padding = options->use_padding; + FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new(); + + if(0 == chain) + die("out of memory allocating chain"); + + if(!FLAC__metadata_chain_read(chain, filename)) { + print_error_with_chain_status(chain, "%s: ERROR: reading metadata", filename); + return false; + } + + for(i = 0; i < options->ops.num_operations && ok; i++) { + /* + * Do OP__ADD_SEEKPOINT last to avoid decoding twice if both + * --add-seekpoint and --import-cuesheet-from are used. + */ + if(options->ops.operations[i].type != OP__ADD_SEEKPOINT) + ok &= do_shorthand_operation(filename, options->prefix_with_filename, chain, &options->ops.operations[i], &needs_write, options->utf8_convert); + + /* The following seems counterintuitive but the meaning + * of 'use_padding' is 'try to keep the overall metadata + * to its original size, adding or truncating extra + * padding if necessary' which is why we need to turn it + * off in this case. If we don't, the extra padding block + * will just be truncated. + */ + if(options->ops.operations[i].type == OP__ADD_PADDING) + use_padding = false; + } + + /* + * Do OP__ADD_SEEKPOINT last to avoid decoding twice if both + * --add-seekpoint and --import-cuesheet-from are used. + */ + for(i = 0; i < options->ops.num_operations && ok; i++) { + if(options->ops.operations[i].type == OP__ADD_SEEKPOINT) + ok &= do_shorthand_operation(filename, options->prefix_with_filename, chain, &options->ops.operations[i], &needs_write, options->utf8_convert); + } + + if(ok && needs_write) { + if(use_padding) + FLAC__metadata_chain_sort_padding(chain); + ok = FLAC__metadata_chain_write(chain, use_padding, options->preserve_modtime); + if(!ok) + print_error_with_chain_status(chain, "%s: ERROR: writing FLAC file", filename); + } + + FLAC__metadata_chain_delete(chain); + + return ok; +} + +FLAC__bool do_shorthand_operation(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert) +{ + FLAC__bool ok = true; + + switch(operation->type) { + case OP__SHOW_MD5SUM: + case OP__SHOW_MIN_BLOCKSIZE: + case OP__SHOW_MAX_BLOCKSIZE: + case OP__SHOW_MIN_FRAMESIZE: + case OP__SHOW_MAX_FRAMESIZE: + case OP__SHOW_SAMPLE_RATE: + case OP__SHOW_CHANNELS: + case OP__SHOW_BPS: + case OP__SHOW_TOTAL_SAMPLES: + case OP__SET_MD5SUM: + case OP__SET_MIN_BLOCKSIZE: + case OP__SET_MAX_BLOCKSIZE: + case OP__SET_MIN_FRAMESIZE: + case OP__SET_MAX_FRAMESIZE: + case OP__SET_SAMPLE_RATE: + case OP__SET_CHANNELS: + case OP__SET_BPS: + case OP__SET_TOTAL_SAMPLES: + ok = do_shorthand_operation__streaminfo(filename, prefix_with_filename, chain, operation, needs_write); + break; + case OP__SHOW_VC_VENDOR: + case OP__SHOW_VC_FIELD: + case OP__REMOVE_VC_ALL: + case OP__REMOVE_VC_FIELD: + case OP__REMOVE_VC_FIRSTFIELD: + case OP__SET_VC_FIELD: + case OP__IMPORT_VC_FROM: + case OP__EXPORT_VC_TO: + ok = do_shorthand_operation__vorbis_comment(filename, prefix_with_filename, chain, operation, needs_write, !utf8_convert); + break; + case OP__IMPORT_CUESHEET_FROM: + case OP__EXPORT_CUESHEET_TO: + ok = do_shorthand_operation__cuesheet(filename, chain, operation, needs_write); + break; + case OP__IMPORT_PICTURE_FROM: + case OP__EXPORT_PICTURE_TO: + ok = do_shorthand_operation__picture(filename, chain, operation, needs_write); + break; + case OP__ADD_SEEKPOINT: + ok = do_shorthand_operation__add_seekpoints(filename, chain, operation->argument.add_seekpoint.specification, needs_write); + break; + case OP__ADD_REPLAY_GAIN: + /* this command is always executed last */ + ok = true; + break; + case OP__ADD_PADDING: + ok = do_shorthand_operation__add_padding(filename, chain, operation->argument.add_padding.length, needs_write); + break; + default: + ok = false; + FLAC__ASSERT(0); + break; + }; + + return ok; +} + +FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files, FLAC__bool preserve_modtime) +{ + FLAC__StreamMetadata streaminfo; + float *title_gains = 0, *title_peaks = 0; + float album_gain, album_peak; + unsigned sample_rate = 0; + unsigned bits_per_sample = 0; + unsigned channels = 0; + unsigned i; + const char *error; + FLAC__bool first = true; + + FLAC__ASSERT(num_files > 0); + + for(i = 0; i < num_files; i++) { + FLAC__ASSERT(0 != filenames[i]); + if(!FLAC__metadata_get_streaminfo(filenames[i], &streaminfo)) { + fprintf(stderr, "%s: ERROR: can't open file or get STREAMINFO block\n", filenames[i]); + return false; + } + if(first) { + first = false; + sample_rate = streaminfo.data.stream_info.sample_rate; + bits_per_sample = streaminfo.data.stream_info.bits_per_sample; + channels = streaminfo.data.stream_info.channels; + } + else { + if(sample_rate != streaminfo.data.stream_info.sample_rate) { + fprintf(stderr, "%s: ERROR: sample rate of %u Hz does not match previous files' %u Hz\n", filenames[i], streaminfo.data.stream_info.sample_rate, sample_rate); + return false; + } + if(bits_per_sample != streaminfo.data.stream_info.bits_per_sample) { + fprintf(stderr, "%s: ERROR: resolution of %u bps does not match previous files' %u bps\n", filenames[i], streaminfo.data.stream_info.bits_per_sample, bits_per_sample); + return false; + } + if(channels != streaminfo.data.stream_info.channels) { + fprintf(stderr, "%s: ERROR: # channels (%u) does not match previous files' (%u)\n", filenames[i], streaminfo.data.stream_info.channels, channels); + return false; + } + } + if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) { + fprintf(stderr, "%s: ERROR: sample rate of %u Hz is not supported\n", filenames[i], sample_rate); + return false; + } + if(channels != 1 && channels != 2) { + fprintf(stderr, "%s: ERROR: # of channels (%u) is not supported, must be 1 or 2\n", filenames[i], channels); + return false; + } + } + FLAC__ASSERT(bits_per_sample >= FLAC__MIN_BITS_PER_SAMPLE && bits_per_sample <= FLAC__MAX_BITS_PER_SAMPLE); + + if(!grabbag__replaygain_init(sample_rate)) { + FLAC__ASSERT(0); + /* double protection */ + fprintf(stderr, "internal error\n"); + return false; + } + + if( + 0 == (title_gains = (float*)safe_malloc_mul_2op_(sizeof(float), /*times*/num_files)) || + 0 == (title_peaks = (float*)safe_malloc_mul_2op_(sizeof(float), /*times*/num_files)) + ) + die("out of memory allocating space for title gains/peaks"); + + for(i = 0; i < num_files; i++) { + if(0 != (error = grabbag__replaygain_analyze_file(filenames[i], title_gains+i, title_peaks+i))) { + fprintf(stderr, "%s: ERROR: during analysis (%s)\n", filenames[i], error); + free(title_gains); + free(title_peaks); + return false; + } + } + grabbag__replaygain_get_album(&album_gain, &album_peak); + + for(i = 0; i < num_files; i++) { + if(0 != (error = grabbag__replaygain_store_to_file(filenames[i], album_gain, album_peak, title_gains[i], title_peaks[i], preserve_modtime))) { + fprintf(stderr, "%s: ERROR: writing tags (%s)\n", filenames[i], error); + free(title_gains); + free(title_peaks); + return false; + } + } + + free(title_gains); + free(title_peaks); + return true; +} + +FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write) +{ + FLAC__StreamMetadata *padding = 0; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + while(FLAC__metadata_iterator_next(iterator)) + ; + + padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + if(0 == padding) + die("out of memory allocating PADDING block"); + + padding->length = length; + + if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) { + print_error_with_chain_status(chain, "%s: ERROR: adding new PADDING block to metadata", filename); + FLAC__metadata_object_delete(padding); + FLAC__metadata_iterator_delete(iterator); + return false; + } + + FLAC__metadata_iterator_delete(iterator); + *needs_write = true; + return true; +} + +FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number) +{ + unsigned i, j; + FLAC__bool matches_number = false, matches_type = false; + FLAC__bool has_block_number_arg = false; + + for(i = 0; i < options->args.num_arguments; i++) { + if(options->args.arguments[i].type == ARG__BLOCK_TYPE || options->args.arguments[i].type == ARG__EXCEPT_BLOCK_TYPE) { + for(j = 0; j < options->args.arguments[i].value.block_type.num_entries; j++) { + if(options->args.arguments[i].value.block_type.entries[j].type == block->type) { + if(block->type != FLAC__METADATA_TYPE_APPLICATION || !options->args.arguments[i].value.block_type.entries[j].filter_application_by_id || 0 == memcmp(options->args.arguments[i].value.block_type.entries[j].application_id, block->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)) + matches_type = true; + } + } + } + else if(options->args.arguments[i].type == ARG__BLOCK_NUMBER) { + has_block_number_arg = true; + for(j = 0; j < options->args.arguments[i].value.block_number.num_entries; j++) { + if(options->args.arguments[i].value.block_number.entries[j] == block_number) + matches_number = true; + } + } + } + + if(!has_block_number_arg) + matches_number = true; + + if(options->args.checks.has_block_type) { + FLAC__ASSERT(!options->args.checks.has_except_block_type); + } + else if(options->args.checks.has_except_block_type) + matches_type = !matches_type; + else + matches_type = true; + + return matches_number && matches_type; +} + +void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application) +{ + unsigned i, j; + +/*@@@ yuck, should do this with a varargs function or something: */ +#define PPR if(filename)printf("%s:",filename); + PPR; printf("METADATA block #%u\n", block_number); + PPR; printf(" type: %u (%s)\n", (unsigned)block->type, block->type < FLAC__METADATA_TYPE_UNDEFINED? FLAC__MetadataTypeString[block->type] : "UNKNOWN"); + PPR; printf(" is last: %s\n", block->is_last? "true":"false"); + PPR; printf(" length: %u\n", block->length); + + switch(block->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + PPR; printf(" minimum blocksize: %u samples\n", block->data.stream_info.min_blocksize); + PPR; printf(" maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize); + PPR; printf(" minimum framesize: %u bytes\n", block->data.stream_info.min_framesize); + PPR; printf(" maximum framesize: %u bytes\n", block->data.stream_info.max_framesize); + PPR; printf(" sample_rate: %u Hz\n", block->data.stream_info.sample_rate); + PPR; printf(" channels: %u\n", block->data.stream_info.channels); + PPR; printf(" bits-per-sample: %u\n", block->data.stream_info.bits_per_sample); +#ifdef _MSC_VER + PPR; printf(" total samples: %I64u\n", block->data.stream_info.total_samples); +#else + PPR; printf(" total samples: %llu\n", (unsigned long long)block->data.stream_info.total_samples); +#endif + PPR; printf(" MD5 signature: "); + for(i = 0; i < 16; i++) { + printf("%02x", (unsigned)block->data.stream_info.md5sum[i]); + } + printf("\n"); + break; + case FLAC__METADATA_TYPE_PADDING: + /* nothing to print */ + break; + case FLAC__METADATA_TYPE_APPLICATION: + PPR; printf(" application ID: "); + for(i = 0; i < 4; i++) + printf("%02x", block->data.application.id[i]); + printf("\n"); + PPR; printf(" data contents:\n"); + if(0 != block->data.application.data) { + if(hexdump_application) + hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, " "); + else + (void) local_fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout); + } + break; + case FLAC__METADATA_TYPE_SEEKTABLE: + PPR; printf(" seek points: %u\n", block->data.seek_table.num_points); + for(i = 0; i < block->data.seek_table.num_points; i++) { + if(block->data.seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) { +#ifdef _MSC_VER + PPR; printf(" point %u: sample_number=%I64u, stream_offset=%I64u, frame_samples=%u\n", i, block->data.seek_table.points[i].sample_number, block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples); +#else + PPR; printf(" point %u: sample_number=%llu, stream_offset=%llu, frame_samples=%u\n", i, (unsigned long long)block->data.seek_table.points[i].sample_number, (unsigned long long)block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples); +#endif + } + else { + PPR; printf(" point %u: PLACEHOLDER\n", i); + } + } + break; + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + PPR; printf(" vendor string: "); + write_vc_field(0, &block->data.vorbis_comment.vendor_string, raw, stdout); + PPR; printf(" comments: %u\n", block->data.vorbis_comment.num_comments); + for(i = 0; i < block->data.vorbis_comment.num_comments; i++) { + PPR; printf(" comment[%u]: ", i); + write_vc_field(0, &block->data.vorbis_comment.comments[i], raw, stdout); + } + break; + case FLAC__METADATA_TYPE_CUESHEET: + PPR; printf(" media catalog number: %s\n", block->data.cue_sheet.media_catalog_number); +#ifdef _MSC_VER + PPR; printf(" lead-in: %I64u\n", block->data.cue_sheet.lead_in); +#else + PPR; printf(" lead-in: %llu\n", (unsigned long long)block->data.cue_sheet.lead_in); +#endif + PPR; printf(" is CD: %s\n", block->data.cue_sheet.is_cd? "true":"false"); + PPR; printf(" number of tracks: %u\n", block->data.cue_sheet.num_tracks); + for(i = 0; i < block->data.cue_sheet.num_tracks; i++) { + const FLAC__StreamMetadata_CueSheet_Track *track = block->data.cue_sheet.tracks+i; + const FLAC__bool is_last = (i == block->data.cue_sheet.num_tracks-1); + const FLAC__bool is_leadout = is_last && track->num_indices == 0; + PPR; printf(" track[%u]\n", i); +#ifdef _MSC_VER + PPR; printf(" offset: %I64u\n", track->offset); +#else + PPR; printf(" offset: %llu\n", (unsigned long long)track->offset); +#endif + if(is_last) { + PPR; printf(" number: %u (%s)\n", (unsigned)track->number, is_leadout? "LEAD-OUT" : "INVALID"); + } + else { + PPR; printf(" number: %u\n", (unsigned)track->number); + } + if(!is_leadout) { + PPR; printf(" ISRC: %s\n", track->isrc); + PPR; printf(" type: %s\n", track->type == 1? "DATA" : "AUDIO"); + PPR; printf(" pre-emphasis: %s\n", track->pre_emphasis? "true":"false"); + PPR; printf(" number of index points: %u\n", track->num_indices); + for(j = 0; j < track->num_indices; j++) { + const FLAC__StreamMetadata_CueSheet_Index *index = track->indices+j; + PPR; printf(" index[%u]\n", j); +#ifdef _MSC_VER + PPR; printf(" offset: %I64u\n", index->offset); +#else + PPR; printf(" offset: %llu\n", (unsigned long long)index->offset); +#endif + PPR; printf(" number: %u\n", (unsigned)index->number); + } + } + } + break; + case FLAC__METADATA_TYPE_PICTURE: + PPR; printf(" type: %u (%s)\n", block->data.picture.type, block->data.picture.type < FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED? FLAC__StreamMetadata_Picture_TypeString[block->data.picture.type] : "UNDEFINED"); + PPR; printf(" MIME type: %s\n", block->data.picture.mime_type); + PPR; printf(" description: %s\n", block->data.picture.description); + PPR; printf(" width: %u\n", (unsigned)block->data.picture.width); + PPR; printf(" height: %u\n", (unsigned)block->data.picture.height); + PPR; printf(" depth: %u\n", (unsigned)block->data.picture.depth); + PPR; printf(" colors: %u%s\n", (unsigned)block->data.picture.colors, block->data.picture.colors? "" : " (unindexed)"); + PPR; printf(" data length: %u\n", (unsigned)block->data.picture.data_length); + PPR; printf(" data:\n"); + if(0 != block->data.picture.data) + hexdump(filename, block->data.picture.data, block->data.picture.data_length, " "); + break; + default: + PPR; printf(" data contents:\n"); + if(0 != block->data.unknown.data) + hexdump(filename, block->data.unknown.data, block->length, " "); + break; + } +#undef PPR +} diff --git a/flac/src/metaflac/operations.h b/flac/src/metaflac/operations.h new file mode 100644 index 0000000..fb36d00 --- /dev/null +++ b/flac/src/metaflac/operations.h @@ -0,0 +1,26 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef metaflac__operations_h +#define metaflac__operations_h + +#include "options.h" + +FLAC__bool do_operations(const CommandLineOptions *options); + +#endif diff --git a/flac/src/metaflac/operations_shorthand.h b/flac/src/metaflac/operations_shorthand.h new file mode 100644 index 0000000..5fbd479 --- /dev/null +++ b/flac/src/metaflac/operations_shorthand.h @@ -0,0 +1,25 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "options.h" + +FLAC__bool do_shorthand_operation__picture(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); +FLAC__bool do_shorthand_operation__cuesheet(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); +FLAC__bool do_shorthand_operation__add_seekpoints(const char *filename, FLAC__Metadata_Chain *chain, const char *specification, FLAC__bool *needs_write); +FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); +FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw); diff --git a/flac/src/metaflac/operations_shorthand_cuesheet.c b/flac/src/metaflac/operations_shorthand_cuesheet.c new file mode 100644 index 0000000..2c650a5 --- /dev/null +++ b/flac/src/metaflac/operations_shorthand_cuesheet.c @@ -0,0 +1,217 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for snprintf() */ +#include +#include "options.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "share/grabbag.h" +#include "operations_shorthand.h" + +static FLAC__bool import_cs_from(const char *filename, FLAC__StreamMetadata **cuesheet, const char *cs_filename, FLAC__bool *needs_write, FLAC__uint64 lead_out_offset, FLAC__bool is_cdda, Argument_AddSeekpoint *add_seekpoint_link); +static FLAC__bool export_cs_to(const char *filename, const FLAC__StreamMetadata *cuesheet, const char *cs_filename); + +FLAC__bool do_shorthand_operation__cuesheet(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write) +{ + FLAC__bool ok = true; + FLAC__StreamMetadata *cuesheet = 0; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + FLAC__uint64 lead_out_offset = 0; + FLAC__bool is_cdda = false; + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + do { + FLAC__StreamMetadata *block = FLAC__metadata_iterator_get_block(iterator); + if(block->type == FLAC__METADATA_TYPE_STREAMINFO) { + lead_out_offset = block->data.stream_info.total_samples; + if(lead_out_offset == 0) { + fprintf(stderr, "%s: ERROR: FLAC file must have total_samples set in STREAMINFO in order to import/export cuesheet\n", filename); + FLAC__metadata_iterator_delete(iterator); + return false; + } + is_cdda = (block->data.stream_info.channels == 1 || block->data.stream_info.channels == 2) && (block->data.stream_info.bits_per_sample == 16) && (block->data.stream_info.sample_rate == 44100); + } + else if(block->type == FLAC__METADATA_TYPE_CUESHEET) + cuesheet = block; + } while(FLAC__metadata_iterator_next(iterator)); + + if(lead_out_offset == 0) { + fprintf(stderr, "%s: ERROR: FLAC stream has no STREAMINFO block\n", filename); + FLAC__metadata_iterator_delete(iterator); + return false; + } + + switch(operation->type) { + case OP__IMPORT_CUESHEET_FROM: + if(0 != cuesheet) { + fprintf(stderr, "%s: ERROR: FLAC file already has CUESHEET block\n", filename); + ok = false; + } + else { + ok = import_cs_from(filename, &cuesheet, operation->argument.import_cuesheet_from.filename, needs_write, lead_out_offset, is_cdda, operation->argument.import_cuesheet_from.add_seekpoint_link); + if(ok) { + /* append CUESHEET block */ + while(FLAC__metadata_iterator_next(iterator)) + ; + if(!FLAC__metadata_iterator_insert_block_after(iterator, cuesheet)) { + print_error_with_chain_status(chain, "%s: ERROR: adding new CUESHEET block to metadata", filename); + FLAC__metadata_object_delete(cuesheet); + ok = false; + } + } + } + break; + case OP__EXPORT_CUESHEET_TO: + if(0 == cuesheet) { + fprintf(stderr, "%s: ERROR: FLAC file has no CUESHEET block\n", filename); + ok = false; + } + else + ok = export_cs_to(filename, cuesheet, operation->argument.filename.value); + break; + default: + ok = false; + FLAC__ASSERT(0); + break; + }; + + FLAC__metadata_iterator_delete(iterator); + return ok; +} + +/* + * local routines + */ + +FLAC__bool import_cs_from(const char *filename, FLAC__StreamMetadata **cuesheet, const char *cs_filename, FLAC__bool *needs_write, FLAC__uint64 lead_out_offset, FLAC__bool is_cdda, Argument_AddSeekpoint *add_seekpoint_link) +{ + FILE *f; + const char *error_message; + char **seekpoint_specification = add_seekpoint_link? &(add_seekpoint_link->specification) : 0; + unsigned last_line_read; + + if(0 == cs_filename || strlen(cs_filename) == 0) { + fprintf(stderr, "%s: ERROR: empty import file name\n", filename); + return false; + } + if(0 == strcmp(cs_filename, "-")) + f = stdin; + else + f = fopen(cs_filename, "r"); + + if(0 == f) { + fprintf(stderr, "%s: ERROR: can't open import file %s: %s\n", filename, cs_filename, strerror(errno)); + return false; + } + + *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, is_cdda, lead_out_offset); + + if(f != stdin) + fclose(f); + + if(0 == *cuesheet) { + fprintf(stderr, "%s: ERROR: while parsing cuesheet \"%s\" on line %u: %s\n", filename, cs_filename, last_line_read, error_message); + return false; + } + + if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) { + fprintf(stderr, "%s: ERROR parsing cuesheet \"%s\": %s\n", filename, cs_filename, error_message); + return false; + } + + /* if we're expecting CDDA, warn about non-compliance */ + if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) { + fprintf(stderr, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", filename, cs_filename, error_message); + (*cuesheet)->data.cue_sheet.is_cd = false; + } + + /* add seekpoints for each index point if required */ + if(0 != seekpoint_specification) { + char spec[128]; + unsigned track, index; + const FLAC__StreamMetadata_CueSheet *cs = &(*cuesheet)->data.cue_sheet; + if(0 == *seekpoint_specification) + *seekpoint_specification = local_strdup(""); + for(track = 0; track < cs->num_tracks; track++) { + const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+track; + for(index = 0; index < tr->num_indices; index++) { +#ifdef _MSC_VER + sprintf(spec, "%I64u;", tr->offset + tr->indices[index].offset); +#else + sprintf(spec, "%llu;", (unsigned long long)(tr->offset + tr->indices[index].offset)); +#endif + local_strcat(seekpoint_specification, spec); + } + } + } + + *needs_write = true; + return true; +} + +FLAC__bool export_cs_to(const char *filename, const FLAC__StreamMetadata *cuesheet, const char *cs_filename) +{ + FILE *f; + char *ref = 0; + size_t reflen; + + if(0 == cs_filename || strlen(cs_filename) == 0) { + fprintf(stderr, "%s: ERROR: empty export file name\n", filename); + return false; + } + if(0 == strcmp(cs_filename, "-")) + f = stdout; + else + f = fopen(cs_filename, "w"); + + if(0 == f) { + fprintf(stderr, "%s: ERROR: can't open export file %s: %s\n", filename, cs_filename, strerror(errno)); + return false; + } + + reflen = strlen(filename) + 7 + 1; + if(0 == (ref = malloc(reflen))) { + fprintf(stderr, "%s: ERROR: allocating memory\n", filename); + return false; + } + +#if defined _MSC_VER || defined __MINGW32__ + _snprintf(ref, reflen, "\"%s\" FLAC", filename); +#else + snprintf(ref, reflen, "\"%s\" FLAC", filename); +#endif + + grabbag__cuesheet_emit(f, cuesheet, ref); + + free(ref); + + if(f != stdout) + fclose(f); + + return true; +} diff --git a/flac/src/metaflac/operations_shorthand_picture.c b/flac/src/metaflac/operations_shorthand_picture.c new file mode 100644 index 0000000..1b75d20 --- /dev/null +++ b/flac/src/metaflac/operations_shorthand_picture.c @@ -0,0 +1,173 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "options.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "share/grabbag.h" /* for grabbag__picture_parse_specification() etc */ + +#include "operations_shorthand.h" + +static FLAC__bool import_pic_from(const char *filename, FLAC__StreamMetadata **picture, const char *specification, FLAC__bool *needs_write); +static FLAC__bool export_pic_to(const char *filename, const FLAC__StreamMetadata *picture, const char *pic_filename); + +FLAC__bool do_shorthand_operation__picture(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write) +{ + FLAC__bool ok = true, has_type1 = false, has_type2 = false; + FLAC__StreamMetadata *picture = 0; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + switch(operation->type) { + case OP__IMPORT_PICTURE_FROM: + ok = import_pic_from(filename, &picture, operation->argument.specification.value, needs_write); + if(ok) { + /* append PICTURE block */ + while(FLAC__metadata_iterator_next(iterator)) + ; + if(!FLAC__metadata_iterator_insert_block_after(iterator, picture)) { + print_error_with_chain_status(chain, "%s: ERROR: adding new PICTURE block to metadata", filename); + FLAC__metadata_object_delete(picture); + ok = false; + } + } + if(ok) { + /* check global PICTURE constraints (max 1 block each of type=1 and type=2) */ + while(FLAC__metadata_iterator_prev(iterator)) + ; + do { + FLAC__StreamMetadata *block = FLAC__metadata_iterator_get_block(iterator); + if(block->type == FLAC__METADATA_TYPE_PICTURE) { + if(block->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) { + if(has_type1) { + print_error_with_chain_status(chain, "%s: ERROR: FLAC stream can only have one 32x32 standard icon (type=1) PICTURE block", filename); + ok = false; + } + has_type1 = true; + } + else if(block->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) { + if(has_type2) { + print_error_with_chain_status(chain, "%s: ERROR: FLAC stream can only have one icon (type=2) PICTURE block", filename); + ok = false; + } + has_type2 = true; + } + } + } while(FLAC__metadata_iterator_next(iterator)); + } + break; + case OP__EXPORT_PICTURE_TO: + { + const Argument_BlockNumber *a = operation->argument.export_picture_to.block_number_link; + int block_number = (a && a->num_entries > 0)? (int)a->entries[0] : -1; + unsigned i = 0; + do { + FLAC__StreamMetadata *block = FLAC__metadata_iterator_get_block(iterator); + if(block->type == FLAC__METADATA_TYPE_PICTURE && (block_number < 0 || i == (unsigned)block_number)) + picture = block; + i++; + } while(FLAC__metadata_iterator_next(iterator) && 0 == picture); + if(0 == picture) { + if(block_number < 0) + fprintf(stderr, "%s: ERROR: FLAC file has no PICTURE block\n", filename); + else + fprintf(stderr, "%s: ERROR: FLAC file has no PICTURE block at block #%d\n", filename, block_number); + ok = false; + } + else + ok = export_pic_to(filename, picture, operation->argument.filename.value); + } + break; + default: + ok = false; + FLAC__ASSERT(0); + break; + }; + + FLAC__metadata_iterator_delete(iterator); + return ok; +} + +/* + * local routines + */ + +FLAC__bool import_pic_from(const char *filename, FLAC__StreamMetadata **picture, const char *specification, FLAC__bool *needs_write) +{ + const char *error_message; + + if(0 == specification || strlen(specification) == 0) { + fprintf(stderr, "%s: ERROR: empty picture specification\n", filename); + return false; + } + + *picture = grabbag__picture_parse_specification(specification, &error_message); + + if(0 == *picture) { + fprintf(stderr, "%s: ERROR: while parsing picture specification \"%s\": %s\n", filename, specification, error_message); + return false; + } + + if(!FLAC__format_picture_is_legal(&(*picture)->data.picture, &error_message)) { + fprintf(stderr, "%s: ERROR: new PICTURE block for \"%s\" is illegal: %s\n", filename, specification, error_message); + return false; + } + + *needs_write = true; + return true; +} + +FLAC__bool export_pic_to(const char *filename, const FLAC__StreamMetadata *picture, const char *pic_filename) +{ + FILE *f; + const FLAC__uint32 len = picture->data.picture.data_length; + + if(0 == pic_filename || strlen(pic_filename) == 0) { + fprintf(stderr, "%s: ERROR: empty export file name\n", filename); + return false; + } + if(0 == strcmp(pic_filename, "-")) + f = grabbag__file_get_binary_stdout(); + else + f = fopen(pic_filename, "wb"); + + if(0 == f) { + fprintf(stderr, "%s: ERROR: can't open export file %s: %s\n", filename, pic_filename, strerror(errno)); + return false; + } + + if(fwrite(picture->data.picture.data, 1, len, f) != len) { + fprintf(stderr, "%s: ERROR: writing PICTURE data to file\n", filename); + return false; + } + + if(f != stdout) + fclose(f); + + return true; +} diff --git a/flac/src/metaflac/operations_shorthand_seektable.c b/flac/src/metaflac/operations_shorthand_seektable.c new file mode 100644 index 0000000..9e4903a --- /dev/null +++ b/flac/src/metaflac/operations_shorthand_seektable.c @@ -0,0 +1,217 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "utils.h" +#include "FLAC/assert.h" +#include "FLAC/stream_decoder.h" +#include "FLAC/metadata.h" +#include "share/grabbag.h" +#include "operations_shorthand.h" + +static FLAC__bool populate_seekpoint_values(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write); + +FLAC__bool do_shorthand_operation__add_seekpoints(const char *filename, FLAC__Metadata_Chain *chain, const char *specification, FLAC__bool *needs_write) +{ + FLAC__bool ok = true, found_seektable_block = false; + FLAC__StreamMetadata *block = 0; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + FLAC__uint64 total_samples = 0; + unsigned sample_rate = 0; + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + do { + block = FLAC__metadata_iterator_get_block(iterator); + if(block->type == FLAC__METADATA_TYPE_STREAMINFO) { + sample_rate = block->data.stream_info.sample_rate; + total_samples = block->data.stream_info.total_samples; + } + else if(block->type == FLAC__METADATA_TYPE_SEEKTABLE) + found_seektable_block = true; + } while(!found_seektable_block && FLAC__metadata_iterator_next(iterator)); + + if(total_samples == 0) { + fprintf(stderr, "%s: ERROR: cannot add seekpoints because STREAMINFO block does not specify total_samples\n", filename); + return false; + } + + if(!found_seektable_block) { + /* create a new block */ + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE); + if(0 == block) + die("out of memory allocating SEEKTABLE block"); + while(FLAC__metadata_iterator_prev(iterator)) + ; + if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) { + print_error_with_chain_status(chain, "%s: ERROR: adding new SEEKTABLE block to metadata", filename); + FLAC__metadata_object_delete(block); + return false; + } + /* iterator is left pointing to new block */ + FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block); + } + + FLAC__metadata_iterator_delete(iterator); + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_SEEKTABLE); + + if(!grabbag__seektable_convert_specification_to_template(specification, /*only_explicit_placeholders=*/false, total_samples, sample_rate, block, /*spec_has_real_points=*/0)) { + fprintf(stderr, "%s: ERROR (internal) preparing seektable with seekpoints\n", filename); + return false; + } + + ok = populate_seekpoint_values(filename, block, needs_write); + + if(ok) + (void) FLAC__format_seektable_sort(&block->data.seek_table); + + return ok; +} + +/* + * local routines + */ + +typedef struct { + FLAC__StreamMetadata_SeekTable *seektable_template; + FLAC__uint64 samples_written; + FLAC__uint64 audio_offset, last_offset; + unsigned first_seekpoint_to_check; + FLAC__bool error_occurred; + FLAC__StreamDecoderErrorStatus error_status; +} ClientData; + +static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + ClientData *cd = (ClientData*)client_data; + + (void)buffer; + FLAC__ASSERT(0 != cd); + + if(!cd->error_occurred) { + const unsigned blocksize = frame->header.blocksize; + const FLAC__uint64 frame_first_sample = cd->samples_written; + const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1; + FLAC__uint64 test_sample; + unsigned i; + for(i = cd->first_seekpoint_to_check; i < cd->seektable_template->num_points; i++) { + test_sample = cd->seektable_template->points[i].sample_number; + if(test_sample > frame_last_sample) { + break; + } + else if(test_sample >= frame_first_sample) { + cd->seektable_template->points[i].sample_number = frame_first_sample; + cd->seektable_template->points[i].stream_offset = cd->last_offset - cd->audio_offset; + cd->seektable_template->points[i].frame_samples = blocksize; + cd->first_seekpoint_to_check++; + /* DO NOT: "break;" and here's why: + * The seektable template may contain more than one target + * sample for any given frame; we will keep looping, generating + * duplicate seekpoints for them, and we'll clean it up later, + * just before writing the seektable back to the metadata. + */ + } + else { + cd->first_seekpoint_to_check++; + } + } + cd->samples_written += blocksize; + if(!FLAC__stream_decoder_get_decode_position(decoder, &cd->last_offset)) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; + } + else + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; +} + +static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + ClientData *cd = (ClientData*)client_data; + + (void)decoder; + FLAC__ASSERT(0 != cd); + + if(!cd->error_occurred) { /* don't let multiple errors overwrite the first one */ + cd->error_occurred = true; + cd->error_status = status; + } +} + +FLAC__bool populate_seekpoint_values(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write) +{ + FLAC__StreamDecoder *decoder; + ClientData client_data; + FLAC__bool ok = true; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_SEEKTABLE); + + client_data.seektable_template = &block->data.seek_table; + client_data.samples_written = 0; + /* client_data.audio_offset must be determined later */ + client_data.first_seekpoint_to_check = 0; + client_data.error_occurred = false; + + decoder = FLAC__stream_decoder_new(); + + if(0 == decoder) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) creating the decoder instance\n", filename); + return false; + } + + FLAC__stream_decoder_set_md5_checking(decoder, false); + FLAC__stream_decoder_set_metadata_ignore_all(decoder); + + if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, /*metadata_callback=*/0, error_callback_, &client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) initializing the decoder instance (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder)); + ok = false; + } + + if(ok && !FLAC__stream_decoder_process_until_end_of_metadata(decoder)) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder)); + ok = false; + } + + if(ok && !FLAC__stream_decoder_get_decode_position(decoder, &client_data.audio_offset)) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file\n", filename); + ok = false; + } + client_data.last_offset = client_data.audio_offset; + + if(ok && !FLAC__stream_decoder_process_until_end_of_stream(decoder)) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder)); + ok = false; + } + + if(ok && client_data.error_occurred) { + fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%u:%s)\n", filename, (unsigned)client_data.error_status, FLAC__StreamDecoderErrorStatusString[client_data.error_status]); + ok = false; + } + + *needs_write = true; + FLAC__stream_decoder_delete(decoder); + return ok; +} diff --git a/flac/src/metaflac/operations_shorthand_streaminfo.c b/flac/src/metaflac/operations_shorthand_streaminfo.c new file mode 100644 index 0000000..e1d4764 --- /dev/null +++ b/flac/src/metaflac/operations_shorthand_streaminfo.c @@ -0,0 +1,129 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "options.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include +#include "operations_shorthand.h" + +FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write) +{ + unsigned i; + FLAC__bool ok = true; + FLAC__StreamMetadata *block; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + block = FLAC__metadata_iterator_get_block(iterator); + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_STREAMINFO); + + if(prefix_with_filename) + printf("%s:", filename); + + switch(operation->type) { + case OP__SHOW_MD5SUM: + for(i = 0; i < 16; i++) + printf("%02x", block->data.stream_info.md5sum[i]); + printf("\n"); + break; + case OP__SHOW_MIN_BLOCKSIZE: + printf("%u\n", block->data.stream_info.min_blocksize); + break; + case OP__SHOW_MAX_BLOCKSIZE: + printf("%u\n", block->data.stream_info.max_blocksize); + break; + case OP__SHOW_MIN_FRAMESIZE: + printf("%u\n", block->data.stream_info.min_framesize); + break; + case OP__SHOW_MAX_FRAMESIZE: + printf("%u\n", block->data.stream_info.max_framesize); + break; + case OP__SHOW_SAMPLE_RATE: + printf("%u\n", block->data.stream_info.sample_rate); + break; + case OP__SHOW_CHANNELS: + printf("%u\n", block->data.stream_info.channels); + break; + case OP__SHOW_BPS: + printf("%u\n", block->data.stream_info.bits_per_sample); + break; + case OP__SHOW_TOTAL_SAMPLES: +#ifdef _MSC_VER + printf("%I64u\n", block->data.stream_info.total_samples); +#else + printf("%llu\n", (unsigned long long)block->data.stream_info.total_samples); +#endif + break; + case OP__SET_MD5SUM: + memcpy(block->data.stream_info.md5sum, operation->argument.streaminfo_md5.value, 16); + *needs_write = true; + break; + case OP__SET_MIN_BLOCKSIZE: + block->data.stream_info.min_blocksize = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_MAX_BLOCKSIZE: + block->data.stream_info.max_blocksize = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_MIN_FRAMESIZE: + block->data.stream_info.min_framesize = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_MAX_FRAMESIZE: + block->data.stream_info.max_framesize = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_SAMPLE_RATE: + block->data.stream_info.sample_rate = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_CHANNELS: + block->data.stream_info.channels = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_BPS: + block->data.stream_info.bits_per_sample = operation->argument.streaminfo_uint32.value; + *needs_write = true; + break; + case OP__SET_TOTAL_SAMPLES: + block->data.stream_info.total_samples = operation->argument.streaminfo_uint64.value; + *needs_write = true; + break; + default: + ok = false; + FLAC__ASSERT(0); + break; + }; + + FLAC__metadata_iterator_delete(iterator); + + return ok; +} diff --git a/flac/src/metaflac/operations_shorthand_vorbiscomment.c b/flac/src/metaflac/operations_shorthand_vorbiscomment.c new file mode 100644 index 0000000..8225e6f --- /dev/null +++ b/flac/src/metaflac/operations_shorthand_vorbiscomment.c @@ -0,0 +1,368 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "options.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "share/grabbag.h" /* for grabbag__file_get_filesize() */ +#include "share/utf8.h" +#include +#include +#include +#include "operations_shorthand.h" + +static FLAC__bool remove_vc_all(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write); +static FLAC__bool remove_vc_field(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write); +static FLAC__bool remove_vc_firstfield(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write); +static FLAC__bool set_vc_field(const char *filename, FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw); +static FLAC__bool import_vc_from(const char *filename, FLAC__StreamMetadata *block, const Argument_String *vc_filename, FLAC__bool *needs_write, FLAC__bool raw); +static FLAC__bool export_vc_to(const char *filename, FLAC__StreamMetadata *block, const Argument_String *vc_filename, FLAC__bool raw); + +FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw) +{ + FLAC__bool ok = true, found_vc_block = false; + FLAC__StreamMetadata *block = 0; + FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); + + if(0 == iterator) + die("out of memory allocating iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + do { + block = FLAC__metadata_iterator_get_block(iterator); + if(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + found_vc_block = true; + } while(!found_vc_block && FLAC__metadata_iterator_next(iterator)); + + if(!found_vc_block) { + /* create a new block if necessary */ + if(operation->type == OP__SET_VC_FIELD || operation->type == OP__IMPORT_VC_FROM) { + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 == block) + die("out of memory allocating VORBIS_COMMENT block"); + while(FLAC__metadata_iterator_next(iterator)) + ; + if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) { + print_error_with_chain_status(chain, "%s: ERROR: adding new VORBIS_COMMENT block to metadata", filename); + return false; + } + /* iterator is left pointing to new block */ + FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block); + } + else { + FLAC__metadata_iterator_delete(iterator); + return ok; + } + } + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + switch(operation->type) { + case OP__SHOW_VC_VENDOR: + write_vc_field(prefix_with_filename? filename : 0, &block->data.vorbis_comment.vendor_string, raw, stdout); + break; + case OP__SHOW_VC_FIELD: + write_vc_fields(prefix_with_filename? filename : 0, operation->argument.vc_field_name.value, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, stdout); + break; + case OP__REMOVE_VC_ALL: + ok = remove_vc_all(filename, block, needs_write); + break; + case OP__REMOVE_VC_FIELD: + ok = remove_vc_field(filename, block, operation->argument.vc_field_name.value, needs_write); + break; + case OP__REMOVE_VC_FIRSTFIELD: + ok = remove_vc_firstfield(filename, block, operation->argument.vc_field_name.value, needs_write); + break; + case OP__SET_VC_FIELD: + ok = set_vc_field(filename, block, &operation->argument.vc_field, needs_write, raw); + break; + case OP__IMPORT_VC_FROM: + ok = import_vc_from(filename, block, &operation->argument.filename, needs_write, raw); + break; + case OP__EXPORT_VC_TO: + ok = export_vc_to(filename, block, &operation->argument.filename, raw); + break; + default: + ok = false; + FLAC__ASSERT(0); + break; + }; + + FLAC__metadata_iterator_delete(iterator); + return ok; +} + +/* + * local routines + */ + +FLAC__bool remove_vc_all(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write) +{ + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != needs_write); + + if(0 != block->data.vorbis_comment.comments) { + FLAC__ASSERT(block->data.vorbis_comment.num_comments > 0); + if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, 0)) { + fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename); + return false; + } + *needs_write = true; + } + else { + FLAC__ASSERT(block->data.vorbis_comment.num_comments == 0); + } + + return true; +} + +FLAC__bool remove_vc_field(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write) +{ + int n; + + FLAC__ASSERT(0 != needs_write); + + n = FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, field_name); + + if(n < 0) { + fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename); + return false; + } + else if(n > 0) + *needs_write = true; + + return true; +} + +FLAC__bool remove_vc_firstfield(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write) +{ + int n; + + FLAC__ASSERT(0 != needs_write); + + n = FLAC__metadata_object_vorbiscomment_remove_entry_matching(block, field_name); + + if(n < 0) { + fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename); + return false; + } + else if(n > 0) + *needs_write = true; + + return true; +} + +FLAC__bool set_vc_field(const char *filename, FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw) +{ + FLAC__StreamMetadata_VorbisComment_Entry entry; + char *converted; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != field); + FLAC__ASSERT(0 != needs_write); + + if(field->field_value_from_file) { + /* read the file into 'data' */ + FILE *f = 0; + char *data = 0; + const off_t size = grabbag__file_get_filesize(field->field_value); + if(size < 0) { + fprintf(stderr, "%s: ERROR: can't open file '%s' for '%s' tag value\n", filename, field->field_value, field->field_name); + return false; + } + if(size >= 0x100000) { /* magic arbitrary limit, actual format limit is near 16MB */ + fprintf(stderr, "%s: ERROR: file '%s' for '%s' tag value is too large\n", filename, field->field_value, field->field_name); + return false; + } + if(0 == (data = malloc(size+1))) + die("out of memory allocating tag value"); + data[size] = '\0'; + if(0 == (f = fopen(field->field_value, "rb")) || fread(data, 1, size, f) != (size_t)size) { + fprintf(stderr, "%s: ERROR: while reading file '%s' for '%s' tag value: %s\n", filename, field->field_value, field->field_name, strerror(errno)); + free(data); + if(f) + fclose(f); + return false; + } + fclose(f); + if(strlen(data) != (size_t)size) { + free(data); + fprintf(stderr, "%s: ERROR: file '%s' for '%s' tag value has embedded NULs\n", filename, field->field_value, field->field_name); + return false; + } + + /* move 'data' into 'converted', converting to UTF-8 if necessary */ + if(raw) { + converted = data; + } + else if(utf8_encode(data, &converted) >= 0) { + free(data); + } + else { + free(data); + fprintf(stderr, "%s: ERROR: converting file '%s' contents to UTF-8 for tag value\n", filename, field->field_value); + return false; + } + + /* create and entry and append it */ + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, field->field_name, converted)) { + free(converted); + fprintf(stderr, "%s: ERROR: file '%s' for '%s' tag value is not valid UTF-8\n", filename, field->field_value, field->field_name); + return false; + } + free(converted); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/false)) { + fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename); + return false; + } + + *needs_write = true; + return true; + } + else { + FLAC__bool needs_free = false; + if(raw) { + entry.entry = (FLAC__byte *)field->field; + } + else if(utf8_encode(field->field, &converted) >= 0) { + entry.entry = (FLAC__byte *)converted; + needs_free = true; + } + else { + fprintf(stderr, "%s: ERROR: converting comment '%s' to UTF-8\n", filename, field->field); + return false; + } + entry.length = strlen((const char *)entry.entry); + if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) { + if(needs_free) + free(converted); + /* + * our previous parsing has already established that the field + * name is OK, so it must be the field value + */ + fprintf(stderr, "%s: ERROR: tag value for '%s' is not valid UTF-8\n", filename, field->field_name); + return false; + } + + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + if(needs_free) + free(converted); + fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename); + return false; + } + + *needs_write = true; + if(needs_free) + free(converted); + return true; + } +} + +FLAC__bool import_vc_from(const char *filename, FLAC__StreamMetadata *block, const Argument_String *vc_filename, FLAC__bool *needs_write, FLAC__bool raw) +{ + FILE *f; + char line[65536]; + FLAC__bool ret; + + if(0 == vc_filename->value || strlen(vc_filename->value) == 0) { + fprintf(stderr, "%s: ERROR: empty import file name\n", filename); + return false; + } + if(0 == strcmp(vc_filename->value, "-")) + f = stdin; + else + f = fopen(vc_filename->value, "r"); + + if(0 == f) { + fprintf(stderr, "%s: ERROR: can't open import file %s: %s\n", filename, vc_filename->value, strerror(errno)); + return false; + } + + ret = true; + while(ret && !feof(f)) { + fgets(line, sizeof(line), f); + if(!feof(f)) { + char *p = strchr(line, '\n'); + if(0 == p) { + fprintf(stderr, "%s: ERROR: line too long, aborting\n", vc_filename->value); + ret = false; + } + else { + const char *violation; + Argument_VcField field; + *p = '\0'; + memset(&field, 0, sizeof(Argument_VcField)); + field.field_value_from_file = false; + if(!parse_vorbis_comment_field(line, &field.field, &field.field_name, &field.field_value, &field.field_value_length, &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "%s: ERROR: malformed vorbis comment field \"%s\",\n %s\n", vc_filename->value, line, violation); + ret = false; + } + else { + ret = set_vc_field(filename, block, &field, needs_write, raw); + } + if(0 != field.field) + free(field.field); + if(0 != field.field_name) + free(field.field_name); + if(0 != field.field_value) + free(field.field_value); + } + } + }; + + if(f != stdin) + fclose(f); + return ret; +} + +FLAC__bool export_vc_to(const char *filename, FLAC__StreamMetadata *block, const Argument_String *vc_filename, FLAC__bool raw) +{ + FILE *f; + FLAC__bool ret; + + if(0 == vc_filename->value || strlen(vc_filename->value) == 0) { + fprintf(stderr, "%s: ERROR: empty export file name\n", filename); + return false; + } + if(0 == strcmp(vc_filename->value, "-")) + f = stdout; + else + f = fopen(vc_filename->value, "w"); + + if(0 == f) { + fprintf(stderr, "%s: ERROR: can't open export file %s: %s\n", filename, vc_filename->value, strerror(errno)); + return false; + } + + ret = true; + + write_vc_fields(0, 0, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, f); + + if(f != stdout) + fclose(f); + return ret; +} diff --git a/flac/src/metaflac/options.c b/flac/src/metaflac/options.c new file mode 100644 index 0000000..9a23e98 --- /dev/null +++ b/flac/src/metaflac/options.c @@ -0,0 +1,1109 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "options.h" +#include "usage.h" +#include "utils.h" +#include "FLAC/assert.h" +#include "share/alloc.h" +#include "share/grabbag/replaygain.h" +#include +#include +#include +#include + +/* + share__getopt format struct; note we don't use short options so we just + set the 'val' field to 0 everywhere to indicate a valid option. +*/ +struct share__option long_options_[] = { + /* global options */ + { "preserve-modtime", 0, 0, 0 }, + { "with-filename", 0, 0, 0 }, + { "no-filename", 0, 0, 0 }, + { "no-utf8-convert", 0, 0, 0 }, + { "dont-use-padding", 0, 0, 0 }, + { "no-cued-seekpoints", 0, 0, 0 }, + /* shorthand operations */ + { "show-md5sum", 0, 0, 0 }, + { "show-min-blocksize", 0, 0, 0 }, + { "show-max-blocksize", 0, 0, 0 }, + { "show-min-framesize", 0, 0, 0 }, + { "show-max-framesize", 0, 0, 0 }, + { "show-sample-rate", 0, 0, 0 }, + { "show-channels", 0, 0, 0 }, + { "show-bps", 0, 0, 0 }, + { "show-total-samples", 0, 0, 0 }, + { "set-md5sum", 1, 0, 0 }, /* undocumented */ + { "set-min-blocksize", 1, 0, 0 }, /* undocumented */ + { "set-max-blocksize", 1, 0, 0 }, /* undocumented */ + { "set-min-framesize", 1, 0, 0 }, /* undocumented */ + { "set-max-framesize", 1, 0, 0 }, /* undocumented */ + { "set-sample-rate", 1, 0, 0 }, /* undocumented */ + { "set-channels", 1, 0, 0 }, /* undocumented */ + { "set-bps", 1, 0, 0 }, /* undocumented */ + { "set-total-samples", 1, 0, 0 }, /* undocumented */ /* WATCHOUT: used by test/test_flac.sh on windows */ + { "show-vendor-tag", 0, 0, 0 }, + { "show-tag", 1, 0, 0 }, + { "remove-all-tags", 0, 0, 0 }, + { "remove-tag", 1, 0, 0 }, + { "remove-first-tag", 1, 0, 0 }, + { "set-tag", 1, 0, 0 }, + { "set-tag-from-file", 1, 0, 0 }, + { "import-tags-from", 1, 0, 0 }, + { "export-tags-to", 1, 0, 0 }, + { "import-cuesheet-from", 1, 0, 0 }, + { "export-cuesheet-to", 1, 0, 0 }, + { "import-picture-from", 1, 0, 0 }, + { "export-picture-to", 1, 0, 0 }, + { "add-seekpoint", 1, 0, 0 }, + { "add-replay-gain", 0, 0, 0 }, + { "remove-replay-gain", 0, 0, 0 }, + { "add-padding", 1, 0, 0 }, + /* major operations */ + { "help", 0, 0, 0 }, + { "version", 0, 0, 0 }, + { "list", 0, 0, 0 }, + { "append", 0, 0, 0 }, + { "remove", 0, 0, 0 }, + { "remove-all", 0, 0, 0 }, + { "merge-padding", 0, 0, 0 }, + { "sort-padding", 0, 0, 0 }, + /* major operation arguments */ + { "block-number", 1, 0, 0 }, + { "block-type", 1, 0, 0 }, + { "except-block-type", 1, 0, 0 }, + { "data-format", 1, 0, 0 }, + { "application-data-format", 1, 0, 0 }, + { "from-file", 1, 0, 0 }, + {0, 0, 0, 0} +}; + +static FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options); +static void append_new_operation(CommandLineOptions *options, Operation operation); +static void append_new_argument(CommandLineOptions *options, Argument argument); +static Operation *append_major_operation(CommandLineOptions *options, OperationType type); +static Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type); +static Argument *find_argument(CommandLineOptions *options, ArgumentType type); +static Operation *find_shorthand_operation(CommandLineOptions *options, OperationType type); +static Argument *append_argument(CommandLineOptions *options, ArgumentType type); +static FLAC__bool parse_md5(const char *src, FLAC__byte dest[16]); +static FLAC__bool parse_uint32(const char *src, FLAC__uint32 *dest); +static FLAC__bool parse_uint64(const char *src, FLAC__uint64 *dest); +static FLAC__bool parse_string(const char *src, char **dest); +static FLAC__bool parse_vorbis_comment_field_name(const char *field_ref, char **name, const char **violation); +static FLAC__bool parse_add_seekpoint(const char *in, char **out, const char **violation); +static FLAC__bool parse_add_padding(const char *in, unsigned *out); +static FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out); +static FLAC__bool parse_block_type(const char *in, Argument_BlockType *out); +static FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out); +static FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out); +static void undocumented_warning(const char *opt); + + +void init_options(CommandLineOptions *options) +{ + options->preserve_modtime = false; + + /* '2' is a hack to mean "use default if not forced on command line" */ + FLAC__ASSERT(true != 2); + options->prefix_with_filename = 2; + + options->utf8_convert = true; + options->use_padding = true; + options->cued_seekpoints = true; + options->show_long_help = false; + options->show_version = false; + options->application_data_format_is_hexdump = false; + + options->ops.operations = 0; + options->ops.num_operations = 0; + options->ops.capacity = 0; + + options->args.arguments = 0; + options->args.num_arguments = 0; + options->args.capacity = 0; + + options->args.checks.num_shorthand_ops = 0; + options->args.checks.num_major_ops = 0; + options->args.checks.has_block_type = false; + options->args.checks.has_except_block_type = false; + + options->num_files = 0; + options->filenames = 0; +} + +FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options) +{ + int ret; + int option_index = 1; + FLAC__bool had_error = false; + + while ((ret = share__getopt_long(argc, argv, "", long_options_, &option_index)) != -1) { + switch (ret) { + case 0: + had_error |= !parse_option(option_index, share__optarg, options); + break; + case '?': + case ':': + had_error = true; + break; + default: + FLAC__ASSERT(0); + break; + } + } + + if(options->prefix_with_filename == 2) + options->prefix_with_filename = (argc - share__optind > 1); + + if(share__optind >= argc && !options->show_long_help && !options->show_version) { + fprintf(stderr,"ERROR: you must specify at least one FLAC file;\n"); + fprintf(stderr," metaflac cannot be used as a pipe\n"); + had_error = true; + } + + options->num_files = argc - share__optind; + + if(options->num_files > 0) { + unsigned i = 0; + if(0 == (options->filenames = (char**)safe_malloc_mul_2op_(sizeof(char*), /*times*/options->num_files))) + die("out of memory allocating space for file names list"); + while(share__optind < argc) + options->filenames[i++] = local_strdup(argv[share__optind++]); + } + + if(options->args.checks.num_major_ops > 0) { + if(options->args.checks.num_major_ops > 1) { + fprintf(stderr, "ERROR: you may only specify one major operation at a time\n"); + had_error = true; + } + else if(options->args.checks.num_shorthand_ops > 0) { + fprintf(stderr, "ERROR: you may not mix shorthand and major operations\n"); + had_error = true; + } + } + + /* check for only one FLAC file used with certain options */ + if(options->num_files > 1) { + if(0 != find_shorthand_operation(options, OP__IMPORT_CUESHEET_FROM)) { + fprintf(stderr, "ERROR: you may only specify one FLAC file when using '--import-cuesheet-from'\n"); + had_error = true; + } + if(0 != find_shorthand_operation(options, OP__EXPORT_CUESHEET_TO)) { + fprintf(stderr, "ERROR: you may only specify one FLAC file when using '--export-cuesheet-to'\n"); + had_error = true; + } + if(0 != find_shorthand_operation(options, OP__EXPORT_PICTURE_TO)) { + fprintf(stderr, "ERROR: you may only specify one FLAC file when using '--export-picture-to'\n"); + had_error = true; + } + if( + 0 != find_shorthand_operation(options, OP__IMPORT_VC_FROM) && + 0 == strcmp(find_shorthand_operation(options, OP__IMPORT_VC_FROM)->argument.filename.value, "-") + ) { + fprintf(stderr, "ERROR: you may only specify one FLAC file when using '--import-tags-from=-'\n"); + had_error = true; + } + } + + if(options->args.checks.has_block_type && options->args.checks.has_except_block_type) { + fprintf(stderr, "ERROR: you may not specify both '--block-type' and '--except-block-type'\n"); + had_error = true; + } + + if(had_error) + short_usage(0); + + /* + * We need to create an OP__ADD_SEEKPOINT operation if there is + * not one already, and --import-cuesheet-from was specified but + * --no-cued-seekpoints was not: + */ + if(options->cued_seekpoints) { + Operation *op = find_shorthand_operation(options, OP__IMPORT_CUESHEET_FROM); + if(0 != op) { + Operation *op2 = find_shorthand_operation(options, OP__ADD_SEEKPOINT); + if(0 == op2) + op2 = append_shorthand_operation(options, OP__ADD_SEEKPOINT); + op->argument.import_cuesheet_from.add_seekpoint_link = &(op2->argument.add_seekpoint); + } + } + + return !had_error; +} + +void free_options(CommandLineOptions *options) +{ + unsigned i; + Operation *op; + Argument *arg; + + FLAC__ASSERT(0 == options->ops.operations || options->ops.num_operations > 0); + FLAC__ASSERT(0 == options->args.arguments || options->args.num_arguments > 0); + + for(i = 0, op = options->ops.operations; i < options->ops.num_operations; i++, op++) { + switch(op->type) { + case OP__SHOW_VC_FIELD: + case OP__REMOVE_VC_FIELD: + case OP__REMOVE_VC_FIRSTFIELD: + if(0 != op->argument.vc_field_name.value) + free(op->argument.vc_field_name.value); + break; + case OP__SET_VC_FIELD: + if(0 != op->argument.vc_field.field) + free(op->argument.vc_field.field); + if(0 != op->argument.vc_field.field_name) + free(op->argument.vc_field.field_name); + if(0 != op->argument.vc_field.field_value) + free(op->argument.vc_field.field_value); + break; + case OP__IMPORT_VC_FROM: + case OP__EXPORT_VC_TO: + case OP__EXPORT_CUESHEET_TO: + if(0 != op->argument.filename.value) + free(op->argument.filename.value); + break; + case OP__IMPORT_CUESHEET_FROM: + if(0 != op->argument.import_cuesheet_from.filename) + free(op->argument.import_cuesheet_from.filename); + break; + case OP__IMPORT_PICTURE_FROM: + if(0 != op->argument.specification.value) + free(op->argument.specification.value); + break; + case OP__EXPORT_PICTURE_TO: + if(0 != op->argument.export_picture_to.filename) + free(op->argument.export_picture_to.filename); + break; + case OP__ADD_SEEKPOINT: + if(0 != op->argument.add_seekpoint.specification) + free(op->argument.add_seekpoint.specification); + break; + default: + break; + } + } + + for(i = 0, arg = options->args.arguments; i < options->args.num_arguments; i++, arg++) { + switch(arg->type) { + case ARG__BLOCK_NUMBER: + if(0 != arg->value.block_number.entries) + free(arg->value.block_number.entries); + break; + case ARG__BLOCK_TYPE: + case ARG__EXCEPT_BLOCK_TYPE: + if(0 != arg->value.block_type.entries) + free(arg->value.block_type.entries); + break; + case ARG__FROM_FILE: + if(0 != arg->value.from_file.file_name) + free(arg->value.from_file.file_name); + break; + default: + break; + } + } + + if(0 != options->ops.operations) + free(options->ops.operations); + + if(0 != options->args.arguments) + free(options->args.arguments); + + if(0 != options->filenames) { + for(i = 0; i < options->num_files; i++) { + if(0 != options->filenames[i]) + free(options->filenames[i]); + } + free(options->filenames); + } +} + +/* + * local routines + */ + +FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options) +{ + const char *opt = long_options_[option_index].name; + Operation *op; + Argument *arg; + FLAC__bool ok = true; + + if(0 == strcmp(opt, "preserve-modtime")) { + options->preserve_modtime = true; + } + else if(0 == strcmp(opt, "with-filename")) { + options->prefix_with_filename = true; + } + else if(0 == strcmp(opt, "no-filename")) { + options->prefix_with_filename = false; + } + else if(0 == strcmp(opt, "no-utf8-convert")) { + options->utf8_convert = false; + } + else if(0 == strcmp(opt, "dont-use-padding")) { + options->use_padding = false; + } + else if(0 == strcmp(opt, "no-cued-seekpoints")) { + options->cued_seekpoints = false; + } + else if(0 == strcmp(opt, "show-md5sum")) { + (void) append_shorthand_operation(options, OP__SHOW_MD5SUM); + } + else if(0 == strcmp(opt, "show-min-blocksize")) { + (void) append_shorthand_operation(options, OP__SHOW_MIN_BLOCKSIZE); + } + else if(0 == strcmp(opt, "show-max-blocksize")) { + (void) append_shorthand_operation(options, OP__SHOW_MAX_BLOCKSIZE); + } + else if(0 == strcmp(opt, "show-min-framesize")) { + (void) append_shorthand_operation(options, OP__SHOW_MIN_FRAMESIZE); + } + else if(0 == strcmp(opt, "show-max-framesize")) { + (void) append_shorthand_operation(options, OP__SHOW_MAX_FRAMESIZE); + } + else if(0 == strcmp(opt, "show-sample-rate")) { + (void) append_shorthand_operation(options, OP__SHOW_SAMPLE_RATE); + } + else if(0 == strcmp(opt, "show-channels")) { + (void) append_shorthand_operation(options, OP__SHOW_CHANNELS); + } + else if(0 == strcmp(opt, "show-bps")) { + (void) append_shorthand_operation(options, OP__SHOW_BPS); + } + else if(0 == strcmp(opt, "show-total-samples")) { + (void) append_shorthand_operation(options, OP__SHOW_TOTAL_SAMPLES); + } + else if(0 == strcmp(opt, "set-md5sum")) { + op = append_shorthand_operation(options, OP__SET_MD5SUM); + FLAC__ASSERT(0 != option_argument); + if(!parse_md5(option_argument, op->argument.streaminfo_md5.value)) { + fprintf(stderr, "ERROR (--%s): bad MD5 sum\n", opt); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-min-blocksize")) { + op = append_shorthand_operation(options, OP__SET_MIN_BLOCKSIZE); + if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BLOCK_SIZE || op->argument.streaminfo_uint32.value > FLAC__MAX_BLOCK_SIZE) { + fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-max-blocksize")) { + op = append_shorthand_operation(options, OP__SET_MAX_BLOCKSIZE); + if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BLOCK_SIZE || op->argument.streaminfo_uint32.value > FLAC__MAX_BLOCK_SIZE) { + fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-min-framesize")) { + op = append_shorthand_operation(options, OP__SET_MIN_FRAMESIZE); + if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value >= (1u<argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value >= (1u<argument.streaminfo_uint32.value)) || !FLAC__format_sample_rate_is_valid(op->argument.streaminfo_uint32.value)) { + fprintf(stderr, "ERROR (--%s): invalid sample rate\n", opt); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-channels")) { + op = append_shorthand_operation(options, OP__SET_CHANNELS); + if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value > FLAC__MAX_CHANNELS) { + fprintf(stderr, "ERROR (--%s): value must be > 0 and <= %u\n", opt, FLAC__MAX_CHANNELS); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-bps")) { + op = append_shorthand_operation(options, OP__SET_BPS); + if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BITS_PER_SAMPLE || op->argument.streaminfo_uint32.value > FLAC__MAX_BITS_PER_SAMPLE) { + fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BITS_PER_SAMPLE, FLAC__MAX_BITS_PER_SAMPLE); + ok = false; + } + else + undocumented_warning(opt); + } + else if(0 == strcmp(opt, "set-total-samples")) { + op = append_shorthand_operation(options, OP__SET_TOTAL_SAMPLES); + if(!parse_uint64(option_argument, &(op->argument.streaminfo_uint64.value)) || op->argument.streaminfo_uint64.value >= (((FLAC__uint64)1)<argument.vc_field_name.value), &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + } + else if(0 == strcmp(opt, "remove-all-tags")) { + (void) append_shorthand_operation(options, OP__REMOVE_VC_ALL); + } + else if(0 == strcmp(opt, "remove-tag")) { + const char *violation; + op = append_shorthand_operation(options, OP__REMOVE_VC_FIELD); + FLAC__ASSERT(0 != option_argument); + if(!parse_vorbis_comment_field_name(option_argument, &(op->argument.vc_field_name.value), &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + } + else if(0 == strcmp(opt, "remove-first-tag")) { + const char *violation; + op = append_shorthand_operation(options, OP__REMOVE_VC_FIRSTFIELD); + FLAC__ASSERT(0 != option_argument); + if(!parse_vorbis_comment_field_name(option_argument, &(op->argument.vc_field_name.value), &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + } + else if(0 == strcmp(opt, "set-tag")) { + const char *violation; + op = append_shorthand_operation(options, OP__SET_VC_FIELD); + FLAC__ASSERT(0 != option_argument); + op->argument.vc_field.field_value_from_file = false; + if(!parse_vorbis_comment_field(option_argument, &(op->argument.vc_field.field), &(op->argument.vc_field.field_name), &(op->argument.vc_field.field_value), &(op->argument.vc_field.field_value_length), &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed vorbis comment field \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + } + else if(0 == strcmp(opt, "set-tag-from-file")) { + const char *violation; + op = append_shorthand_operation(options, OP__SET_VC_FIELD); + FLAC__ASSERT(0 != option_argument); + op->argument.vc_field.field_value_from_file = true; + if(!parse_vorbis_comment_field(option_argument, &(op->argument.vc_field.field), &(op->argument.vc_field.field_name), &(op->argument.vc_field.field_value), &(op->argument.vc_field.field_value_length), &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed vorbis comment field \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + } + else if(0 == strcmp(opt, "import-tags-from")) { + op = append_shorthand_operation(options, OP__IMPORT_VC_FROM); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.filename.value))) { + fprintf(stderr, "ERROR (--%s): missing filename\n", opt); + ok = false; + } + } + else if(0 == strcmp(opt, "export-tags-to")) { + op = append_shorthand_operation(options, OP__EXPORT_VC_TO); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.filename.value))) { + fprintf(stderr, "ERROR (--%s): missing filename\n", opt); + ok = false; + } + } + else if(0 == strcmp(opt, "import-cuesheet-from")) { + if(0 != find_shorthand_operation(options, OP__IMPORT_CUESHEET_FROM)) { + fprintf(stderr, "ERROR (--%s): may be specified only once\n", opt); + ok = false; + } + op = append_shorthand_operation(options, OP__IMPORT_CUESHEET_FROM); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.import_cuesheet_from.filename))) { + fprintf(stderr, "ERROR (--%s): missing filename\n", opt); + ok = false; + } + } + else if(0 == strcmp(opt, "export-cuesheet-to")) { + op = append_shorthand_operation(options, OP__EXPORT_CUESHEET_TO); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.filename.value))) { + fprintf(stderr, "ERROR (--%s): missing filename\n", opt); + ok = false; + } + } + else if(0 == strcmp(opt, "import-picture-from")) { + op = append_shorthand_operation(options, OP__IMPORT_PICTURE_FROM); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.specification.value))) { + fprintf(stderr, "ERROR (--%s): missing specification\n", opt); + ok = false; + } + } + else if(0 == strcmp(opt, "export-picture-to")) { + const Argument *arg = find_argument(options, ARG__BLOCK_NUMBER); + op = append_shorthand_operation(options, OP__EXPORT_PICTURE_TO); + FLAC__ASSERT(0 != option_argument); + if(!parse_string(option_argument, &(op->argument.export_picture_to.filename))) { + fprintf(stderr, "ERROR (--%s): missing filename\n", opt); + ok = false; + } + op->argument.export_picture_to.block_number_link = arg? &(arg->value.block_number) : 0; + } + else if(0 == strcmp(opt, "add-seekpoint")) { + const char *violation; + char *spec; + FLAC__ASSERT(0 != option_argument); + if(!parse_add_seekpoint(option_argument, &spec, &violation)) { + FLAC__ASSERT(0 != violation); + fprintf(stderr, "ERROR (--%s): malformed seekpoint specification \"%s\",\n %s\n", opt, option_argument, violation); + ok = false; + } + else { + op = find_shorthand_operation(options, OP__ADD_SEEKPOINT); + if(0 == op) + op = append_shorthand_operation(options, OP__ADD_SEEKPOINT); + local_strcat(&(op->argument.add_seekpoint.specification), spec); + local_strcat(&(op->argument.add_seekpoint.specification), ";"); + free(spec); + } + } + else if(0 == strcmp(opt, "add-replay-gain")) { + (void) append_shorthand_operation(options, OP__ADD_REPLAY_GAIN); + } + else if(0 == strcmp(opt, "remove-replay-gain")) { + const FLAC__byte * const tags[5] = { + GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, + GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, + GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, + GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, + GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK + }; + size_t i; + for(i = 0; i < sizeof(tags)/sizeof(tags[0]); i++) { + op = append_shorthand_operation(options, OP__REMOVE_VC_FIELD); + op->argument.vc_field_name.value = local_strdup((const char *)tags[i]); + } + } + else if(0 == strcmp(opt, "add-padding")) { + op = append_shorthand_operation(options, OP__ADD_PADDING); + FLAC__ASSERT(0 != option_argument); + if(!parse_add_padding(option_argument, &(op->argument.add_padding.length))) { + fprintf(stderr, "ERROR (--%s): illegal length \"%s\", length must be >= 0 and < 2^%u\n", opt, option_argument, FLAC__STREAM_METADATA_LENGTH_LEN); + ok = false; + } + } + else if(0 == strcmp(opt, "help")) { + options->show_long_help = true; + } + else if(0 == strcmp(opt, "version")) { + options->show_version = true; + } + else if(0 == strcmp(opt, "list")) { + (void) append_major_operation(options, OP__LIST); + } + else if(0 == strcmp(opt, "append")) { + (void) append_major_operation(options, OP__APPEND); + } + else if(0 == strcmp(opt, "remove")) { + (void) append_major_operation(options, OP__REMOVE); + } + else if(0 == strcmp(opt, "remove-all")) { + (void) append_major_operation(options, OP__REMOVE_ALL); + } + else if(0 == strcmp(opt, "merge-padding")) { + (void) append_major_operation(options, OP__MERGE_PADDING); + } + else if(0 == strcmp(opt, "sort-padding")) { + (void) append_major_operation(options, OP__SORT_PADDING); + } + else if(0 == strcmp(opt, "block-number")) { + arg = append_argument(options, ARG__BLOCK_NUMBER); + FLAC__ASSERT(0 != option_argument); + if(!parse_block_number(option_argument, &(arg->value.block_number))) { + fprintf(stderr, "ERROR: malformed block number specification \"%s\"\n", option_argument); + ok = false; + } + } + else if(0 == strcmp(opt, "block-type")) { + arg = append_argument(options, ARG__BLOCK_TYPE); + FLAC__ASSERT(0 != option_argument); + if(!parse_block_type(option_argument, &(arg->value.block_type))) { + fprintf(stderr, "ERROR (--%s): malformed block type specification \"%s\"\n", opt, option_argument); + ok = false; + } + options->args.checks.has_block_type = true; + } + else if(0 == strcmp(opt, "except-block-type")) { + arg = append_argument(options, ARG__EXCEPT_BLOCK_TYPE); + FLAC__ASSERT(0 != option_argument); + if(!parse_block_type(option_argument, &(arg->value.block_type))) { + fprintf(stderr, "ERROR (--%s): malformed block type specification \"%s\"\n", opt, option_argument); + ok = false; + } + options->args.checks.has_except_block_type = true; + } + else if(0 == strcmp(opt, "data-format")) { + arg = append_argument(options, ARG__DATA_FORMAT); + FLAC__ASSERT(0 != option_argument); + if(!parse_data_format(option_argument, &(arg->value.data_format))) { + fprintf(stderr, "ERROR (--%s): illegal data format \"%s\"\n", opt, option_argument); + ok = false; + } + } + else if(0 == strcmp(opt, "application-data-format")) { + FLAC__ASSERT(0 != option_argument); + if(!parse_application_data_format(option_argument, &(options->application_data_format_is_hexdump))) { + fprintf(stderr, "ERROR (--%s): illegal application data format \"%s\"\n", opt, option_argument); + ok = false; + } + } + else if(0 == strcmp(opt, "from-file")) { + arg = append_argument(options, ARG__FROM_FILE); + FLAC__ASSERT(0 != option_argument); + arg->value.from_file.file_name = local_strdup(option_argument); + } + else { + FLAC__ASSERT(0); + } + + return ok; +} + +void append_new_operation(CommandLineOptions *options, Operation operation) +{ + if(options->ops.capacity == 0) { + options->ops.capacity = 50; + if(0 == (options->ops.operations = (Operation*)malloc(sizeof(Operation) * options->ops.capacity))) + die("out of memory allocating space for option list"); + memset(options->ops.operations, 0, sizeof(Operation) * options->ops.capacity); + } + if(options->ops.capacity <= options->ops.num_operations) { + unsigned original_capacity = options->ops.capacity; + if(options->ops.capacity > SIZE_MAX / 2) /* overflow check */ + die("out of memory allocating space for option list"); + options->ops.capacity *= 2; + if(0 == (options->ops.operations = (Operation*)safe_realloc_mul_2op_(options->ops.operations, sizeof(Operation), /*times*/options->ops.capacity))) + die("out of memory allocating space for option list"); + memset(options->ops.operations + original_capacity, 0, sizeof(Operation) * (options->ops.capacity - original_capacity)); + } + + options->ops.operations[options->ops.num_operations++] = operation; +} + +void append_new_argument(CommandLineOptions *options, Argument argument) +{ + if(options->args.capacity == 0) { + options->args.capacity = 50; + if(0 == (options->args.arguments = (Argument*)malloc(sizeof(Argument) * options->args.capacity))) + die("out of memory allocating space for option list"); + memset(options->args.arguments, 0, sizeof(Argument) * options->args.capacity); + } + if(options->args.capacity <= options->args.num_arguments) { + unsigned original_capacity = options->args.capacity; + if(options->args.capacity > SIZE_MAX / 2) /* overflow check */ + die("out of memory allocating space for option list"); + options->args.capacity *= 2; + if(0 == (options->args.arguments = (Argument*)safe_realloc_mul_2op_(options->args.arguments, sizeof(Argument), /*times*/options->args.capacity))) + die("out of memory allocating space for option list"); + memset(options->args.arguments + original_capacity, 0, sizeof(Argument) * (options->args.capacity - original_capacity)); + } + + options->args.arguments[options->args.num_arguments++] = argument; +} + +Operation *append_major_operation(CommandLineOptions *options, OperationType type) +{ + Operation op; + memset(&op, 0, sizeof(op)); + op.type = type; + append_new_operation(options, op); + options->args.checks.num_major_ops++; + return options->ops.operations + (options->ops.num_operations - 1); +} + +Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type) +{ + Operation op; + memset(&op, 0, sizeof(op)); + op.type = type; + append_new_operation(options, op); + options->args.checks.num_shorthand_ops++; + return options->ops.operations + (options->ops.num_operations - 1); +} + +Argument *find_argument(CommandLineOptions *options, ArgumentType type) +{ + unsigned i; + for(i = 0; i < options->args.num_arguments; i++) + if(options->args.arguments[i].type == type) + return &options->args.arguments[i]; + return 0; +} + +Operation *find_shorthand_operation(CommandLineOptions *options, OperationType type) +{ + unsigned i; + for(i = 0; i < options->ops.num_operations; i++) + if(options->ops.operations[i].type == type) + return &options->ops.operations[i]; + return 0; +} + +Argument *append_argument(CommandLineOptions *options, ArgumentType type) +{ + Argument arg; + memset(&arg, 0, sizeof(arg)); + arg.type = type; + append_new_argument(options, arg); + return options->args.arguments + (options->args.num_arguments - 1); +} + +FLAC__bool parse_md5(const char *src, FLAC__byte dest[16]) +{ + unsigned i, d; + int c; + FLAC__ASSERT(0 != src); + if(strlen(src) != 32) + return false; + /* strtoul() accepts negative numbers which we do not want, so we do it the hard way */ + for(i = 0; i < 16; i++) { + c = (int)(*src++); + if(isdigit(c)) + d = (unsigned)(c - '0'); + else if(c >= 'a' && c <= 'f') + d = (unsigned)(c - 'a') + 10u; + else if(c >= 'A' && c <= 'F') + d = (unsigned)(c - 'A') + 10u; + else + return false; + d <<= 4; + c = (int)(*src++); + if(isdigit(c)) + d |= (unsigned)(c - '0'); + else if(c >= 'a' && c <= 'f') + d |= (unsigned)(c - 'a') + 10u; + else if(c >= 'A' && c <= 'F') + d |= (unsigned)(c - 'A') + 10u; + else + return false; + dest[i] = (FLAC__byte)d; + } + return true; +} + +FLAC__bool parse_uint32(const char *src, FLAC__uint32 *dest) +{ + FLAC__ASSERT(0 != src); + if(strlen(src) == 0 || strspn(src, "0123456789") != strlen(src)) + return false; + *dest = strtoul(src, 0, 10); + return true; +} + +#ifdef _MSC_VER +/* There's no strtoull() in MSVC6 so we just write a specialized one */ +static FLAC__uint64 local__strtoull(const char *src) +{ + FLAC__uint64 ret = 0; + int c; + FLAC__ASSERT(0 != src); + while(0 != (c = *src++)) { + c -= '0'; + if(c >= 0 && c <= 9) + ret = (ret * 10) + c; + else + break; + } + return ret; +} +#endif + +FLAC__bool parse_uint64(const char *src, FLAC__uint64 *dest) +{ + FLAC__ASSERT(0 != src); + if(strlen(src) == 0 || strspn(src, "0123456789") != strlen(src)) + return false; +#ifdef _MSC_VER + *dest = local__strtoull(src); +#else + *dest = strtoull(src, 0, 10); +#endif + return true; +} + +FLAC__bool parse_string(const char *src, char **dest) +{ + if(0 == src || strlen(src) == 0) + return false; + *dest = strdup(src); + return true; +} + +FLAC__bool parse_vorbis_comment_field_name(const char *field_ref, char **name, const char **violation) +{ + static const char * const violations[] = { + "field name contains invalid character" + }; + + char *q, *s; + + s = local_strdup(field_ref); + + for(q = s; *q; q++) { + if(*q < 0x20 || *q > 0x7d || *q == 0x3d) { + free(s); + *violation = violations[0]; + return false; + } + } + + *name = s; + + return true; +} + +FLAC__bool parse_add_seekpoint(const char *in, char **out, const char **violation) +{ + static const char *garbled_ = "garbled specification"; + const unsigned n = strlen(in); + + FLAC__ASSERT(0 != in); + FLAC__ASSERT(0 != out); + + if(n == 0) { + *violation = "specification is empty"; + return false; + } + + if(n > strspn(in, "0123456789.Xsx")) { + *violation = "specification contains invalid character"; + return false; + } + + if(in[n-1] == 'X') { + if(n > 1) { + *violation = garbled_; + return false; + } + } + else if(in[n-1] == 's') { + if(n-1 > strspn(in, "0123456789.")) { + *violation = garbled_; + return false; + } + } + else if(in[n-1] == 'x') { + if(n-1 > strspn(in, "0123456789")) { + *violation = garbled_; + return false; + } + } + else { + if(n > strspn(in, "0123456789")) { + *violation = garbled_; + return false; + } + } + + *out = local_strdup(in); + return true; +} + +FLAC__bool parse_add_padding(const char *in, unsigned *out) +{ + FLAC__ASSERT(0 != in); + FLAC__ASSERT(0 != out); + *out = (unsigned)strtoul(in, 0, 10); + return *out < (1u << FLAC__STREAM_METADATA_LENGTH_LEN); +} + +FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out) +{ + char *p, *q, *s, *end; + long i; + unsigned entry; + + if(*in == '\0') + return false; + + s = local_strdup(in); + + /* first count the entries */ + for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ',')) + ; + + /* make space */ + FLAC__ASSERT(out->num_entries > 0); + if(0 == (out->entries = (unsigned*)safe_malloc_mul_2op_(sizeof(unsigned), /*times*/out->num_entries))) + die("out of memory allocating space for option list"); + + /* load 'em up */ + entry = 0; + q = s; + while(q) { + FLAC__ASSERT(entry < out->num_entries); + if(0 != (p = strchr(q, ','))) + *p++ = '\0'; + if(!isdigit((int)(*q)) || (i = strtol(q, &end, 10)) < 0 || *end) { + free(s); + return false; + } + out->entries[entry++] = (unsigned)i; + q = p; + } + FLAC__ASSERT(entry == out->num_entries); + + free(s); + return true; +} + +FLAC__bool parse_block_type(const char *in, Argument_BlockType *out) +{ + char *p, *q, *r, *s; + unsigned entry; + + if(*in == '\0') + return false; + + s = local_strdup(in); + + /* first count the entries */ + for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ',')) + ; + + /* make space */ + FLAC__ASSERT(out->num_entries > 0); + if(0 == (out->entries = (Argument_BlockTypeEntry*)safe_malloc_mul_2op_(sizeof(Argument_BlockTypeEntry), /*times*/out->num_entries))) + die("out of memory allocating space for option list"); + + /* load 'em up */ + entry = 0; + q = s; + while(q) { + FLAC__ASSERT(entry < out->num_entries); + if(0 != (p = strchr(q, ','))) + *p++ = 0; + r = strchr(q, ':'); + if(r) + *r++ = '\0'; + if(0 != r && 0 != strcmp(q, "APPLICATION")) { + free(s); + return false; + } + if(0 == strcmp(q, "STREAMINFO")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_STREAMINFO; + } + else if(0 == strcmp(q, "PADDING")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_PADDING; + } + else if(0 == strcmp(q, "APPLICATION")) { + out->entries[entry].type = FLAC__METADATA_TYPE_APPLICATION; + out->entries[entry].filter_application_by_id = (0 != r); + if(0 != r) { + if(strlen(r) == 4) { + strcpy(out->entries[entry].application_id, r); + } + else if(strlen(r) == 10 && strncmp(r, "0x", 2) == 0 && strspn(r+2, "0123456789ABCDEFabcdef") == 8) { + FLAC__uint32 x = strtoul(r+2, 0, 16); + out->entries[entry].application_id[3] = (FLAC__byte)(x & 0xff); + out->entries[entry].application_id[2] = (FLAC__byte)((x>>=8) & 0xff); + out->entries[entry].application_id[1] = (FLAC__byte)((x>>=8) & 0xff); + out->entries[entry].application_id[0] = (FLAC__byte)((x>>=8) & 0xff); + } + else { + free(s); + return false; + } + } + entry++; + } + else if(0 == strcmp(q, "SEEKTABLE")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_SEEKTABLE; + } + else if(0 == strcmp(q, "VORBIS_COMMENT")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_VORBIS_COMMENT; + } + else if(0 == strcmp(q, "CUESHEET")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_CUESHEET; + } + else if(0 == strcmp(q, "PICTURE")) { + out->entries[entry++].type = FLAC__METADATA_TYPE_PICTURE; + } + else { + free(s); + return false; + } + q = p; + } + FLAC__ASSERT(entry == out->num_entries); + + free(s); + return true; +} + +FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out) +{ + if(0 == strcmp(in, "binary")) + out->is_binary = true; + else if(0 == strcmp(in, "text")) + out->is_binary = false; + else + return false; + return true; +} + +FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out) +{ + if(0 == strcmp(in, "hexdump")) + *out = true; + else if(0 == strcmp(in, "text")) + *out = false; + else + return false; + return true; +} + +void undocumented_warning(const char *opt) +{ + fprintf(stderr, "WARNING: undocmented option --%s should be used with caution,\n only for repairing a damaged STREAMINFO block\n", opt); +} diff --git a/flac/src/metaflac/options.h b/flac/src/metaflac/options.h new file mode 100644 index 0000000..0f67320 --- /dev/null +++ b/flac/src/metaflac/options.h @@ -0,0 +1,215 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef metaflac__options_h +#define metaflac__options_h + +#include "FLAC/format.h" + +#if 0 +/*[JEC] was:#if HAVE_GETOPT_LONG*/ +/*[JEC] see flac/include/share/getopt.h as to why the change */ +# include +#else +# include "share/getopt.h" +#endif + +extern struct share__option long_options_[]; + +typedef enum { + OP__SHOW_MD5SUM, + OP__SHOW_MIN_BLOCKSIZE, + OP__SHOW_MAX_BLOCKSIZE, + OP__SHOW_MIN_FRAMESIZE, + OP__SHOW_MAX_FRAMESIZE, + OP__SHOW_SAMPLE_RATE, + OP__SHOW_CHANNELS, + OP__SHOW_BPS, + OP__SHOW_TOTAL_SAMPLES, + OP__SET_MD5SUM, + OP__SET_MIN_BLOCKSIZE, + OP__SET_MAX_BLOCKSIZE, + OP__SET_MIN_FRAMESIZE, + OP__SET_MAX_FRAMESIZE, + OP__SET_SAMPLE_RATE, + OP__SET_CHANNELS, + OP__SET_BPS, + OP__SET_TOTAL_SAMPLES, + OP__SHOW_VC_VENDOR, + OP__SHOW_VC_FIELD, + OP__REMOVE_VC_ALL, + OP__REMOVE_VC_FIELD, + OP__REMOVE_VC_FIRSTFIELD, + OP__SET_VC_FIELD, + OP__IMPORT_VC_FROM, + OP__EXPORT_VC_TO, + OP__IMPORT_CUESHEET_FROM, + OP__EXPORT_CUESHEET_TO, + OP__IMPORT_PICTURE_FROM, + OP__EXPORT_PICTURE_TO, + OP__ADD_SEEKPOINT, + OP__ADD_REPLAY_GAIN, + OP__ADD_PADDING, + OP__LIST, + OP__APPEND, + OP__REMOVE, + OP__REMOVE_ALL, + OP__MERGE_PADDING, + OP__SORT_PADDING +} OperationType; + +typedef enum { + ARG__BLOCK_NUMBER, + ARG__BLOCK_TYPE, + ARG__EXCEPT_BLOCK_TYPE, + ARG__DATA_FORMAT, + ARG__FROM_FILE +} ArgumentType; + +typedef struct { + FLAC__byte value[16]; +} Argument_StreaminfoMD5; + +typedef struct { + FLAC__uint32 value; +} Argument_StreaminfoUInt32; + +typedef struct { + FLAC__uint64 value; +} Argument_StreaminfoUInt64; + +typedef struct { + char *value; +} Argument_VcFieldName; + +typedef struct { + char *field; /* the whole field as passed on the command line, i.e. "NAME=VALUE" */ + char *field_name; + /* according to the vorbis spec, field values can contain \0 so simple C strings are not enough here */ + unsigned field_value_length; + char *field_value; + FLAC__bool field_value_from_file; /* true if field_value holds a filename for the value, false for plain value */ +} Argument_VcField; + +typedef struct { + char *value; +} Argument_String; + +typedef struct { + unsigned num_entries; + unsigned *entries; +} Argument_BlockNumber; + +typedef struct { + FLAC__MetadataType type; + char application_id[4]; /* only relevant if type == FLAC__STREAM_METADATA_TYPE_APPLICATION */ + FLAC__bool filter_application_by_id; +} Argument_BlockTypeEntry; + +typedef struct { + unsigned num_entries; + Argument_BlockTypeEntry *entries; +} Argument_BlockType; + +typedef struct { + FLAC__bool is_binary; +} Argument_DataFormat; + +typedef struct { + char *file_name; +} Argument_FromFile; + +typedef struct { + char *specification; +} Argument_AddSeekpoint; + +typedef struct { + char *filename; + Argument_AddSeekpoint *add_seekpoint_link; +} Argument_ImportCuesheetFrom; + +typedef struct { + char *filename; + const Argument_BlockNumber *block_number_link; /* may be NULL to mean 'first PICTURE block' */ +} Argument_ExportPictureTo; + +typedef struct { + unsigned length; +} Argument_AddPadding; + +typedef struct { + OperationType type; + union { + Argument_StreaminfoMD5 streaminfo_md5; + Argument_StreaminfoUInt32 streaminfo_uint32; + Argument_StreaminfoUInt64 streaminfo_uint64; + Argument_VcFieldName vc_field_name; + Argument_VcField vc_field; + Argument_String filename; + Argument_String specification; + Argument_ImportCuesheetFrom import_cuesheet_from; + Argument_ExportPictureTo export_picture_to; + Argument_AddSeekpoint add_seekpoint; + Argument_AddPadding add_padding; + } argument; +} Operation; + +typedef struct { + ArgumentType type; + union { + Argument_BlockNumber block_number; + Argument_BlockType block_type; + Argument_DataFormat data_format; + Argument_FromFile from_file; + } value; +} Argument; + +typedef struct { + FLAC__bool preserve_modtime; + FLAC__bool prefix_with_filename; + FLAC__bool utf8_convert; + FLAC__bool use_padding; + FLAC__bool cued_seekpoints; + FLAC__bool show_long_help; + FLAC__bool show_version; + FLAC__bool application_data_format_is_hexdump; + struct { + Operation *operations; + unsigned num_operations; + unsigned capacity; + } ops; + struct { + struct { + unsigned num_shorthand_ops; + unsigned num_major_ops; + FLAC__bool has_block_type; + FLAC__bool has_except_block_type; + } checks; + Argument *arguments; + unsigned num_arguments; + unsigned capacity; + } args; + unsigned num_files; + char **filenames; +} CommandLineOptions; + +void init_options(CommandLineOptions *options); +FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options); +void free_options(CommandLineOptions *options); + +#endif diff --git a/flac/src/metaflac/usage.c b/flac/src/metaflac/usage.c new file mode 100644 index 0000000..738873d --- /dev/null +++ b/flac/src/metaflac/usage.c @@ -0,0 +1,325 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "usage.h" +#include "FLAC/format.h" +#include +#include + +static void usage_header(FILE *out) +{ + fprintf(out, "==============================================================================\n"); + fprintf(out, "metaflac - Command-line FLAC metadata editor version %s\n", FLAC__VERSION_STRING); + fprintf(out, "Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson\n"); + fprintf(out, "\n"); + fprintf(out, "This program is free software; you can redistribute it and/or\n"); + fprintf(out, "modify it under the terms of the GNU General Public License\n"); + fprintf(out, "as published by the Free Software Foundation; either version 2\n"); + fprintf(out, "of the License, or (at your option) any later version.\n"); + fprintf(out, "\n"); + fprintf(out, "This program is distributed in the hope that it will be useful,\n"); + fprintf(out, "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); + fprintf(out, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); + fprintf(out, "GNU General Public License for more details.\n"); + fprintf(out, "\n"); + fprintf(out, "You should have received a copy of the GNU General Public License\n"); + fprintf(out, "along with this program; if not, write to the Free Software\n"); + fprintf(out, "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n"); + fprintf(out, "==============================================================================\n"); +} + +static void usage_summary(FILE *out) +{ + fprintf(out, "Usage:\n"); + fprintf(out, " metaflac [options] [operations] FLACfile [FLACfile ...]\n"); + fprintf(out, "\n"); + fprintf(out, "Use metaflac to list, add, remove, or edit metadata in one or more FLAC files.\n"); + fprintf(out, "You may perform one major operation, or many shorthand operations at a time.\n"); + fprintf(out, "\n"); + fprintf(out, "Options:\n"); + fprintf(out, "--preserve-modtime Preserve the original modification time in spite of edits\n"); + fprintf(out, "--with-filename Prefix each output line with the FLAC file name\n"); + fprintf(out, " (the default if more than one FLAC file is specified)\n"); + fprintf(out, "--no-filename Do not prefix each output line with the FLAC file name\n"); + fprintf(out, " (the default if only one FLAC file is specified)\n"); + fprintf(out, "--no-utf8-convert Do not convert tags from UTF-8 to local charset,\n"); + fprintf(out, " or vice versa. This is useful for scripts, and setting\n"); + fprintf(out, " tags in situations where the locale is wrong.\n"); + fprintf(out, "--dont-use-padding By default metaflac tries to use padding where possible\n"); + fprintf(out, " to avoid rewriting the entire file if the metadata size\n"); + fprintf(out, " changes. Use this option to tell metaflac to not take\n"); + fprintf(out, " advantage of padding this way.\n"); +} + +int short_usage(const char *message, ...) +{ + va_list args; + + if(message) { + va_start(args, message); + + (void) vfprintf(stderr, message, args); + + va_end(args); + + } + usage_header(stderr); + fprintf(stderr, "\n"); + fprintf(stderr, "This is the short help; for full help use 'metaflac --help'\n"); + fprintf(stderr, "\n"); + usage_summary(stderr); + + return message? 1 : 0; +} + +int long_usage(const char *message, ...) +{ + FILE *out = (message? stderr : stdout); + va_list args; + + if(message) { + va_start(args, message); + + (void) vfprintf(stderr, message, args); + + va_end(args); + + } + usage_header(out); + fprintf(out, "\n"); + usage_summary(out); + fprintf(out, "\n"); + fprintf(out, "Shorthand operations:\n"); + fprintf(out, "--show-md5sum Show the MD5 signature from the STREAMINFO block.\n"); + fprintf(out, "--show-min-blocksize Show the minimum block size from the STREAMINFO block.\n"); + fprintf(out, "--show-max-blocksize Show the maximum block size from the STREAMINFO block.\n"); + fprintf(out, "--show-min-framesize Show the minimum frame size from the STREAMINFO block.\n"); + fprintf(out, "--show-max-framesize Show the maximum frame size from the STREAMINFO block.\n"); + fprintf(out, "--show-sample-rate Show the sample rate from the STREAMINFO block.\n"); + fprintf(out, "--show-channels Show the number of channels from the STREAMINFO block.\n"); + fprintf(out, "--show-bps Show the # of bits per sample from the STREAMINFO block.\n"); + fprintf(out, "--show-total-samples Show the total # of samples from the STREAMINFO block.\n"); + fprintf(out, "\n"); + fprintf(out, "--show-vendor-tag Show the vendor string from the VORBIS_COMMENT block.\n"); + fprintf(out, "--show-tag=NAME Show all tags where the the field name matches 'NAME'.\n"); + fprintf(out, "--remove-tag=NAME Remove all tags whose field name is 'NAME'.\n"); + fprintf(out, "--remove-first-tag=NAME Remove first tag whose field name is 'NAME'.\n"); + fprintf(out, "--remove-all-tags Remove all tags, leaving only the vendor string.\n"); + fprintf(out, "--set-tag=FIELD Add a tag. The FIELD must comply with the Vorbis comment\n"); + fprintf(out, " spec, of the form \"NAME=VALUE\". If there is currently\n"); + fprintf(out, " no tag block, one will be created.\n"); + fprintf(out, "--set-tag-from-file=FIELD Like --set-tag, except the VALUE is a filename\n"); + fprintf(out, " whose contents will be read verbatim to set the tag value.\n"); + fprintf(out, " Unless --no-utf8-convert is specified, the contents will\n"); + fprintf(out, " be converted to UTF-8 from the local charset. This can\n"); + fprintf(out, " be used to store a cuesheet in a tag (e.g.\n"); + fprintf(out, " --set-tag-from-file=\"CUESHEET=image.cue\"). Do not try\n"); + fprintf(out, " to store binary data in tag fields! Use APPLICATION\n"); + fprintf(out, " blocks for that.\n"); + fprintf(out, "--import-tags-from=FILE Import tags from a file. Use '-' for stdin. Each line\n"); + fprintf(out, " should be of the form NAME=VALUE. Multi-line comments\n"); + fprintf(out, " are currently not supported. Specify --remove-all-tags\n"); + fprintf(out, " and/or --no-utf8-convert before --import-tags-from if\n"); + fprintf(out, " necessary. If FILE is '-' (stdin), only one FLAC file\n"); + fprintf(out, " may be specified.\n"); + fprintf(out, "--export-tags-to=FILE Export tags to a file. Use '-' for stdout. Each line\n"); + fprintf(out, " will be of the form NAME=VALUE. Specify\n"); + fprintf(out, " --no-utf8-convert if necessary.\n"); + fprintf(out, "--import-cuesheet-from=FILE Import a cuesheet from a file. Use '-' for stdin.\n"); + fprintf(out, " Only one FLAC file may be specified. A seekpoint will be\n"); + fprintf(out, " added for each index point in the cuesheet to the\n"); + fprintf(out, " SEEKTABLE unless --no-cued-seekpoints is specified.\n"); + fprintf(out, "--export-cuesheet-to=FILE Export CUESHEET block to a cuesheet file, suitable\n"); + fprintf(out, " for use by CD authoring software. Use '-' for stdout.\n"); + fprintf(out, " Only one FLAC file may be specified on the command line.\n"); + fprintf(out, "--import-picture-from=FILENAME|SPECIFICATION Import a picture and store it in a\n"); + fprintf(out, " PICTURE block. Either a filename for the picture file or\n"); + fprintf(out, " a more complete specification form can be used. The\n"); + fprintf(out, " SPECIFICATION is a string whose parts are separated by |\n"); + fprintf(out, " characters. Some parts may be left empty to invoke\n"); + fprintf(out, " default values. FILENAME is just shorthand for\n"); + fprintf(out, " \"||||FILENAME\". The format of SPECIFICATION is:\n"); + fprintf(out, " [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE\n"); + fprintf(out, " TYPE is optional; it is a number from one of:\n"); + fprintf(out, " 0: Other\n"); + fprintf(out, " 1: 32x32 pixels 'file icon' (PNG only)\n"); + fprintf(out, " 2: Other file icon\n"); + fprintf(out, " 3: Cover (front)\n"); + fprintf(out, " 4: Cover (back)\n"); + fprintf(out, " 5: Leaflet page\n"); + fprintf(out, " 6: Media (e.g. label side of CD)\n"); + fprintf(out, " 7: Lead artist/lead performer/soloist\n"); + fprintf(out, " 8: Artist/performer\n"); + fprintf(out, " 9: Conductor\n"); + fprintf(out, " 10: Band/Orchestra\n"); + fprintf(out, " 11: Composer\n"); + fprintf(out, " 12: Lyricist/text writer\n"); + fprintf(out, " 13: Recording Location\n"); + fprintf(out, " 14: During recording\n"); + fprintf(out, " 15: During performance\n"); + fprintf(out, " 16: Movie/video screen capture\n"); + fprintf(out, " 17: A bright coloured fish\n"); + fprintf(out, " 18: Illustration\n"); + fprintf(out, " 19: Band/artist logotype\n"); + fprintf(out, " 20: Publisher/Studio logotype\n"); + fprintf(out, " The default is 3 (front cover). There may only be one picture each\n"); + fprintf(out, " of type 1 and 2 in a file.\n"); + fprintf(out, " MIME-TYPE is optional; if left blank, it will be detected from the\n"); + fprintf(out, " file. For best compatibility with players, use pictures with MIME\n"); + fprintf(out, " type image/jpeg or image/png. The MIME type can also be --> to\n"); + fprintf(out, " mean that FILE is actually a URL to an image, though this use is\n"); + fprintf(out, " discouraged.\n"); + fprintf(out, " DESCRIPTION is optional; the default is an empty string\n"); + fprintf(out, " The next part specfies the resolution and color information. If\n"); + fprintf(out, " the MIME-TYPE is image/jpeg, image/png, or image/gif, you can\n"); + fprintf(out, " usually leave this empty and they can be detected from the file.\n"); + fprintf(out, " Otherwise, you must specify the width in pixels, height in pixels,\n"); + fprintf(out, " and color depth in bits-per-pixel. If the image has indexed colors\n"); + fprintf(out, " you should also specify the number of colors used.\n"); + fprintf(out, " FILE is the path to the picture file to be imported, or the URL if\n"); + fprintf(out, " MIME type is -->\n"); + fprintf(out, "--export-picture-to=FILE Export PICTURE block to a file. Use '-' for stdout.\n"); + fprintf(out, " Only one FLAC file may be specified. The first PICTURE\n"); + fprintf(out, " block will be exported unless --export-picture-to is\n"); + fprintf(out, " preceded by a --block-number=# option to specify the exact\n"); + fprintf(out, " metadata block to extract. Note that the block number is\n"); + fprintf(out, " the one shown by --list.\n"); + fprintf(out, "--add-replay-gain Calculates the title and album gains/peaks of the given\n"); + fprintf(out, " FLAC files as if all the files were part of one album,\n"); + fprintf(out, " then stores them in the VORBIS_COMMENT block. The tags\n"); + fprintf(out, " are the same as those used by vorbisgain. Existing\n"); + fprintf(out, " ReplayGain tags will be replaced. If only one FLAC file\n"); + fprintf(out, " is given, the album and title gains will be the same.\n"); + fprintf(out, " Since this operation requires two passes, it is always\n"); + fprintf(out, " executed last, after all other operations have been\n"); + fprintf(out, " completed and written to disk. All FLAC files specified\n"); + fprintf(out, " must have the same resolution, sample rate, and number\n"); + fprintf(out, " of channels. The sample rate must be one of 8, 11.025,\n"); + fprintf(out, " 12, 16, 22.05, 24, 32, 44.1, or 48 kHz.\n"); + fprintf(out, "--remove-replay-gain Removes the ReplayGain tags.\n"); + fprintf(out, "--add-seekpoint={#|X|#x|#s} Add seek points to a SEEKTABLE block\n"); + fprintf(out, " # : a specific sample number for a seek point\n"); + fprintf(out, " X : a placeholder point (always goes at the end of the SEEKTABLE)\n"); + fprintf(out, " #x : # evenly spaced seekpoints, the first being at sample 0\n"); + fprintf(out, " #s : a seekpoint every # seconds; # does not have to be a whole number\n"); + fprintf(out, " If no SEEKTABLE block exists, one will be created. If\n"); + fprintf(out, " one already exists, points will be added to the existing\n"); + fprintf(out, " table, and any duplicates will be turned into placeholder\n"); + fprintf(out, " points. You may use many --add-seekpoint options; the\n"); + fprintf(out, " resulting SEEKTABLE will be the unique-ified union of\n"); + fprintf(out, " all such values. Example: --add-seekpoint=100x\n"); + fprintf(out, " --add-seekpoint=3.5s will add 100 evenly spaced\n"); + fprintf(out, " seekpoints and a seekpoint every 3.5 seconds.\n"); + fprintf(out, "--add-padding=length Add a padding block of the given length (in bytes).\n"); + fprintf(out, " The overall length of the new block will be 4 + length;\n"); + fprintf(out, " the extra 4 bytes is for the metadata block header.\n"); + fprintf(out, "\n"); + fprintf(out, "Major operations:\n"); + fprintf(out, "--version\n"); + fprintf(out, " Show the metaflac version number.\n"); + fprintf(out, "--list\n"); + fprintf(out, " List the contents of one or more metadata blocks to stdout. By default,\n"); + fprintf(out, " all metadata blocks are listed in text format. Use the following options\n"); + fprintf(out, " to change this behavior:\n"); + fprintf(out, "\n"); + fprintf(out, " --block-number=#[,#[...]]\n"); + fprintf(out, " An optional comma-separated list of block numbers to display. The first\n"); + fprintf(out, " block, the STREAMINFO block, is block 0.\n"); + fprintf(out, "\n"); + fprintf(out, " --block-type=type[,type[...]]\n"); + fprintf(out, " --except-block-type=type[,type[...]]\n"); + fprintf(out, " An optional comma-separated list of block types to be included or ignored\n"); + fprintf(out, " with this option. Use only one of --block-type or --except-block-type.\n"); + fprintf(out, " The valid block types are: STREAMINFO, PADDING, APPLICATION, SEEKTABLE,\n"); + fprintf(out, " VORBIS_COMMENT. You may narrow down the types of APPLICATION blocks\n"); + fprintf(out, " displayed as follows:\n"); + fprintf(out, " APPLICATION:abcd The APPLICATION block(s) whose textual repre-\n"); + fprintf(out, " sentation of the 4-byte ID is \"abcd\"\n"); + fprintf(out, " APPLICATION:0xXXXXXXXX The APPLICATION block(s) whose hexadecimal big-\n"); + fprintf(out, " endian representation of the 4-byte ID is\n"); + fprintf(out, " \"0xXXXXXXXX\". For the example \"abcd\" above the\n"); + fprintf(out, " hexadecimal equivalalent is 0x61626364\n"); + fprintf(out, "\n"); + fprintf(out, " NOTE: if both --block-number and --[except-]block-type are specified,\n"); + fprintf(out, " the result is the logical AND of both arguments.\n"); + fprintf(out, "\n"); +#if 0 + /*@@@ not implemented yet */ + fprintf(out, " --data-format=binary|text\n"); + fprintf(out, " By default a human-readable text representation of the data is displayed.\n"); + fprintf(out, " You may specify --data-format=binary to dump the raw binary form of each\n"); + fprintf(out, " metadata block. The output can be read in using a subsequent call to\n"); + fprintf(out, " "metaflac --append --from-file=..."\n"); + fprintf(out, "\n"); +#endif + fprintf(out, " --application-data-format=hexdump|text\n"); + fprintf(out, " If the application block you are displaying contains binary data but your\n"); + fprintf(out, " --data-format=text, you can display a hex dump of the application data\n"); + fprintf(out, " contents instead using --application-data-format=hexdump\n"); + fprintf(out, "\n"); +#if 0 + /*@@@ not implemented yet */ + fprintf(out, "--append\n"); + fprintf(out, " Insert a metadata block from a file. The input file must be in the same\n"); + fprintf(out, " format as generated with --list.\n"); + fprintf(out, "\n"); + fprintf(out, " --block-number=#\n"); + fprintf(out, " Specify the insertion point (defaults to last block). The new block will\n"); + fprintf(out, " be added after the given block number. This prevents the illegal insertion\n"); + fprintf(out, " of a block before the first STREAMINFO block. You may not --append another\n"); + fprintf(out, " STREAMINFO block.\n"); + fprintf(out, "\n"); + fprintf(out, " --from-file=filename\n"); + fprintf(out, " Mandatory 'option' to specify the input file containing the block contents.\n"); + fprintf(out, "\n"); + fprintf(out, " --data-format=binary|text\n"); + fprintf(out, " By default the block contents are assumed to be in binary format. You can\n"); + fprintf(out, " override this by specifying --data-format=text\n"); + fprintf(out, "\n"); +#endif + fprintf(out, "--remove\n"); + fprintf(out, " Remove one or more metadata blocks from the metadata. Unless\n"); + fprintf(out, " --dont-use-padding is specified, the blocks will be replaced with padding.\n"); + fprintf(out, " You may not remove the STREAMINFO block.\n"); + fprintf(out, "\n"); + fprintf(out, " --block-number=#[,#[...]]\n"); + fprintf(out, " --block-type=type[,type[...]]\n"); + fprintf(out, " --except-block-type=type[,type[...]]\n"); + fprintf(out, " See --list above for usage.\n"); + fprintf(out, "\n"); + fprintf(out, " NOTE: if both --block-number and --[except-]block-type are specified,\n"); + fprintf(out, " the result is the logical AND of both arguments.\n"); + fprintf(out, "\n"); + fprintf(out, "--remove-all\n"); + fprintf(out, " Remove all metadata blocks (except the STREAMINFO block) from the\n"); + fprintf(out, " metadata. Unless --dont-use-padding is specified, the blocks will be\n"); + fprintf(out, " replaced with padding.\n"); + fprintf(out, "\n"); + fprintf(out, "--merge-padding\n"); + fprintf(out, " Merge adjacent PADDING blocks into single blocks.\n"); + fprintf(out, "\n"); + fprintf(out, "--sort-padding\n"); + fprintf(out, " Move all PADDING blocks to the end of the metadata and merge them into a\n"); + fprintf(out, " single block.\n"); + + return message? 1 : 0; +} diff --git a/flac/src/metaflac/usage.h b/flac/src/metaflac/usage.h new file mode 100644 index 0000000..39dddd5 --- /dev/null +++ b/flac/src/metaflac/usage.h @@ -0,0 +1,25 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef metaflac__usage_h +#define metaflac__usage_h + +int short_usage(const char *message, ...); +int long_usage(const char *message, ...); + +#endif diff --git a/flac/src/metaflac/utils.c b/flac/src/metaflac/utils.c new file mode 100644 index 0000000..cd9e066 --- /dev/null +++ b/flac/src/metaflac/utils.c @@ -0,0 +1,258 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "utils.h" +#include "FLAC/assert.h" +#include "share/alloc.h" +#include "share/utf8.h" +#include +#include +#include +#include +#include + +void die(const char *message) +{ + FLAC__ASSERT(0 != message); + fprintf(stderr, "ERROR: %s\n", message); + exit(1); +} + +#ifdef FLAC__VALGRIND_TESTING +size_t local_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#endif + +char *local_strdup(const char *source) +{ + char *ret; + FLAC__ASSERT(0 != source); + if(0 == (ret = strdup(source))) + die("out of memory during strdup()"); + return ret; +} + +void local_strcat(char **dest, const char *source) +{ + size_t ndest, nsource; + + FLAC__ASSERT(0 != dest); + FLAC__ASSERT(0 != source); + + ndest = *dest? strlen(*dest) : 0; + nsource = strlen(source); + + if(nsource == 0) + return; + + *dest = (char*)safe_realloc_add_3op_(*dest, ndest, /*+*/nsource, /*+*/1); + if(0 == *dest) + die("out of memory growing string"); + strcpy((*dest)+ndest, source); +} + +void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent) +{ + unsigned i, left = bytes; + const FLAC__byte *b = buf; + + for(i = 0; i < bytes; i += 16) { + printf("%s%s%s%08X: " + "%02X %02X %02X %02X %02X %02X %02X %02X " + "%02X %02X %02X %02X %02X %02X %02X %02X " + "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", + filename? filename:"", filename? ":":"", + indent, i, + left > 0? (unsigned char)b[ 0] : 0, + left > 1? (unsigned char)b[ 1] : 0, + left > 2? (unsigned char)b[ 2] : 0, + left > 3? (unsigned char)b[ 3] : 0, + left > 4? (unsigned char)b[ 4] : 0, + left > 5? (unsigned char)b[ 5] : 0, + left > 6? (unsigned char)b[ 6] : 0, + left > 7? (unsigned char)b[ 7] : 0, + left > 8? (unsigned char)b[ 8] : 0, + left > 9? (unsigned char)b[ 9] : 0, + left > 10? (unsigned char)b[10] : 0, + left > 11? (unsigned char)b[11] : 0, + left > 12? (unsigned char)b[12] : 0, + left > 13? (unsigned char)b[13] : 0, + left > 14? (unsigned char)b[14] : 0, + left > 15? (unsigned char)b[15] : 0, + (left > 0) ? (isprint(b[ 0]) ? b[ 0] : '.') : ' ', + (left > 1) ? (isprint(b[ 1]) ? b[ 1] : '.') : ' ', + (left > 2) ? (isprint(b[ 2]) ? b[ 2] : '.') : ' ', + (left > 3) ? (isprint(b[ 3]) ? b[ 3] : '.') : ' ', + (left > 4) ? (isprint(b[ 4]) ? b[ 4] : '.') : ' ', + (left > 5) ? (isprint(b[ 5]) ? b[ 5] : '.') : ' ', + (left > 6) ? (isprint(b[ 6]) ? b[ 6] : '.') : ' ', + (left > 7) ? (isprint(b[ 7]) ? b[ 7] : '.') : ' ', + (left > 8) ? (isprint(b[ 8]) ? b[ 8] : '.') : ' ', + (left > 9) ? (isprint(b[ 9]) ? b[ 9] : '.') : ' ', + (left > 10) ? (isprint(b[10]) ? b[10] : '.') : ' ', + (left > 11) ? (isprint(b[11]) ? b[11] : '.') : ' ', + (left > 12) ? (isprint(b[12]) ? b[12] : '.') : ' ', + (left > 13) ? (isprint(b[13]) ? b[13] : '.') : ' ', + (left > 14) ? (isprint(b[14]) ? b[14] : '.') : ' ', + (left > 15) ? (isprint(b[15]) ? b[15] : '.') : ' ' + ); + left -= 16; + b += 16; + } +} + +void print_error_with_chain_status(FLAC__Metadata_Chain *chain, const char *format, ...) +{ + const FLAC__Metadata_ChainStatus status = FLAC__metadata_chain_status(chain); + va_list args; + + FLAC__ASSERT(0 != format); + + va_start(args, format); + + (void) vfprintf(stderr, format, args); + + va_end(args); + + fprintf(stderr, ", status = \"%s\"\n", FLAC__Metadata_ChainStatusString[status]); + + if(status == FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE) { + fprintf(stderr, "\n" + "The FLAC file could not be opened. Most likely the file does not exist\n" + "or is not readable.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE) { + fprintf(stderr, "\n" + "The file does not appear to be a FLAC file.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE) { + fprintf(stderr, "\n" + "The FLAC file does not have write permissions.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_BAD_METADATA) { + fprintf(stderr, "\n" + "The metadata to be writted does not conform to the FLAC metadata\n" + "specifications.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_READ_ERROR) { + fprintf(stderr, "\n" + "There was an error while reading the FLAC file.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR) { + fprintf(stderr, "\n" + "There was an error while writing FLAC file; most probably the disk is\n" + "full.\n" + ); + } + else if(status == FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR) { + fprintf(stderr, "\n" + "There was an error removing the temporary FLAC file.\n" + ); + } +} + +FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation) +{ + static const char * const violations[] = { + "field name contains invalid character", + "field contains no '=' character" + }; + + char *p, *q, *s; + + if(0 != field) + *field = local_strdup(field_ref); + + s = local_strdup(field_ref); + + if(0 == (p = strchr(s, '='))) { + free(s); + *violation = violations[1]; + return false; + } + *p++ = '\0'; + + for(q = s; *q; q++) { + if(*q < 0x20 || *q > 0x7d || *q == 0x3d) { + free(s); + *violation = violations[0]; + return false; + } + } + + *name = local_strdup(s); + *value = local_strdup(p); + *length = strlen(p); + + free(s); + return true; +} + +void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__bool raw, FILE *f) +{ + if(0 != entry->entry) { + if(filename) + fprintf(f, "%s:", filename); + + if(!raw) { + /* + * WATCHOUT: comments that contain an embedded null will + * be truncated by utf_decode(). + */ + char *converted; + + if(utf8_decode((const char *)entry->entry, &converted) >= 0) { + (void) local_fwrite(converted, 1, strlen(converted), f); + free(converted); + } + else { + (void) local_fwrite(entry->entry, 1, entry->length, f); + } + } + else { + (void) local_fwrite(entry->entry, 1, entry->length, f); + } + } + + putc('\n', f); +} + +void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries, FLAC__bool raw, FILE *f) +{ + unsigned i; + const unsigned field_name_length = (0 != field_name)? strlen(field_name) : 0; + + for(i = 0; i < num_entries; i++) { + if(0 == field_name || FLAC__metadata_object_vorbiscomment_entry_matches(entry[i], field_name, field_name_length)) + write_vc_field(filename, entry + i, raw, f); + } +} diff --git a/flac/src/metaflac/utils.h b/flac/src/metaflac/utils.h new file mode 100644 index 0000000..dbed8e7 --- /dev/null +++ b/flac/src/metaflac/utils.h @@ -0,0 +1,41 @@ +/* metaflac - Command-line FLAC metadata editor + * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef metaflac__utils_h +#define metaflac__utils_h + +#include "FLAC/metadata.h" +#include /* for FILE */ + +void die(const char *message); +#ifdef FLAC__VALGRIND_TESTING +size_t local_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); +#else +#define local_fwrite fwrite +#endif +char *local_strdup(const char *source); +void local_strcat(char **dest, const char *source); +void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent); +void print_error_with_chain_status(FLAC__Metadata_Chain *chain, const char *format, ...); + +FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation); + +void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__bool raw, FILE *f); +void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries, FLAC__bool raw, FILE *f); + +#endif diff --git a/flac/src/monkeys_audio_utilities/Makefile.am b/flac/src/monkeys_audio_utilities/Makefile.am new file mode 100644 index 0000000..b3016aa --- /dev/null +++ b/flac/src/monkeys_audio_utilities/Makefile.am @@ -0,0 +1,18 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = flac_mac flac_ren diff --git a/flac/src/monkeys_audio_utilities/flac_mac/Makefile.am b/flac/src/monkeys_audio_utilities/flac_mac/Makefile.am new file mode 100644 index 0000000..1bde520 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_mac/Makefile.am @@ -0,0 +1,21 @@ +# flac_mac - wedge utility to add FLAC support to Monkey's Audio +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + flac_mac.dsp \ + flac_mac.vcproj \ + main.c diff --git a/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.dsp b/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.dsp new file mode 100644 index 0000000..1401447 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="flac_mac" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=flac_mac - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "flac_mac.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "flac_mac.mak" CFG="flac_mac - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "flac_mac - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "flac_mac - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "flac_mac - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "flac_mac - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "flac_mac - Win32 Release" +# Name "flac_mac - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.vcproj b/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.vcproj new file mode 100644 index 0000000..65df3d8 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_mac/flac_mac.vcproj @@ -0,0 +1,364 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/monkeys_audio_utilities/flac_mac/main.c b/flac/src/monkeys_audio_utilities/flac_mac/main.c new file mode 100644 index 0000000..1d56115 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_mac/main.c @@ -0,0 +1,208 @@ +/* flac_mac - wedge utility to add FLAC support to Monkey's Audio + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This program can be used to allow FLAC to masquerade as one of the other + * supported lossless codecs in Monkey's Audio. See the documentation for + * how to do this. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include + +static int execit(char *prog, char *args); +static int forkit(char *prog, char *args); + +int main(int argc, char *argv[]) +{ + int flac_return_val = 0, opt_arg = 1, from_arg = -1, to_arg = -1, flac_level = 5, i; + char prog[MAX_PATH], cmdline[MAX_PATH*2], from[MAX_PATH], to[MAX_PATH], macdir[MAX_PATH], options[256], *p; + enum { WAVPACK, RKAU, SHORTEN } codec; + + /* get the directory where MAC external codecs reside */ + if(0 != (p = strrchr(argv[0],'\\'))) { + strcpy(macdir, argv[0]); + *(strrchr(macdir,'\\')+1) = '\0'; + } + else { + strcpy(macdir, ""); + } + + /* determine which codec we were called as and parse the options */ + if(p == 0) + p = argv[0]; + else + p++; + if(0 == strnicmp(p, "short", 5)) { + codec = SHORTEN; + } + else if(0 == strnicmp(p, "rkau", 4)) { + codec = RKAU; + if(argv[1][0] == '-' && argv[1][1] == 'l') { + opt_arg = 2; + switch(argv[1][2]) { + case '1': flac_level = 1; break; + case '2': flac_level = 5; break; + case '3': flac_level = 8; break; + } + } + } + else if(0 == strnicmp(p, "wavpack", 7)) { + codec = WAVPACK; + if(argv[1][0] == '-') { + opt_arg = 2; + switch(argv[1][1]) { + case 'f': flac_level = 1; break; + case 'h': flac_level = 8; break; + default: opt_arg = 1; + } + } + } + else { + return -5; + } + + /* figure out which arguments are the source and destination files */ + for(i = 1; i < argc; i++) + if(argv[i][0] != '-') { + from_arg = i++; + break; + } + for( ; i < argc; i++) + if(argv[i][0] != '-') { + to_arg = i++; + break; + } + if(to_arg < 0) + return -4; + + /* build the command to call flac with */ + sprintf(prog, "%sflac.exe", macdir); + sprintf(options, "-%d", flac_level); + for(i = opt_arg; i < argc; i++) + if(argv[i][0] == '-') { + strcat(options, " "); + strcat(options, argv[i]); + } + sprintf(cmdline, "\"%s\" %s -o \"%s\" \"%s\"", prog, options, argv[to_arg], argv[from_arg]); + + flac_return_val = execit(prog, cmdline); + + /* + * Now that flac has finished, we need to fork a process that will rename + * the resulting file with the correct extension once MAC has moved it to + * it's final resting place. + */ + if(0 == flac_return_val) { + /* get the destination directory, if any */ + if(0 != (p = strchr(argv[to_arg],'\\'))) { + strcpy(from, argv[to_arg]); + *(strrchr(from,'\\')+1) = '\0'; + } + else { + strcpy(from, ""); + } + + /* for the full 'from' and 'to' paths for the renamer process */ + p = strrchr(argv[from_arg],'\\'); + strcat(from, p? p+1 : argv[from_arg]); + strcpy(to, from); + if(0 == strchr(from,'.')) + return -3; + switch(codec) { + case SHORTEN: strcpy(strrchr(from,'.'), ".shn"); break; + case WAVPACK: strcpy(strrchr(from,'.'), ".wv"); break; + case RKAU: strcpy(strrchr(from,'.'), ".rka"); break; + } + strcpy(strrchr(to,'.'), ".flac"); + + sprintf(prog, "%sflac_ren.exe", macdir); + sprintf(cmdline, "\"%s\" \"%s\" \"%s\"", prog, from, to); + + flac_return_val = forkit(prog, cmdline); + } + + return flac_return_val; +} + +int execit(char *prog, char *args) +{ + BOOL ok; + STARTUPINFO startup_info; + PROCESS_INFORMATION proc_info; + + GetStartupInfo(&startup_info); + + ok = CreateProcess( + prog, + args, + 0, /*process security attributes*/ + 0, /*thread security attributes*/ + FALSE, + 0, /*dwCreationFlags*/ + 0, /*environment*/ + 0, /*lpCurrentDirectory*/ + &startup_info, + &proc_info + ); + if(ok) { + DWORD dw; + dw = WaitForSingleObject(proc_info.hProcess, INFINITE); + ok = (dw != 0xFFFFFFFF); + CloseHandle(proc_info.hThread); + CloseHandle(proc_info.hProcess); + } + + return ok? 0 : -1; +} + +int forkit(char *prog, char *args) +{ + BOOL ok; + STARTUPINFO startup_info; + PROCESS_INFORMATION proc_info; + + GetStartupInfo(&startup_info); + + ok = CreateProcess( + prog, + args, + 0, /*process security attributes*/ + 0, /*thread security attributes*/ + FALSE, + DETACHED_PROCESS, /*dwCreationFlags*/ + 0, /*environment*/ + 0, /*lpCurrentDirectory*/ + &startup_info, + &proc_info + ); + if(ok) { + CloseHandle(proc_info.hThread); + CloseHandle(proc_info.hProcess); + } + + return ok? 0 : -2; +} diff --git a/flac/src/monkeys_audio_utilities/flac_ren/Makefile.am b/flac/src/monkeys_audio_utilities/flac_ren/Makefile.am new file mode 100644 index 0000000..ecf6f46 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_ren/Makefile.am @@ -0,0 +1,21 @@ +# flac_ren - renamer part of utility to add FLAC support to Monkey's Audio +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + flac_ren.dsp \ + flac_ren.vcproj \ + main.c diff --git a/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.dsp b/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.dsp new file mode 100644 index 0000000..01e5798 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="flac_ren" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=flac_ren - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "flac_ren.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "flac_ren.mak" CFG="flac_ren - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "flac_ren - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "flac_ren - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "flac_ren - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "flac_ren - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "flac_ren - Win32 Release" +# Name "flac_ren - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.vcproj b/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.vcproj new file mode 100644 index 0000000..a5e005b --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_ren/flac_ren.vcproj @@ -0,0 +1,364 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/monkeys_audio_utilities/flac_ren/main.c b/flac/src/monkeys_audio_utilities/flac_ren/main.c new file mode 100644 index 0000000..41a3466 --- /dev/null +++ b/flac/src/monkeys_audio_utilities/flac_ren/main.c @@ -0,0 +1,39 @@ +/* flac_ren - renamer part of utility to add FLAC support to Monkey's Audio + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + struct stat s; + + /* wait till the 'from' file has reached its final destination */ + do { + Sleep(2000); + } while(stat(argv[1], &s) < 0); + + /* now rename it */ + return rename(argv[1], argv[2]); +} diff --git a/flac/src/plugin_common/Makefile.am b/flac/src/plugin_common/Makefile.am new file mode 100644 index 0000000..7aa189a --- /dev/null +++ b/flac/src/plugin_common/Makefile.am @@ -0,0 +1,48 @@ +# plugin_common - Routines common to several plugins +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I$(top_srcdir)/include + +noinst_LTLIBRARIES = libplugin_common.la + +noinst_HEADERS = \ + all.h \ + charset.h \ + defs.h \ + dither.h \ + replaygain.h \ + tags.h + +libplugin_common_la_SOURCES = \ + charset.c \ + dither.c \ + replaygain.c \ + tags.c + +EXTRA_DIST = \ + Makefile.lite \ + README \ + plugin_common_static.dsp \ + plugin_common_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/plugin_common/Makefile.lite b/flac/src/plugin_common/Makefile.lite new file mode 100644 index 0000000..5fc3d29 --- /dev/null +++ b/flac/src/plugin_common/Makefile.lite @@ -0,0 +1,36 @@ +# plugin_common - Routines common to several plugins +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +# +# GNU makefile +# + +topdir = ../.. + +LIB_NAME = libplugin_common +INCLUDES = -I$(topdir)/include -I$(HOME)/local/include +DEFINES = + +SRCS_C = \ + charset.c \ + dither.c \ + replaygain.c \ + tags.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/plugin_common/README b/flac/src/plugin_common/README new file mode 100644 index 0000000..dffc5b8 --- /dev/null +++ b/flac/src/plugin_common/README @@ -0,0 +1,2 @@ +This directory contains a convenience library of routines that are +common to the plugins. diff --git a/flac/src/plugin_common/all.h b/flac/src/plugin_common/all.h new file mode 100644 index 0000000..0582a4c --- /dev/null +++ b/flac/src/plugin_common/all.h @@ -0,0 +1,26 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__PLUGIN_COMMON__ALL_H +#define FLAC__PLUGIN_COMMON__ALL_H + +#include "charset.h" +#include "dither.h" +#include "tags.h" + +#endif diff --git a/flac/src/plugin_common/charset.c b/flac/src/plugin_common/charset.c new file mode 100644 index 0000000..a189241 --- /dev/null +++ b/flac/src/plugin_common/charset.c @@ -0,0 +1,157 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Only slightly modified charset.c from: + * EasyTAG - Tag editor for MP3 and OGG files + * Copyright (C) 1999-2001 Hvard Kvlen + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +#ifdef HAVE_ICONV +#include +#endif + +#ifdef HAVE_LANGINFO_CODESET +#include +#endif + +#include "charset.h" + + +/************* + * Functions * + *************/ + +char* FLAC_plugin__charset_get_current (void) +{ + char *charset = getenv("CHARSET"); + +#ifdef HAVE_LANGINFO_CODESET + if (!charset) + charset = nl_langinfo(CODESET); +#endif + if (!charset) + charset = "ISO-8859-1"; + + return charset; +} + + +#ifdef HAVE_ICONV +char* FLAC_plugin__charset_convert_string (const char *string, char *from, char *to) +{ + size_t outleft, outsize, length; + iconv_t cd; + char *out, *outptr; + const char *input = string; + + if (!string) + return NULL; + + length = strlen(string); + + if ((cd = iconv_open(to, from)) == (iconv_t)-1) + { +#ifdef DEBUG + fprintf(stderr, "convert_string(): Conversion not supported. Charsets: %s -> %s", from, to); +#endif + return strdup(string); + } + + /* Due to a GLIBC bug, round outbuf_size up to a multiple of 4 */ + /* + 1 for nul in case len == 1 */ + outsize = ((length + 3) & ~3) + 1; + if(outsize < length) /* overflow check */ + return NULL; + out = (char*)malloc(outsize); + outleft = outsize - 1; + outptr = out; + +retry: + if (iconv(cd, (char**)&input, &length, &outptr, &outleft) == (size_t)(-1)) + { + int used; + switch (errno) + { + case E2BIG: + used = outptr - out; + if((outsize - 1) * 2 + 1 <= outsize) { /* overflow check */ + free(out); + return NULL; + } + outsize = (outsize - 1) * 2 + 1; + out = realloc(out, outsize); + outptr = out + used; + outleft = outsize - 1 - used; + goto retry; + case EINVAL: + break; + case EILSEQ: + /* Invalid sequence, try to get the rest of the string */ + input++; + length = strlen(input); + goto retry; + default: +#ifdef DEBUG + fprintf(stderr, "convert_string(): Conversion failed. Inputstring: %s; Error: %s", string, strerror(errno)); +#endif + break; + } + } + *outptr = '\0'; + + iconv_close(cd); + return out; +} +#else +char* FLAC_plugin__charset_convert_string (const char *string, char *from, char *to) +{ + (void)from, (void)to; + if (!string) + return NULL; + return strdup(string); +} +#endif + +#ifdef HAVE_ICONV +int FLAC_plugin__charset_test_conversion (char *from, char *to) +{ + iconv_t cd; + + if ((cd=iconv_open(to,from)) == (iconv_t)-1) + { + /* Conversion not supported */ + return 0; + } + iconv_close(cd); + return 1; +} +#else +int FLAC_plugin__charset_test_conversion (char *from, char *to) +{ + (void)from, (void)to; + return 1; +} +#endif diff --git a/flac/src/plugin_common/charset.h b/flac/src/plugin_common/charset.h new file mode 100644 index 0000000..e17f6fd --- /dev/null +++ b/flac/src/plugin_common/charset.h @@ -0,0 +1,39 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * Only slightly modified charset.h from: + * charset.h - 2001/12/04 + * EasyTAG - Tag editor for MP3 and OGG files + * Copyright (C) 1999-2001 H蛆ard Kv虱en + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + + +#ifndef FLAC__PLUGIN_COMMON__CHARSET_H +#define FLAC__PLUGIN_COMMON__CHARSET_H + + +/************** + * Prototypes * + **************/ + +char *FLAC_plugin__charset_get_current(void); +char *FLAC_plugin__charset_convert_string(const char *string, char *from, char *to); + +/* returns 1 for success, 0 for failure or no iconv */ +int FLAC_plugin__charset_test_conversion(char *from, char *to); + +#endif diff --git a/flac/src/plugin_common/defs.h b/flac/src/plugin_common/defs.h new file mode 100644 index 0000000..8a39aef --- /dev/null +++ b/flac/src/plugin_common/defs.h @@ -0,0 +1,24 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__PLUGIN_COMMON__DEFS_H +#define FLAC__PLUGIN_COMMON__DEFS_H + +#define FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS 2 + +#endif diff --git a/flac/src/plugin_common/dither.c b/flac/src/plugin_common/dither.c new file mode 100644 index 0000000..a8e4460 --- /dev/null +++ b/flac/src/plugin_common/dither.c @@ -0,0 +1,262 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * dithering routine derived from (other GPLed source): + * mad - MPEG audio decoder + * Copyright (C) 2000-2001 Robert Leslie + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "dither.h" +#include "FLAC/assert.h" + +#ifdef max +#undef max +#endif +#define max(a,b) ((a)>(b)?(a):(b)) + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + + +/* 32-bit pseudo-random number generator + * + * @@@ According to Miroslav, this one is poor quality, the one from the + * @@@ original replaygain code is much better + */ +static FLaC__INLINE FLAC__uint32 prng(FLAC__uint32 state) +{ + return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL; +} + +/* dither routine derived from MAD winamp plugin */ + +typedef struct { + FLAC__int32 error[3]; + FLAC__int32 random; +} dither_state; + +static FLaC__INLINE FLAC__int32 linear_dither(unsigned source_bps, unsigned target_bps, FLAC__int32 sample, dither_state *dither, const FLAC__int32 MIN, const FLAC__int32 MAX) +{ + unsigned scalebits; + FLAC__int32 output, mask, random; + + FLAC__ASSERT(source_bps < 32); + FLAC__ASSERT(target_bps <= 24); + FLAC__ASSERT(target_bps <= source_bps); + + /* noise shape */ + sample += dither->error[0] - dither->error[1] + dither->error[2]; + + dither->error[2] = dither->error[1]; + dither->error[1] = dither->error[0] / 2; + + /* bias */ + output = sample + (1L << (source_bps - target_bps - 1)); + + scalebits = source_bps - target_bps; + mask = (1L << scalebits) - 1; + + /* dither */ + random = (FLAC__int32)prng(dither->random); + output += (random & mask) - (dither->random & mask); + + dither->random = random; + + /* clip */ + if(output > MAX) { + output = MAX; + + if(sample > MAX) + sample = MAX; + } + else if(output < MIN) { + output = MIN; + + if(sample < MIN) + sample = MIN; + } + + /* quantize */ + output &= ~mask; + + /* error feedback */ + dither->error[0] = sample - output; + + /* scale */ + return output >> scalebits; +} + +size_t FLAC__plugin_common__pack_pcm_signed_big_endian(FLAC__byte *data, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, unsigned source_bps, unsigned target_bps) +{ + static dither_state dither[FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS]; + FLAC__byte * const start = data; + FLAC__int32 sample; + const FLAC__int32 *input_; + unsigned samples, channel; + const unsigned bytes_per_sample = target_bps / 8; + const unsigned incr = bytes_per_sample * channels; + + FLAC__ASSERT(channels > 0 && channels <= FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS); + FLAC__ASSERT(source_bps < 32); + FLAC__ASSERT(target_bps <= 24); + FLAC__ASSERT(target_bps <= source_bps); + FLAC__ASSERT((source_bps & 7) == 0); + FLAC__ASSERT((target_bps & 7) == 0); + + if(source_bps != target_bps) { + const FLAC__int32 MIN = -(1L << (source_bps - 1)); + const FLAC__int32 MAX = ~MIN; /*(1L << (source_bps-1)) - 1 */ + + for(channel = 0; channel < channels; channel++) { + + samples = wide_samples; + data = start + bytes_per_sample * channel; + input_ = input[channel]; + + while(samples--) { + sample = linear_dither(source_bps, target_bps, *input_++, &dither[channel], MIN, MAX); + + switch(target_bps) { + case 8: + data[0] = sample ^ 0x80; + break; + case 16: + data[0] = (FLAC__byte)(sample >> 8); + data[1] = (FLAC__byte)sample; + break; + case 24: + data[0] = (FLAC__byte)(sample >> 16); + data[1] = (FLAC__byte)(sample >> 8); + data[2] = (FLAC__byte)sample; + break; + } + + data += incr; + } + } + } + else { + for(channel = 0; channel < channels; channel++) { + samples = wide_samples; + data = start + bytes_per_sample * channel; + input_ = input[channel]; + + while(samples--) { + sample = *input_++; + + switch(target_bps) { + case 8: + data[0] = sample ^ 0x80; + break; + case 16: + data[0] = (FLAC__byte)(sample >> 8); + data[1] = (FLAC__byte)sample; + break; + case 24: + data[0] = (FLAC__byte)(sample >> 16); + data[1] = (FLAC__byte)(sample >> 8); + data[2] = (FLAC__byte)sample; + break; + } + + data += incr; + } + } + } + + return wide_samples * channels * (target_bps/8); +} + +size_t FLAC__plugin_common__pack_pcm_signed_little_endian(FLAC__byte *data, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, unsigned source_bps, unsigned target_bps) +{ + static dither_state dither[FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS]; + FLAC__byte * const start = data; + FLAC__int32 sample; + const FLAC__int32 *input_; + unsigned samples, channel; + const unsigned bytes_per_sample = target_bps / 8; + const unsigned incr = bytes_per_sample * channels; + + FLAC__ASSERT(channels > 0 && channels <= FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS); + FLAC__ASSERT(source_bps < 32); + FLAC__ASSERT(target_bps <= 24); + FLAC__ASSERT(target_bps <= source_bps); + FLAC__ASSERT((source_bps & 7) == 0); + FLAC__ASSERT((target_bps & 7) == 0); + + if(source_bps != target_bps) { + const FLAC__int32 MIN = -(1L << (source_bps - 1)); + const FLAC__int32 MAX = ~MIN; /*(1L << (source_bps-1)) - 1 */ + + for(channel = 0; channel < channels; channel++) { + + samples = wide_samples; + data = start + bytes_per_sample * channel; + input_ = input[channel]; + + while(samples--) { + sample = linear_dither(source_bps, target_bps, *input_++, &dither[channel], MIN, MAX); + + switch(target_bps) { + case 8: + data[0] = sample ^ 0x80; + break; + case 24: + data[2] = (FLAC__byte)(sample >> 16); + /* fall through */ + case 16: + data[1] = (FLAC__byte)(sample >> 8); + data[0] = (FLAC__byte)sample; + } + + data += incr; + } + } + } + else { + for(channel = 0; channel < channels; channel++) { + samples = wide_samples; + data = start + bytes_per_sample * channel; + input_ = input[channel]; + + while(samples--) { + sample = *input_++; + + switch(target_bps) { + case 8: + data[0] = sample ^ 0x80; + break; + case 24: + data[2] = (FLAC__byte)(sample >> 16); + /* fall through */ + case 16: + data[1] = (FLAC__byte)(sample >> 8); + data[0] = (FLAC__byte)sample; + } + + data += incr; + } + } + } + + return wide_samples * channels * (target_bps/8); +} diff --git a/flac/src/plugin_common/dither.h b/flac/src/plugin_common/dither.h new file mode 100644 index 0000000..98cf4c3 --- /dev/null +++ b/flac/src/plugin_common/dither.h @@ -0,0 +1,29 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__PLUGIN_COMMON__DITHER_H +#define FLAC__PLUGIN_COMMON__DITHER_H + +#include /* for size_t */ +#include "defs.h" /* buy FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS for the caller */ +#include "FLAC/ordinals.h" + +size_t FLAC__plugin_common__pack_pcm_signed_big_endian(FLAC__byte *data, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, unsigned source_bps, unsigned target_bps); +size_t FLAC__plugin_common__pack_pcm_signed_little_endian(FLAC__byte *data, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, unsigned source_bps, unsigned target_bps); + +#endif diff --git a/flac/src/plugin_common/plugin_common_static.dsp b/flac/src/plugin_common/plugin_common_static.dsp new file mode 100644 index 0000000..b05f4e4 --- /dev/null +++ b/flac/src/plugin_common/plugin_common_static.dsp @@ -0,0 +1,128 @@ +# Microsoft Developer Studio Project File - Name="plugin_common_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=plugin_common_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "plugin_common_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "plugin_common_static.mak" CFG="plugin_common_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "plugin_common_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "plugin_common_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "plugin_common" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "plugin_common_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /WX /GX /Ox /Og /Oi /Os /Op /I ".\include" /I "..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "plugin_common_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "plugin_common_static - Win32 Release" +# Name "plugin_common_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp" +# Begin Source File + +SOURCE=.\charset.c +# End Source File +# Begin Source File + +SOURCE=.\dither.c +# End Source File +# Begin Source File + +SOURCE=.\replaygain.c +# End Source File +# Begin Source File + +SOURCE=.\tags.c +# End Source File +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\all.h +# End Source File +# Begin Source File + +SOURCE=.\charset.h +# End Source File +# Begin Source File + +SOURCE=.\dither.h +# End Source File +# Begin Source File + +SOURCE=.\replaygain.h +# End Source File +# Begin Source File + +SOURCE=.\tags.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/plugin_common/plugin_common_static.vcproj b/flac/src/plugin_common/plugin_common_static.vcproj new file mode 100644 index 0000000..fec6ecd --- /dev/null +++ b/flac/src/plugin_common/plugin_common_static.vcproj @@ -0,0 +1,346 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/plugin_common/replaygain.c b/flac/src/plugin_common/replaygain.c new file mode 100644 index 0000000..bc14a46 --- /dev/null +++ b/flac/src/plugin_common/replaygain.c @@ -0,0 +1,64 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * Copyright (C) 2003 Philip Jgenstedt + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "replaygain.h" +#include "FLAC/ordinals.h" +#include "FLAC/metadata.h" +#include "share/grabbag.h" + +FLAC__bool FLAC_plugin__replaygain_get_from_file(const char *filename, + double *reference, FLAC__bool *reference_set, + double *track_gain, FLAC__bool *track_gain_set, + double *album_gain, FLAC__bool *album_gain_set, + double *track_peak, FLAC__bool *track_peak_set, + double *album_peak, FLAC__bool *album_peak_set) +{ + FLAC__Metadata_SimpleIterator *iterator = FLAC__metadata_simple_iterator_new(); + FLAC__bool ret = false; + + *track_gain_set = *album_gain_set = *track_peak_set = *album_peak_set = false; + + if(0 != iterator) { + if(FLAC__metadata_simple_iterator_init(iterator, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) { + FLAC__bool got_vorbis_comments = false; + ret = true; + do { + if(FLAC__metadata_simple_iterator_get_block_type(iterator) == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + FLAC__StreamMetadata *block = FLAC__metadata_simple_iterator_get_block(iterator); + if(0 != block) { + if(grabbag__replaygain_load_from_vorbiscomment(block, /*album_mode=*/false, /*strict=*/true, reference, track_gain, track_peak)) { + *reference_set = *track_gain_set = *track_peak_set = true; + } + if(grabbag__replaygain_load_from_vorbiscomment(block, /*album_mode=*/true, /*strict=*/true, reference, album_gain, album_peak)) { + *reference_set = *album_gain_set = *album_peak_set = true; + } + FLAC__metadata_object_delete(block); + got_vorbis_comments = true; + } + } + } while (!got_vorbis_comments && FLAC__metadata_simple_iterator_next(iterator)); + } + FLAC__metadata_simple_iterator_delete(iterator); + } + return ret; +} diff --git a/flac/src/plugin_common/replaygain.h b/flac/src/plugin_common/replaygain.h new file mode 100644 index 0000000..14556d1 --- /dev/null +++ b/flac/src/plugin_common/replaygain.h @@ -0,0 +1,32 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * Copyright (C) 2003 Philip Jgenstedt + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__PLUGIN_COMMON__REPLAYGAIN_H +#define FLAC__PLUGIN_COMMON__REPLAYGAIN_H + +#include "FLAC/ordinals.h" + +FLAC__bool FLAC_plugin__replaygain_get_from_file(const char *filename, + double *reference, FLAC__bool *reference_set, + double *track_gain, FLAC__bool *track_gain_set, + double *album_gain, FLAC__bool *album_gain_set, + double *track_peak, FLAC__bool *track_peak_set, + double *album_peak, FLAC__bool *album_peak_set); + +#endif diff --git a/flac/src/plugin_common/tags.c b/flac/src/plugin_common/tags.c new file mode 100644 index 0000000..5878734 --- /dev/null +++ b/flac/src/plugin_common/tags.c @@ -0,0 +1,358 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +#include "tags.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "share/alloc.h" + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + + +static FLaC__INLINE size_t local__wide_strlen(const FLAC__uint16 *s) +{ + size_t n = 0; + while(*s++) + n++; + return n; +} + +/* + * also disallows non-shortest-form encodings, c.f. + * http://www.unicode.org/versions/corrigendum1.html + * and a more clear explanation at the end of this section: + * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + */ +static FLaC__INLINE size_t local__utf8len(const FLAC__byte *utf8) +{ + FLAC__ASSERT(0 != utf8); + if ((utf8[0] & 0x80) == 0) { + return 1; + } + else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) { + if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */ + return 0; + return 2; + } + else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) { + if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */ + return 0; + /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */ + if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */ + return 0; + if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */ + return 0; + return 3; + } + else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) { + if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */ + return 0; + return 4; + } + else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) { + if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */ + return 0; + return 5; + } + else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) { + if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */ + return 0; + return 6; + } + else { + return 0; + } +} + + +static FLaC__INLINE size_t local__utf8_to_ucs2(const FLAC__byte *utf8, FLAC__uint16 *ucs2) +{ + const size_t len = local__utf8len(utf8); + + FLAC__ASSERT(0 != ucs2); + + if (len == 1) + *ucs2 = *utf8; + else if (len == 2) + *ucs2 = (*utf8 & 0x3F)<<6 | (*(utf8+1) & 0x3F); + else if (len == 3) + *ucs2 = (*utf8 & 0x1F)<<12 | (*(utf8+1) & 0x3F)<<6 | (*(utf8+2) & 0x3F); + else + *ucs2 = '?'; + + return len; +} + +static FLAC__uint16 *local__convert_utf8_to_ucs2(const char *src, unsigned length) +{ + FLAC__uint16 *out; + size_t chars = 0; + + FLAC__ASSERT(0 != src); + + /* calculate length */ + { + const unsigned char *s, *end; + for (s=(const unsigned char *)src, end=s+length; s> 6); + utf8[1] = 0x80 | (ucs2 & 0x3f); + return 2; + } + else { + utf8[0] = 0xe0 | (ucs2 >> 12); + utf8[1] = 0x80 | ((ucs2 >> 6) & 0x3f); + utf8[2] = 0x80 | (ucs2 & 0x3f); + return 3; + } +} + +static char *local__convert_ucs2_to_utf8(const FLAC__uint16 *src, unsigned length) +{ + char *out; + size_t len = 0, n; + + FLAC__ASSERT(0 != src); + + /* calculate length */ + { + unsigned i; + for (i = 0; i < length; i++) { + n = local__ucs2len(src[i]); + if(len + n < len) /* overflow check */ + return 0; + len += n; + } + } + + /* allocate */ + out = (char*)safe_malloc_mul_2op_(len, /*times*/sizeof(char)); + if (0 == out) + return 0; + + /* convert */ + { + unsigned char *u = (unsigned char *)out; + for ( ; *src; src++) + u += local__ucs2_to_utf8(*src, u); + local__ucs2_to_utf8(*src, u); + } + + return out; +} + + +FLAC__bool FLAC_plugin__tags_get(const char *filename, FLAC__StreamMetadata **tags) +{ + if(!FLAC__metadata_get_tags(filename, tags)) + if(0 == (*tags = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT))) + return false; + return true; +} + +FLAC__bool FLAC_plugin__tags_set(const char *filename, const FLAC__StreamMetadata *tags) +{ + FLAC__Metadata_Chain *chain; + FLAC__Metadata_Iterator *iterator; + FLAC__StreamMetadata *block; + FLAC__bool got_vorbis_comments = false; + FLAC__bool ok; + + if(0 == (chain = FLAC__metadata_chain_new())) + return false; + + if(!FLAC__metadata_chain_read(chain, filename)) { + FLAC__metadata_chain_delete(chain); + return false; + } + + if(0 == (iterator = FLAC__metadata_iterator_new())) { + FLAC__metadata_chain_delete(chain); + return false; + } + + FLAC__metadata_iterator_init(iterator, chain); + + do { + if(FLAC__metadata_iterator_get_block_type(iterator) == FLAC__METADATA_TYPE_VORBIS_COMMENT) + got_vorbis_comments = true; + } while(!got_vorbis_comments && FLAC__metadata_iterator_next(iterator)); + + if(0 == (block = FLAC__metadata_object_clone(tags))) { + FLAC__metadata_chain_delete(chain); + FLAC__metadata_iterator_delete(iterator); + return false; + } + + if(got_vorbis_comments) + ok = FLAC__metadata_iterator_set_block(iterator, block); + else + ok = FLAC__metadata_iterator_insert_block_after(iterator, block); + + FLAC__metadata_iterator_delete(iterator); + + if(ok) { + FLAC__metadata_chain_sort_padding(chain); + ok = FLAC__metadata_chain_write(chain, /*use_padding=*/true, /*preserve_file_stats=*/true); + } + + FLAC__metadata_chain_delete(chain); + + return ok; +} + +void FLAC_plugin__tags_destroy(FLAC__StreamMetadata **tags) +{ + FLAC__metadata_object_delete(*tags); + *tags = 0; +} + +const char *FLAC_plugin__tags_get_tag_utf8(const FLAC__StreamMetadata *tags, const char *name) +{ + const int i = FLAC__metadata_object_vorbiscomment_find_entry_from(tags, /*offset=*/0, name); + return (i < 0? 0 : strchr((const char *)tags->data.vorbis_comment.comments[i].entry, '=')+1); +} + +FLAC__uint16 *FLAC_plugin__tags_get_tag_ucs2(const FLAC__StreamMetadata *tags, const char *name) +{ + const char *utf8 = FLAC_plugin__tags_get_tag_utf8(tags, name); + if(0 == utf8) + return 0; + return local__convert_utf8_to_ucs2(utf8, strlen(utf8)+1); /* +1 for terminating null */ +} + +int FLAC_plugin__tags_delete_tag(FLAC__StreamMetadata *tags, const char *name) +{ + return FLAC__metadata_object_vorbiscomment_remove_entries_matching(tags, name); +} + +int FLAC_plugin__tags_delete_all(FLAC__StreamMetadata *tags) +{ + int n = (int)tags->data.vorbis_comment.num_comments; + if(n > 0) { + if(!FLAC__metadata_object_vorbiscomment_resize_comments(tags, 0)) + n = -1; + } + return n; +} + +FLAC__bool FLAC_plugin__tags_add_tag_utf8(FLAC__StreamMetadata *tags, const char *name, const char *value, const char *separator) +{ + int i; + + FLAC__ASSERT(0 != tags); + FLAC__ASSERT(0 != name); + FLAC__ASSERT(0 != value); + + if(separator && (i = FLAC__metadata_object_vorbiscomment_find_entry_from(tags, /*offset=*/0, name)) >= 0) { + FLAC__StreamMetadata_VorbisComment_Entry *entry = tags->data.vorbis_comment.comments+i; + const size_t value_len = strlen(value); + const size_t separator_len = strlen(separator); + FLAC__byte *new_entry; + if(0 == (new_entry = (FLAC__byte*)safe_realloc_add_4op_(entry->entry, entry->length, /*+*/value_len, /*+*/separator_len, /*+*/1))) + return false; + memcpy(new_entry+entry->length, separator, separator_len); + entry->length += separator_len; + memcpy(new_entry+entry->length, value, value_len); + entry->length += value_len; + new_entry[entry->length] = '\0'; + entry->entry = new_entry; + } + else { + FLAC__StreamMetadata_VorbisComment_Entry entry; + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, name, value)) + return false; + FLAC__metadata_object_vorbiscomment_append_comment(tags, entry, /*copy=*/false); + } + return true; +} + +FLAC__bool FLAC_plugin__tags_set_tag_ucs2(FLAC__StreamMetadata *tags, const char *name, const FLAC__uint16 *value, FLAC__bool replace_all) +{ + FLAC__StreamMetadata_VorbisComment_Entry entry; + + FLAC__ASSERT(0 != tags); + FLAC__ASSERT(0 != name); + FLAC__ASSERT(0 != value); + + { + char *utf8 = local__convert_ucs2_to_utf8(value, local__wide_strlen(value)+1); /* +1 for the terminating null */ + if(0 == utf8) + return false; + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, name, utf8)) { + free(utf8); + return false; + } + free(utf8); + } + if(!FLAC__metadata_object_vorbiscomment_replace_comment(tags, entry, replace_all, /*copy=*/false)) + return false; + return true; +} diff --git a/flac/src/plugin_common/tags.h b/flac/src/plugin_common/tags.h new file mode 100644 index 0000000..b1b586f --- /dev/null +++ b/flac/src/plugin_common/tags.h @@ -0,0 +1,74 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FLAC__PLUGIN_COMMON__TAGS_H +#define FLAC__PLUGIN_COMMON__TAGS_H + +#include "FLAC/format.h" + +FLAC__bool FLAC_plugin__tags_get(const char *filename, FLAC__StreamMetadata **tags); +FLAC__bool FLAC_plugin__tags_set(const char *filename, const FLAC__StreamMetadata *tags); + +/* + * Deletes the tags object and sets '*tags' to NULL. + */ +void FLAC_plugin__tags_destroy(FLAC__StreamMetadata **tags); + +/* + * Gets the value (in UTF-8) of the first tag with the given name (NULL if no + * such tag exists). + */ +const char *FLAC_plugin__tags_get_tag_utf8(const FLAC__StreamMetadata *tags, const char *name); + +/* + * Gets the value (in UCS-2) of the first tag with the given name (NULL if no + * such tag exists). + * + * NOTE: the returned string is malloc()ed and must be free()d by the caller. + */ +FLAC__uint16 *FLAC_plugin__tags_get_tag_ucs2(const FLAC__StreamMetadata *tags, const char *name); + +/* + * Removes all tags with the given 'name'. Returns the number of tags removed, + * or -1 on memory allocation error. + */ +int FLAC_plugin__tags_delete_tag(FLAC__StreamMetadata *tags, const char *name); + +/* + * Removes all tags. Returns the number of tags removed, or -1 on memory + * allocation error. + */ +int FLAC_plugin__tags_delete_all(FLAC__StreamMetadata *tags); + +/* + * Adds a "name=value" tag to the tags. 'value' must be in UTF-8. If + * 'separator' is non-NULL and 'tags' already contains a tag for 'name', the + * first such tag's value is appended with separator, then value. + */ +FLAC__bool FLAC_plugin__tags_add_tag_utf8(FLAC__StreamMetadata *tags, const char *name, const char *value, const char *separator); + +/* + * Adds a "name=value" tag to the tags. 'value' must be in UCS-2. If 'tags' + * already contains a tag or tags for 'name', then they will be replaced + * according to 'replace_all': if 'replace_all' is false, only the first such + * tag will be replaced; if true, all matching tags will be replaced by the one + * new tag. + */ +FLAC__bool FLAC_plugin__tags_set_tag_ucs2(FLAC__StreamMetadata *tags, const char *name, const FLAC__uint16 *value, FLAC__bool replace_all); + +#endif diff --git a/flac/src/plugin_winamp2/Makefile.am b/flac/src/plugin_winamp2/Makefile.am new file mode 100644 index 0000000..541161f --- /dev/null +++ b/flac/src/plugin_winamp2/Makefile.am @@ -0,0 +1,33 @@ +# in_flac - Winamp2 FLAC input plugin +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +SUBDIRS = include + +EXTRA_DIST = \ + configure.h \ + configure.c \ + in_flac.c \ + in_flac.dsp \ + in_flac.vcproj \ + infobox.c \ + infobox.h \ + playback.c \ + playback.h \ + resource.h \ + resource.rc \ + tagz.cpp \ + tagz.h diff --git a/flac/src/plugin_winamp2/configure.c b/flac/src/plugin_winamp2/configure.c new file mode 100644 index 0000000..8ffc7aa --- /dev/null +++ b/flac/src/plugin_winamp2/configure.c @@ -0,0 +1,428 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include "configure.h" +#include "tagz.h" +#include "resource.h" +#include "share/alloc.h" + + +static char buffer[256]; +static char ini_name[MAX_PATH]; + +/* + * Read/write config + */ + +#define RI(x, def) (x = GetPrivateProfileInt("FLAC", #x, def, ini_name)) +#define WI(x) WritePrivateProfileString("FLAC", #x, itoa(x, buffer, 10), ini_name) +#define RS(x, n, def) GetPrivateProfileString("FLAC", #x, def, x, n, ini_name) +#define WS(x) WritePrivateProfileString("FLAC", #x, x, ini_name) + +static const char default_format[] = "[%artist% - ]$if2(%title%,%filename%)"; +static const char default_sep[] = ", "; + +static wchar_t *convert_ansi_to_wide_(const char *src) +{ + int len; + wchar_t *dest; + + FLAC__ASSERT(0 != src); + + len = strlen(src) + 1; + /* copy */ + dest = safe_malloc_mul_2op_(len, /*times*/sizeof(wchar_t)); + if (dest) mbstowcs(dest, src, len); + return dest; +} + +void InitConfig() +{ + char *p; + + GetModuleFileName(NULL, ini_name, sizeof(ini_name)); + p = strrchr(ini_name, '.'); + if (!p) p = ini_name + strlen(ini_name); + strcpy(p, ".ini"); + + flac_cfg.title.tag_format_w = NULL; +} + +void ReadConfig() +{ + RS(flac_cfg.title.tag_format, sizeof(flac_cfg.title.tag_format), default_format); + if (flac_cfg.title.tag_format_w) + free(flac_cfg.title.tag_format_w); + flac_cfg.title.tag_format_w = convert_ansi_to_wide_(flac_cfg.title.tag_format); + /* @@@ FIXME: trailing spaces */ + RS(flac_cfg.title.sep, sizeof(flac_cfg.title.sep), default_sep); + RI(flac_cfg.tag.reserve_space, 1); + + RI(flac_cfg.display.show_bps, 1); + RI(flac_cfg.output.misc.stop_err, 0); + RI(flac_cfg.output.replaygain.enable, 1); + RI(flac_cfg.output.replaygain.album_mode, 0); + RI(flac_cfg.output.replaygain.hard_limit, 0); + RI(flac_cfg.output.replaygain.preamp, 0); + RI(flac_cfg.output.resolution.normal.dither_24_to_16, 0); + RI(flac_cfg.output.resolution.replaygain.dither, 0); + RI(flac_cfg.output.resolution.replaygain.noise_shaping, 1); + RI(flac_cfg.output.resolution.replaygain.bps_out, 16); +} + +void WriteConfig() +{ + WS(flac_cfg.title.tag_format); + WI(flac_cfg.tag.reserve_space); + WS(flac_cfg.title.sep); + + WI(flac_cfg.display.show_bps); + WI(flac_cfg.output.misc.stop_err); + WI(flac_cfg.output.replaygain.enable); + WI(flac_cfg.output.replaygain.album_mode); + WI(flac_cfg.output.replaygain.hard_limit); + WI(flac_cfg.output.replaygain.preamp); + WI(flac_cfg.output.resolution.normal.dither_24_to_16); + WI(flac_cfg.output.resolution.replaygain.dither); + WI(flac_cfg.output.resolution.replaygain.noise_shaping); + WI(flac_cfg.output.resolution.replaygain.bps_out); +} + +/* + * Dialog + */ + +#define PREAMP_RANGE 24 + +#define Check(x,y) CheckDlgButton(hwnd, x, y ? BST_CHECKED : BST_UNCHECKED) +#define GetCheck(x) (IsDlgButtonChecked(hwnd, x)==BST_CHECKED) +#define GetSel(x) SendDlgItemMessage(hwnd, x, CB_GETCURSEL, 0, 0) +#define GetPos(x) SendDlgItemMessage(hwnd, x, TBM_GETPOS, 0, 0) +#define Enable(x,y) EnableWindow(GetDlgItem(hwnd, x), y) + +static INT_PTR CALLBACK GeneralProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + /* init */ + case WM_INITDIALOG: + SendDlgItemMessage(hwnd, IDC_TITLE, EM_LIMITTEXT, 255, 0); + SendDlgItemMessage(hwnd, IDC_SEP, EM_LIMITTEXT, 15, 0); + + SetDlgItemText(hwnd, IDC_TITLE, flac_cfg.title.tag_format); + SetDlgItemText(hwnd, IDC_SEP, flac_cfg.title.sep); + Check(IDC_ID3V1, 0); +/*! Check(IDC_RESERVE, flac_cfg.tag.reserve_space); */ + Check(IDC_BPS, flac_cfg.display.show_bps); + Check(IDC_ERRORS, flac_cfg.output.misc.stop_err); + return TRUE; + /* commands */ + case WM_COMMAND: + switch (LOWORD(wParam)) + { + /* ok */ + case IDOK: + GetDlgItemText(hwnd, IDC_TITLE, flac_cfg.title.tag_format, sizeof(flac_cfg.title.tag_format)); + if (flac_cfg.title.tag_format_w) + free(flac_cfg.title.tag_format_w); + GetDlgItemText(hwnd, IDC_SEP, flac_cfg.title.sep, sizeof(flac_cfg.title.sep)); + flac_cfg.title.tag_format_w = convert_ansi_to_wide_(flac_cfg.title.tag_format); + +/*! flac_cfg.tag.reserve_space = GetCheck(IDC_RESERVE); */ + flac_cfg.display.show_bps = GetCheck(IDC_BPS); + flac_cfg.output.misc.stop_err = GetCheck(IDC_ERRORS); + break; + /* reset */ + case IDC_RESET: + Check(IDC_ID3V1, 0); + Check(IDC_RESERVE, 1); + Check(IDC_BPS, 1); + Check(IDC_ERRORS, 0); + /* fall throught */ + /* default */ + case IDC_TAGZ_DEFAULT: + SetDlgItemText(hwnd, IDC_TITLE, default_format); + break; + /* help */ + case IDC_TAGZ_HELP: + MessageBox(hwnd, tagz_manual, "Help", 0); + break; + } + break; + } + + return 0; +} + + +static void UpdatePreamp(HWND hwnd, HWND hamp) +{ + int pos = SendMessage(hamp, TBM_GETPOS, 0, 0) - PREAMP_RANGE; + sprintf(buffer, "%d dB", pos); + SetDlgItemText(hwnd, IDC_PA, buffer); +} + +static void UpdateRG(HWND hwnd) +{ + int on = GetCheck(IDC_ENABLE); + Enable(IDC_ALBUM, on); + Enable(IDC_LIMITER, on); + Enable(IDC_PREAMP, on); + Enable(IDC_PA, on); +} + +static void UpdateDither(HWND hwnd) +{ + int on = GetCheck(IDC_DITHERRG); + Enable(IDC_SHAPE, on); +} + +static INT_PTR CALLBACK OutputProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + /* init */ + case WM_INITDIALOG: + Check(IDC_ENABLE, flac_cfg.output.replaygain.enable); + Check(IDC_ALBUM, flac_cfg.output.replaygain.album_mode); + Check(IDC_LIMITER, flac_cfg.output.replaygain.hard_limit); + Check(IDC_DITHER, flac_cfg.output.resolution.normal.dither_24_to_16); + Check(IDC_DITHERRG, flac_cfg.output.resolution.replaygain.dither); + /* prepare preamp slider */ + { + HWND hamp = GetDlgItem(hwnd, IDC_PREAMP); + SendMessage(hamp, TBM_SETRANGE, 1, MAKELONG(0, PREAMP_RANGE*2)); + SendMessage(hamp, TBM_SETPOS, 1, flac_cfg.output.replaygain.preamp+PREAMP_RANGE); + UpdatePreamp(hwnd, hamp); + } + /* fill comboboxes */ + { + HWND hlist = GetDlgItem(hwnd, IDC_TO); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"16 bps"); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"24 bps"); + SendMessage(hlist, CB_SETCURSEL, flac_cfg.output.resolution.replaygain.bps_out/8 - 2, 0); + + hlist = GetDlgItem(hwnd, IDC_SHAPE); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"None"); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"Low"); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"Medium"); + SendMessage(hlist, CB_ADDSTRING, 0, (LPARAM)"High"); + SendMessage(hlist, CB_SETCURSEL, flac_cfg.output.resolution.replaygain.noise_shaping, 0); + } + UpdateRG(hwnd); + UpdateDither(hwnd); + return TRUE; + /* commands */ + case WM_COMMAND: + switch (LOWORD(wParam)) + { + /* ok */ + case IDOK: + flac_cfg.output.replaygain.enable = GetCheck(IDC_ENABLE); + flac_cfg.output.replaygain.album_mode = GetCheck(IDC_ALBUM); + flac_cfg.output.replaygain.hard_limit = GetCheck(IDC_LIMITER); + flac_cfg.output.replaygain.preamp = GetPos(IDC_PREAMP) - PREAMP_RANGE; + flac_cfg.output.resolution.normal.dither_24_to_16 = GetCheck(IDC_DITHER); + flac_cfg.output.resolution.replaygain.dither = GetCheck(IDC_DITHERRG); + flac_cfg.output.resolution.replaygain.noise_shaping = GetSel(IDC_SHAPE); + flac_cfg.output.resolution.replaygain.bps_out = (GetSel(IDC_TO)+2)*8; + break; + /* reset */ + case IDC_RESET: + Check(IDC_ENABLE, 1); + Check(IDC_ALBUM, 0); + Check(IDC_LIMITER, 0); + Check(IDC_DITHER, 0); + Check(IDC_DITHERRG, 0); + + SendDlgItemMessage(hwnd, IDC_PREAMP, TBM_SETPOS, 1, PREAMP_RANGE); + SendDlgItemMessage(hwnd, IDC_TO, CB_SETCURSEL, 0, 0); + SendDlgItemMessage(hwnd, IDC_SHAPE, CB_SETCURSEL, 1, 0); + + UpdatePreamp(hwnd, GetDlgItem(hwnd, IDC_PREAMP)); + UpdateRG(hwnd); + UpdateDither(hwnd); + break; + /* active check-boxes */ + case IDC_ENABLE: + UpdateRG(hwnd); + break; + case IDC_DITHERRG: + UpdateDither(hwnd); + break; + } + break; + /* scroller */ + case WM_HSCROLL: + if (GetDlgCtrlID((HWND)lParam)==IDC_PREAMP) + UpdatePreamp(hwnd, (HWND)lParam); + return 0; + } + + return 0; +} + +#define NUM_PAGES 2 + +typedef struct +{ + HWND htab; + HWND hdlg; + RECT r; + HWND all[NUM_PAGES]; +} LOCALDATA; + +static void ScreenToClientRect(HWND hwnd, RECT *rect) +{ + POINT pt = { rect->left, rect->top }; + ScreenToClient(hwnd, &pt); + rect->left = pt.x; + rect->top = pt.y; + + pt.x = rect->right; + pt.y = rect->bottom; + ScreenToClient(hwnd, &pt); + rect->right = pt.x; + rect->bottom = pt.y; +} + +static void SendCommand(HWND hwnd, int command) +{ + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + SendMessage(data->hdlg, WM_COMMAND, command, 0); +} + +static void BroadcastCommand(HWND hwnd, int command) +{ + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + int i; + + for (i=0; iall[i], WM_COMMAND, command, 0); +} + +static void OnSelChange(HWND hwnd) +{ + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + int index = TabCtrl_GetCurSel(data->htab); + if (index < 0) return; + /* hide previous */ + if (data->hdlg) + ShowWindow(data->hdlg, SW_HIDE); + /* display */ + data->hdlg = data->all[index]; + SetWindowPos(data->hdlg, HWND_TOP, data->r.left, data->r.top, data->r.right-data->r.left, data->r.bottom-data->r.top, SWP_SHOWWINDOW); + SetFocus(hwnd); +} + +static INT_PTR CALLBACK DialogProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static activePage = 0; + + switch (msg) + { + /* init */ + case WM_INITDIALOG: + { + LOCALDATA *data = LocalAlloc(LPTR, sizeof(LOCALDATA)); + HINSTANCE inst = (HINSTANCE)lParam; + TCITEM item; + + /* init */ + SetWindowLong(hwnd, GWL_USERDATA, (LONG)data); + data->htab = GetDlgItem(hwnd, IDC_TABS); + data->hdlg = NULL; + /* add pages */ + item.mask = TCIF_TEXT; + data->all[0] = CreateDialog(inst, MAKEINTRESOURCE(IDD_CONFIG_GENERAL), hwnd, GeneralProc); + item.pszText = "General"; + TabCtrl_InsertItem(data->htab, 0, &item); + + data->all[1] = CreateDialog(inst, MAKEINTRESOURCE(IDD_CONFIG_OUTPUT), hwnd, OutputProc); + item.pszText = "Output"; + TabCtrl_InsertItem(data->htab, 1, &item); + /* get rect (after adding pages) */ + GetWindowRect(data->htab, &data->r); + ScreenToClientRect(hwnd, &data->r); + TabCtrl_AdjustRect(data->htab, 0, &data->r); + /* simulate item change */ + TabCtrl_SetCurSel(data->htab, activePage); + OnSelChange(hwnd); + } + return TRUE; + /* destory */ + case WM_DESTROY: + { + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + int i; + + activePage = TabCtrl_GetCurSel(data->htab); + + for (i=0; iall[i]); + + LocalFree(data); + } + break; + /* commands */ + case WM_COMMAND: + switch (LOWORD(wParam)) + { + /* ok/cancel */ + case IDOK: + BroadcastCommand(hwnd, IDOK); + /* fall through */ + case IDCANCEL: + EndDialog(hwnd, LOWORD(wParam)); + return TRUE; + case IDC_RESET: + SendCommand(hwnd, IDC_RESET); + break; + } + break; + /* notification */ + case WM_NOTIFY: + if (LOWORD(wParam) == IDC_TABS) + { + NMHDR *hdr = (NMHDR*)lParam; + + switch (hdr->code) + { + case TCN_SELCHANGE: + OnSelChange(hwnd); + break; + } + } + break; + } + + return 0; +} + + +int DoConfig(HINSTANCE inst, HWND parent) +{ + return DialogBoxParam(inst, MAKEINTRESOURCE(IDD_CONFIG), parent, DialogProc, (LONG)inst) == IDOK; +} diff --git a/flac/src/plugin_winamp2/configure.h b/flac/src/plugin_winamp2/configure.h new file mode 100644 index 0000000..79d391e --- /dev/null +++ b/flac/src/plugin_winamp2/configure.h @@ -0,0 +1,49 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "playback.h" + +/* + * common stuff + */ + +typedef struct { + struct { + char tag_format[256]; + char sep[16]; + WCHAR *tag_format_w; + } title; + struct { + BOOL reserve_space; + } tag; + struct { + FLAC__bool show_bps; + } display; + output_config_t output; +} flac_config_t; + +extern flac_config_t flac_cfg; + +/* + * prototypes + */ + +void InitConfig(); +void ReadConfig(); +void WriteConfig(); +int DoConfig(HINSTANCE inst, HWND parent); diff --git a/flac/src/plugin_winamp2/in_flac.c b/flac/src/plugin_winamp2/in_flac.c new file mode 100644 index 0000000..f8833c1 --- /dev/null +++ b/flac/src/plugin_winamp2/in_flac.c @@ -0,0 +1,443 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for INT_MAX */ +#include + +#include "share/alloc.h" +#include "winamp2/in2.h" +#include "configure.h" +#include "infobox.h" +#include "tagz.h" + +#define PLUGIN_VERSION "1.2.1" + +static In_Module mod_; /* the input module (declared near the bottom of this file) */ +static char lastfn_[MAX_PATH]; /* currently playing file (used for getting info on the current file) */ +flac_config_t flac_cfg; + +static stream_data_struct stream_data_; +static int paused; +static FLAC__StreamDecoder *decoder_; +static char sample_buffer_[SAMPLES_PER_WRITE * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS * (24/8) * 2]; +/* (24/8) for max bytes per sample, and 2 for DSPs */ + +static HANDLE thread_handle = NULL; /* the handle to the decode thread */ +static DWORD WINAPI DecodeThread(void *b); /* the decode thread procedure */ + +/* + * init/quit + */ + +static void init() +{ + decoder_ = FLAC__stream_decoder_new(); + strcpy(lastfn_, ""); + + InitConfig(); + ReadConfig(); + InitInfobox(); +} + +static void quit() +{ + WriteConfig(); + DeinitInfobox(); + FLAC_plugin__decoder_delete(decoder_); + decoder_ = 0; +} + +/* + * open/close + */ + +static int isourfile(char *fn) { return 0; } + +static int play(char *fn) +{ + LONGLONG filesize; + DWORD thread_id; + int maxlatency; + /* checks */ + if (decoder_ == 0) return 1; + if (!(filesize = FileSize(fn))) return -1; + /* init decoder */ + if (!FLAC_plugin__decoder_init(decoder_, fn, filesize, &stream_data_, &flac_cfg.output)) + return 1; + strcpy(lastfn_, fn); + /* open output */ + maxlatency = mod_.outMod->Open(stream_data_.sample_rate, stream_data_.channels, stream_data_.output_bits_per_sample, -1, -1); + if (maxlatency < 0) + { + FLAC_plugin__decoder_finish(decoder_); + return 1; + } + /* set defaults */ + mod_.outMod->SetVolume(-666); + mod_.outMod->SetPan(0); + /* initialize vis stuff */ + mod_.SAVSAInit(maxlatency, stream_data_.sample_rate); + mod_.VSASetInfo(stream_data_.sample_rate, stream_data_.channels); + /* set info */ + mod_.SetInfo(stream_data_.average_bps, stream_data_.sample_rate/1000, stream_data_.channels, 1); + /* start playing thread */ + paused = 0; + thread_handle = CreateThread(NULL, 0, DecodeThread, NULL, 0, &thread_id); + if (!thread_handle) return 1; + + return 0; +} + +static void stop() +{ + if (thread_handle) + { + stream_data_.is_playing = false; + if (WaitForSingleObject(thread_handle, 2000) == WAIT_TIMEOUT) + { + FLAC_plugin__show_error("Error while stopping decoding thread."); + TerminateThread(thread_handle, 0); + } + CloseHandle(thread_handle); + thread_handle = NULL; + } + + FLAC_plugin__decoder_finish(decoder_); + mod_.outMod->Close(); + mod_.SAVSADeInit(); +} + +/* + * play control + */ + +static void pause() +{ + paused = 1; + mod_.outMod->Pause(1); +} + +static void unpause() +{ + paused = 0; + mod_.outMod->Pause(0); +} + +static int ispaused() +{ + return paused; +} + +static int getlength() +{ + return stream_data_.length_in_msec; +} + +static int getoutputtime() +{ + return mod_.outMod->GetOutputTime(); +} + +static void setoutputtime(int time_in_ms) +{ + stream_data_.seek_to = time_in_ms; +} + +static void setvolume(int volume) +{ + mod_.outMod->SetVolume(volume); +} + +static void setpan(int pan) +{ + mod_.outMod->SetPan(pan); +} + +static void eq_set(int on, char data[10], int preamp) {} + +/* + * playing loop + */ + +static void do_vis(char *data, int nch, int resolution, int position, unsigned samples) +{ + static char vis_buffer[SAMPLES_PER_WRITE * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS]; + char *ptr; + int size, count; + + /* + * Winamp visuals may have problems accepting sample sizes larger than + * 16 bits, so we reduce the sample size here if necessary. + */ + + switch(resolution) { + case 32: + case 24: + size = resolution / 8; + count = samples * nch; + data += size - 1; + + ptr = vis_buffer; + while(count--) { + *ptr++ = data[0] ^ 0x80; + data += size; + } + + data = vis_buffer; + resolution = 8; + /* fall through */ + case 16: + case 8: + mod_.SAAddPCMData(data, nch, resolution, position); + mod_.VSAAddPCMData(data, nch, resolution, position); + } +} + +static DWORD WINAPI DecodeThread(void *unused) +{ + const unsigned channels = stream_data_.channels; + const unsigned bits_per_sample = stream_data_.bits_per_sample; + const unsigned target_bps = stream_data_.output_bits_per_sample; + const unsigned sample_rate = stream_data_.sample_rate; + const unsigned fact = channels * (target_bps/8); + + while (stream_data_.is_playing) + { + /* seek needed */ + if (stream_data_.seek_to != -1) + { + const int pos = FLAC_plugin__seek(decoder_, &stream_data_); + if (pos != -1) mod_.outMod->Flush(pos); + } + /* stream ended */ + else if (stream_data_.eof) + { + if (!mod_.outMod->IsPlaying()) + { + PostMessage(mod_.hMainWindow, WM_WA_MPEG_EOF, 0, 0); + return 0; + } + Sleep(10); + } + /* decode */ + else + { + /* decode samples */ + int bytes = FLAC_plugin__decode(decoder_, &stream_data_, sample_buffer_); + const int n = bytes / fact; + /* visualization */ + do_vis(sample_buffer_, channels, target_bps, mod_.outMod->GetWrittenTime(), n); + /* dsp */ + if (mod_.dsp_isactive()) + bytes = mod_.dsp_dosamples((short*)sample_buffer_, n, target_bps, channels, sample_rate) * fact; + /* output */ + while (mod_.outMod->CanWrite()Write(sample_buffer_, bytes); + /* show bitrate */ + if (flac_cfg.display.show_bps) + { + const int rate = FLAC_plugin__get_rate(mod_.outMod->GetWrittenTime(), mod_.outMod->GetOutputTime(), &stream_data_); + if (rate) mod_.SetInfo(rate/1000, stream_data_.sample_rate/1000, stream_data_.channels, 1); + } + } + } + + return 0; +} + +/* + * title formatting + */ + +static T_CHAR *get_tag(const T_CHAR *tag, void *param) +{ + FLAC__StreamMetadata *tags = (FLAC__StreamMetadata*)param; + char *tagname, *p; + T_CHAR *val; + + if (!tag) + return 0; + /* Vorbis comment names must be ASCII, so convert 'tag' first */ + tagname = safe_malloc_add_2op_(wcslen(tag), /*+*/1); + for(p=tagname;*tag;) { + if(*tag > 0x7d) { + free(tagname); + return 0; + } + else + *p++ = (char)(*tag++); + } + *p++ = '\0'; + /* now get it */ + val = FLAC_plugin__tags_get_tag_ucs2(tags, tagname); + free(tagname); + /* some "user friendly cheavats" */ + if (!val) + { + if (!wcsicmp(tag, L"ARTIST")) + { + val = FLAC_plugin__tags_get_tag_ucs2(tags, "PERFORMER"); + if (!val) val = FLAC_plugin__tags_get_tag_ucs2(tags, "COMPOSER"); + } + else if (!wcsicmp(tag, L"YEAR") || !wcsicmp(tag, L"DATE")) + { + val = FLAC_plugin__tags_get_tag_ucs2(tags, "YEAR_RECORDED"); + if (!val) val = FLAC_plugin__tags_get_tag_ucs2(tags, "YEAR_PERFORMED"); + } + } + + return val; +} + +static void free_tag(T_CHAR *tag, void *param) +{ + (void)param; + free(tag); +} + +static void format_title(const char *filename, WCHAR *title, unsigned max_size) +{ + FLAC__StreamMetadata *tags; + + ReadTags(filename, &tags, /*forDisplay=*/true); + + tagz_format(flac_cfg.title.tag_format_w, get_tag, free_tag, tags, title, max_size); + + FLAC_plugin__tags_destroy(&tags); +} + +static void getfileinfo(char *filename, char *title, int *length_in_msec) +{ + FLAC__StreamMetadata streaminfo; + + if (!filename || !*filename) { + filename = lastfn_; + if (length_in_msec) { + *length_in_msec = stream_data_.length_in_msec; + length_in_msec = 0; /* force skip in following code */ + } + } + + if (!FLAC__metadata_get_streaminfo(filename, &streaminfo)) { + if (length_in_msec) + *length_in_msec = -1; + return; + } + + if (title) { + static WCHAR buffer[400]; + format_title(filename, buffer, 400); + WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, buffer, -1, title, 400, NULL, NULL); + } + + if (length_in_msec) { + /* with VC++ you have to spoon feed it the casting from uint64->int64->double */ + FLAC__uint64 l = (FLAC__uint64)((double)(FLAC__int64)streaminfo.data.stream_info.total_samples / (double)streaminfo.data.stream_info.sample_rate * 1000.0 + 0.5); + if (l > INT_MAX) + l = INT_MAX; + *length_in_msec = (int)l; + } +} + +/* + * interface + */ + +void FLAC_plugin__show_error(const char *message,...) +{ + char foo[512]; + va_list args; + va_start(args, message); + vsprintf(foo, message, args); + va_end(args); + MessageBox(mod_.hMainWindow, foo, "FLAC Plug-in Error", MB_ICONSTOP); +} + +static void about(HWND hwndParent) +{ + MessageBox(hwndParent, "Winamp2 FLAC Plugin v"PLUGIN_VERSION"\nby Josh Coalson and X-Fixer\n\nuses libFLAC "VERSION"\nSee http://flac.sourceforge.net/\n", "About FLAC Plugin", MB_ICONINFORMATION); +} + +static void config(HWND hwndParent) +{ + if (DoConfig(mod_.hDllInstance, hwndParent)) + WriteConfig(); +} + +static int infobox(char *fn, HWND hwnd) +{ + DoInfoBox(mod_.hDllInstance, hwnd, fn); + return 0; +} + +/* + * exported stuff + */ + +static In_Module mod_ = +{ + IN_VER, + "FLAC Decoder v" PLUGIN_VERSION, + 0, /* hMainWindow */ + 0, /* hDllInstance */ + "FLAC\0FLAC Audio File (*.FLAC)\0", + 1, /* is_seekable */ + 1, /* uses output */ + config, + about, + init, + quit, + getfileinfo, + infobox, + isourfile, + play, + pause, + unpause, + ispaused, + stop, + + getlength, + getoutputtime, + setoutputtime, + + setvolume, + setpan, + + 0,0,0,0,0,0,0,0,0, /* vis stuff */ + 0,0, /* dsp */ + eq_set, + NULL, /* setinfo */ + 0 /* out_mod */ +}; + +__declspec(dllexport) In_Module *winampGetInModule2() +{ + return &mod_; +} + +BOOL WINAPI _DllMainCRTStartup(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) +{ + return TRUE; +} diff --git a/flac/src/plugin_winamp2/in_flac.dsp b/flac/src/plugin_winamp2/in_flac.dsp new file mode 100644 index 0000000..6732287 --- /dev/null +++ b/flac/src/plugin_winamp2/in_flac.dsp @@ -0,0 +1,154 @@ +# Microsoft Developer Studio Project File - Name="in_flac" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=in_flac - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "in_flac.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "in_flac.mak" CFG="in_flac - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "in_flac - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "in_flac - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "$/Studio/in_flac" +# PROP Scc_LocalPath "." +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "in_flac - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "in_flac_EXPORTS" /YX /FD /c +# ADD CPP /nologo /MD /W3 /WX /GX /Ox /Og /Oi /Os /Op /Gf /Gy /I "include" /I ".." /I "..\..\include" /D "NDEBUG" /D VERSION=\"1.2.1\" /D "in_flac_EXPORTS" /D "FLAC__NO_DLL" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TAGZ_UNICODE" /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 plugin_common_static.lib grabbag_static.lib libFLAC_static.lib replaygain_analysis_static.lib replaygain_synthesis_static.lib kernel32.lib user32.lib /nologo /dll /machine:I386 /out:"../../obj/release/bin/in_flac.dll" /libpath:"../../obj/release/lib" ..\..\obj\release\lib\ogg_static.lib /opt:nowin98 +# SUBTRACT LINK32 /pdb:none + +!ELSEIF "$(CFG)" == "in_flac - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "in_flac_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "include" /I ".." /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "REAL_STDIO" /D VERSION=\"1.2.1\" /D "in_flac_EXPORTS" /D "FLAC__NO_DLL" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TAGZ_UNICODE" /YX /FD /GZ /c +# SUBTRACT CPP /WX +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 plugin_common_static.lib grabbag_static.lib libFLAC_static.lib replaygain_analysis_static.lib replaygain_synthesis_static.lib kernel32.lib user32.lib /nologo /dll /debug /machine:I386 /out:"../../obj/debug/bin/in_flac.dll" /pdbtype:sept /libpath:"../../obj/debug/lib" ..\..\obj\release\lib\ogg_static.lib +# SUBTRACT LINK32 /pdb:none + +!ENDIF + +# Begin Target + +# Name "in_flac - Win32 Release" +# Name "in_flac - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Group "Winamp2 SDK" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\winamp2\in2.h +# End Source File +# Begin Source File + +SOURCE=.\include\winamp2\out.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\configure.c +# End Source File +# Begin Source File + +SOURCE=.\configure.h +# End Source File +# Begin Source File + +SOURCE=.\in_flac.c +# End Source File +# Begin Source File + +SOURCE=.\infobox.c +# End Source File +# Begin Source File + +SOURCE=.\infobox.h +# End Source File +# Begin Source File + +SOURCE=.\playback.c +# End Source File +# Begin Source File + +SOURCE=.\playback.h +# End Source File +# Begin Source File + +SOURCE=.\resource.h +# End Source File +# Begin Source File + +SOURCE=.\resource.rc +# End Source File +# Begin Source File + +SOURCE=.\tagz.cpp +# End Source File +# Begin Source File + +SOURCE=.\tagz.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/plugin_winamp2/in_flac.vcproj b/flac/src/plugin_winamp2/in_flac.vcproj new file mode 100644 index 0000000..86a23e3 --- /dev/null +++ b/flac/src/plugin_winamp2/in_flac.vcproj @@ -0,0 +1,429 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/plugin_winamp2/include/Makefile.am b/flac/src/plugin_winamp2/include/Makefile.am new file mode 100644 index 0000000..65b0921 --- /dev/null +++ b/flac/src/plugin_winamp2/include/Makefile.am @@ -0,0 +1,18 @@ +# in_flac - Winamp2 FLAC input plugin +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +SUBDIRS = winamp2 diff --git a/flac/src/plugin_winamp2/include/winamp2/Makefile.am b/flac/src/plugin_winamp2/include/winamp2/Makefile.am new file mode 100644 index 0000000..cc8b024 --- /dev/null +++ b/flac/src/plugin_winamp2/include/winamp2/Makefile.am @@ -0,0 +1,20 @@ +# in_flac - Winamp2 FLAC input plugin +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +EXTRA_DIST = \ + in2.h \ + out.h diff --git a/flac/src/plugin_winamp2/include/winamp2/in2.h b/flac/src/plugin_winamp2/include/winamp2/in2.h new file mode 100644 index 0000000..09322e1 --- /dev/null +++ b/flac/src/plugin_winamp2/include/winamp2/in2.h @@ -0,0 +1,107 @@ +/* Standard Winamp input-plugin header + */ + +#include "out.h" + +/* post this to the main window at end of file (after playback as stopped) */ +#define WM_WA_MPEG_EOF (WM_USER + 2) + +// note: exported symbol is now winampGetInModule2. + +#define IN_VER 0x100 + +typedef struct +{ + int version; // module type (IN_VER) + char *description; // description of module, with version string + + HWND hMainWindow; // winamp's main window (filled in by winamp) + HINSTANCE hDllInstance; // DLL instance handle (Also filled in by winamp) + + char *FileExtensions; // "mp3\0Layer 3 MPEG\0mp2\0Layer 2 MPEG\0mpg\0Layer 1 MPEG\0" + // May be altered from Config, so the user can select what they want + + int is_seekable; // is this stream seekable? + int UsesOutputPlug; // does this plug-in use the output plug-ins? (musn't ever change, ever :) + + void (*Config)(HWND hwndParent); // configuration dialog + void (*About)(HWND hwndParent); // about dialog + + void (*Init)(); // called at program init + void (*Quit)(); // called at program quit + + void (*GetFileInfo)(char *file, char *title, int *length_in_ms); // if file == NULL, current playing is used + int (*InfoBox)(char *file, HWND hwndParent); + + int (*IsOurFile)(char *fn); // called before extension checks, to allow detection of mms://, etc + // playback stuff + int (*Play)(char *fn); // return zero on success, -1 on file-not-found, some other value on other (stopping winamp) error + void (*Pause)(); // pause stream + void (*UnPause)(); // unpause stream + int (*IsPaused)(); // ispaused? return 1 if paused, 0 if not + void (*Stop)(); // stop (unload) stream + + // time stuff + int (*GetLength)(); // get length in ms + int (*GetOutputTime)(); // returns current output time in ms. (usually returns outMod->GetOutputTime() + void (*SetOutputTime)(int time_in_ms); // seeks to point in stream (in ms). Usually you signal yoru thread to seek, which seeks and calls outMod->Flush().. + + // volume stuff + void (*SetVolume)(int volume); // from 0 to 255.. usually just call outMod->SetVolume + void (*SetPan)(int pan); // from -127 to 127.. usually just call outMod->SetPan + + // in-window builtin vis stuff + + void (*SAVSAInit)(int maxlatency_in_ms, int srate); // call once in Play(). maxlatency_in_ms should be the value returned from outMod->Open() + // call after opening audio device with max latency in ms and samplerate + void (*SAVSADeInit)(); // call in Stop() + + + // simple vis supplying mode + void (*SAAddPCMData)(void *PCMData, int nch, int bps, int timestamp); + // sets the spec data directly from PCM data + // quick and easy way to get vis working :) + // needs at least 576 samples :) + + // advanced vis supplying mode, only use if you're cool. Use SAAddPCMData for most stuff. + int (*SAGetMode)(); // gets csa (the current type (4=ws,2=osc,1=spec)) + // use when calling SAAdd() + void (*SAAdd)(void *data, int timestamp, int csa); // sets the spec data, filled in by winamp + + + // vis stuff (plug-in) + // simple vis supplying mode + void (*VSAAddPCMData)(void *PCMData, int nch, int bps, int timestamp); // sets the vis data directly from PCM data + // quick and easy way to get vis working :) + // needs at least 576 samples :) + + // advanced vis supplying mode, only use if you're cool. Use VSAAddPCMData for most stuff. + int (*VSAGetMode)(int *specNch, int *waveNch); // use to figure out what to give to VSAAdd + void (*VSAAdd)(void *data, int timestamp); // filled in by winamp, called by plug-in + + + // call this in Play() to tell the vis plug-ins the current output params. + void (*VSASetInfo)(int nch, int srate); + + + // dsp plug-in processing: + // (filled in by winamp, called by input plug) + + // returns 1 if active (which means that the number of samples returned by dsp_dosamples + // could be greater than went in.. Use it to estimate if you'll have enough room in the + // output buffer + int (*dsp_isactive)(); + + // returns number of samples to output. This can be as much as twice numsamples. + // be sure to allocate enough buffer for samples, then. + int (*dsp_dosamples)(short int *samples, int numsamples, int bps, int nch, int srate); + + + // eq stuff + void (*EQSet)(int on, char data[10], int preamp); // 0-64 each, 31 is +0, 0 is +12, 63 is -12. Do nothing to ignore. + + // info setting (filled in by winamp) + void (*SetInfo)(int bitrate, int srate, int stereo, int synched); // if -1, changes ignored? :) + + Out_Module *outMod; // filled in by winamp, optionally used :) +} In_Module; diff --git a/flac/src/plugin_winamp2/include/winamp2/out.h b/flac/src/plugin_winamp2/include/winamp2/out.h new file mode 100644 index 0000000..ec08ff4 --- /dev/null +++ b/flac/src/plugin_winamp2/include/winamp2/out.h @@ -0,0 +1,55 @@ +/* Standard Winamp output-plugin header + */ + +#define OUT_VER 0x10 + +typedef struct +{ + int version; // module version (OUT_VER) + char *description; // description of module, with version string + int id; // module id. each input module gets its own. non-nullsoft modules should + // be >= 65536. + + HWND hMainWindow; // winamp's main window (filled in by winamp) + HINSTANCE hDllInstance; // DLL instance handle (filled in by winamp) + + void (*Config)(HWND hwndParent); // configuration dialog + void (*About)(HWND hwndParent); // about dialog + + void (*Init)(); // called when loaded + void (*Quit)(); // called when unloaded + + int (*Open)(int samplerate, int numchannels, int bitspersamp, int bufferlenms, int prebufferms); + // returns >=0 on success, <0 on failure + // NOTENOTENOTE: bufferlenms and prebufferms are ignored in most if not all output plug-ins. + // ... so don't expect the max latency returned to be what you asked for. + // returns max latency in ms (0 for diskwriters, etc) + // bufferlenms and prebufferms must be in ms. 0 to use defaults. + // prebufferms must be <= bufferlenms + + void (*Close)(); // close the ol' output device. + + int (*Write)(char *buf, int len); + // 0 on success. Len == bytes to write (<= 8192 always). buf is straight audio data. + // 1 returns not able to write (yet). Non-blocking, always. + + int (*CanWrite)(); // returns number of bytes possible to write at a given time. + // Never will decrease unless you call Write (or Close, heh) + + int (*IsPlaying)(); // non0 if output is still going or if data in buffers waiting to be + // written (i.e. closing while IsPlaying() returns 1 would truncate the song + + int (*Pause)(int pause); // returns previous pause state + + void (*SetVolume)(int volume); // volume is 0-255 + void (*SetPan)(int pan); // pan is -128 to 128 + + void (*Flush)(int t); // flushes buffers and restarts output at time t (in ms) + // (used for seeking) + + int (*GetOutputTime)(); // returns played time in MS + int (*GetWrittenTime)(); // returns time written in MS (used for synching up vis stuff) + +} Out_Module; + + diff --git a/flac/src/plugin_winamp2/infobox.c b/flac/src/plugin_winamp2/infobox.c new file mode 100644 index 0000000..18a3422 --- /dev/null +++ b/flac/src/plugin_winamp2/infobox.c @@ -0,0 +1,459 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "FLAC/all.h" +#include "share/alloc.h" +#include "plugin_common/all.h" +#include "infobox.h" +#include "configure.h" +#include "resource.h" + + +typedef struct +{ + char filename[MAX_PATH]; + FLAC__StreamMetadata *tags; +} LOCALDATA; + +static char buffer[8192]; +static char *genres = NULL; +static DWORD genresSize = 0, genresCount = 0; +static BOOL genresChanged = FALSE, isNT; + +static const char infoTitle[] = "FLAC File Info"; + +/* + * Genres + */ + +/* TODO: write genres in utf-8 ? */ + +static __inline int GetGenresFileName(char *buffer, int size) +{ + char *c; + + if (!GetModuleFileName(NULL, buffer, size)) + return 0; + c = strrchr(buffer, '\\'); + if (!c) return 0; + strcpy(c+1, "genres.txt"); + + return 1; +} + +static void LoadGenres() +{ + HANDLE hFile; + DWORD spam; + char *c; + + FLAC__ASSERT(0 != genres); + + if (!GetGenresFileName(buffer, sizeof(buffer))) return; + /* load file */ + hFile = CreateFile(buffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) return; + genresSize = GetFileSize(hFile, 0); + if (genresSize && (genres = (char*)safe_malloc_add_2op_(genresSize, /*+*/2))) + { + if (!ReadFile(hFile, genres, genresSize, &spam, NULL) || spam!=genresSize) + { + free(genres); + genres = NULL; + } + else + { + genres[genresSize] = 0; + genres[genresSize+1] = 0; + /* replace newlines */ + genresChanged = FALSE; + genresCount = 1; + + for (c=genres; *c; c++) + { + if (*c == 10) + { + *c = 0; + if (*(c+1)) + genresCount++; + else genresSize--; + } + } + } + } + + CloseHandle(hFile); +} + +static void SaveGenres(HWND hlist) +{ + HANDLE hFile; + DWORD spam; + int i, count, len; + + if (!GetGenresFileName(buffer, sizeof(buffer))) return; + /* write file */ + hFile = CreateFile(buffer, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) return; + + count = SendMessage(hlist, CB_GETCOUNT, 0, 0); + for (i=0; itags, y); \ + WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, ucs2, -1, buffer, sizeof(buffer), NULL, NULL); \ + if(ucs2) free(ucs2); \ + SetDlgItemText(hwnd, x, buffer) + +#define GetText(x,y) GetDlgItemText(hwnd, x, buffer, sizeof(buffer)); \ + if (*buffer) { ucs2 = AnsiToWide(buffer); FLAC_plugin__tags_set_tag_ucs2(data->tags, y, ucs2, /*replace_all=*/false); free(ucs2); } \ + else FLAC_plugin__tags_delete_tag(data->tags, y) + +#define SetTextW(x,y) ucs2 = FLAC_plugin__tags_get_tag_ucs2(data->tags, y); \ + SetDlgItemTextW(hwnd, x, ucs2); \ + free(ucs2) + +#define GetTextW(x,y) GetDlgItemTextW(hwnd, x, (WCHAR*)buffer, sizeof(buffer)/2); \ + if (*(WCHAR*)buffer) FLAC_plugin__tags_set_tag_ucs2(data->tags, y, (WCHAR*)buffer, /*replace_all=*/false); \ + else FLAC_plugin__tags_delete_tag(data->tags, y) + + +static BOOL InitInfoboxInfo(HWND hwnd, const char *file) +{ + LOCALDATA *data = LocalAlloc(LPTR, sizeof(LOCALDATA)); + wchar_t *ucs2; + FLAC__StreamMetadata streaminfo; + DWORD length, bps, ratio, rg; + LONGLONG filesize; + + SetWindowLong(hwnd, GWL_USERDATA, (LONG)data); + /* file name */ + strncpy(data->filename, file, sizeof(data->filename)); + SetDlgItemText(hwnd, IDC_NAME, file); + /* stream data and vorbis comment */ + filesize = FileSize(file); + if (!filesize) return FALSE; + if (!FLAC__metadata_get_streaminfo(file, &streaminfo)) + return FALSE; + ReadTags(file, &data->tags, false); + + length = (DWORD)(streaminfo.data.stream_info.total_samples / streaminfo.data.stream_info.sample_rate); + bps = (DWORD)(filesize / (125*streaminfo.data.stream_info.total_samples/streaminfo.data.stream_info.sample_rate)); + ratio = bps*1000000 / (streaminfo.data.stream_info.sample_rate*streaminfo.data.stream_info.channels*streaminfo.data.stream_info.bits_per_sample); + rg = FLAC_plugin__tags_get_tag_utf8(data->tags, "REPLAYGAIN_TRACK_GAIN") ? 1 : 0; + rg |= FLAC_plugin__tags_get_tag_utf8(data->tags, "REPLAYGAIN_ALBUM_GAIN") ? 2 : 0; + + sprintf(buffer, "Sample rate: %d Hz\nChannels: %d\nBits per sample: %d\nMin block size: %d\nMax block size: %d\n" + "File size: %I64d bytes\nTotal samples: %I64d\nLength: %d:%02d\nAvg. bitrate: %d\nCompression ratio: %d.%d%%\n" + "ReplayGain: %s\n", + streaminfo.data.stream_info.sample_rate, streaminfo.data.stream_info.channels, streaminfo.data.stream_info.bits_per_sample, + streaminfo.data.stream_info.min_blocksize, streaminfo.data.stream_info.max_blocksize, filesize, streaminfo.data.stream_info.total_samples, + length/60, length%60, bps, ratio/10, ratio%10, + rg==3 ? "track gain\nReplayGain: album gain" : rg==2 ? "album gain" : rg==1 ? "track gain" : "not present"); + + SetDlgItemText(hwnd, IDC_INFO, buffer); + /* tag */ + if (isNT) + { + SetTextW(IDC_TITLE, "TITLE"); + SetTextW(IDC_ARTIST, "ARTIST"); + SetTextW(IDC_ALBUM, "ALBUM"); + SetTextW(IDC_COMMENT, "COMMENT"); + SetTextW(IDC_YEAR, "DATE"); + SetTextW(IDC_TRACK, "TRACKNUMBER"); + SetTextW(IDC_GENRE, "GENRE"); + } + else + { + SetText(IDC_TITLE, "TITLE"); + SetText(IDC_ARTIST, "ARTIST"); + SetText(IDC_ALBUM, "ALBUM"); + SetText(IDC_COMMENT, "COMMENT"); + SetText(IDC_YEAR, "DATE"); + SetText(IDC_TRACK, "TRACKNUMBER"); + SetText(IDC_GENRE, "GENRE"); + } + + return TRUE; +} + +static void __inline SetTag(HWND hwnd, const char *filename, FLAC__StreamMetadata *tags) +{ + strcpy(buffer, infoTitle); + + if (FLAC_plugin__tags_set(filename, tags)) + strcat(buffer, " [Updated]"); + else strcat(buffer, " [Failed]"); + + SetWindowText(hwnd, buffer); +} + +static void UpdateTag(HWND hwnd) +{ + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + wchar_t *ucs2; + + /* get fields */ + if (isNT) + { + GetTextW(IDC_TITLE, "TITLE"); + GetTextW(IDC_ARTIST, "ARTIST"); + GetTextW(IDC_ALBUM, "ALBUM"); + GetTextW(IDC_COMMENT, "COMMENT"); + GetTextW(IDC_YEAR, "DATE"); + GetTextW(IDC_TRACK, "TRACKNUMBER"); + GetTextW(IDC_GENRE, "GENRE"); + + ucs2 = FLAC_plugin__tags_get_tag_ucs2(data->tags, "GENRE"); + WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, ucs2, -1, buffer, sizeof(buffer), NULL, NULL); + free(ucs2); + } + else + { + GetText(IDC_TITLE, "TITLE"); + GetText(IDC_ARTIST, "ARTIST"); + GetText(IDC_ALBUM, "ALBUM"); + GetText(IDC_COMMENT, "COMMENT"); + GetText(IDC_YEAR, "DATE"); + GetText(IDC_TRACK, "TRACKNUMBER"); + GetText(IDC_GENRE, "GENRE"); + } + + /* update genres list (buffer should contain genre) */ + if (buffer[0]) AddGenre(hwnd, buffer); + + /* write tag */ + SetTag(hwnd, data->filename, data->tags); +} + +static void RemoveTag(HWND hwnd) +{ + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + FLAC_plugin__tags_delete_all(data->tags); + + SetDlgItemText(hwnd, IDC_TITLE, ""); + SetDlgItemText(hwnd, IDC_ARTIST, ""); + SetDlgItemText(hwnd, IDC_ALBUM, ""); + SetDlgItemText(hwnd, IDC_COMMENT, ""); + SetDlgItemText(hwnd, IDC_YEAR, ""); + SetDlgItemText(hwnd, IDC_TRACK, ""); + SetDlgItemText(hwnd, IDC_GENRE, ""); + + SetTag(hwnd, data->filename, data->tags); +} + + +static INT_PTR CALLBACK InfoProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + /* init */ + case WM_INITDIALOG: + SetWindowText(hwnd, infoTitle); + InitGenres(hwnd); + /* init fields */ + if (!InitInfoboxInfo(hwnd, (const char*)lParam)) + PostMessage(hwnd, WM_CLOSE, 0, 0); + return TRUE; + /* destroy */ + case WM_DESTROY: + { + LOCALDATA *data = (LOCALDATA*)GetWindowLong(hwnd, GWL_USERDATA); + FLAC_plugin__tags_destroy(&data->tags); + LocalFree(data); + DeinitGenres(hwnd, FALSE); + } + break; + /* commands */ + case WM_COMMAND: + switch (LOWORD(wParam)) + { + /* ok/cancel */ + case IDOK: + case IDCANCEL: + EndDialog(hwnd, LOWORD(wParam)); + return TRUE; + /* save */ + case IDC_UPDATE: + UpdateTag(hwnd); + break; + /* remove */ + case IDC_REMOVE: + RemoveTag(hwnd); + break; + } + break; + } + + return 0; +} + +/* + * Helpers + */ + +ULONGLONG FileSize(const char *fileName) +{ + LARGE_INTEGER res; + HANDLE hFile = CreateFile(fileName, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + + if (hFile == INVALID_HANDLE_VALUE) return 0; + res.LowPart = GetFileSize(hFile, &res.HighPart); + CloseHandle(hFile); + return res.QuadPart; +} + +static __inline char *GetFileName(const char *fullname) +{ + const char *c = fullname + strlen(fullname) - 1; + + while (c > fullname) + { + if (*c=='\\' || *c=='/') + { + c++; + break; + } + c--; + } + + return (char*)c; +} + +void ReadTags(const char *fileName, FLAC__StreamMetadata **tags, BOOL forDisplay) +{ + if(FLAC_plugin__tags_get(fileName, tags)) { + + /* add file name */ + if (forDisplay) + { + char *c; + wchar_t *ucs2; + ucs2 = AnsiToWide(fileName); + FLAC_plugin__tags_set_tag_ucs2(*tags, "filepath", ucs2, /*replace_all=*/true); + free(ucs2); + + strcpy(buffer, GetFileName(fileName)); + if (c = strrchr(buffer, '.')) *c = 0; + ucs2 = AnsiToWide(buffer); + FLAC_plugin__tags_set_tag_ucs2(*tags, "filename", ucs2, /*replace_all=*/true); + free(ucs2); + } + } +} + +/* + * Front-end + */ + +void InitInfobox() +{ + isNT = !(GetVersion() & 0x80000000); +} + +void DeinitInfobox() +{ + DeinitGenres(NULL, true); +} + +void DoInfoBox(HINSTANCE inst, HWND hwnd, const char *filename) +{ + DialogBoxParam(inst, MAKEINTRESOURCE(IDD_INFOBOX), hwnd, InfoProc, (LONG)filename); +} diff --git a/flac/src/plugin_winamp2/infobox.h b/flac/src/plugin_winamp2/infobox.h new file mode 100644 index 0000000..f7a3099 --- /dev/null +++ b/flac/src/plugin_winamp2/infobox.h @@ -0,0 +1,28 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * prototypes + */ + +ULONGLONG FileSize(const char *fileName); +void ReadTags(const char *fileName, FLAC__StreamMetadata **tags, BOOL forDisplay); + +void InitInfobox(); +void DeinitInfobox(); +void DoInfoBox(HINSTANCE inst, HWND hwnd, const char *filename); diff --git a/flac/src/plugin_winamp2/playback.c b/flac/src/plugin_winamp2/playback.c new file mode 100644 index 0000000..c8e2432 --- /dev/null +++ b/flac/src/plugin_winamp2/playback.c @@ -0,0 +1,307 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for INT_MAX */ +#include +#include /* for memmove() */ +#include "playback.h" +#include "share/grabbag.h" + + +static FLAC__int32 reservoir_[FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS][FLAC__MAX_BLOCK_SIZE * 2/*for overflow*/]; +static FLAC__int32 *reservoir__[FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS] = { reservoir_[0], reservoir_[1] }; /*@@@ kind of a hard-coded hack */ +static unsigned wide_samples_in_reservoir_; +static output_config_t cfg; /* local copy */ + +static unsigned bh_index_last_w, bh_index_last_o, written_time_last; +static FLAC__int64 decode_position, decode_position_last; + +/* + * callbacks + */ + +static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct*)client_data; + const unsigned channels = stream_data->channels, wide_samples = frame->header.blocksize; + unsigned channel; + + (void)decoder; + + if (stream_data->abort_flag) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + for (channel = 0; channel < channels; channel++) + memcpy(&reservoir_[channel][wide_samples_in_reservoir_], buffer[channel], sizeof(buffer[0][0]) * wide_samples); + + wide_samples_in_reservoir_ += wide_samples; + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct*)client_data; + (void)decoder; + + if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) + { + stream_data->total_samples = metadata->data.stream_info.total_samples; + stream_data->bits_per_sample = metadata->data.stream_info.bits_per_sample; + stream_data->channels = metadata->data.stream_info.channels; + stream_data->sample_rate = metadata->data.stream_info.sample_rate; + + if (stream_data->bits_per_sample!=8 && stream_data->bits_per_sample!=16 && stream_data->bits_per_sample!=24) + { + FLAC_plugin__show_error("This plugin can only handle 8/16/24-bit samples."); + stream_data->abort_flag = true; + return; + } + + { + /* with VC++ you have to spoon feed it the casting from uint64->int64->double */ + FLAC__uint64 l = (FLAC__uint64)((double)(FLAC__int64)stream_data->total_samples / (double)stream_data->sample_rate * 1000.0 + 0.5); + if (l > INT_MAX) + l = INT_MAX; + stream_data->length_in_msec = (int)l; + } + } + else if (metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + { + double reference, gain, peak; + if (grabbag__replaygain_load_from_vorbiscomment(metadata, cfg.replaygain.album_mode, /*strict=*/false, &reference, &gain, &peak)) + { + stream_data->has_replaygain = true; + stream_data->replay_scale = grabbag__replaygain_compute_scale_factor(peak, gain, (double)cfg.replaygain.preamp, !cfg.replaygain.hard_limit); + } + } +} + +static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct*)client_data; + (void)decoder; + + if (cfg.misc.stop_err || status!=FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC) + stream_data->abort_flag = true; +} + +/* + * init/delete + */ + +FLAC__bool FLAC_plugin__decoder_init(FLAC__StreamDecoder *decoder, const char *filename, FLAC__int64 filesize, stream_data_struct *stream_data, output_config_t *config) +{ + FLAC__StreamDecoderInitStatus init_status; + + FLAC__ASSERT(decoder); + FLAC_plugin__decoder_finish(decoder); + /* init decoder */ + FLAC__stream_decoder_set_md5_checking(decoder, false); + FLAC__stream_decoder_set_metadata_ignore_all(decoder); + FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO); + FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT); + + if ((init_status = FLAC__stream_decoder_init_file(decoder, filename, write_callback, metadata_callback, error_callback, /*client_data=*/stream_data)) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + { + FLAC_plugin__show_error("Error while initializing decoder (%s [%s]).", FLAC__StreamDecoderInitStatusString[init_status], FLAC__stream_decoder_get_resolved_state_string(decoder)); + return false; + } + /* process */ + cfg = *config; + wide_samples_in_reservoir_ = 0; + stream_data->is_playing = false; + stream_data->abort_flag = false; + stream_data->has_replaygain = false; + + if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) + { + FLAC_plugin__show_error("Error while processing metadata (%s).", FLAC__stream_decoder_get_resolved_state_string(decoder)); + return false; + } + /* check results */ + if (stream_data->abort_flag) return false; /* metadata callback already popped up the error dialog */ + /* init replaygain */ + stream_data->output_bits_per_sample = stream_data->has_replaygain && cfg.replaygain.enable ? + cfg.resolution.replaygain.bps_out : + cfg.resolution.normal.dither_24_to_16 ? min(stream_data->bits_per_sample, 16) : stream_data->bits_per_sample; + + if (stream_data->has_replaygain && cfg.replaygain.enable && cfg.resolution.replaygain.dither) + FLAC__replaygain_synthesis__init_dither_context(&stream_data->dither_context, stream_data->bits_per_sample, cfg.resolution.replaygain.noise_shaping); + /* more inits */ + stream_data->eof = false; + stream_data->seek_to = -1; + stream_data->is_playing = true; + stream_data->average_bps = (unsigned)(filesize / (125.*(double)(FLAC__int64)stream_data->total_samples/(double)stream_data->sample_rate)); + + bh_index_last_w = 0; + bh_index_last_o = BITRATE_HIST_SIZE; + decode_position = 0; + decode_position_last = 0; + written_time_last = 0; + + return true; +} + +void FLAC_plugin__decoder_finish(FLAC__StreamDecoder *decoder) +{ + if (decoder && FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED) + (void)FLAC__stream_decoder_finish(decoder); +} + +void FLAC_plugin__decoder_delete(FLAC__StreamDecoder *decoder) +{ + if (decoder) + { + FLAC_plugin__decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + } +} + +/* + * decode + */ + +int FLAC_plugin__seek(FLAC__StreamDecoder *decoder, stream_data_struct *stream_data) +{ + int pos; + FLAC__uint64 target_sample = stream_data->total_samples * stream_data->seek_to / stream_data->length_in_msec; + + if (stream_data->total_samples > 0 && target_sample >= stream_data->total_samples && target_sample > 0) + target_sample = stream_data->total_samples - 1; + + /* even if the seek fails we have to reset these so that we don't repeat the seek */ + stream_data->seek_to = -1; + stream_data->eof = false; + wide_samples_in_reservoir_ = 0; + pos = (int)(target_sample*1000 / stream_data->sample_rate); + + if (!FLAC__stream_decoder_seek_absolute(decoder, target_sample)) { + if(FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_SEEK_ERROR) + FLAC__stream_decoder_flush(decoder); + pos = -1; + } + + bh_index_last_o = bh_index_last_w = (pos/BITRATE_HIST_SEGMENT_MSEC) % BITRATE_HIST_SIZE; + if (!FLAC__stream_decoder_get_decode_position(decoder, &decode_position)) + decode_position = 0; + + return pos; +} + +unsigned FLAC_plugin__decode(FLAC__StreamDecoder *decoder, stream_data_struct *stream_data, char *sample_buffer) +{ + /* fill reservoir */ + while (wide_samples_in_reservoir_ < SAMPLES_PER_WRITE) + { + if (FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_END_OF_STREAM) + { + stream_data->eof = true; + break; + } + else if (!FLAC__stream_decoder_process_single(decoder)) + { + FLAC_plugin__show_error("Error while processing frame (%s).", FLAC__stream_decoder_get_resolved_state_string(decoder)); + stream_data->eof = true; + break; + } + if (!FLAC__stream_decoder_get_decode_position(decoder, &decode_position)) + decode_position = 0; + } + /* output samples */ + if (wide_samples_in_reservoir_ > 0) + { + const unsigned n = min(wide_samples_in_reservoir_, SAMPLES_PER_WRITE); + const unsigned channels = stream_data->channels; + unsigned i; + int bytes; + + if (cfg.replaygain.enable && stream_data->has_replaygain) + { + bytes = FLAC__replaygain_synthesis__apply_gain( + sample_buffer, + true, /* little_endian_data_out */ + stream_data->output_bits_per_sample == 8, /* unsigned_data_out */ + reservoir__, + n, + channels, + stream_data->bits_per_sample, + stream_data->output_bits_per_sample, + stream_data->replay_scale, + cfg.replaygain.hard_limit, + cfg.resolution.replaygain.dither, + &stream_data->dither_context + ); + } + else + { + bytes = FLAC__plugin_common__pack_pcm_signed_little_endian( + sample_buffer, + reservoir__, + n, + channels, + stream_data->bits_per_sample, + stream_data->output_bits_per_sample + ); + } + + wide_samples_in_reservoir_ -= n; + for (i = 0; i < channels; i++) + memmove(&reservoir_[i][0], &reservoir_[i][n], sizeof(reservoir_[0][0]) * wide_samples_in_reservoir_); + + return bytes; + } + else + { + stream_data->eof = true; + return 0; + } +} + +int FLAC_plugin__get_rate(unsigned written_time, unsigned output_time, stream_data_struct *stream_data) +{ + static int bitrate_history_[BITRATE_HIST_SIZE]; + unsigned bh_index_w = (written_time/BITRATE_HIST_SEGMENT_MSEC) % BITRATE_HIST_SIZE; + unsigned bh_index_o = (output_time/BITRATE_HIST_SEGMENT_MSEC) % BITRATE_HIST_SIZE; + + /* written bitrate */ + if (bh_index_w != bh_index_last_w) + { + bitrate_history_[(bh_index_w + BITRATE_HIST_SIZE-1)%BITRATE_HIST_SIZE] = + decode_position>decode_position_last && written_time > written_time_last ? + (unsigned)(8000*(decode_position - decode_position_last)/(written_time - written_time_last)) : + stream_data->average_bps; + + bh_index_last_w = bh_index_w; + written_time_last = written_time; + decode_position_last = decode_position; + } + + /* output bitrate */ + if (bh_index_o!=bh_index_last_o && bh_index_o!=bh_index_last_w) + { + bh_index_last_o = bh_index_o; + return bitrate_history_[bh_index_o]; + } + + return 0; +} diff --git a/flac/src/plugin_winamp2/playback.h b/flac/src/plugin_winamp2/playback.h new file mode 100644 index 0000000..d604132 --- /dev/null +++ b/flac/src/plugin_winamp2/playback.h @@ -0,0 +1,92 @@ +/* in_flac - Winamp2 FLAC input plugin + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "FLAC/all.h" +#include "share/replaygain_synthesis.h" +#include "plugin_common/all.h" + +/* + * constants + */ + +#define SAMPLES_PER_WRITE 576 + +#define BITRATE_HIST_SEGMENT_MSEC 500 +#define BITRATE_HIST_SIZE 64 + +/* + * common structures + */ + +typedef struct { + volatile FLAC__bool is_playing; + volatile FLAC__bool abort_flag; + volatile FLAC__bool eof; + volatile int seek_to; + FLAC__uint64 total_samples; + unsigned bits_per_sample; + unsigned output_bits_per_sample; + unsigned channels; + unsigned sample_rate; + int length_in_msec; /* int (instead of FLAC__uint64) only because that's what Winamp uses; seeking won't work right if this maxes out */ + unsigned average_bps; + FLAC__bool has_replaygain; + double replay_scale; + DitherContext dither_context; +} stream_data_struct; + + +typedef struct { + struct { + FLAC__bool enable; + FLAC__bool album_mode; + int preamp; + FLAC__bool hard_limit; + } replaygain; + struct { + struct { + FLAC__bool dither_24_to_16; + } normal; + struct { + FLAC__bool dither; + int noise_shaping; /* value must be one of NoiseShaping enum, see plugin_common/replaygain_synthesis.h */ + int bps_out; + } replaygain; + } resolution; + struct { + FLAC__bool stop_err; + } misc; +} output_config_t; + +/* + * protopytes + */ + +FLAC__bool FLAC_plugin__decoder_init(FLAC__StreamDecoder *decoder, const char *filename, FLAC__int64 filesize, stream_data_struct *stream_data, output_config_t *config); +void FLAC_plugin__decoder_finish(FLAC__StreamDecoder *decoder); +void FLAC_plugin__decoder_delete(FLAC__StreamDecoder *decoder); + +int FLAC_plugin__seek(FLAC__StreamDecoder *decoder, stream_data_struct *stream_data); +unsigned FLAC_plugin__decode(FLAC__StreamDecoder *decoder, stream_data_struct *stream_data, char *sample_buffer); +int FLAC_plugin__get_rate(unsigned written_time, unsigned output_time, stream_data_struct *stream_data); + +/* + * these should be defined in plug-in + */ + +extern void FLAC_plugin__show_error(const char *message,...); diff --git a/flac/src/plugin_winamp2/resource.h b/flac/src/plugin_winamp2/resource.h new file mode 100644 index 0000000..31300c1 --- /dev/null +++ b/flac/src/plugin_winamp2/resource.h @@ -0,0 +1,47 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by resource.rc +// +#define IDC_RESET 3 +#define IDD_CONFIG 101 +#define IDD_CONFIG_GENERAL 103 +#define IDD_CONFIG_OUTPUT 104 +#define IDD_INFOBOX 105 +#define IDC_ENABLE 1000 +#define IDC_ALBUM 1001 +#define IDC_LIMITER 1002 +#define IDC_COMMENT 1002 +#define IDC_PREAMP 1003 +#define IDC_YEAR 1003 +#define IDC_PA 1004 +#define IDC_TRACK 1004 +#define IDC_DITHER 1005 +#define IDC_DITHERRG 1006 +#define IDC_TO 1008 +#define IDC_SHAPE 1009 +#define IDC_TABS 1009 +#define IDC_TITLE 1010 +#define IDC_TAGZ_HELP 1011 +#define IDC_ARTIST 1011 +#define IDC_TAGZ_DEFAULT 1012 +#define IDC_SEP 1013 +#define IDC_NAME 1014 +#define IDC_INFO 1015 +#define IDC_GENRE 1017 +#define IDC_REMOVE 1020 +#define IDC_UPDATE 1021 +#define IDC_ID3V1 1030 +#define IDC_RESERVE 1032 +#define IDC_BPS 1036 +#define IDC_ERRORS 1037 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 106 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1037 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/flac/src/plugin_winamp2/resource.rc b/flac/src/plugin_winamp2/resource.rc new file mode 100644 index 0000000..d21c924 --- /dev/null +++ b/flac/src/plugin_winamp2/resource.rc @@ -0,0 +1,236 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Russian resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +#ifdef _WIN32 +LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +#pragma code_page(1251) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_INFOBOX DIALOG DISCARDABLE 0, 0, 292, 148 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +FONT 8, "MS Sans Serif" +BEGIN + EDITTEXT IDC_NAME,3,3,285,12,ES_AUTOHSCROLL | ES_READONLY | NOT + WS_TABSTOP + GROUPBOX " Tag ",IDC_STATIC,3,20,182,104 + RTEXT "&Title",IDC_STATIC,8,32,31,8 + EDITTEXT IDC_TITLE,43,30,137,12,ES_AUTOHSCROLL + RTEXT "&Artist",IDC_STATIC,8,47,31,8 + EDITTEXT IDC_ARTIST,43,45,137,12,ES_AUTOHSCROLL + RTEXT "Albu&m",IDC_STATIC,8,62,31,8 + EDITTEXT IDC_ALBUM,43,60,137,12,ES_AUTOHSCROLL + RTEXT "&Comment",IDC_STATIC,8,77,31,8 + EDITTEXT IDC_COMMENT,43,75,137,12,ES_AUTOHSCROLL + RTEXT "&Date",IDC_STATIC,8,92,31,8 + EDITTEXT IDC_YEAR,43,90,40,12,ES_AUTOHSCROLL + RTEXT "Track &number",IDC_STATIC,90,92,46,8 + EDITTEXT IDC_TRACK,141,90,39,12,ES_AUTOHSCROLL + RTEXT "&Genre",IDC_STATIC,8,107,31,8 + COMBOBOX IDC_GENRE,43,105,137,95,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + GROUPBOX " FLAC Info ",IDC_STATIC,191,20,97,124 + LTEXT "",IDC_INFO,195,30,90,110 + DEFPUSHBUTTON "Close",IDOK,3,130,50,14 + PUSHBUTTON "&Update",IDC_UPDATE,69,130,50,14 + PUSHBUTTON "&Remove",IDC_REMOVE,135,130,50,14 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_INFOBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 285 + TOPMARGIN, 7 + BOTTOMMARGIN, 141 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Russian resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_CONFIG DIALOG DISCARDABLE 0, 0, 237, 212 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "FLAC Configuration" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,75,195,50,14 + PUSHBUTTON "Cancel",IDCANCEL,129,195,50,14 + PUSHBUTTON "Reset",IDC_RESET,183,195,50,14 + CONTROL "Tab1",IDC_TABS,"SysTabControl32",WS_TABSTOP,3,3,230,187 +END + +IDD_CONFIG_GENERAL DIALOG DISCARDABLE 0, 0, 226, 171 +STYLE DS_CONTROL | WS_CHILD +FONT 8, "MS Sans Serif" +BEGIN + GROUPBOX " Title Formatting ",IDC_STATIC,2,2,220,58 + LTEXT "&Title",IDC_STATIC,8,17,14,8 + EDITTEXT IDC_TITLE,27,15,188,12,ES_AUTOHSCROLL + PUSHBUTTON "default",IDC_TAGZ_DEFAULT,156,28,30,10 + PUSHBUTTON "help",IDC_TAGZ_HELP,188,28,27,10 + LTEXT "Separate tag values &with",IDC_STATIC,8,43,79,8 + EDITTEXT IDC_SEP,91,41,27,12,ES_AUTOHSCROLL + CONTROL "Read ID3v&1 tags",IDC_ID3V1,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,147,43,70,10 + GROUPBOX " Tag Editor ",IDC_STATIC,2,63,220,30 + CONTROL "Reserve space for &FLAC tags",IDC_RESERVE,"Button", + BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,8,76,125,10 + GROUPBOX " Miscellaneous ",IDC_STATIC,2,96,220,72 + CONTROL "&Show instantaneous bitrate while playing",IDC_BPS,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,8,108,125,10 + CONTROL "Stop on &all errors",IDC_ERRORS,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,8,120,69,10 +END + +IDD_CONFIG_OUTPUT DIALOG DISCARDABLE 0, 0, 224, 171 +STYLE DS_CONTROL | WS_CHILD +FONT 8, "MS Sans Serif" +BEGIN + GROUPBOX " ReplayGain ",IDC_STATIC,2,2,220,57 + CONTROL "&Enable ReplayGain",IDC_ENABLE,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,8,15,77,10 + CONTROL "&Album mode",IDC_ALBUM,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,8,27,55,10 + CONTROL "6dB &hard limiter",IDC_LIMITER,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,123,27,64,10 + LTEXT "&Preamp",IDC_STATIC,8,44,25,8 + CONTROL "Slider1",IDC_PREAMP,"msctls_trackbar32",TBS_NOTICKS | + WS_TABSTOP,36,43,154,12 + RTEXT "",IDC_PA,194,44,21,8 + GROUPBOX " Resolution ",IDC_STATIC,1,62,220,95 + GROUPBOX " Without ReplayGain ",IDC_STATIC,7,71,209,30 + CONTROL "&Dither 24bps to 16bps",IDC_DITHER,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,16,84,85,10 + GROUPBOX " With ReplayGain ",IDC_STATIC,7,104,209,47 + LTEXT "&Output bit depth",IDC_STATIC,16,119,52,8 + COMBOBOX IDC_TO,71,116,39,43,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + CONTROL "E&nable dithering",IDC_DITHERRG,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,16,134,67,10 + LTEXT "Noise &shaping",IDC_STATIC,113,135,46,8 + COMBOBOX IDC_SHAPE,164,132,46,48,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Note: changes take effect after restarting playback", + IDC_STATIC,2,160,161,8 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_CONFIG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 230 + TOPMARGIN, 7 + BOTTOMMARGIN, 205 + END + + IDD_CONFIG_GENERAL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 164 + END + + IDD_CONFIG_OUTPUT, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 217 + TOPMARGIN, 7 + BOTTOMMARGIN, 164 + END +END +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/flac/src/plugin_winamp2/tagz.cpp b/flac/src/plugin_winamp2/tagz.cpp new file mode 100644 index 0000000..1a084a2 --- /dev/null +++ b/flac/src/plugin_winamp2/tagz.cpp @@ -0,0 +1,921 @@ +#include +#include +#include +#include +#include "tagz.h" + +#ifdef TAGZ_UNICODE + +#define _TX(X) L##X +#define t_strdup wcsdup +#define t_strlen wcslen +#define t_strnicmp wcsnicmp +#define t_atoi(x) wcstol(x,0,10) +#define t_stricmp wcsicmp +#define t_strstr wcsstr +#define sprintf swprintf + +#else + +#define _TX(X) X +#define t_strdup strdup +#define t_strlen strlen +#define t_strnicmp strnicmp +#define t_atoi atoi +#define t_stricmp stricmp +#define t_strstr strstr + +#endif + +#define TABSIZE(x) (sizeof(x)/sizeof(x[0])) + + +class T_String +{ +private: + T_CHAR * data; + UINT size,used; +public: + T_String() {data=0;size=0;used=0;} + void AddChar(T_CHAR c) + { + if (!data) + { + data=(T_CHAR*)malloc((size=512)*sizeof(T_CHAR)); + used=0; + } + else if (size==used) + { + size<<=1; + data=(T_CHAR*)realloc((char*)data,size*sizeof(T_CHAR)); + } + if (data) data[used++]=c; + } + void AddInt(int i) + { + T_CHAR foo[16]; + sprintf(foo,_TX("%i"),i); + AddString(foo); + } + void AddString(const T_CHAR * z) + { + while(*z) {AddChar(*z);z++;} + } + void AddString(T_String & s) + { + AddString(s.Peek()); + } + ~T_String() + { + if (data) free(data); + } + T_CHAR * GetBuf() + { + if (!data) return ::t_strdup(_TX("")); + T_CHAR * r=(T_CHAR*)realloc(data,(used+1)*sizeof(T_CHAR)); + r[used]=0; + data=0; + return r; + } + T_CHAR operator[](UINT i) + { + if (!data || i>=used) return 0; + else return data[i]; + } + UINT Len() {return data ? used : 0;} + void Reset() + { + if (data) {free(data);data=0;} + } + const T_CHAR * Peek() + { + AddChar(0); + used--; + return data; + } + T_CHAR * strdup() + { + return ::t_strdup(Peek()); + } +}; + + + + +static int separator(T_CHAR x) +{ + if (!x || x==' ') return 1; + if (x=='\'' || x=='_') return 0; +#ifdef TAGZ_UNICODE + return !iswalnum(x); +#else + return !isalnum(x); +#endif +} + +static int sepcmp(T_CHAR* src,T_CHAR* val) +{ + UINT l=t_strlen(val); + return !t_strnicmp(src,val,l) && separator(src[l]); +} + +static char roman_num[]= +{ + 'I','V','X','L','C','D','M' +}; + + +static int is_roman(T_CHAR * ptr)/* could be more smart i think */ +{ + if (ptr[0]==']' && ptr[1]=='[' && separator(ptr[2])) return 1; + while(!separator(*ptr)) + { + UINT n; + bool found=0; + for(n=0;n'9') return 0; + ptr++; + } + return 1; +} + +typedef bool (*TEXTFUNC)(UINT n_src,T_CHAR **src,UINT*,T_String &out); + +#define MAKEFUNC(X) static bool X(UINT n_src,T_CHAR ** src,UINT *found_src,T_String &out) + + +MAKEFUNC(If) +{ + if (n_src!=3) return false; + + out.AddString(src[found_src[0] ? 1 : 2]); + return true; +} + +MAKEFUNC(If2) +{ + if (n_src!=2) return false; + + out.AddString(src[found_src[0] ? 0 : 1]); + return true; +} + + +MAKEFUNC(Iflonger) +{ + if (n_src!=4) return false; + + out.AddString(src[(int)t_strlen(src[0])>t_atoi(src[1]) ? 2 : 3]); + return true; +} + +MAKEFUNC(Ifgreater) +{ + if (n_src!=4) return false; + + out.AddString(src[t_atoi(src[0])>t_atoi(src[1]) ? 2 : 3]); + return true; +} + +MAKEFUNC(Upper) +{ + if (n_src!=1) return false; + + T_CHAR * s=src[0]; + + while(*s) + out.AddChar(toupper(*(s++))); + + return true; +} + +MAKEFUNC(Lower) +{ + if (n_src!=1) return false; + + T_CHAR * s=src[0]; + + while(*s) + out.AddChar(tolower(*(s++))); + + return true; +} + +MAKEFUNC(Pad) +{ + if (n_src<2 || n_src>3) return false; + + T_CHAR *fill=_TX(" "); + if (n_src==3 && src[2][0]) + fill = src[2]; + + int num = t_atoi(src[1]); + T_CHAR *p = src[0]; + + while (*p) { out.AddChar(*(p++)); num--; } + + UINT fl = t_strlen(fill); + while (num>0) + out.AddChar(fill[(--num)%fl]); + + return true; +} + +MAKEFUNC(Cut) +{ + if (n_src!=2) return false; + + UINT num = t_atoi(src[1]); + T_CHAR *p = src[0]; + + while (*p && num>0) {out.AddChar(*(p++));num--;} + + return true; +} + +MAKEFUNC(PadCut) +{ + if (n_src<2 || n_src>3) return false; + + T_CHAR *fill = _TX(" "); + if (n_src==3 && src[2][0]) + fill = src[2]; + + int num = t_atoi(src[1]); + T_CHAR *p = src[0]; + + while(*p && num>0) {out.AddChar(*(p++));num--;} + + UINT fl=t_strlen(fill); + while (num>0) + out.AddChar(fill[(--num)%fl]); + + return true; +} + +/* abbr(string) */ +/* abbr(string,len) */ +MAKEFUNC(Abbr) +{ + if (n_src==0 || n_src>2) return false; + + + if (n_src==2 && (int)t_strlen(src[0])m) {m=l;ptr=src[n];} + } + + if (ptr) out.AddString(ptr); + return true; +} + +MAKEFUNC(Shortest) +{ + T_CHAR * ptr=0; + UINT n,m=(UINT)(-1); + + for(n=0;n3) return false; + + int n1 = t_atoi(src[1]), n2; + + if (n_src == 3) + n2 = t_atoi(src[2]); + else n2 = n1; + + if (n1 < 1) n1=1; + if (n2 >= n1) + { + n1--; + n2--; + while(n1<=n2 && src[0][n1]) + out.AddChar(src[0][n1++]); + } + + return true; +} + +MAKEFUNC(Len) +{ + if (n_src!=1) return false; + + out.AddInt(t_strlen(src[0])); + return true; +} + +MAKEFUNC(Add) +{ + UINT n; + int s=0; + + for (n=0;n m) m = t; + } + out.AddInt(m); + + return true; +} + +MAKEFUNC(Min) +{ + if (!n_src) return false; + + int m=t_atoi(src[0]); + UINT n; + + for(n=1;ns2 || (*p!=',' && *p!=')')) {Error(_TX("internal error"));return;} + T_CHAR bk=*p; + *p=0; + temp[nt]=_FMT(p1,&temp_f[nt]); + nt++; + *p=bk;; + p1=p+1; + p++; + } + *s1=0; + UINT n; + + for (n=0; nf; + ff=base->ff; + fp=base->fp; + spec=_spec; + } +public: + FMT(const T_CHAR * p_spec,TAGFUNC _f,TAGFREEFUNC _ff,void * _fp) + { + found=0; + org_spec=spec=t_strdup(p_spec); + f=_f; + ff=_ff; + fp=_fp; + } + operator T_CHAR*() + { + run(); + return str.GetBuf(); + } + ~FMT() + { + if (org_spec) free(org_spec); + } +}; + +extern "C" +{ + +UINT tagz_format(const T_CHAR * spec,TAGFUNC f,TAGFREEFUNC ff,void *fp,T_CHAR* out,UINT max) +{ + T_CHAR * zz=tagz_format_r(spec,f,ff,fp); + UINT r=0; + while(r, eg. \"%artist%\"\n" + "* $abbr(x) - inserts abbreviation of x, eg. \"$abbr(%album%)\" - will convert album name of \"Final Fantasy VI\" to \"FFVI\"\n" + "* $abbr(x,y) - inserts abbreviation of x if x is longer than y characters; otherwise inserts full value of x, eg. \"$abbr(%album%,10)\"\n" + "* $lower(x), $upper(x) - converts x to in lower/uppercase, eg. \"$upper(%title%)\"\n" + "* $num(x,y) - displays x number and pads with zeros up to y characters (useful for track numbers), eg. $num(%tracknumber%,2)\n" + "* $caps(x) - converts first letter in every word of x to uppercase, and all other letters to lowercase, eg. \"blah BLAH\" -> \"Blah Blah\"\n" + "* $caps2(x) - similar to $caps, but leaves uppercase letters as they are, eg. \"blah BLAH\" -> \"Blah BLAH\"\n" + "* $if(A,B,C) - if A contains at least one valid tag, displays B, otherwise displays C; eg. \"$if(%artist%,%artist%,unknown artist)\" will display artist name if present; otherwise will display \"unknown artist\"; note that \"$if(A,A,)\" is equivalent to \"[A]\" (see below)\n" + "* $if2(A,B) - equals to $if(A,A,B)\n" + "* $longest(A,B,C,....) - compares lengths of output strings produced by A,B,C... and displays the longest one, eg. \"$longest(%title%,%comment%)\" will display either title if it's longer than comment; otherwise it will display comment\n" + "* $pad(x,y) - pads x with spaces up to y characters\n" + "* $cut(x,y) - truncates x to y characters\n" + "* $padcut(x,y) - pads x to y characters and truncates to y if longer\n" + "* [ .... ] - displays contents of brackets only if at least one of fields referenced inside has been found, eg. \"%artist% - [%album% / ]%title%\" will hide [] block if album field is not present\n" + "* \' (single quotation mark) - outputs raw text without parsing, eg, \'blah$blah%blah[][]\' will output the contained string and ignore all reserved characters (%,$,[,]) in it; you can use this feature to insert square brackets for an example.\n" + "\n" + "eg. \"[%artist% - ][$abbr(%album%,10)[ %tracknumber%] / ]%title%[ %streamtitle%]\"\n"; + + +} diff --git a/flac/src/plugin_winamp2/tagz.h b/flac/src/plugin_winamp2/tagz.h new file mode 100644 index 0000000..064fba3 --- /dev/null +++ b/flac/src/plugin_winamp2/tagz.h @@ -0,0 +1,32 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef UINT +typedef unsigned int UINT; +#endif + +#ifdef TAGZ_UNICODE +#if _MSC_VER <= 1200 +typedef unsigned short T_CHAR; +#else +typedef wchar_t T_CHAR; +#endif +#else +#define T_CHAR char +#endif + +typedef T_CHAR* (*TAGFUNC)(const T_CHAR *tag,void *p); /* return 0 if not found */ +typedef void (*TAGFREEFUNC)(T_CHAR *tag,void *p); + + +UINT tagz_format(const T_CHAR * spec,TAGFUNC f,TAGFREEFUNC ff,void *fp,T_CHAR * out,UINT max); +T_CHAR * tagz_format_r(const T_CHAR * spec,TAGFUNC f,TAGFREEFUNC ff,void * fp); + +extern const char tagz_manual[]; + +#ifdef __cplusplus +} +#endif diff --git a/flac/src/plugin_xmms/Makefile.am b/flac/src/plugin_xmms/Makefile.am new file mode 100644 index 0000000..0484617 --- /dev/null +++ b/flac/src/plugin_xmms/Makefile.am @@ -0,0 +1,70 @@ +# libxmms-flac - XMMS FLAC input plugin +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +EXTRA_DIST = \ + Makefile.lite + +noinst_HEADERS = \ + charset.h \ + configure.h \ + http.h \ + locale_hack.h \ + plugin.h \ + tag.h + +AM_CFLAGS = @OGG_CFLAGS@ @XMMS_CFLAGS@ + +INCLUDES = -I$(top_srcdir)/src +if FLaC__INSTALL_XMMS_PLUGIN_LOCALLY +xmmsinputplugindir = $(HOME)/.xmms/Plugins +else +xmmsinputplugindir = @XMMS_INPUT_PLUGIN_DIR@ +endif + +# Don't build a static library +LIBTOOL = $(top_builddir)/libtool-disable-static + +xmmsinputplugin_LTLIBRARIES = libxmms-flac.la + +plugin_sources = charset.c configure.c fileinfo.c http.c plugin.c tag.c + +libxmms_flac_la_SOURCES = $(plugin_sources) + +# work around the bug in libtool where its relinking fails with a different DESTDIR +# for libtool bug info see: +# http://mail.gnu.org/pipermail/bug-libtool/2002-February/003018.html +# http://mail.gnu.org/pipermail/libtool/2002-April/006244.html +# http://mail.gnu.org/pipermail/libtool/2002-April/006250.html +# for fix info see: +# http://lists.freshrpms.net/pipermail/rpm-list/2002-April/000746.html +# the workaround is the extra '-L$(top_builddir)/src/libFLAC/.libs' +libxmms_flac_la_LIBADD = \ + $(top_builddir)/src/plugin_common/libplugin_common.la \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/share/replaygain_synthesis/libreplaygain_synthesis.la \ + $(top_builddir)/src/share/utf8/libutf8.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + -L$(top_builddir)/src/libFLAC/.libs \ + @OGG_LIBS@ \ + @XMMS_LIBS@ \ + @LIBICONV@ +libxmms_flac_la_LDFLAGS = -module -avoid-version diff --git a/flac/src/plugin_xmms/Makefile.lite b/flac/src/plugin_xmms/Makefile.lite new file mode 100644 index 0000000..74655b0 --- /dev/null +++ b/flac/src/plugin_xmms/Makefile.lite @@ -0,0 +1,43 @@ +# libxmms-flac - XMMS FLAC input plugin +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. + +LIB_NAME = libxmms-flac +INCLUDES = -I./include -I$(topdir)/include -I.. $(shell xmms-config --cflags) +# refer to the static libs explicitly +ifeq ($(OS),Darwin) +LIBS = $(topdir)/obj/$(BUILD)/lib/libFLAC.a $(topdir)/obj/$(BUILD)/lib/libplugin_common.a $(topdir)/obj/$(BUILD)/lib/libgrabbag.a $(topdir)/obj/$(BUILD)/lib/libreplaygain_analysis.a $(topdir)/obj/$(BUILD)/lib/libreplaygain_synthesis.a $(OGG_LIB_DIR)/libogg.a -liconv -lstdc++ -lz +else +LIBS = $(topdir)/obj/$(BUILD)/lib/libFLAC.a $(topdir)/obj/$(BUILD)/lib/libplugin_common.a $(topdir)/obj/$(BUILD)/lib/libgrabbag.a $(topdir)/obj/$(BUILD)/lib/libreplaygain_analysis.a $(topdir)/obj/$(BUILD)/lib/libreplaygain_synthesis.a -L$(OGG_LIB_DIR) -logg -lstdc++ -lz +endif + +SRCS_C = \ + charset.c \ + configure.c \ + plugin.c \ + fileinfo.c \ + http.c \ + tag.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/plugin_xmms/charset.c b/flac/src/plugin_xmms/charset.c new file mode 100644 index 0000000..8c1cf47 --- /dev/null +++ b/flac/src/plugin_xmms/charset.c @@ -0,0 +1,198 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * Almost from charset.c + * EasyTAG - Tag editor for MP3 and OGG files + * Copyright (C) 1999-2001 Hvard Kvlen + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +#include "plugin_common/charset.h" +#include "charset.h" +#include "configure.h" +#include "locale_hack.h" + + +/**************** + * Declarations * + ****************/ + +#define CHARSET_TRANS_ARRAY_LEN ( sizeof(charset_trans_array) / sizeof((charset_trans_array)[0]) ) +const CharsetInfo charset_trans_array[] = { + {N_("Arabic (IBM-864)"), "IBM864" }, + {N_("Arabic (ISO-8859-6)"), "ISO-8859-6" }, + {N_("Arabic (Windows-1256)"), "windows-1256" }, + {N_("Baltic (ISO-8859-13)"), "ISO-8859-13" }, + {N_("Baltic (ISO-8859-4)"), "ISO-8859-4" }, + {N_("Baltic (Windows-1257)"), "windows-1257" }, + {N_("Celtic (ISO-8859-14)"), "ISO-8859-14" }, + {N_("Central European (IBM-852)"), "IBM852" }, + {N_("Central European (ISO-8859-2)"), "ISO-8859-2" }, + {N_("Central European (Windows-1250)"), "windows-1250" }, + {N_("Chinese Simplified (GB18030)"), "gb18030" }, + {N_("Chinese Simplified (GB2312)"), "GB2312" }, + {N_("Chinese Traditional (Big5)"), "Big5" }, + {N_("Chinese Traditional (Big5-HKSCS)"), "Big5-HKSCS" }, + {N_("Cyrillic (IBM-855)"), "IBM855" }, + {N_("Cyrillic (ISO-8859-5)"), "ISO-8859-5" }, + {N_("Cyrillic (ISO-IR-111)"), "ISO-IR-111" }, + {N_("Cyrillic (KOI8-R)"), "KOI8-R" }, + {N_("Cyrillic (Windows-1251)"), "windows-1251" }, + {N_("Cyrillic/Russian (CP-866)"), "IBM866" }, + {N_("Cyrillic/Ukrainian (KOI8-U)"), "KOI8-U" }, + {N_("English (US-ASCII)"), "us-ascii" }, + {N_("Greek (ISO-8859-7)"), "ISO-8859-7" }, + {N_("Greek (Windows-1253)"), "windows-1253" }, + {N_("Hebrew (IBM-862)"), "IBM862" }, + {N_("Hebrew (Windows-1255)"), "windows-1255" }, + {N_("Japanese (EUC-JP)"), "EUC-JP" }, + {N_("Japanese (ISO-2022-JP)"), "ISO-2022-JP" }, + {N_("Japanese (Shift_JIS)"), "Shift_JIS" }, + {N_("Korean (EUC-KR)"), "EUC-KR" }, + {N_("Nordic (ISO-8859-10)"), "ISO-8859-10" }, + {N_("South European (ISO-8859-3)"), "ISO-8859-3" }, + {N_("Thai (TIS-620)"), "TIS-620" }, + {N_("Turkish (IBM-857)"), "IBM857" }, + {N_("Turkish (ISO-8859-9)"), "ISO-8859-9" }, + {N_("Turkish (Windows-1254)"), "windows-1254" }, + {N_("Unicode (UTF-7)"), "UTF-7" }, + {N_("Unicode (UTF-8)"), "UTF-8" }, + {N_("Unicode (UTF-16BE)"), "UTF-16BE" }, + {N_("Unicode (UTF-16LE)"), "UTF-16LE" }, + {N_("Unicode (UTF-32BE)"), "UTF-32BE" }, + {N_("Unicode (UTF-32LE)"), "UTF-32LE" }, + {N_("Vietnamese (VISCII)"), "VISCII" }, + {N_("Vietnamese (Windows-1258)"), "windows-1258" }, + {N_("Visual Hebrew (ISO-8859-8)"), "ISO-8859-8" }, + {N_("Western (IBM-850)"), "IBM850" }, + {N_("Western (ISO-8859-1)"), "ISO-8859-1" }, + {N_("Western (ISO-8859-15)"), "ISO-8859-15" }, + {N_("Western (Windows-1252)"), "windows-1252" } + + /* + * From this point, character sets aren't supported by iconv + */ +#if 0 + {N_("Arabic (IBM-864-I)"), "IBM864i" }, + {N_("Arabic (ISO-8859-6-E)"), "ISO-8859-6-E" }, + {N_("Arabic (ISO-8859-6-I)"), "ISO-8859-6-I" }, + {N_("Arabic (MacArabic)"), "x-mac-arabic" }, + {N_("Armenian (ARMSCII-8)"), "armscii-8" }, + {N_("Central European (MacCE)"), "x-mac-ce" }, + {N_("Chinese Simplified (GBK)"), "x-gbk" }, + {N_("Chinese Simplified (HZ)"), "HZ-GB-2312" }, + {N_("Chinese Traditional (EUC-TW)"), "x-euc-tw" }, + {N_("Croatian (MacCroatian)"), "x-mac-croatian" }, + {N_("Cyrillic (MacCyrillic)"), "x-mac-cyrillic" }, + {N_("Cyrillic/Ukrainian (MacUkrainian)"), "x-mac-ukrainian" }, + {N_("Farsi (MacFarsi)"), "x-mac-farsi"}, + {N_("Greek (MacGreek)"), "x-mac-greek" }, + {N_("Gujarati (MacGujarati)"), "x-mac-gujarati" }, + {N_("Gurmukhi (MacGurmukhi)"), "x-mac-gurmukhi" }, + {N_("Hebrew (ISO-8859-8-E)"), "ISO-8859-8-E" }, + {N_("Hebrew (ISO-8859-8-I)"), "ISO-8859-8-I" }, + {N_("Hebrew (MacHebrew)"), "x-mac-hebrew" }, + {N_("Hindi (MacDevanagari)"), "x-mac-devanagari" }, + {N_("Icelandic (MacIcelandic)"), "x-mac-icelandic" }, + {N_("Korean (JOHAB)"), "x-johab" }, + {N_("Korean (UHC)"), "x-windows-949" }, + {N_("Romanian (MacRomanian)"), "x-mac-romanian" }, + {N_("Turkish (MacTurkish)"), "x-mac-turkish" }, + {N_("User Defined"), "x-user-defined" }, + {N_("Vietnamese (TCVN)"), "x-viet-tcvn5712" }, + {N_("Vietnamese (VPS)"), "x-viet-vps" }, + {N_("Western (MacRoman)"), "x-mac-roman" }, + /* charsets whithout posibly translatable names */ + {"T61.8bit", "T61.8bit" }, + {"x-imap4-modified-utf7", "x-imap4-modified-utf7"}, + {"x-u-escaped", "x-u-escaped" }, + {"windows-936", "windows-936" } +#endif +}; + +/************* + * Functions * + *************/ + +/* + * Commons conversion functions + */ +char *convert_from_utf8_to_user(const char *string) +{ + return FLAC_plugin__charset_convert_string(string, "UTF-8", flac_cfg.title.user_char_set); +} + +char *convert_from_user_to_utf8(const char *string) +{ + return FLAC_plugin__charset_convert_string(string, flac_cfg.title.user_char_set, "UTF-8"); +} + +GList *Charset_Create_List (void) +{ + GList *list = NULL; + guint i; + + for (i=0; i + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + + +#ifndef FLAC__PLUGIN_XMMS__CHARSET_H +#define FLAC__PLUGIN_XMMS__CHARSET_H + + +/*************** + * Declaration * + ***************/ + +typedef struct { + gchar *charset_title; + gchar *charset_name; +} CharsetInfo; + +/* translated charset titles */ +extern const CharsetInfo charset_trans_array[]; + +/************** + * Prototypes * + **************/ + +/* + * The returned strings are malloc()ed an must be free()d by the caller + */ +char *convert_from_utf8_to_user(const char *string); +char *convert_from_user_to_utf8(const char *string); + +GList *Charset_Create_List (void); +GList *Charset_Create_List_UTF8_Only (void); +gchar *Charset_Get_Name_From_Title (gchar *charset_title); +gchar *Charset_Get_Title_From_Name (gchar *charset_name); + +#endif /* __CHARSET_H__ */ + diff --git a/flac/src/plugin_xmms/configure.c b/flac/src/plugin_xmms/configure.c new file mode 100644 index 0000000..b46d191 --- /dev/null +++ b/flac/src/plugin_xmms/configure.c @@ -0,0 +1,823 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * Based on mpg123 plugin + * and prefs.c - 2000/05/06 + * EasyTAG - Tag editor for MP3 and OGG files + * Copyright (C) 2000-2002 Jerome Couderc + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "share/replaygain_synthesis.h" /* for NOISE_SHAPING_LOW */ +#include "charset.h" +#include "configure.h" +#include "locale_hack.h" + +/* + * Initialize Global Valueable + */ +flac_config_t flac_cfg = { + /* title */ + { + FALSE, /* tag_override */ + NULL, /* tag_format */ + FALSE, /* convert_char_set */ + NULL /* user_char_set */ + }, + /* stream */ + { + 100 /* KB */, /* http_buffer_size */ + 50, /* http_prebuffer */ + FALSE, /* use_proxy */ + NULL, /* proxy_host */ + 0, /* proxy_port */ + FALSE, /* proxy_use_auth */ + NULL, /* proxy_user */ + NULL, /* proxy_pass */ + FALSE, /* save_http_stream */ + NULL, /* save_http_path */ + FALSE, /* cast_title_streaming */ + FALSE /* use_udp_channel */ + }, + /* output */ + { + /* replaygain */ + { + FALSE, /* enable */ + TRUE, /* album_mode */ + 0, /* preamp */ + FALSE /* hard_limit */ + }, + /* resolution */ + { + /* normal */ + { + TRUE /* dither_24_to_16 */ + }, + /* replaygain */ + { + TRUE, /* dither */ + NOISE_SHAPING_LOW, /* noise_shaping */ + 16 /* bps_out */ + } + } + } +}; + + +static GtkWidget *flac_configurewin = NULL; +static GtkWidget *vbox, *notebook; + +static GtkWidget *title_tag_override, *title_tag_box, *title_tag_entry, *title_desc; +static GtkWidget *convert_char_set, *fileCharacterSetEntry, *userCharacterSetEntry; +static GtkWidget *replaygain_enable, *replaygain_album_mode; +static GtkWidget *replaygain_preamp_hscale, *replaygain_preamp_label, *replaygain_hard_limit; +static GtkObject *replaygain_preamp; +static GtkWidget *resolution_normal_dither_24_to_16; +static GtkWidget *resolution_replaygain_dither; +static GtkWidget *resolution_replaygain_noise_shaping_frame; +static GtkWidget *resolution_replaygain_noise_shaping_radio_none; +static GtkWidget *resolution_replaygain_noise_shaping_radio_low; +static GtkWidget *resolution_replaygain_noise_shaping_radio_medium; +static GtkWidget *resolution_replaygain_noise_shaping_radio_high; +static GtkWidget *resolution_replaygain_bps_out_frame; +static GtkWidget *resolution_replaygain_bps_out_radio_16bps; +static GtkWidget *resolution_replaygain_bps_out_radio_24bps; + +static GtkObject *streaming_size_adj, *streaming_pre_adj; +static GtkWidget *streaming_proxy_use, *streaming_proxy_host_entry; +static GtkWidget *streaming_proxy_port_entry, *streaming_save_use, *streaming_save_entry; +static GtkWidget *streaming_proxy_auth_use; +static GtkWidget *streaming_proxy_auth_pass_entry, *streaming_proxy_auth_user_entry; +static GtkWidget *streaming_proxy_auth_user_label, *streaming_proxy_auth_pass_label; +#ifdef FLAC_ICECAST +static GtkWidget *streaming_cast_title, *streaming_udp_title; +#endif +static GtkWidget *streaming_proxy_hbox, *streaming_proxy_auth_hbox, *streaming_save_dirbrowser; +static GtkWidget *streaming_save_hbox; + +static gchar *gtk_entry_get_text_1 (GtkWidget *widget); +static void flac_configurewin_ok(GtkWidget * widget, gpointer data); +static void configure_destroy(GtkWidget * w, gpointer data); + +static void flac_configurewin_ok(GtkWidget * widget, gpointer data) +{ + ConfigFile *cfg; + gchar *filename; + + (void)widget, (void)data; /* unused arguments */ + g_free(flac_cfg.title.tag_format); + flac_cfg.title.tag_format = g_strdup(gtk_entry_get_text(GTK_ENTRY(title_tag_entry))); + flac_cfg.title.user_char_set = Charset_Get_Name_From_Title(gtk_entry_get_text_1(userCharacterSetEntry)); + + filename = g_strconcat(g_get_home_dir(), "/.xmms/config", NULL); + cfg = xmms_cfg_open_file(filename); + if (!cfg) + cfg = xmms_cfg_new(); + /* title */ + xmms_cfg_write_boolean(cfg, "flac", "title.tag_override", flac_cfg.title.tag_override); + xmms_cfg_write_string(cfg, "flac", "title.tag_format", flac_cfg.title.tag_format); + xmms_cfg_write_boolean(cfg, "flac", "title.convert_char_set", flac_cfg.title.convert_char_set); + xmms_cfg_write_string(cfg, "flac", "title.user_char_set", flac_cfg.title.user_char_set); + /* output */ + xmms_cfg_write_boolean(cfg, "flac", "output.replaygain.enable", flac_cfg.output.replaygain.enable); + xmms_cfg_write_boolean(cfg, "flac", "output.replaygain.album_mode", flac_cfg.output.replaygain.album_mode); + xmms_cfg_write_int(cfg, "flac", "output.replaygain.preamp", flac_cfg.output.replaygain.preamp); + xmms_cfg_write_boolean(cfg, "flac", "output.replaygain.hard_limit", flac_cfg.output.replaygain.hard_limit); + xmms_cfg_write_boolean(cfg, "flac", "output.resolution.normal.dither_24_to_16", flac_cfg.output.resolution.normal.dither_24_to_16); + xmms_cfg_write_boolean(cfg, "flac", "output.resolution.replaygain.dither", flac_cfg.output.resolution.replaygain.dither); + xmms_cfg_write_int(cfg, "flac", "output.resolution.replaygain.noise_shaping", flac_cfg.output.resolution.replaygain.noise_shaping); + xmms_cfg_write_int(cfg, "flac", "output.resolution.replaygain.bps_out", flac_cfg.output.resolution.replaygain.bps_out); + /* streaming */ + flac_cfg.stream.http_buffer_size = (gint) GTK_ADJUSTMENT(streaming_size_adj)->value; + flac_cfg.stream.http_prebuffer = (gint) GTK_ADJUSTMENT(streaming_pre_adj)->value; + + flac_cfg.stream.use_proxy = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_use)); + if(flac_cfg.stream.proxy_host) + g_free(flac_cfg.stream.proxy_host); + flac_cfg.stream.proxy_host = g_strdup(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_host_entry))); + flac_cfg.stream.proxy_port = atoi(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_port_entry))); + + flac_cfg.stream.proxy_use_auth = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_auth_use)); + + if(flac_cfg.stream.proxy_user) + g_free(flac_cfg.stream.proxy_user); + flac_cfg.stream.proxy_user = NULL; + if(strlen(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_auth_user_entry))) > 0) + flac_cfg.stream.proxy_user = g_strdup(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_auth_user_entry))); + + if(flac_cfg.stream.proxy_pass) + g_free(flac_cfg.stream.proxy_pass); + flac_cfg.stream.proxy_pass = NULL; + if(strlen(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_auth_pass_entry))) > 0) + flac_cfg.stream.proxy_pass = g_strdup(gtk_entry_get_text(GTK_ENTRY(streaming_proxy_auth_pass_entry))); + + + flac_cfg.stream.save_http_stream = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_save_use)); + if (flac_cfg.stream.save_http_path) + g_free(flac_cfg.stream.save_http_path); + flac_cfg.stream.save_http_path = g_strdup(gtk_entry_get_text(GTK_ENTRY(streaming_save_entry))); + +#ifdef FLAC_ICECAST + flac_cfg.stream.cast_title_streaming = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_cast_title)); + flac_cfg.stream.use_udp_channel = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_udp_title)); +#endif + + xmms_cfg_write_int(cfg, "flac", "stream.http_buffer_size", flac_cfg.stream.http_buffer_size); + xmms_cfg_write_int(cfg, "flac", "stream.http_prebuffer", flac_cfg.stream.http_prebuffer); + xmms_cfg_write_boolean(cfg, "flac", "stream.use_proxy", flac_cfg.stream.use_proxy); + xmms_cfg_write_string(cfg, "flac", "stream.proxy_host", flac_cfg.stream.proxy_host); + xmms_cfg_write_int(cfg, "flac", "stream.proxy_port", flac_cfg.stream.proxy_port); + xmms_cfg_write_boolean(cfg, "flac", "stream.proxy_use_auth", flac_cfg.stream.proxy_use_auth); + if(flac_cfg.stream.proxy_user) + xmms_cfg_write_string(cfg, "flac", "stream.proxy_user", flac_cfg.stream.proxy_user); + else + xmms_cfg_remove_key(cfg, "flac", "stream.proxy_user"); + if(flac_cfg.stream.proxy_pass) + xmms_cfg_write_string(cfg, "flac", "stream.proxy_pass", flac_cfg.stream.proxy_pass); + else + xmms_cfg_remove_key(cfg, "flac", "stream.proxy_pass"); + xmms_cfg_write_boolean(cfg, "flac", "stream.save_http_stream", flac_cfg.stream.save_http_stream); + xmms_cfg_write_string(cfg, "flac", "stream.save_http_path", flac_cfg.stream.save_http_path); +#ifdef FLAC_ICECAST + xmms_cfg_write_boolean(cfg, "flac", "stream.cast_title_streaming", flac_cfg.stream.cast_title_streaming); + xmms_cfg_write_boolean(cfg, "flac", "stream.use_udp_channel", flac_cfg.stream.use_udp_channel); +#endif + + xmms_cfg_write_file(cfg, filename); + xmms_cfg_free(cfg); + g_free(filename); + gtk_widget_destroy(flac_configurewin); +} + +static void configure_destroy(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ +} + +static void title_tag_override_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.title.tag_override = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(title_tag_override)); + + gtk_widget_set_sensitive(title_tag_box, flac_cfg.title.tag_override); + gtk_widget_set_sensitive(title_desc, flac_cfg.title.tag_override); + +} + +static void convert_char_set_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.title.convert_char_set = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(convert_char_set)); + + gtk_widget_set_sensitive(fileCharacterSetEntry, FALSE); + gtk_widget_set_sensitive(userCharacterSetEntry, flac_cfg.title.convert_char_set); +} + +static void replaygain_enable_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.replaygain.enable = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(replaygain_enable)); + + gtk_widget_set_sensitive(replaygain_album_mode, flac_cfg.output.replaygain.enable); + gtk_widget_set_sensitive(replaygain_preamp_hscale, flac_cfg.output.replaygain.enable); + gtk_widget_set_sensitive(replaygain_hard_limit, flac_cfg.output.replaygain.enable); +} + +static void replaygain_album_mode_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.replaygain.album_mode = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(replaygain_album_mode)); +} + +static void replaygain_hard_limit_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.replaygain.hard_limit = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(replaygain_hard_limit)); +} + +static void replaygain_preamp_cb(GtkWidget *widget, gpointer data) +{ + GString *gstring = g_string_new(""); + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.replaygain.preamp = (int) floor(GTK_ADJUSTMENT(replaygain_preamp)->value + 0.5); + + g_string_sprintf(gstring, "%i dB", flac_cfg.output.replaygain.preamp); + gtk_label_set_text(GTK_LABEL(replaygain_preamp_label), _(gstring->str)); +} + +static void resolution_normal_dither_24_to_16_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.resolution.normal.dither_24_to_16 = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_normal_dither_24_to_16)); +} + +static void resolution_replaygain_dither_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.resolution.replaygain.dither = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_dither)); + + gtk_widget_set_sensitive(resolution_replaygain_noise_shaping_frame, flac_cfg.output.resolution.replaygain.dither); +} + +static void resolution_replaygain_noise_shaping_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.resolution.replaygain.noise_shaping = + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_none))? 0 : + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_low))? 1 : + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_medium))? 2 : + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_high))? 3 : + 0 + ; +} + +static void resolution_replaygain_bps_out_cb(GtkWidget *widget, gpointer data) +{ + (void)widget, (void)data; /* unused arguments */ + flac_cfg.output.resolution.replaygain.bps_out = + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_bps_out_radio_16bps))? 16 : + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(resolution_replaygain_bps_out_radio_24bps))? 24 : + 16 + ; +} + +static void proxy_use_cb(GtkWidget * w, gpointer data) +{ + gboolean use_proxy, use_proxy_auth; + (void) w; + (void) data; + + use_proxy = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_use)); + use_proxy_auth = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_auth_use)); + + gtk_widget_set_sensitive(streaming_proxy_hbox, use_proxy); + gtk_widget_set_sensitive(streaming_proxy_auth_use, use_proxy); + gtk_widget_set_sensitive(streaming_proxy_auth_hbox, use_proxy && use_proxy_auth); +} + +static void proxy_auth_use_cb(GtkWidget *w, gpointer data) +{ + gboolean use_proxy, use_proxy_auth; + (void) w; + (void) data; + + use_proxy = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_use)); + use_proxy_auth = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_proxy_auth_use)); + + gtk_widget_set_sensitive(streaming_proxy_auth_hbox, use_proxy && use_proxy_auth); +} + +static void streaming_save_dirbrowser_cb(gchar * dir) +{ + gtk_entry_set_text(GTK_ENTRY(streaming_save_entry), dir); +} + +static void streaming_save_browse_cb(GtkWidget * w, gpointer data) +{ + (void) w; + (void) data; + if (!streaming_save_dirbrowser) + { + streaming_save_dirbrowser = xmms_create_dir_browser(_("Select the directory where you want to store the MPEG streams:"), + flac_cfg.stream.save_http_path, GTK_SELECTION_SINGLE, streaming_save_dirbrowser_cb); + gtk_signal_connect(GTK_OBJECT(streaming_save_dirbrowser), "destroy", GTK_SIGNAL_FUNC(gtk_widget_destroyed), &streaming_save_dirbrowser); + gtk_window_set_transient_for(GTK_WINDOW(streaming_save_dirbrowser), GTK_WINDOW(flac_configurewin)); + gtk_widget_show(streaming_save_dirbrowser); + } +} + +static void streaming_save_use_cb(GtkWidget * w, gpointer data) +{ + gboolean save_stream; + (void) w; + (void) data; + + save_stream = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(streaming_save_use)); + + gtk_widget_set_sensitive(streaming_save_hbox, save_stream); +} + + +void FLAC_XMMS__configure(void) +{ + GtkWidget *title_frame, *title_tag_vbox, *title_tag_label; + GtkWidget *replaygain_frame, *resolution_frame, *output_vbox, *resolution_normal_frame, *resolution_replaygain_frame; + GtkWidget *replaygain_vbox, *resolution_hbox, *resolution_normal_vbox, *resolution_replaygain_vbox; + GtkWidget *resolution_replaygain_noise_shaping_vbox; + GtkWidget *resolution_replaygain_bps_out_vbox; + GtkWidget *label, *hbox; + GtkWidget *bbox, *ok, *cancel; + GList *list; + + GtkWidget *streaming_vbox; + GtkWidget *streaming_buf_frame, *streaming_buf_hbox; + GtkWidget *streaming_size_box, *streaming_size_label, *streaming_size_spin; + GtkWidget *streaming_pre_box, *streaming_pre_label, *streaming_pre_spin; + GtkWidget *streaming_proxy_frame, *streaming_proxy_vbox; + GtkWidget *streaming_proxy_port_label, *streaming_proxy_host_label; + GtkWidget *streaming_save_frame, *streaming_save_vbox; + GtkWidget *streaming_save_label, *streaming_save_browse; +#ifdef FLAC_ICECAST + GtkWidget *streaming_cast_frame, *streaming_cast_vbox; +#endif + char *temp; + + if (flac_configurewin != NULL) { + gdk_window_raise(flac_configurewin->window); + return; + } + flac_configurewin = gtk_window_new(GTK_WINDOW_DIALOG); + gtk_signal_connect(GTK_OBJECT(flac_configurewin), "destroy", GTK_SIGNAL_FUNC(gtk_widget_destroyed), &flac_configurewin); + gtk_signal_connect(GTK_OBJECT(flac_configurewin), "destroy", GTK_SIGNAL_FUNC(configure_destroy), &flac_configurewin); + gtk_window_set_title(GTK_WINDOW(flac_configurewin), _("Flac Configuration")); + gtk_window_set_policy(GTK_WINDOW(flac_configurewin), FALSE, FALSE, FALSE); + gtk_container_border_width(GTK_CONTAINER(flac_configurewin), 10); + + vbox = gtk_vbox_new(FALSE, 10); + gtk_container_add(GTK_CONTAINER(flac_configurewin), vbox); + + notebook = gtk_notebook_new(); + gtk_box_pack_start(GTK_BOX(vbox), notebook, TRUE, TRUE, 0); + + /* Title config.. */ + + title_frame = gtk_frame_new(_("Tag Handling")); + gtk_container_border_width(GTK_CONTAINER(title_frame), 5); + + title_tag_vbox = gtk_vbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(title_tag_vbox), 5); + gtk_container_add(GTK_CONTAINER(title_frame), title_tag_vbox); + + /* Convert Char Set */ + + convert_char_set = gtk_check_button_new_with_label(_("Convert Character Set")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(convert_char_set), flac_cfg.title.convert_char_set); + gtk_signal_connect(GTK_OBJECT(convert_char_set), "clicked", convert_char_set_cb, NULL); + gtk_box_pack_start(GTK_BOX(title_tag_vbox), convert_char_set, FALSE, FALSE, 0); + /* Combo boxes... */ + hbox = gtk_hbox_new(FALSE,4); + gtk_container_add(GTK_CONTAINER(title_tag_vbox),hbox); + label = gtk_label_new(_("Convert character set from :")); + gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,FALSE,0); + fileCharacterSetEntry = gtk_combo_new(); + gtk_box_pack_start(GTK_BOX(hbox),fileCharacterSetEntry,TRUE,TRUE,0); + + label = gtk_label_new (_("to :")); + gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,FALSE,0); + userCharacterSetEntry = gtk_combo_new(); + gtk_box_pack_start(GTK_BOX(hbox),userCharacterSetEntry,TRUE,TRUE,0); + + gtk_entry_set_editable(GTK_ENTRY(GTK_COMBO(fileCharacterSetEntry)->entry),FALSE); + gtk_entry_set_editable(GTK_ENTRY(GTK_COMBO(userCharacterSetEntry)->entry),FALSE); + gtk_combo_set_value_in_list(GTK_COMBO(fileCharacterSetEntry),TRUE,FALSE); + gtk_combo_set_value_in_list(GTK_COMBO(userCharacterSetEntry),TRUE,FALSE); + + list = Charset_Create_List(); + gtk_combo_set_popdown_strings(GTK_COMBO(fileCharacterSetEntry),Charset_Create_List_UTF8_Only()); + gtk_combo_set_popdown_strings(GTK_COMBO(userCharacterSetEntry),list); + gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(userCharacterSetEntry)->entry),Charset_Get_Title_From_Name(flac_cfg.title.user_char_set)); + gtk_widget_set_sensitive(fileCharacterSetEntry, FALSE); + gtk_widget_set_sensitive(userCharacterSetEntry, flac_cfg.title.convert_char_set); + + /* Override Tagging Format */ + + title_tag_override = gtk_check_button_new_with_label(_("Override generic titles")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(title_tag_override), flac_cfg.title.tag_override); + gtk_signal_connect(GTK_OBJECT(title_tag_override), "clicked", title_tag_override_cb, NULL); + gtk_box_pack_start(GTK_BOX(title_tag_vbox), title_tag_override, FALSE, FALSE, 0); + + title_tag_box = gtk_hbox_new(FALSE, 5); + gtk_widget_set_sensitive(title_tag_box, flac_cfg.title.tag_override); + gtk_box_pack_start(GTK_BOX(title_tag_vbox), title_tag_box, FALSE, FALSE, 0); + + title_tag_label = gtk_label_new(_("Title format:")); + gtk_box_pack_start(GTK_BOX(title_tag_box), title_tag_label, FALSE, FALSE, 0); + + title_tag_entry = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(title_tag_entry), flac_cfg.title.tag_format); + gtk_box_pack_start(GTK_BOX(title_tag_box), title_tag_entry, TRUE, TRUE, 0); + + title_desc = xmms_titlestring_descriptions("pafFetnygc", 2); + gtk_widget_set_sensitive(title_desc, flac_cfg.title.tag_override); + gtk_box_pack_start(GTK_BOX(title_tag_vbox), title_desc, FALSE, FALSE, 0); + + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), title_frame, gtk_label_new(_("Title"))); + + /* Output config.. */ + + output_vbox = gtk_vbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(output_vbox), 5); + + /* replaygain */ + + replaygain_frame = gtk_frame_new(_("ReplayGain")); + gtk_container_border_width(GTK_CONTAINER(replaygain_frame), 5); + gtk_box_pack_start(GTK_BOX(output_vbox), replaygain_frame, TRUE, TRUE, 0); + + replaygain_vbox = gtk_vbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(replaygain_vbox), 5); + gtk_container_add(GTK_CONTAINER(replaygain_frame), replaygain_vbox); + + replaygain_enable = gtk_check_button_new_with_label(_("Enable ReplayGain processing")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(replaygain_enable), flac_cfg.output.replaygain.enable); + gtk_signal_connect(GTK_OBJECT(replaygain_enable), "clicked", replaygain_enable_cb, NULL); + gtk_box_pack_start(GTK_BOX(replaygain_vbox), replaygain_enable, FALSE, FALSE, 0); + + replaygain_album_mode = gtk_check_button_new_with_label(_("Album mode")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(replaygain_album_mode), flac_cfg.output.replaygain.album_mode); + gtk_signal_connect(GTK_OBJECT(replaygain_album_mode), "clicked", replaygain_album_mode_cb, NULL); + gtk_box_pack_start(GTK_BOX(replaygain_vbox), replaygain_album_mode, FALSE, FALSE, 0); + + hbox = gtk_hbox_new(FALSE,3); + gtk_container_add(GTK_CONTAINER(replaygain_vbox),hbox); + label = gtk_label_new(_("Preamp:")); + gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,FALSE,0); + replaygain_preamp = gtk_adjustment_new(flac_cfg.output.replaygain.preamp, -24.0, +24.0, 1.0, 6.0, 0.0); + gtk_signal_connect(GTK_OBJECT(replaygain_preamp), "value-changed", replaygain_preamp_cb, NULL); + replaygain_preamp_hscale = gtk_hscale_new(GTK_ADJUSTMENT(replaygain_preamp)); + gtk_scale_set_draw_value(GTK_SCALE(replaygain_preamp_hscale), FALSE); + gtk_box_pack_start(GTK_BOX(hbox),replaygain_preamp_hscale,TRUE,TRUE,0); + replaygain_preamp_label = gtk_label_new(_("0 dB")); + gtk_box_pack_start(GTK_BOX(hbox),replaygain_preamp_label,FALSE,FALSE,0); + gtk_adjustment_value_changed(GTK_ADJUSTMENT(replaygain_preamp)); + + replaygain_hard_limit = gtk_check_button_new_with_label(_("6dB hard limiting")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(replaygain_hard_limit), flac_cfg.output.replaygain.hard_limit); + gtk_signal_connect(GTK_OBJECT(replaygain_hard_limit), "clicked", replaygain_hard_limit_cb, NULL); + gtk_box_pack_start(GTK_BOX(replaygain_vbox), replaygain_hard_limit, FALSE, FALSE, 0); + + replaygain_enable_cb(replaygain_enable, NULL); + + /* resolution */ + + resolution_frame = gtk_frame_new(_("Resolution")); + gtk_container_border_width(GTK_CONTAINER(resolution_frame), 5); + gtk_box_pack_start(GTK_BOX(output_vbox), resolution_frame, TRUE, TRUE, 0); + + resolution_hbox = gtk_hbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(resolution_hbox), 5); + gtk_container_add(GTK_CONTAINER(resolution_frame), resolution_hbox); + + resolution_normal_frame = gtk_frame_new(_("Without ReplayGain")); + gtk_container_border_width(GTK_CONTAINER(resolution_normal_frame), 5); + gtk_box_pack_start(GTK_BOX(resolution_hbox), resolution_normal_frame, TRUE, TRUE, 0); + + resolution_normal_vbox = gtk_vbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(resolution_normal_vbox), 5); + gtk_container_add(GTK_CONTAINER(resolution_normal_frame), resolution_normal_vbox); + + resolution_normal_dither_24_to_16 = gtk_check_button_new_with_label(_("Dither 24bps to 16bps")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_normal_dither_24_to_16), flac_cfg.output.resolution.normal.dither_24_to_16); + gtk_signal_connect(GTK_OBJECT(resolution_normal_dither_24_to_16), "clicked", resolution_normal_dither_24_to_16_cb, NULL); + gtk_box_pack_start(GTK_BOX(resolution_normal_vbox), resolution_normal_dither_24_to_16, FALSE, FALSE, 0); + + resolution_replaygain_frame = gtk_frame_new(_("With ReplayGain")); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_frame), 5); + gtk_box_pack_start(GTK_BOX(resolution_hbox), resolution_replaygain_frame, TRUE, TRUE, 0); + + resolution_replaygain_vbox = gtk_vbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_vbox), 5); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_frame), resolution_replaygain_vbox); + + resolution_replaygain_dither = gtk_check_button_new_with_label(_("Enable dithering")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_dither), flac_cfg.output.resolution.replaygain.dither); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_dither), "clicked", resolution_replaygain_dither_cb, NULL); + gtk_box_pack_start(GTK_BOX(resolution_replaygain_vbox), resolution_replaygain_dither, FALSE, FALSE, 0); + + hbox = gtk_hbox_new(FALSE, 10); + gtk_container_border_width(GTK_CONTAINER(hbox), 5); + gtk_box_pack_start(GTK_BOX(resolution_replaygain_vbox), hbox, TRUE, TRUE, 0); + + resolution_replaygain_noise_shaping_frame = gtk_frame_new(_("Noise shaping")); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_noise_shaping_frame), 5); + gtk_box_pack_start(GTK_BOX(hbox), resolution_replaygain_noise_shaping_frame, TRUE, TRUE, 0); + + resolution_replaygain_noise_shaping_vbox = gtk_vbutton_box_new(); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_noise_shaping_vbox), 5); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_noise_shaping_frame), resolution_replaygain_noise_shaping_vbox); + + resolution_replaygain_noise_shaping_radio_none = gtk_radio_button_new_with_label(NULL, _("none")); + if(flac_cfg.output.resolution.replaygain.noise_shaping == 0) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_none), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_noise_shaping_radio_none), "clicked", resolution_replaygain_noise_shaping_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_noise_shaping_vbox), resolution_replaygain_noise_shaping_radio_none); + + resolution_replaygain_noise_shaping_radio_low = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(resolution_replaygain_noise_shaping_radio_none), _("low")); + if(flac_cfg.output.resolution.replaygain.noise_shaping == 1) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_low), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_noise_shaping_radio_low), "clicked", resolution_replaygain_noise_shaping_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_noise_shaping_vbox), resolution_replaygain_noise_shaping_radio_low); + + resolution_replaygain_noise_shaping_radio_medium = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(resolution_replaygain_noise_shaping_radio_none), _("medium")); + if(flac_cfg.output.resolution.replaygain.noise_shaping == 2) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_medium), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_noise_shaping_radio_medium), "clicked", resolution_replaygain_noise_shaping_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_noise_shaping_vbox), resolution_replaygain_noise_shaping_radio_medium); + + resolution_replaygain_noise_shaping_radio_high = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(resolution_replaygain_noise_shaping_radio_none), _("high")); + if(flac_cfg.output.resolution.replaygain.noise_shaping == 3) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_noise_shaping_radio_high), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_noise_shaping_radio_high), "clicked", resolution_replaygain_noise_shaping_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_noise_shaping_vbox), resolution_replaygain_noise_shaping_radio_high); + + resolution_replaygain_bps_out_frame = gtk_frame_new(_("Dither to")); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_bps_out_frame), 5); + gtk_box_pack_start(GTK_BOX(hbox), resolution_replaygain_bps_out_frame, FALSE, FALSE, 0); + + resolution_replaygain_bps_out_vbox = gtk_vbutton_box_new(); + gtk_container_border_width(GTK_CONTAINER(resolution_replaygain_bps_out_vbox), 0); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_bps_out_frame), resolution_replaygain_bps_out_vbox); + + resolution_replaygain_bps_out_radio_16bps = gtk_radio_button_new_with_label(NULL, _("16 bps")); + if(flac_cfg.output.resolution.replaygain.bps_out == 16) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_bps_out_radio_16bps), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_bps_out_radio_16bps), "clicked", resolution_replaygain_bps_out_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_bps_out_vbox), resolution_replaygain_bps_out_radio_16bps); + + resolution_replaygain_bps_out_radio_24bps = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(resolution_replaygain_bps_out_radio_16bps), _("24 bps")); + if(flac_cfg.output.resolution.replaygain.bps_out == 24) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolution_replaygain_bps_out_radio_24bps), TRUE); + gtk_signal_connect(GTK_OBJECT(resolution_replaygain_bps_out_radio_24bps), "clicked", resolution_replaygain_bps_out_cb, NULL); + gtk_container_add(GTK_CONTAINER(resolution_replaygain_bps_out_vbox), resolution_replaygain_bps_out_radio_24bps); + + resolution_replaygain_dither_cb(resolution_replaygain_dither, NULL); + + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), output_vbox, gtk_label_new(_("Output"))); + + /* Streaming */ + + streaming_vbox = gtk_vbox_new(FALSE, 0); + + streaming_buf_frame = gtk_frame_new(_("Buffering:")); + gtk_container_set_border_width(GTK_CONTAINER(streaming_buf_frame), 5); + gtk_box_pack_start(GTK_BOX(streaming_vbox), streaming_buf_frame, FALSE, FALSE, 0); + + streaming_buf_hbox = gtk_hbox_new(TRUE, 5); + gtk_container_set_border_width(GTK_CONTAINER(streaming_buf_hbox), 5); + gtk_container_add(GTK_CONTAINER(streaming_buf_frame), streaming_buf_hbox); + + streaming_size_box = gtk_hbox_new(FALSE, 5); + /*gtk_table_attach_defaults(GTK_TABLE(streaming_buf_table),streaming_size_box,0,1,0,1); */ + gtk_box_pack_start(GTK_BOX(streaming_buf_hbox), streaming_size_box, TRUE, TRUE, 0); + streaming_size_label = gtk_label_new(_("Buffer size (kb):")); + gtk_box_pack_start(GTK_BOX(streaming_size_box), streaming_size_label, FALSE, FALSE, 0); + streaming_size_adj = gtk_adjustment_new(flac_cfg.stream.http_buffer_size, 4, 4096, 4, 4, 4); + streaming_size_spin = gtk_spin_button_new(GTK_ADJUSTMENT(streaming_size_adj), 8, 0); + gtk_widget_set_usize(streaming_size_spin, 60, -1); + gtk_box_pack_start(GTK_BOX(streaming_size_box), streaming_size_spin, FALSE, FALSE, 0); + + streaming_pre_box = gtk_hbox_new(FALSE, 5); + /*gtk_table_attach_defaults(GTK_TABLE(streaming_buf_table),streaming_pre_box,1,2,0,1); */ + gtk_box_pack_start(GTK_BOX(streaming_buf_hbox), streaming_pre_box, TRUE, TRUE, 0); + streaming_pre_label = gtk_label_new(_("Pre-buffer (percent):")); + gtk_box_pack_start(GTK_BOX(streaming_pre_box), streaming_pre_label, FALSE, FALSE, 0); + streaming_pre_adj = gtk_adjustment_new(flac_cfg.stream.http_prebuffer, 0, 90, 1, 1, 1); + streaming_pre_spin = gtk_spin_button_new(GTK_ADJUSTMENT(streaming_pre_adj), 1, 0); + gtk_widget_set_usize(streaming_pre_spin, 60, -1); + gtk_box_pack_start(GTK_BOX(streaming_pre_box), streaming_pre_spin, FALSE, FALSE, 0); + + /* + * Proxy config. + */ + streaming_proxy_frame = gtk_frame_new(_("Proxy:")); + gtk_container_set_border_width(GTK_CONTAINER(streaming_proxy_frame), 5); + gtk_box_pack_start(GTK_BOX(streaming_vbox), streaming_proxy_frame, FALSE, FALSE, 0); + + streaming_proxy_vbox = gtk_vbox_new(FALSE, 5); + gtk_container_set_border_width(GTK_CONTAINER(streaming_proxy_vbox), 5); + gtk_container_add(GTK_CONTAINER(streaming_proxy_frame), streaming_proxy_vbox); + + streaming_proxy_use = gtk_check_button_new_with_label(_("Use proxy")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(streaming_proxy_use), flac_cfg.stream.use_proxy); + gtk_signal_connect(GTK_OBJECT(streaming_proxy_use), "clicked", GTK_SIGNAL_FUNC(proxy_use_cb), NULL); + gtk_box_pack_start(GTK_BOX(streaming_proxy_vbox), streaming_proxy_use, FALSE, FALSE, 0); + + streaming_proxy_hbox = gtk_hbox_new(FALSE, 5); + gtk_widget_set_sensitive(streaming_proxy_hbox, flac_cfg.stream.use_proxy); + gtk_box_pack_start(GTK_BOX(streaming_proxy_vbox), streaming_proxy_hbox, FALSE, FALSE, 0); + + streaming_proxy_host_label = gtk_label_new(_("Host:")); + gtk_box_pack_start(GTK_BOX(streaming_proxy_hbox), streaming_proxy_host_label, FALSE, FALSE, 0); + + streaming_proxy_host_entry = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(streaming_proxy_host_entry), flac_cfg.stream.proxy_host? flac_cfg.stream.proxy_host : ""); + gtk_box_pack_start(GTK_BOX(streaming_proxy_hbox), streaming_proxy_host_entry, TRUE, TRUE, 0); + + streaming_proxy_port_label = gtk_label_new(_("Port:")); + gtk_box_pack_start(GTK_BOX(streaming_proxy_hbox), streaming_proxy_port_label, FALSE, FALSE, 0); + + streaming_proxy_port_entry = gtk_entry_new(); + gtk_widget_set_usize(streaming_proxy_port_entry, 50, -1); + temp = g_strdup_printf("%d", flac_cfg.stream.proxy_port); + gtk_entry_set_text(GTK_ENTRY(streaming_proxy_port_entry), temp); + g_free(temp); + gtk_box_pack_start(GTK_BOX(streaming_proxy_hbox), streaming_proxy_port_entry, FALSE, FALSE, 0); + + streaming_proxy_auth_use = gtk_check_button_new_with_label(_("Use authentication")); + gtk_widget_set_sensitive(streaming_proxy_auth_use, flac_cfg.stream.use_proxy); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(streaming_proxy_auth_use), flac_cfg.stream.proxy_use_auth); + gtk_signal_connect(GTK_OBJECT(streaming_proxy_auth_use), "clicked", GTK_SIGNAL_FUNC(proxy_auth_use_cb), NULL); + gtk_box_pack_start(GTK_BOX(streaming_proxy_vbox), streaming_proxy_auth_use, FALSE, FALSE, 0); + + streaming_proxy_auth_hbox = gtk_hbox_new(FALSE, 5); + gtk_widget_set_sensitive(streaming_proxy_auth_hbox, flac_cfg.stream.use_proxy && flac_cfg.stream.proxy_use_auth); + gtk_box_pack_start(GTK_BOX(streaming_proxy_vbox), streaming_proxy_auth_hbox, FALSE, FALSE, 0); + + streaming_proxy_auth_user_label = gtk_label_new(_("Username:")); + gtk_box_pack_start(GTK_BOX(streaming_proxy_auth_hbox), streaming_proxy_auth_user_label, FALSE, FALSE, 0); + + streaming_proxy_auth_user_entry = gtk_entry_new(); + if(flac_cfg.stream.proxy_user) + gtk_entry_set_text(GTK_ENTRY(streaming_proxy_auth_user_entry), flac_cfg.stream.proxy_user); + gtk_box_pack_start(GTK_BOX(streaming_proxy_auth_hbox), streaming_proxy_auth_user_entry, TRUE, TRUE, 0); + + streaming_proxy_auth_pass_label = gtk_label_new(_("Password:")); + gtk_box_pack_start(GTK_BOX(streaming_proxy_auth_hbox), streaming_proxy_auth_pass_label, FALSE, FALSE, 0); + + streaming_proxy_auth_pass_entry = gtk_entry_new(); + if(flac_cfg.stream.proxy_pass) + gtk_entry_set_text(GTK_ENTRY(streaming_proxy_auth_pass_entry), flac_cfg.stream.proxy_pass); + gtk_entry_set_visibility(GTK_ENTRY(streaming_proxy_auth_pass_entry), FALSE); + gtk_box_pack_start(GTK_BOX(streaming_proxy_auth_hbox), streaming_proxy_auth_pass_entry, TRUE, TRUE, 0); + + + /* + * Save to disk config. + */ + streaming_save_frame = gtk_frame_new(_("Save stream to disk:")); + gtk_container_set_border_width(GTK_CONTAINER(streaming_save_frame), 5); + gtk_box_pack_start(GTK_BOX(streaming_vbox), streaming_save_frame, FALSE, FALSE, 0); + + streaming_save_vbox = gtk_vbox_new(FALSE, 5); + gtk_container_set_border_width(GTK_CONTAINER(streaming_save_vbox), 5); + gtk_container_add(GTK_CONTAINER(streaming_save_frame), streaming_save_vbox); + + streaming_save_use = gtk_check_button_new_with_label(_("Save stream to disk")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(streaming_save_use), flac_cfg.stream.save_http_stream); + gtk_signal_connect(GTK_OBJECT(streaming_save_use), "clicked", GTK_SIGNAL_FUNC(streaming_save_use_cb), NULL); + gtk_box_pack_start(GTK_BOX(streaming_save_vbox), streaming_save_use, FALSE, FALSE, 0); + + streaming_save_hbox = gtk_hbox_new(FALSE, 5); + gtk_widget_set_sensitive(streaming_save_hbox, flac_cfg.stream.save_http_stream); + gtk_box_pack_start(GTK_BOX(streaming_save_vbox), streaming_save_hbox, FALSE, FALSE, 0); + + streaming_save_label = gtk_label_new(_("Path:")); + gtk_box_pack_start(GTK_BOX(streaming_save_hbox), streaming_save_label, FALSE, FALSE, 0); + + streaming_save_entry = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(streaming_save_entry), flac_cfg.stream.save_http_path? flac_cfg.stream.save_http_path : ""); + gtk_box_pack_start(GTK_BOX(streaming_save_hbox), streaming_save_entry, TRUE, TRUE, 0); + + streaming_save_browse = gtk_button_new_with_label(_("Browse")); + gtk_signal_connect(GTK_OBJECT(streaming_save_browse), "clicked", GTK_SIGNAL_FUNC(streaming_save_browse_cb), NULL); + gtk_box_pack_start(GTK_BOX(streaming_save_hbox), streaming_save_browse, FALSE, FALSE, 0); + +#ifdef FLAC_ICECAST + streaming_cast_frame = gtk_frame_new(_("SHOUT/Icecast:")); + gtk_container_set_border_width(GTK_CONTAINER(streaming_cast_frame), 5); + gtk_box_pack_start(GTK_BOX(streaming_vbox), streaming_cast_frame, FALSE, FALSE, 0); + + streaming_cast_vbox = gtk_vbox_new(5, FALSE); + gtk_container_add(GTK_CONTAINER(streaming_cast_frame), streaming_cast_vbox); + + streaming_cast_title = gtk_check_button_new_with_label(_("Enable SHOUT/Icecast title streaming")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(streaming_cast_title), flac_cfg.stream.cast_title_streaming); + gtk_box_pack_start(GTK_BOX(streaming_cast_vbox), streaming_cast_title, FALSE, FALSE, 0); + + streaming_udp_title = gtk_check_button_new_with_label(_("Enable Icecast Metadata UDP Channel")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(streaming_udp_title), flac_cfg.stream.use_udp_channel); + gtk_box_pack_start(GTK_BOX(streaming_cast_vbox), streaming_udp_title, FALSE, FALSE, 0); +#endif + + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), streaming_vbox, gtk_label_new(_("Streaming"))); + + /* Buttons */ + + bbox = gtk_hbutton_box_new(); + gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END); + gtk_button_box_set_spacing(GTK_BUTTON_BOX(bbox), 5); + gtk_box_pack_start(GTK_BOX(vbox), bbox, FALSE, FALSE, 0); + + ok = gtk_button_new_with_label(_("Ok")); + gtk_signal_connect(GTK_OBJECT(ok), "clicked", GTK_SIGNAL_FUNC(flac_configurewin_ok), NULL); + GTK_WIDGET_SET_FLAGS(ok, GTK_CAN_DEFAULT); + gtk_box_pack_start(GTK_BOX(bbox), ok, TRUE, TRUE, 0); + gtk_widget_grab_default(ok); + + cancel = gtk_button_new_with_label(_("Cancel")); + gtk_signal_connect_object(GTK_OBJECT(cancel), "clicked", GTK_SIGNAL_FUNC(gtk_widget_destroy), GTK_OBJECT(flac_configurewin)); + GTK_WIDGET_SET_FLAGS(cancel, GTK_CAN_DEFAULT); + gtk_box_pack_start(GTK_BOX(bbox), cancel, TRUE, TRUE, 0); + + gtk_widget_show_all(flac_configurewin); +} + +void FLAC_XMMS__aboutbox(void) +{ + static GtkWidget *about_window; + + if (about_window) + gdk_window_raise(about_window->window); + + about_window = xmms_show_message( + _("About Flac Plugin"), + _("Flac Plugin by Josh Coalson\n" + "contributions by\n" + "......\n" + "......\n" + "and\n" + "Daisuke Shimamura\n" + "Visit http://flac.sourceforge.net/"), + _("Ok"), FALSE, NULL, NULL); + gtk_signal_connect(GTK_OBJECT(about_window), "destroy", + GTK_SIGNAL_FUNC(gtk_widget_destroyed), + &about_window); +} + +/* + * Get text of an Entry or a ComboBox + */ +static gchar *gtk_entry_get_text_1 (GtkWidget *widget) +{ + if (GTK_IS_COMBO(widget)) + { + return gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(widget)->entry)); + }else if (GTK_IS_ENTRY(widget)) + { + return gtk_entry_get_text(GTK_ENTRY(widget)); + }else + { + return NULL; + } +} diff --git a/flac/src/plugin_xmms/configure.h b/flac/src/plugin_xmms/configure.h new file mode 100644 index 0000000..d4c5b01 --- /dev/null +++ b/flac/src/plugin_xmms/configure.h @@ -0,0 +1,77 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * Based on mpg123 plugin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__PLUGIN_XMMS__CONFIGURE_H +#define FLAC__PLUGIN_XMMS__CONFIGURE_H + +#include + +typedef struct { + struct { + gboolean tag_override; + gchar *tag_format; + gboolean convert_char_set; + gchar *user_char_set; + } title; + + struct { + gint http_buffer_size; + gint http_prebuffer; + gboolean use_proxy; + gchar *proxy_host; + gint proxy_port; + gboolean proxy_use_auth; + gchar *proxy_user; + gchar *proxy_pass; + gboolean save_http_stream; + gchar *save_http_path; + gboolean cast_title_streaming; + gboolean use_udp_channel; + } stream; + + struct { + struct { + gboolean enable; + gboolean album_mode; + gint preamp; + gboolean hard_limit; + } replaygain; + struct { + struct { + gboolean dither_24_to_16; + } normal; + struct { + gboolean dither; + gint noise_shaping; /* value must be one of NoiseShaping enum, c.f. plugin_common/replaygain_synthesis.h */ + gint bps_out; + } replaygain; + } resolution; + } output; +} flac_config_t; + +extern flac_config_t flac_cfg; + +extern void FLAC_XMMS__configure(void); +extern void FLAC_XMMS__aboutbox(void); + +#endif + + + diff --git a/flac/src/plugin_xmms/fileinfo.c b/flac/src/plugin_xmms/fileinfo.c new file mode 100644 index 0000000..49f8266 --- /dev/null +++ b/flac/src/plugin_xmms/fileinfo.c @@ -0,0 +1,496 @@ +/* XMMS - Cross-platform multimedia player + * Copyright (C) 1998-2000 Peter Alm, Mikael Alm, Olle Hallnas, Thomas Nilsson and 4Front Technologies + * Copyright (C) 1999,2000 Hvard Kvlen + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for strlen() */ +#include +#include +#include +#include +#include + +#include "FLAC/metadata.h" +#include "charset.h" +#include "configure.h" +#include "plugin_common/replaygain.h" +#include "plugin_common/tags.h" +#include "locale_hack.h" + +static GtkWidget *window = NULL; +static GList *genre_list = NULL; +static GtkWidget *filename_entry, *tag_frame; +static GtkWidget *title_entry, *artist_entry, *album_entry, *date_entry, *tracknum_entry, *comment_entry; +static GtkWidget *replaygain_reference, *replaygain_track_gain, *replaygain_album_gain, *replaygain_track_peak, *replaygain_album_peak; +static GtkWidget *genre_combo; +static GtkWidget *flac_samplerate, *flac_channels, *flac_bits_per_sample, *flac_blocksize, *flac_filesize, *flac_samples, *flac_bitrate; + +static gchar *current_filename = NULL; +static FLAC__StreamMetadata *tags_ = NULL; + +static const gchar *vorbis_genres[] = +{ + N_("Blues"), N_("Classic Rock"), N_("Country"), N_("Dance"), + N_("Disco"), N_("Funk"), N_("Grunge"), N_("Hip-Hop"), + N_("Jazz"), N_("Metal"), N_("New Age"), N_("Oldies"), + N_("Other"), N_("Pop"), N_("R&B"), N_("Rap"), N_("Reggae"), + N_("Rock"), N_("Techno"), N_("Industrial"), N_("Alternative"), + N_("Ska"), N_("Death Metal"), N_("Pranks"), N_("Soundtrack"), + N_("Euro-Techno"), N_("Ambient"), N_("Trip-Hop"), N_("Vocal"), + N_("Jazz+Funk"), N_("Fusion"), N_("Trance"), N_("Classical"), + N_("Instrumental"), N_("Acid"), N_("House"), N_("Game"), + N_("Sound Clip"), N_("Gospel"), N_("Noise"), N_("Alt"), + N_("Bass"), N_("Soul"), N_("Punk"), N_("Space"), + N_("Meditative"), N_("Instrumental Pop"), + N_("Instrumental Rock"), N_("Ethnic"), N_("Gothic"), + N_("Darkwave"), N_("Techno-Industrial"), N_("Electronic"), + N_("Pop-Folk"), N_("Eurodance"), N_("Dream"), + N_("Southern Rock"), N_("Comedy"), N_("Cult"), + N_("Gangsta Rap"), N_("Top 40"), N_("Christian Rap"), + N_("Pop/Funk"), N_("Jungle"), N_("Native American"), + N_("Cabaret"), N_("New Wave"), N_("Psychedelic"), N_("Rave"), + N_("Showtunes"), N_("Trailer"), N_("Lo-Fi"), N_("Tribal"), + N_("Acid Punk"), N_("Acid Jazz"), N_("Polka"), N_("Retro"), + N_("Musical"), N_("Rock & Roll"), N_("Hard Rock"), N_("Folk"), + N_("Folk/Rock"), N_("National Folk"), N_("Swing"), + N_("Fast-Fusion"), N_("Bebob"), N_("Latin"), N_("Revival"), + N_("Celtic"), N_("Bluegrass"), N_("Avantgarde"), + N_("Gothic Rock"), N_("Progressive Rock"), + N_("Psychedelic Rock"), N_("Symphonic Rock"), N_("Slow Rock"), + N_("Big Band"), N_("Chorus"), N_("Easy Listening"), + N_("Acoustic"), N_("Humour"), N_("Speech"), N_("Chanson"), + N_("Opera"), N_("Chamber Music"), N_("Sonata"), N_("Symphony"), + N_("Booty Bass"), N_("Primus"), N_("Porn Groove"), + N_("Satire"), N_("Slow Jam"), N_("Club"), N_("Tango"), + N_("Samba"), N_("Folklore"), N_("Ballad"), N_("Power Ballad"), + N_("Rhythmic Soul"), N_("Freestyle"), N_("Duet"), + N_("Punk Rock"), N_("Drum Solo"), N_("A Cappella"), + N_("Euro-House"), N_("Dance Hall"), N_("Goa"), + N_("Drum & Bass"), N_("Club-House"), N_("Hardcore"), + N_("Terror"), N_("Indie"), N_("BritPop"), N_("Negerpunk"), + N_("Polsk Punk"), N_("Beat"), N_("Christian Gangsta Rap"), + N_("Heavy Metal"), N_("Black Metal"), N_("Crossover"), + N_("Contemporary Christian"), N_("Christian Rock"), + N_("Merengue"), N_("Salsa"), N_("Thrash Metal"), + N_("Anime"), N_("JPop"), N_("Synthpop") +}; + +static void label_set_text(GtkWidget * label, char *str, ...) +{ + va_list args; + gchar *tempstr; + + va_start(args, str); + tempstr = g_strdup_vprintf(str, args); + va_end(args); + + gtk_label_set_text(GTK_LABEL(label), tempstr); + g_free(tempstr); +} + +static void set_entry_tag(GtkEntry * entry, const char * utf8) +{ + if(utf8) { + if(flac_cfg.title.convert_char_set) { + char *text = convert_from_utf8_to_user(utf8); + gtk_entry_set_text(entry, text); + free(text); + } + else + gtk_entry_set_text(entry, utf8); + } + else + gtk_entry_set_text(entry, ""); +} + +static void get_entry_tag(GtkEntry * entry, const char *name) +{ + gchar *text; + char *utf8; + + text = gtk_entry_get_text(entry); + if (!text || strlen(text) == 0) + return; + if(flac_cfg.title.convert_char_set) + utf8 = convert_from_user_to_utf8(text); + else + utf8 = text; + + FLAC_plugin__tags_add_tag_utf8(tags_, name, utf8, /*separator=*/0); + + if(flac_cfg.title.convert_char_set) + free(utf8); +} + +static void show_tag(void) +{ + set_entry_tag(GTK_ENTRY(title_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "TITLE")); + set_entry_tag(GTK_ENTRY(artist_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "ARTIST")); + set_entry_tag(GTK_ENTRY(album_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "ALBUM")); + set_entry_tag(GTK_ENTRY(date_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "DATE")); + set_entry_tag(GTK_ENTRY(tracknum_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "TRACKNUMBER")); + set_entry_tag(GTK_ENTRY(comment_entry) , FLAC_plugin__tags_get_tag_utf8(tags_, "DESCRIPTION")); + set_entry_tag(GTK_ENTRY(GTK_COMBO(genre_combo)->entry), FLAC_plugin__tags_get_tag_utf8(tags_, "GENRE")); +} + +static void save_tag(GtkWidget * w, gpointer data) +{ + (void)w; + (void)data; + + FLAC_plugin__tags_delete_tag(tags_, "TITLE"); + FLAC_plugin__tags_delete_tag(tags_, "ARTIST"); + FLAC_plugin__tags_delete_tag(tags_, "ALBUM"); + FLAC_plugin__tags_delete_tag(tags_, "DATE"); + FLAC_plugin__tags_delete_tag(tags_, "TRACKNUMBER"); + FLAC_plugin__tags_delete_tag(tags_, "DESCRIPTION"); + FLAC_plugin__tags_delete_tag(tags_, "GENRE"); + + get_entry_tag(GTK_ENTRY(title_entry) , "TITLE"); + get_entry_tag(GTK_ENTRY(artist_entry) , "ARTIST"); + get_entry_tag(GTK_ENTRY(album_entry) , "ALBUM"); + get_entry_tag(GTK_ENTRY(date_entry) , "DATE"); + get_entry_tag(GTK_ENTRY(tracknum_entry) , "TRACKNUMBER"); + get_entry_tag(GTK_ENTRY(comment_entry) , "DESCRIPTION"); + get_entry_tag(GTK_ENTRY(GTK_COMBO(genre_combo)->entry), "GENRE"); + + FLAC_plugin__tags_set(current_filename, tags_); + gtk_widget_destroy(window); +} + +static void remove_tag(GtkWidget * w, gpointer data) +{ + (void)w; + (void)data; + + FLAC_plugin__tags_delete_tag(tags_, "TITLE"); + FLAC_plugin__tags_delete_tag(tags_, "ARTIST"); + FLAC_plugin__tags_delete_tag(tags_, "ALBUM"); + FLAC_plugin__tags_delete_tag(tags_, "DATE"); + FLAC_plugin__tags_delete_tag(tags_, "TRACKNUMBER"); + FLAC_plugin__tags_delete_tag(tags_, "DESCRIPTION"); + FLAC_plugin__tags_delete_tag(tags_, "GENRE"); + + FLAC_plugin__tags_set(current_filename, tags_); + gtk_widget_destroy(window); +} + +static void show_file_info(void) +{ + FLAC__StreamMetadata streaminfo; + struct stat _stat; + + gtk_label_set_text(GTK_LABEL(flac_samplerate), ""); + gtk_label_set_text(GTK_LABEL(flac_channels), ""); + gtk_label_set_text(GTK_LABEL(flac_bits_per_sample), ""); + gtk_label_set_text(GTK_LABEL(flac_blocksize), ""); + gtk_label_set_text(GTK_LABEL(flac_filesize), ""); + gtk_label_set_text(GTK_LABEL(flac_samples), ""); + gtk_label_set_text(GTK_LABEL(flac_bitrate), ""); + + if(!FLAC__metadata_get_streaminfo(current_filename, &streaminfo)) { + return; + } + + label_set_text(flac_samplerate, _("Samplerate: %d Hz"), streaminfo.data.stream_info.sample_rate); + label_set_text(flac_channels, _("Channels: %d"), streaminfo.data.stream_info.channels); + label_set_text(flac_bits_per_sample, _("Bits/Sample: %d"), streaminfo.data.stream_info.bits_per_sample); + if(streaminfo.data.stream_info.min_blocksize == streaminfo.data.stream_info.max_blocksize) + label_set_text(flac_blocksize, _("Blocksize: %d"), streaminfo.data.stream_info.min_blocksize); + else + label_set_text(flac_blocksize, _("Blocksize: variable\n min/max: %d/%d"), streaminfo.data.stream_info.min_blocksize, streaminfo.data.stream_info.max_blocksize); + + if (streaminfo.data.stream_info.total_samples) + label_set_text(flac_samples, _("Samples: %llu\nLength: %d:%.2d"), + streaminfo.data.stream_info.total_samples, + (int)(streaminfo.data.stream_info.total_samples / streaminfo.data.stream_info.sample_rate / 60), + (int)(streaminfo.data.stream_info.total_samples / streaminfo.data.stream_info.sample_rate % 60)); + + if(!stat(current_filename, &_stat) && S_ISREG(_stat.st_mode)) { +#if _FILE_OFFSET_BITS == 64 + label_set_text(flac_filesize, _("Filesize: %lld B"), _stat.st_size); +#else + label_set_text(flac_filesize, _("Filesize: %ld B"), _stat.st_size); +#endif + if (streaminfo.data.stream_info.total_samples) + label_set_text(flac_bitrate, _("Avg. bitrate: %.1f kb/s\nCompression ratio: %.1f%%"), + 8.0 * (float)(_stat.st_size) / (1000.0 * (float)streaminfo.data.stream_info.total_samples / (float)streaminfo.data.stream_info.sample_rate), + 100.0 * (float)_stat.st_size / (float)(streaminfo.data.stream_info.bits_per_sample / 8 * streaminfo.data.stream_info.channels * streaminfo.data.stream_info.total_samples)); + } +} + +static void show_replaygain(void) +{ + /* known limitation: If only one of gain and peak is set, neither will be shown. This is true for + * both track and album replaygain tags. Written so it will be easy to fix, with some trouble. */ + + gtk_label_set_text(GTK_LABEL(replaygain_reference), ""); + gtk_label_set_text(GTK_LABEL(replaygain_track_gain), ""); + gtk_label_set_text(GTK_LABEL(replaygain_album_gain), ""); + gtk_label_set_text(GTK_LABEL(replaygain_track_peak), ""); + gtk_label_set_text(GTK_LABEL(replaygain_album_peak), ""); + + double reference, track_gain, track_peak, album_gain, album_peak; + FLAC__bool reference_set, track_gain_set, track_peak_set, album_gain_set, album_peak_set; + + if(!FLAC_plugin__replaygain_get_from_file( + current_filename, + &reference, &reference_set, + &track_gain, &track_gain_set, + &album_gain, &album_gain_set, + &track_peak, &track_peak_set, + &album_peak, &album_peak_set + )) + return; + + if(reference_set) + label_set_text(replaygain_reference, _("ReplayGain Reference Loudness: %2.1f dB"), reference); + if(track_gain_set) + label_set_text(replaygain_track_gain, _("ReplayGain Track Gain: %+2.2f dB"), track_gain); + if(album_gain_set) + label_set_text(replaygain_album_gain, _("ReplayGain Album Gain: %+2.2f dB"), album_gain); + if(track_peak_set) + label_set_text(replaygain_track_peak, _("ReplayGain Track Peak: %1.8f"), track_peak); + if(album_peak_set) + label_set_text(replaygain_album_peak, _("ReplayGain Album Peak: %1.8f"), album_peak); +} + +void FLAC_XMMS__file_info_box(char *filename) +{ + unsigned i; + gchar *title; + + if (!window) + { + GtkWidget *vbox, *hbox, *left_vbox, *table; + GtkWidget *flac_frame, *flac_box; + GtkWidget *label, *filename_hbox; + GtkWidget *bbox, *save, *remove, *cancel; + + window = gtk_window_new(GTK_WINDOW_DIALOG); + gtk_window_set_policy(GTK_WINDOW(window), FALSE, FALSE, FALSE); + gtk_signal_connect(GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(gtk_widget_destroyed), &window); + gtk_container_set_border_width(GTK_CONTAINER(window), 10); + + vbox = gtk_vbox_new(FALSE, 10); + gtk_container_add(GTK_CONTAINER(window), vbox); + + filename_hbox = gtk_hbox_new(FALSE, 5); + gtk_box_pack_start(GTK_BOX(vbox), filename_hbox, FALSE, TRUE, 0); + + label = gtk_label_new(_("Filename:")); + gtk_box_pack_start(GTK_BOX(filename_hbox), label, FALSE, TRUE, 0); + filename_entry = gtk_entry_new(); + gtk_editable_set_editable(GTK_EDITABLE(filename_entry), FALSE); + gtk_box_pack_start(GTK_BOX(filename_hbox), filename_entry, TRUE, TRUE, 0); + + hbox = gtk_hbox_new(FALSE, 10); + gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0); + + left_vbox = gtk_vbox_new(FALSE, 10); + gtk_box_pack_start(GTK_BOX(hbox), left_vbox, FALSE, FALSE, 0); + + tag_frame = gtk_frame_new(_("Tag:")); + gtk_box_pack_start(GTK_BOX(left_vbox), tag_frame, FALSE, FALSE, 0); + + table = gtk_table_new(5, 5, FALSE); + gtk_container_set_border_width(GTK_CONTAINER(table), 5); + gtk_container_add(GTK_CONTAINER(tag_frame), table); + + label = gtk_label_new(_("Title:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, GTK_FILL, 5, 5); + + title_entry = gtk_entry_new(); + gtk_table_attach(GTK_TABLE(table), title_entry, 1, 4, 0, 1, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Artist:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, GTK_FILL, GTK_FILL, 5, 5); + + artist_entry = gtk_entry_new(); + gtk_table_attach(GTK_TABLE(table), artist_entry, 1, 4, 1, 2, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Album:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, GTK_FILL, GTK_FILL, 5, 5); + + album_entry = gtk_entry_new(); + gtk_table_attach(GTK_TABLE(table), album_entry, 1, 4, 2, 3, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Comment:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, GTK_FILL, GTK_FILL, 5, 5); + + comment_entry = gtk_entry_new(); + gtk_table_attach(GTK_TABLE(table), comment_entry, 1, 4, 3, 4, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Date:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 4, 5, GTK_FILL, GTK_FILL, 5, 5); + + date_entry = gtk_entry_new(); + gtk_widget_set_usize(date_entry, 40, -1); + gtk_table_attach(GTK_TABLE(table), date_entry, 1, 2, 4, 5, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Track number:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 4, 5, GTK_FILL, GTK_FILL, 5, 5); + + tracknum_entry = gtk_entry_new(); + gtk_widget_set_usize(tracknum_entry, 40, -1); + gtk_table_attach(GTK_TABLE(table), tracknum_entry, 3, 4, 4, 5, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + label = gtk_label_new(_("Genre:")); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 5, 6, GTK_FILL, GTK_FILL, 5, 5); + + genre_combo = gtk_combo_new(); + gtk_entry_set_editable(GTK_ENTRY(GTK_COMBO(genre_combo)->entry), TRUE); + + if (!genre_list) + { + for (i = 0; i < sizeof(vorbis_genres) / sizeof(*vorbis_genres) ; i++) + genre_list = g_list_prepend(genre_list, (char *)vorbis_genres[i]); + genre_list = g_list_prepend(genre_list, ""); + genre_list = g_list_sort(genre_list, (GCompareFunc)g_strcasecmp); + } + gtk_combo_set_popdown_strings(GTK_COMBO(genre_combo), genre_list); + + gtk_table_attach(GTK_TABLE(table), genre_combo, 1, 4, 5, 6, GTK_FILL | GTK_EXPAND | GTK_SHRINK, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 5); + + bbox = gtk_hbutton_box_new(); + gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END); + gtk_button_box_set_spacing(GTK_BUTTON_BOX(bbox), 5); + gtk_box_pack_start(GTK_BOX(left_vbox), bbox, FALSE, FALSE, 0); + + save = gtk_button_new_with_label(_("Save")); + gtk_signal_connect(GTK_OBJECT(save), "clicked", GTK_SIGNAL_FUNC(save_tag), NULL); + GTK_WIDGET_SET_FLAGS(save, GTK_CAN_DEFAULT); + gtk_box_pack_start(GTK_BOX(bbox), save, TRUE, TRUE, 0); + gtk_widget_grab_default(save); + + remove= gtk_button_new_with_label(_("Remove Tag")); + gtk_signal_connect(GTK_OBJECT(remove), "clicked", GTK_SIGNAL_FUNC(remove_tag), NULL); + GTK_WIDGET_SET_FLAGS(remove, GTK_CAN_DEFAULT); + gtk_box_pack_start(GTK_BOX(bbox), remove, TRUE, TRUE, 0); + + cancel = gtk_button_new_with_label(_("Cancel")); + gtk_signal_connect_object(GTK_OBJECT(cancel), "clicked", GTK_SIGNAL_FUNC(gtk_widget_destroy), GTK_OBJECT(window)); + GTK_WIDGET_SET_FLAGS(cancel, GTK_CAN_DEFAULT); + gtk_box_pack_start(GTK_BOX(bbox), cancel, TRUE, TRUE, 0); + + flac_frame = gtk_frame_new(_("FLAC Info:")); + gtk_box_pack_start(GTK_BOX(hbox), flac_frame, FALSE, FALSE, 0); + + flac_box = gtk_vbox_new(FALSE, 5); + gtk_container_add(GTK_CONTAINER(flac_frame), flac_box); + gtk_container_set_border_width(GTK_CONTAINER(flac_box), 10); + gtk_box_set_spacing(GTK_BOX(flac_box), 0); + + flac_samplerate = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_samplerate), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_samplerate), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_samplerate, FALSE, FALSE, 0); + + flac_channels = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_channels), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_channels), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_channels, FALSE, FALSE, 0); + + flac_bits_per_sample = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_bits_per_sample), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_bits_per_sample), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_bits_per_sample, FALSE, FALSE, 0); + + flac_blocksize = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_blocksize), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_blocksize), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_blocksize, FALSE, FALSE, 0); + + flac_filesize = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_filesize), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_filesize), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_filesize, FALSE, FALSE, 0); + + flac_samples = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_samples), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_samples), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_samples, FALSE, FALSE, 0); + + flac_bitrate = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(flac_bitrate), 0, 0); + gtk_label_set_justify(GTK_LABEL(flac_bitrate), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), flac_bitrate, FALSE, FALSE, 0); + + replaygain_reference = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(replaygain_reference), 0, 0); + gtk_label_set_justify(GTK_LABEL(replaygain_reference), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), replaygain_reference, FALSE, FALSE, 0); + + replaygain_track_gain = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(replaygain_track_gain), 0, 0); + gtk_label_set_justify(GTK_LABEL(replaygain_track_gain), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), replaygain_track_gain, FALSE, FALSE, 0); + + replaygain_album_gain = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(replaygain_album_gain), 0, 0); + gtk_label_set_justify(GTK_LABEL(replaygain_album_gain), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), replaygain_album_gain, FALSE, FALSE, 0); + + replaygain_track_peak = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(replaygain_track_peak), 0, 0); + gtk_label_set_justify(GTK_LABEL(replaygain_track_peak), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), replaygain_track_peak, FALSE, FALSE, 0); + + replaygain_album_peak = gtk_label_new(""); + gtk_misc_set_alignment(GTK_MISC(replaygain_album_peak), 0, 0); + gtk_label_set_justify(GTK_LABEL(replaygain_album_peak), GTK_JUSTIFY_LEFT); + gtk_box_pack_start(GTK_BOX(flac_box), replaygain_album_peak, FALSE, FALSE, 0); + + gtk_widget_show_all(window); + } + + if(current_filename) + g_free(current_filename); + if(!(current_filename = g_strdup(filename))) + return; + + title = g_strdup_printf(_("File Info - %s"), g_basename(filename)); + gtk_window_set_title(GTK_WINDOW(window), title); + g_free(title); + + gtk_entry_set_text(GTK_ENTRY(filename_entry), filename); + gtk_editable_set_position(GTK_EDITABLE(filename_entry), -1); + + if(tags_) + FLAC_plugin__tags_destroy(&tags_); + + FLAC_plugin__tags_get(current_filename, &tags_); + + show_tag(); + show_file_info(); + show_replaygain(); + + gtk_widget_set_sensitive(tag_frame, TRUE); +} diff --git a/flac/src/plugin_xmms/http.c b/flac/src/plugin_xmms/http.c new file mode 100644 index 0000000..62bbd7b --- /dev/null +++ b/flac/src/plugin_xmms/http.c @@ -0,0 +1,899 @@ +/* XMMS - Cross-platform multimedia player + * Copyright (C) 1998-2000 Peter Alm, Mikael Alm, Olle Hallnas, Thomas Nilsson and 4Front Technologies + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +/* modified for FLAC support by Steven Richman (2003) */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include "FLAC/format.h" +#include "configure.h" +#include "locale_hack.h" +#include "plugin.h" + +/* on FreeBSD we get socklen_t from */ +#if (!defined HAVE_SOCKLEN_T) && !defined(__FreeBSD__) +typedef unsigned int socklen_t; +#endif + +#define min(x,y) ((x)<(y)?(x):(y)) +#define min3(x,y,z) (min(x,y)<(z)?min(x,y):(z)) +#define min4(x,y,z,w) (min3(x,y,z)<(w)?min3(x,y,z):(w)) + +static gchar *icy_name = NULL; +static gint icy_metaint = 0; + +extern InputPlugin flac_ip; + +#undef DEBUG_UDP + +/* Static udp channel functions */ +static int udp_establish_listener (gint *sock); +static int udp_check_for_data(gint sock); + +static char *flac_http_get_title(char *url); + +static gboolean prebuffering, going, eof = FALSE; +static gint sock, rd_index, wr_index, buffer_length, prebuffer_length; +static guint64 buffer_read = 0; +static gchar *buffer; +static guint64 offset; +static pthread_t thread; +static GtkWidget *error_dialog = NULL; + +static FILE *output_file = NULL; + +#define BASE64_LENGTH(len) (4 * (((len) + 2) / 3)) + +/* Encode the string S of length LENGTH to base64 format and place it + to STORE. STORE will be 0-terminated, and must point to a writable + buffer of at least 1+BASE64_LENGTH(length) bytes. */ +static void base64_encode (const gchar *s, gchar *store, gint length) +{ + /* Conversion table. */ + static gchar tbl[64] = { + 'A','B','C','D','E','F','G','H', + 'I','J','K','L','M','N','O','P', + 'Q','R','S','T','U','V','W','X', + 'Y','Z','a','b','c','d','e','f', + 'g','h','i','j','k','l','m','n', + 'o','p','q','r','s','t','u','v', + 'w','x','y','z','0','1','2','3', + '4','5','6','7','8','9','+','/' + }; + gint i; + guchar *p = (guchar *)store; + + /* Transform the 3x8 bits to 4x6 bits, as required by base64. */ + for (i = 0; i < length; i += 3) + { + *p++ = tbl[s[0] >> 2]; + *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)]; + *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)]; + *p++ = tbl[s[2] & 0x3f]; + s += 3; + } + /* Pad the result if necessary... */ + if (i == length + 1) + *(p - 1) = '='; + else if (i == length + 2) + *(p - 1) = *(p - 2) = '='; + /* ...and zero-terminate it. */ + *p = '\0'; +} + +/* Create the authentication header contents for the `Basic' scheme. + This is done by encoding the string `USER:PASS' in base64 and + prepending `HEADER: Basic ' to it. */ +static gchar *basic_authentication_encode (const gchar *user, const gchar *passwd, const gchar *header) +{ + gchar *t1, *t2, *res; + gint len1 = strlen (user) + 1 + strlen (passwd); + gint len2 = BASE64_LENGTH (len1); + + t1 = g_strdup_printf("%s:%s", user, passwd); + t2 = g_malloc0(len2 + 1); + base64_encode (t1, t2, len1); + res = g_strdup_printf("%s: Basic %s\r\n", header, t2); + g_free(t2); + g_free(t1); + + return res; +} + +static void parse_url(const gchar * url, gchar ** user, gchar ** pass, gchar ** host, int *port, gchar ** filename) +{ + gchar *h, *p, *pt, *f, *temp, *ptr; + + temp = g_strdup(url); + ptr = temp; + + if (!strncasecmp("http://", ptr, 7)) + ptr += 7; + h = strchr(ptr, '@'); + f = strchr(ptr, '/'); + if (h != NULL && (!f || h < f)) + { + *h = '\0'; + p = strchr(ptr, ':'); + if (p != NULL && p < h) + { + *p = '\0'; + p++; + *pass = g_strdup(p); + } + else + *pass = NULL; + *user = g_strdup(ptr); + h++; + ptr = h; + } + else + { + *user = NULL; + *pass = NULL; + h = ptr; + } + pt = strchr(ptr, ':'); + if (pt != NULL && (f == NULL || pt < f)) + { + *pt = '\0'; + *port = atoi(pt + 1); + } + else + { + if (f) + *f = '\0'; + *port = 80; + } + *host = g_strdup(h); + + if (f) + *filename = g_strdup(f + 1); + else + *filename = NULL; + g_free(temp); +} + +void flac_http_close(void) +{ + going = FALSE; + + pthread_join(thread, NULL); + g_free(icy_name); + icy_name = NULL; +} + + +static gint http_used(void) +{ + if (wr_index >= rd_index) + return wr_index - rd_index; + return buffer_length - (rd_index - wr_index); +} + +static gint http_free(void) +{ + if (rd_index > wr_index) + return (rd_index - wr_index) - 1; + return (buffer_length - (wr_index - rd_index)) - 1; +} + +static void http_wait_for_data(gint bytes) +{ + while ((prebuffering || http_used() < bytes) && !eof && going) + xmms_usleep(10000); +} + +static void show_error_message(gchar *error) +{ + if(!error_dialog) + { + GDK_THREADS_ENTER(); + error_dialog = xmms_show_message(_("Error"), error, _("Ok"), FALSE, + NULL, NULL); + gtk_signal_connect(GTK_OBJECT(error_dialog), + "destroy", + GTK_SIGNAL_FUNC(gtk_widget_destroyed), + &error_dialog); + GDK_THREADS_LEAVE(); + } +} + +int flac_http_read(gpointer data, gint length) +{ + gint len, cnt, off = 0, meta_len, meta_off = 0, i; + gchar *meta_data, **tags, *temp, *title; + if (length > buffer_length) { + length = buffer_length; + } + + http_wait_for_data(length); + + if (!going) + return 0; + len = min(http_used(), length); + + while (len && http_used()) + { + if ((flac_cfg.stream.cast_title_streaming) && (icy_metaint > 0) && (buffer_read % icy_metaint) == 0 && (buffer_read > 0)) + { + meta_len = *((guchar *) buffer + rd_index) * 16; + rd_index = (rd_index + 1) % buffer_length; + if (meta_len > 0) + { + http_wait_for_data(meta_len); + meta_data = g_malloc0(meta_len); + if (http_used() >= meta_len) + { + while (meta_len) + { + cnt = min(meta_len, buffer_length - rd_index); + memcpy(meta_data + meta_off, buffer + rd_index, cnt); + rd_index = (rd_index + cnt) % buffer_length; + meta_len -= cnt; + meta_off += cnt; + } + tags = g_strsplit(meta_data, "';", 0); + + for (i = 0; tags[i]; i++) + { + if (!strncasecmp(tags[i], "StreamTitle=", 12)) + { + temp = g_strdup(tags[i] + 13); + title = g_strdup_printf("%s (%s)", temp, icy_name); + set_track_info(title, -1); + g_free(title); + g_free(temp); + } + + } + g_strfreev(tags); + + } + g_free(meta_data); + } + if (!http_used()) + http_wait_for_data(length - off); + cnt = min3(len, buffer_length - rd_index, http_used()); + } + else if ((icy_metaint > 0) && (flac_cfg.stream.cast_title_streaming)) + cnt = min4(len, buffer_length - rd_index, http_used(), icy_metaint - (gint) (buffer_read % icy_metaint)); + else + cnt = min3(len, buffer_length - rd_index, http_used()); + if (output_file) + fwrite(buffer + rd_index, 1, cnt, output_file); + + memcpy((gchar *)data + off, buffer + rd_index, cnt); + rd_index = (rd_index + cnt) % buffer_length; + buffer_read += cnt; + len -= cnt; + off += cnt; + } + if (!off) { + fprintf(stderr, "returning zero\n"); + } + return off; +} + +static gboolean http_check_for_data(void) +{ + + fd_set set; + struct timeval tv; + gint ret; + + tv.tv_sec = 0; + tv.tv_usec = 20000; + FD_ZERO(&set); + FD_SET(sock, &set); + ret = select(sock + 1, &set, NULL, NULL, &tv); + if (ret > 0) + return TRUE; + return FALSE; +} + +gint flac_http_read_line(gchar * buf, gint size) +{ + gint i = 0; + + while (going && i < size - 1) + { + if (http_check_for_data()) + { + if (read(sock, buf + i, 1) <= 0) + return -1; + if (buf[i] == '\n') + break; + if (buf[i] != '\r') + i++; + } + } + if (!going) + return -1; + buf[i] = '\0'; + return i; +} + +/* returns the file descriptor of the socket, or -1 on error */ +static int http_connect (gchar *url_, gboolean head, guint64 offset) +{ + gchar line[1024], *user, *pass, *host, *filename, + *status, *url, *temp, *file; + gchar *chost; + gint cnt, error, port, cport; + socklen_t err_len; + gboolean redirect; + int udp_sock = 0; + fd_set set; + struct hostent *hp; + struct sockaddr_in address; + struct timeval tv; + + url = g_strdup (url_); + + do + { + redirect=FALSE; + + g_strstrip(url); + + parse_url(url, &user, &pass, &host, &port, &filename); + + if ((!filename || !*filename) && url[strlen(url) - 1] != '/') + temp = g_strconcat(url, "/", NULL); + else + temp = g_strdup(url); + g_free(url); + url = temp; + + chost = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_host : host; + cport = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_port : port; + + sock = socket(AF_INET, SOCK_STREAM, 0); + fcntl(sock, F_SETFL, O_NONBLOCK); + address.sin_family = AF_INET; + + status = g_strdup_printf(_("LOOKING UP %s"), chost); + flac_ip.set_info_text(status); + g_free(status); + + if (!(hp = gethostbyname(chost))) + { + status = g_strdup_printf(_("Couldn't look up host %s"), chost); + show_error_message(status); + g_free(status); + + flac_ip.set_info_text(NULL); + eof = TRUE; + } + + if (!eof) + { + memcpy(&address.sin_addr.s_addr, *(hp->h_addr_list), sizeof (address.sin_addr.s_addr)); + address.sin_port = (gint) g_htons(cport); + + status = g_strdup_printf(_("CONNECTING TO %s:%d"), chost, cport); + flac_ip.set_info_text(status); + g_free(status); + if (connect(sock, (struct sockaddr *) &address, sizeof (struct sockaddr_in)) == -1) + { + if (errno != EINPROGRESS) + { + status = g_strdup_printf(_("Couldn't connect to host %s"), chost); + show_error_message(status); + g_free(status); + + flac_ip.set_info_text(NULL); + eof = TRUE; + } + } + while (going) + { + tv.tv_sec = 0; + tv.tv_usec = 10000; + FD_ZERO(&set); + FD_SET(sock, &set); + if (select(sock + 1, NULL, &set, NULL, &tv) > 0) + { + err_len = sizeof (error); + getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &err_len); + if (error) + { + status = g_strdup_printf(_("Couldn't connect to host %s"), + chost); + show_error_message(status); + g_free(status); + + flac_ip.set_info_text(NULL); + eof = TRUE; + + } + break; + } + } + if (!eof) + { + gchar *auth = NULL, *proxy_auth = NULL; + gchar udpspace[30]; + int udp_port; + + if (flac_cfg.stream.use_udp_channel) + { + udp_port = udp_establish_listener (&udp_sock); + if (udp_port > 0) + sprintf (udpspace, "x-audiocast-udpport: %d\r\n", udp_port); + else + udp_sock = 0; + } + + if(user && pass) + auth = basic_authentication_encode(user, pass, "Authorization"); + + if (flac_cfg.stream.use_proxy) + { + file = g_strdup(url); + if(flac_cfg.stream.proxy_use_auth && flac_cfg.stream.proxy_user && flac_cfg.stream.proxy_pass) + { + proxy_auth = basic_authentication_encode(flac_cfg.stream.proxy_user, + flac_cfg.stream.proxy_pass, + "Proxy-Authorization"); + } + } + else + file = g_strconcat("/", filename, NULL); + + temp = g_strdup_printf("GET %s HTTP/1.0\r\n" + "Host: %s\r\n" + "User-Agent: %s/%s\r\n" + "%s%s%s%s", + file, host, "Reference FLAC Player", FLAC__VERSION_STRING, + proxy_auth ? proxy_auth : "", auth ? auth : "", + flac_cfg.stream.cast_title_streaming ? "Icy-MetaData:1\r\n" : "", + flac_cfg.stream.use_udp_channel ? udpspace : ""); + if (offset && !head) { + gchar *temp_dead = temp; + temp = g_strdup_printf ("%sRange: %llu-\r\n", temp, offset); + fprintf (stderr, "%s", temp); + g_free (temp_dead); + } + + g_free(file); + if(proxy_auth) + g_free(proxy_auth); + if(auth) + g_free(auth); + write(sock, temp, strlen(temp)); + write(sock, "\r\n", 2); + g_free(temp); + flac_ip.set_info_text(_("CONNECTED: WAITING FOR REPLY")); + while (going && !eof) + { + if (http_check_for_data()) + { + if (flac_http_read_line(line, 1024)) + { + status = strchr(line, ' '); + if (status) + { + if (status[1] == '2') + break; + else if(status[1] == '3' && status[2] == '0' && status[3] == '2') + { + while(going) + { + if(http_check_for_data()) + { + if((cnt = flac_http_read_line(line, 1024)) != -1) + { + if(!cnt) + break; + if(!strncmp(line, "Location:", 9)) + { + g_free(url); + url = g_strdup(line+10); + } + } + else + { + eof=TRUE; + flac_ip.set_info_text(NULL); + break; + } + } + } + redirect=TRUE; + break; + } + else + { + status = g_strdup_printf(_("Couldn't connect to host %s\nServer reported: %s"), chost, status); + show_error_message(status); + g_free(status); + break; + } + } + } + else + { + eof = TRUE; + flac_ip.set_info_text(NULL); + } + } + } + + while (going && !redirect) + { + if (http_check_for_data()) + { + if ((cnt = flac_http_read_line(line, 1024)) != -1) + { + if (!cnt) + break; + if (!strncmp(line, "icy-name:", 9)) + icy_name = g_strdup(line + 9); + else if (!strncmp(line, "x-audiocast-name:", 17)) + icy_name = g_strdup(line + 17); + if (!strncmp(line, "icy-metaint:", 12)) + icy_metaint = atoi(line + 12); + if (!strncmp(line, "x-audiocast-udpport:", 20)) { +#ifdef DEBUG_UDP + fprintf (stderr, "Server wants udp messages on port %d\n", atoi (line + 20)); +#endif + /*udp_serverport = atoi (line + 20);*/ + } + + } + else + { + eof = TRUE; + flac_ip.set_info_text(NULL); + break; + } + } + } + } + } + + if(redirect) + { + if (output_file) + { + fclose(output_file); + output_file = NULL; + } + close(sock); + } + + g_free(user); + g_free(pass); + g_free(host); + g_free(filename); + } while(redirect); + + g_free(url); + return eof ? -1 : sock; +} + +static void *http_buffer_loop(void *arg) +{ + gchar *status, *url, *temp, *file; + gint cnt, written; + int udp_sock = 0; + + url = (gchar *) arg; + sock = http_connect (url, false, offset); + + if (sock >= 0 && flac_cfg.stream.save_http_stream) { + gchar *output_name; + file = flac_http_get_title(url); + output_name = file; + if (!strncasecmp(output_name, "http://", 7)) + output_name += 7; + temp = strrchr(output_name, '.'); + if (temp && (!strcasecmp(temp, ".fla") || !strcasecmp(temp, ".flac"))) + *temp = '\0'; + + while ((temp = strchr(output_name, '/'))) + *temp = '_'; + output_name = g_strdup_printf("%s/%s.flac", flac_cfg.stream.save_http_path, output_name); + + g_free(file); + + output_file = fopen(output_name, "wb"); + g_free(output_name); + } + + while (going) + { + + if (!http_used() && !flac_ip.output->buffer_playing()) + prebuffering = TRUE; + if (http_free() > 0 && !eof) + { + if (http_check_for_data()) + { + cnt = min(http_free(), buffer_length - wr_index); + if (cnt > 1024) + cnt = 1024; + written = read(sock, buffer + wr_index, cnt); + if (written <= 0) + { + eof = TRUE; + if (prebuffering) + { + prebuffering = FALSE; + + flac_ip.set_info_text(NULL); + } + + } + else + wr_index = (wr_index + written) % buffer_length; + } + + if (prebuffering) + { + if (http_used() > prebuffer_length) + { + prebuffering = FALSE; + flac_ip.set_info_text(NULL); + } + else + { + status = g_strdup_printf(_("PRE-BUFFERING: %dKB/%dKB"), http_used() / 1024, prebuffer_length / 1024); + flac_ip.set_info_text(status); + g_free(status); + } + + } + } + else + xmms_usleep(10000); + + if (flac_cfg.stream.use_udp_channel && udp_sock != 0) + if (udp_check_for_data(udp_sock) < 0) + { + close(udp_sock); + udp_sock = 0; + } + } + if (output_file) + { + fclose(output_file); + output_file = NULL; + } + if (sock >= 0) { + close(sock); + } + if (udp_sock != 0) + close(udp_sock); + + g_free(buffer); + g_free(url); + + pthread_exit(NULL); + return NULL; /* avoid compiler warning */ +} + +int flac_http_open(const gchar * _url, guint64 _offset) +{ + gchar *url; + + url = g_strdup(_url); + + rd_index = 0; + wr_index = 0; + buffer_length = flac_cfg.stream.http_buffer_size * 1024; + prebuffer_length = (buffer_length * flac_cfg.stream.http_prebuffer) / 100; + buffer_read = 0; + icy_metaint = 0; + prebuffering = TRUE; + going = TRUE; + eof = FALSE; + buffer = g_malloc(buffer_length); + offset = _offset; + + pthread_create(&thread, NULL, http_buffer_loop, url); + + return 0; +} + +char *flac_http_get_title(char *url) +{ + if (icy_name) + return g_strdup(icy_name); + if (g_basename(url) && strlen(g_basename(url)) > 0) + return g_strdup(g_basename(url)); + return g_strdup(url); +} + +/* Start UDP Channel specific stuff */ + +/* Find a good local udp port and bind udp_sock to it, return the port */ +static int udp_establish_listener(int *sock) +{ + struct sockaddr_in sin; + socklen_t sinlen = sizeof (struct sockaddr_in); + +#ifdef DEBUG_UDP + fprintf (stderr,"Establishing udp listener\n"); +#endif + + if ((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) + { + g_log(NULL, G_LOG_LEVEL_CRITICAL, + "udp_establish_listener(): unable to create socket"); + return -1; + } + + memset(&sin, 0, sinlen); + sin.sin_family = AF_INET; + sin.sin_addr.s_addr = g_htonl(INADDR_ANY); + + if (bind(*sock, (struct sockaddr *)&sin, sinlen) < 0) + { + g_log(NULL, G_LOG_LEVEL_CRITICAL, + "udp_establish_listener(): Failed to bind socket to localhost: %s", strerror(errno)); + close(*sock); + return -1; + } + if (fcntl(*sock, F_SETFL, O_NONBLOCK) < 0) + { + g_log(NULL, G_LOG_LEVEL_CRITICAL, + "udp_establish_listener(): Failed to set flags: %s", strerror(errno)); + close(*sock); + return -1; + } + + memset(&sin, 0, sinlen); + if (getsockname(*sock, (struct sockaddr *)&sin, &sinlen) < 0) + { + g_log(NULL, G_LOG_LEVEL_CRITICAL, + "udp_establish_listener(): Failed to retrieve socket info: %s", strerror(errno)); + close(*sock); + return -1; + } + +#ifdef DEBUG_UDP + fprintf (stderr,"Listening on local %s:%d\n", inet_ntoa(sin.sin_addr), g_ntohs(sin.sin_port)); +#endif + + return g_ntohs(sin.sin_port); +} + +static int udp_check_for_data(int sock) +{ + char buf[1025], **lines; + char *valptr; + gchar *title; + gint len, i; + struct sockaddr_in from; + socklen_t fromlen; + + fromlen = sizeof(struct sockaddr_in); + + if ((len = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen)) < 0) + { + if (errno != EAGAIN) + { + g_log(NULL, G_LOG_LEVEL_CRITICAL, + "udp_read_data(): Error reading from socket: %s", strerror(errno)); + return -1; + } + return 0; + } + buf[len] = '\0'; +#ifdef DEBUG_UDP + fprintf (stderr,"Received: [%s]\n", buf); +#endif + lines = g_strsplit(buf, "\n", 0); + if (!lines) + return 0; + + for (i = 0; lines[i]; i++) + { + while ((lines[i][strlen(lines[i]) - 1] == '\n') || + (lines[i][strlen(lines[i]) - 1] == '\r')) + lines[i][strlen(lines[i]) - 1] = '\0'; + + valptr = strchr(lines[i], ':'); + + if (!valptr) + continue; + else + valptr++; + + g_strstrip(valptr); + if (!strlen(valptr)) + continue; + + if (strstr(lines[i], "x-audiocast-streamtitle") != NULL) + { + title = g_strdup_printf ("%s (%s)", valptr, icy_name); + if (going) + set_track_info(title, -1); + g_free (title); + } + +#if 0 + else if (strstr(lines[i], "x-audiocast-streamlength") != NULL) + { + if (atoi(valptr) != -1) + set_track_info(NULL, atoi(valptr)); + } +#endif + + else if (strstr(lines[i], "x-audiocast-streammsg") != NULL) + { + /* set_track_info(title, -1); */ +/* xmms_show_message(_("Message"), valptr, _("Ok"), */ +/* FALSE, NULL, NULL); */ + g_message("Stream_message: %s", valptr); + } + +#if 0 + /* Use this to direct your webbrowser.. yeah right.. */ + else if (strstr(lines[i], "x-audiocast-streamurl") != NULL) + { + if (lasturl && g_strcmp (valptr, lasturl)) + { + c_message (stderr, "Song URL: %s\n", valptr); + g_free (lasturl); + lasturl = g_strdup (valptr); + } + } +#endif + else if (strstr(lines[i], "x-audiocast-udpseqnr:") != NULL) + { + gchar obuf[60]; + sprintf(obuf, "x-audiocast-ack: %ld \r\n", atol(valptr)); + if (sendto(sock, obuf, strlen(obuf), 0, (struct sockaddr *) &from, fromlen) < 0) + { + g_log(NULL, G_LOG_LEVEL_WARNING, + "udp_check_for_data(): Unable to send ack to server: %s", strerror(errno)); + } +#ifdef DEBUG_UDP + else + fprintf(stderr,"Sent ack: %s", obuf); + fprintf (stderr,"Remote: %s:%d\n", inet_ntoa(from.sin_addr), g_ntohs(from.sin_port)); +#endif + } + } + g_strfreev(lines); + return 0; +} diff --git a/flac/src/plugin_xmms/http.h b/flac/src/plugin_xmms/http.h new file mode 100644 index 0000000..1ad6d24 --- /dev/null +++ b/flac/src/plugin_xmms/http.h @@ -0,0 +1,26 @@ +/* libxmms-flac - XMMS FLAC input plugin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__PLUGIN_XMMS__HTTP_H +#define FLAC__PLUGIN_XMMS__HTTP_H + +extern int flac_http_open(const gchar * url, guint64 offset); +extern void flac_http_close(void); +extern int flac_http_read(gpointer data, gint length); + + +#endif diff --git a/flac/src/plugin_xmms/locale_hack.h b/flac/src/plugin_xmms/locale_hack.h new file mode 100644 index 0000000..177d8bb --- /dev/null +++ b/flac/src/plugin_xmms/locale_hack.h @@ -0,0 +1,55 @@ +/* plugin_common - Routines common to several plugins + * Copyright (C) 2002,2003,2004,2006,2007,2008 Josh Coalson + * + * Based on: + * locale.h - 2000/05/05 13:10 Jerome Couderc + * EasyTAG - Tag editor for MP3 and OGG files + * Copyright (C) 1999-2001 H蛆ard Kv虱en + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +/* + * Gettext support for EasyTAG + */ + + +#ifndef FLAC__PLUGIN_COMMON__LOCALE_HACK_H +#define FLAC__PLUGIN_COMMON__LOCALE_HACK_H + +#include + +/* + * Standard gettext macros. + */ +#ifdef ENABLE_NLS +# include +# define _(String) gettext (String) +# ifdef gettext_noop +# define N_(String) gettext_noop (String) +# else +# define N_(String) (String) +# endif +#else +# define textdomain(String) (String) +# define gettext(String) (String) +# define dgettext(Domain,Message) (Message) +# define dcgettext(Domain,Message,Type) (Message) +# define bindtextdomain(Domain,Directory) (Domain) +# define _(String) (String) +# define N_(String) (String) +#endif + + +#endif diff --git a/flac/src/plugin_xmms/plugin.c b/flac/src/plugin_xmms/plugin.c new file mode 100644 index 0000000..af92fe7 --- /dev/null +++ b/flac/src/plugin_xmms/plugin.c @@ -0,0 +1,684 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#ifdef HAVE_LANGINFO_CODESET +#include +#endif + +#include "FLAC/all.h" +#include "plugin_common/all.h" +#include "share/grabbag.h" +#include "share/replaygain_synthesis.h" +#include "configure.h" +#include "charset.h" +#include "http.h" +#include "tag.h" + +#ifdef min +#undef min +#endif +#define min(x,y) ((x)<(y)?(x):(y)) + +extern void FLAC_XMMS__file_info_box(char *filename); + +typedef struct { + FLAC__bool abort_flag; + FLAC__bool is_playing; + FLAC__bool is_http_source; + FLAC__bool eof; + FLAC__bool play_thread_open; /* if true, is_playing must also be true */ + FLAC__uint64 total_samples; + unsigned bits_per_sample; + unsigned channels; + unsigned sample_rate; + int length_in_msec; /* int (instead of FLAC__uint64) only because that's what XMMS uses; seeking won't work right if this maxes out */ + gchar *title; + AFormat sample_format; + unsigned sample_format_bytes_per_sample; + int seek_to_in_sec; + FLAC__bool has_replaygain; + double replay_scale; + DitherContext dither_context; +} stream_data_struct; + +static void FLAC_XMMS__init(void); +static int FLAC_XMMS__is_our_file(char *filename); +static void FLAC_XMMS__play_file(char *filename); +static void FLAC_XMMS__stop(void); +static void FLAC_XMMS__pause(short p); +static void FLAC_XMMS__seek(int time); +static int FLAC_XMMS__get_time(void); +static void FLAC_XMMS__cleanup(void); +static void FLAC_XMMS__get_song_info(char *filename, char **title, int *length); + +static void *play_loop_(void *arg); + +static FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder); +static void safe_decoder_finish_(FLAC__StreamDecoder *decoder); +static void safe_decoder_delete_(FLAC__StreamDecoder *decoder); + +static FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); +static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); +static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); +static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); + +InputPlugin flac_ip = +{ + NULL, + NULL, + "FLAC Player v" VERSION, + FLAC_XMMS__init, + FLAC_XMMS__aboutbox, + FLAC_XMMS__configure, + FLAC_XMMS__is_our_file, + NULL, + FLAC_XMMS__play_file, + FLAC_XMMS__stop, + FLAC_XMMS__pause, + FLAC_XMMS__seek, + NULL, + FLAC_XMMS__get_time, + NULL, + NULL, + FLAC_XMMS__cleanup, + NULL, + NULL, + NULL, + NULL, + FLAC_XMMS__get_song_info, + FLAC_XMMS__file_info_box, + NULL +}; + +#define SAMPLES_PER_WRITE 512 +#define SAMPLE_BUFFER_SIZE ((FLAC__MAX_BLOCK_SIZE + SAMPLES_PER_WRITE) * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS * (24/8)) +static FLAC__byte sample_buffer_[SAMPLE_BUFFER_SIZE]; +static unsigned sample_buffer_first_, sample_buffer_last_; + +static FLAC__StreamDecoder *decoder_ = 0; +static stream_data_struct stream_data_; +static pthread_t decode_thread_; +static FLAC__bool audio_error_ = false; +static FLAC__bool is_big_endian_host_; + +#define BITRATE_HIST_SEGMENT_MSEC 500 +/* 500ms * 50 = 25s should be enough */ +#define BITRATE_HIST_SIZE 50 +static unsigned bitrate_history_[BITRATE_HIST_SIZE]; + + +InputPlugin *get_iplugin_info(void) +{ + flac_ip.description = g_strdup_printf("Reference FLAC Player v%s", FLAC__VERSION_STRING); + return &flac_ip; +} + +void set_track_info(const char* title, int length_in_msec) +{ + if (stream_data_.is_playing) { + flac_ip.set_info((char*) title, length_in_msec, stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample, stream_data_.sample_rate, stream_data_.channels); + } +} + +static gchar* homedir(void) +{ + gchar *result; + char *env_home = getenv("HOME"); + if (env_home) { + result = g_strdup (env_home); + } else { + uid_t uid = getuid(); + struct passwd *pwent; + do { + pwent = getpwent(); + } while (pwent && pwent->pw_uid != uid); + result = pwent ? g_strdup (pwent->pw_dir) : NULL; + endpwent(); + } + return result; +} + +static FLAC__bool is_http_source(const char *source) +{ + return 0 == strncasecmp(source, "http://", 7); +} + +void FLAC_XMMS__init(void) +{ + ConfigFile *cfg; + FLAC__uint32 test = 1; + + is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true; + + flac_cfg.title.tag_override = FALSE; + if (flac_cfg.title.tag_format) + g_free(flac_cfg.title.tag_format); + flac_cfg.title.convert_char_set = FALSE; + + cfg = xmms_cfg_open_default_file(); + + /* title */ + + xmms_cfg_read_boolean(cfg, "flac", "title.tag_override", &flac_cfg.title.tag_override); + + if(!xmms_cfg_read_string(cfg, "flac", "title.tag_format", &flac_cfg.title.tag_format)) + flac_cfg.title.tag_format = g_strdup("%p - %t"); + + xmms_cfg_read_boolean(cfg, "flac", "title.convert_char_set", &flac_cfg.title.convert_char_set); + + if(!xmms_cfg_read_string(cfg, "flac", "title.user_char_set", &flac_cfg.title.user_char_set)) + flac_cfg.title.user_char_set = FLAC_plugin__charset_get_current(); + + /* replaygain */ + + xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.enable", &flac_cfg.output.replaygain.enable); + + xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.album_mode", &flac_cfg.output.replaygain.album_mode); + + if(!xmms_cfg_read_int(cfg, "flac", "output.replaygain.preamp", &flac_cfg.output.replaygain.preamp)) + flac_cfg.output.replaygain.preamp = 0; + + xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.hard_limit", &flac_cfg.output.replaygain.hard_limit); + + xmms_cfg_read_boolean(cfg, "flac", "output.resolution.normal.dither_24_to_16", &flac_cfg.output.resolution.normal.dither_24_to_16); + xmms_cfg_read_boolean(cfg, "flac", "output.resolution.replaygain.dither", &flac_cfg.output.resolution.replaygain.dither); + + if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.noise_shaping", &flac_cfg.output.resolution.replaygain.noise_shaping)) + flac_cfg.output.resolution.replaygain.noise_shaping = 1; + + if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.bps_out", &flac_cfg.output.resolution.replaygain.bps_out)) + flac_cfg.output.resolution.replaygain.bps_out = 16; + + /* stream */ + + xmms_cfg_read_int(cfg, "flac", "stream.http_buffer_size", &flac_cfg.stream.http_buffer_size); + xmms_cfg_read_int(cfg, "flac", "stream.http_prebuffer", &flac_cfg.stream.http_prebuffer); + xmms_cfg_read_boolean(cfg, "flac", "stream.use_proxy", &flac_cfg.stream.use_proxy); + if(flac_cfg.stream.proxy_host) + g_free(flac_cfg.stream.proxy_host); + if(!xmms_cfg_read_string(cfg, "flac", "stream.proxy_host", &flac_cfg.stream.proxy_host)) + flac_cfg.stream.proxy_host = g_strdup(""); + xmms_cfg_read_int(cfg, "flac", "stream.proxy_port", &flac_cfg.stream.proxy_port); + xmms_cfg_read_boolean(cfg, "flac", "stream.proxy_use_auth", &flac_cfg.stream.proxy_use_auth); + if(flac_cfg.stream.proxy_user) + g_free(flac_cfg.stream.proxy_user); + flac_cfg.stream.proxy_user = NULL; + xmms_cfg_read_string(cfg, "flac", "stream.proxy_user", &flac_cfg.stream.proxy_user); + if(flac_cfg.stream.proxy_pass) + g_free(flac_cfg.stream.proxy_pass); + flac_cfg.stream.proxy_pass = NULL; + xmms_cfg_read_string(cfg, "flac", "stream.proxy_pass", &flac_cfg.stream.proxy_pass); + xmms_cfg_read_boolean(cfg, "flac", "stream.save_http_stream", &flac_cfg.stream.save_http_stream); + if (flac_cfg.stream.save_http_path) + g_free (flac_cfg.stream.save_http_path); + if (!xmms_cfg_read_string(cfg, "flac", "stream.save_http_path", &flac_cfg.stream.save_http_path) || ! *flac_cfg.stream.save_http_path) { + if (flac_cfg.stream.save_http_path) + g_free (flac_cfg.stream.save_http_path); + flac_cfg.stream.save_http_path = homedir(); + } + xmms_cfg_read_boolean(cfg, "flac", "stream.cast_title_streaming", &flac_cfg.stream.cast_title_streaming); + xmms_cfg_read_boolean(cfg, "flac", "stream.use_udp_channel", &flac_cfg.stream.use_udp_channel); + + decoder_ = FLAC__stream_decoder_new(); + + xmms_cfg_free(cfg); +} + +int FLAC_XMMS__is_our_file(char *filename) +{ + char *ext; + + ext = strrchr(filename, '.'); + if(ext) + if(!strcasecmp(ext, ".flac") || !strcasecmp(ext, ".fla")) + return 1; + return 0; +} + +void FLAC_XMMS__play_file(char *filename) +{ + FILE *f; + + sample_buffer_first_ = sample_buffer_last_ = 0; + audio_error_ = false; + stream_data_.abort_flag = false; + stream_data_.is_playing = false; + stream_data_.is_http_source = is_http_source(filename); + stream_data_.eof = false; + stream_data_.play_thread_open = false; + stream_data_.has_replaygain = false; + + if(!is_http_source(filename)) { + if(0 == (f = fopen(filename, "r"))) + return; + fclose(f); + } + + if(decoder_ == 0) + return; + + if(!safe_decoder_init_(filename, decoder_)) + return; + + if(stream_data_.has_replaygain && flac_cfg.output.replaygain.enable) { + if(flac_cfg.output.resolution.replaygain.bps_out == 8) { + stream_data_.sample_format = FMT_U8; + stream_data_.sample_format_bytes_per_sample = 1; + } + else if(flac_cfg.output.resolution.replaygain.bps_out == 16) { + stream_data_.sample_format = (is_big_endian_host_) ? FMT_S16_BE : FMT_S16_LE; + stream_data_.sample_format_bytes_per_sample = 2; + } + else { + /*@@@ need some error here like wa2: MessageBox(mod_.hMainWindow, "ERROR: plugin can only handle 8/16-bit samples\n", "ERROR: plugin can only handle 8/16-bit samples", 0); */ + fprintf(stderr, "libxmms-flac: can't handle %d bit output\n", flac_cfg.output.resolution.replaygain.bps_out); + safe_decoder_finish_(decoder_); + return; + } + } + else { + if(stream_data_.bits_per_sample == 8) { + stream_data_.sample_format = FMT_U8; + stream_data_.sample_format_bytes_per_sample = 1; + } + else if(stream_data_.bits_per_sample == 16 || (stream_data_.bits_per_sample == 24 && flac_cfg.output.resolution.normal.dither_24_to_16)) { + stream_data_.sample_format = (is_big_endian_host_) ? FMT_S16_BE : FMT_S16_LE; + stream_data_.sample_format_bytes_per_sample = 2; + } + else { + /*@@@ need some error here like wa2: MessageBox(mod_.hMainWindow, "ERROR: plugin can only handle 8/16-bit samples\n", "ERROR: plugin can only handle 8/16-bit samples", 0); */ + fprintf(stderr, "libxmms-flac: can't handle %d bit output\n", stream_data_.bits_per_sample); + safe_decoder_finish_(decoder_); + return; + } + } + FLAC__replaygain_synthesis__init_dither_context(&stream_data_.dither_context, stream_data_.sample_format_bytes_per_sample * 8, flac_cfg.output.resolution.replaygain.noise_shaping); + stream_data_.is_playing = true; + + if(flac_ip.output->open_audio(stream_data_.sample_format, stream_data_.sample_rate, stream_data_.channels) == 0) { + audio_error_ = true; + safe_decoder_finish_(decoder_); + return; + } + + stream_data_.title = flac_format_song_title(filename); + flac_ip.set_info(stream_data_.title, stream_data_.length_in_msec, stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample, stream_data_.sample_rate, stream_data_.channels); + + stream_data_.seek_to_in_sec = -1; + stream_data_.play_thread_open = true; + pthread_create(&decode_thread_, NULL, play_loop_, NULL); +} + +void FLAC_XMMS__stop(void) +{ + if(stream_data_.is_playing) { + stream_data_.is_playing = false; + if(stream_data_.play_thread_open) { + stream_data_.play_thread_open = false; + pthread_join(decode_thread_, NULL); + } + flac_ip.output->close_audio(); + safe_decoder_finish_(decoder_); + } +} + +void FLAC_XMMS__pause(short p) +{ + flac_ip.output->pause(p); +} + +void FLAC_XMMS__seek(int time) +{ + if(!stream_data_.is_http_source) { + stream_data_.seek_to_in_sec = time; + stream_data_.eof = false; + + while(stream_data_.seek_to_in_sec != -1) + xmms_usleep(10000); + } +} + +int FLAC_XMMS__get_time(void) +{ + if(audio_error_) + return -2; + if(!stream_data_.is_playing || (stream_data_.eof && !flac_ip.output->buffer_playing())) + return -1; + else + return flac_ip.output->output_time(); +} + +void FLAC_XMMS__cleanup(void) +{ + safe_decoder_delete_(decoder_); + decoder_ = 0; +} + +void FLAC_XMMS__get_song_info(char *filename, char **title, int *length_in_msec) +{ + FLAC__StreamMetadata streaminfo; + + if(0 == filename) + filename = ""; + + if(!FLAC__metadata_get_streaminfo(filename, &streaminfo)) { + /* @@@ how to report the error? */ + if(title) { + if (!is_http_source(filename)) { + static const char *errtitle = "Invalid FLAC File: "; + if(strlen(errtitle) + 1 + strlen(filename) + 1 + 1 < strlen(filename)) { /* overflow check */ + *title = NULL; + } + else { + *title = g_malloc(strlen(errtitle) + 1 + strlen(filename) + 1 + 1); + sprintf(*title, "%s\"%s\"", errtitle, filename); + } + } else { + *title = NULL; + } + } + if(length_in_msec) + *length_in_msec = -1; + return; + } + + if(title) { + *title = flac_format_song_title(filename); + } + if(length_in_msec) { + FLAC__uint64 l = (FLAC__uint64)((double)streaminfo.data.stream_info.total_samples / (double)streaminfo.data.stream_info.sample_rate * 1000.0 + 0.5); + if (l > INT_MAX) + l = INT_MAX; + *length_in_msec = (int)l; + } +} + +/*********************************************************************** + * local routines + **********************************************************************/ + +void *play_loop_(void *arg) +{ + unsigned written_time_last = 0, bh_index_last_w = 0, bh_index_last_o = BITRATE_HIST_SIZE, blocksize = 1; + FLAC__uint64 decode_position_last = 0, decode_position_frame_last = 0, decode_position_frame = 0; + + (void)arg; + + while(stream_data_.is_playing) { + if(!stream_data_.eof) { + while(sample_buffer_last_ - sample_buffer_first_ < SAMPLES_PER_WRITE) { + unsigned s; + + s = sample_buffer_last_ - sample_buffer_first_; + if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_END_OF_STREAM) { + stream_data_.eof = true; + break; + } + else if(!FLAC__stream_decoder_process_single(decoder_)) { + /*@@@ this should probably be a dialog */ + fprintf(stderr, "libxmms-flac: READ ERROR processing frame\n"); + stream_data_.eof = true; + break; + } + blocksize = sample_buffer_last_ - sample_buffer_first_ - s; + decode_position_frame_last = decode_position_frame; + if(stream_data_.is_http_source || !FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame)) + decode_position_frame = 0; + } + if(sample_buffer_last_ - sample_buffer_first_ > 0) { + const unsigned n = min(sample_buffer_last_ - sample_buffer_first_, SAMPLES_PER_WRITE); + int bytes = n * stream_data_.channels * stream_data_.sample_format_bytes_per_sample; + FLAC__byte *sample_buffer_start = sample_buffer_ + sample_buffer_first_ * stream_data_.channels * stream_data_.sample_format_bytes_per_sample; + unsigned written_time, bh_index_w; + FLAC__uint64 decode_position; + + sample_buffer_first_ += n; + flac_ip.add_vis_pcm(flac_ip.output->written_time(), stream_data_.sample_format, stream_data_.channels, bytes, sample_buffer_start); + while(flac_ip.output->buffer_free() < (int)bytes && stream_data_.is_playing && stream_data_.seek_to_in_sec == -1) + xmms_usleep(10000); + if(stream_data_.is_playing && stream_data_.seek_to_in_sec == -1) + flac_ip.output->write_audio(sample_buffer_start, bytes); + + /* compute current bitrate */ + + written_time = flac_ip.output->written_time(); + bh_index_w = written_time / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE; + if(bh_index_w != bh_index_last_w) { + bh_index_last_w = bh_index_w; + decode_position = decode_position_frame - (double)(sample_buffer_last_ - sample_buffer_first_) * (double)(decode_position_frame - decode_position_frame_last) / (double)blocksize; + bitrate_history_[(bh_index_w + BITRATE_HIST_SIZE - 1) % BITRATE_HIST_SIZE] = + decode_position > decode_position_last && written_time > written_time_last ? + 8000 * (decode_position - decode_position_last) / (written_time - written_time_last) : + stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample; + decode_position_last = decode_position; + written_time_last = written_time; + } + } + else { + stream_data_.eof = true; + xmms_usleep(10000); + } + } + else + xmms_usleep(10000); + if(!stream_data_.is_http_source && stream_data_.seek_to_in_sec != -1) { + const double distance = (double)stream_data_.seek_to_in_sec * 1000.0 / (double)stream_data_.length_in_msec; + FLAC__uint64 target_sample = (FLAC__uint64)(distance * (double)stream_data_.total_samples); + if(stream_data_.total_samples > 0 && target_sample >= stream_data_.total_samples) + target_sample = stream_data_.total_samples - 1; + if(FLAC__stream_decoder_seek_absolute(decoder_, target_sample)) { + flac_ip.output->flush(stream_data_.seek_to_in_sec * 1000); + bh_index_last_w = bh_index_last_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE; + if(!FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame)) + decode_position_frame = 0; + stream_data_.eof = false; + sample_buffer_first_ = sample_buffer_last_ = 0; + } + else if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_SEEK_ERROR) { + /*@@@ this should probably be a dialog */ + fprintf(stderr, "libxmms-flac: SEEK ERROR\n"); + FLAC__stream_decoder_flush(decoder_); + stream_data_.eof = false; + sample_buffer_first_ = sample_buffer_last_ = 0; + } + stream_data_.seek_to_in_sec = -1; + } + else { + /* display the right bitrate from history */ + unsigned bh_index_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE; + if(bh_index_o != bh_index_last_o && bh_index_o != bh_index_last_w && bh_index_o != (bh_index_last_w + 1) % BITRATE_HIST_SIZE) { + bh_index_last_o = bh_index_o; + flac_ip.set_info(stream_data_.title, stream_data_.length_in_msec, bitrate_history_[bh_index_o], stream_data_.sample_rate, stream_data_.channels); + } + } + } + + safe_decoder_finish_(decoder_); + + /* are these two calls necessary? */ + flac_ip.output->buffer_free(); + flac_ip.output->buffer_free(); + + g_free(stream_data_.title); + + pthread_exit(NULL); + return 0; /* to silence the compiler warning about not returning a value */ +} + +FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder) +{ + if(decoder == 0) + return false; + + safe_decoder_finish_(decoder); + + FLAC__stream_decoder_set_md5_checking(decoder, false); + FLAC__stream_decoder_set_metadata_ignore_all(decoder); + FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO); + FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(stream_data_.is_http_source) { + flac_http_open(filename, 0); + if(FLAC__stream_decoder_init_stream(decoder, http_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, write_callback_, metadata_callback_, error_callback_, /*client_data=*/&stream_data_) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return false; + } + else { + if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/&stream_data_) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return false; + } + + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) + return false; + + return true; +} + +void safe_decoder_finish_(FLAC__StreamDecoder *decoder) +{ + if(decoder && FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED) + (void)FLAC__stream_decoder_finish(decoder); + if(stream_data_.is_http_source) + flac_http_close(); +} + +void safe_decoder_delete_(FLAC__StreamDecoder *decoder) +{ + if(decoder) { + safe_decoder_finish_(decoder); + FLAC__stream_decoder_delete(decoder); + } +} + +FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + (void)decoder; + (void)client_data; + *bytes = flac_http_read(buffer, *bytes); + return *bytes ? FLAC__STREAM_DECODER_READ_STATUS_CONTINUE : FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; +} + +FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct *)client_data; + const unsigned channels = stream_data->channels, wide_samples = frame->header.blocksize; + const unsigned bits_per_sample = stream_data->bits_per_sample; + FLAC__byte *sample_buffer_start; + + (void)decoder; + + if(stream_data->abort_flag) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + if((sample_buffer_last_ + wide_samples) > (SAMPLE_BUFFER_SIZE / (channels * stream_data->sample_format_bytes_per_sample))) { + memmove(sample_buffer_, sample_buffer_ + sample_buffer_first_ * channels * stream_data->sample_format_bytes_per_sample, (sample_buffer_last_ - sample_buffer_first_) * channels * stream_data->sample_format_bytes_per_sample); + sample_buffer_last_ -= sample_buffer_first_; + sample_buffer_first_ = 0; + } + sample_buffer_start = sample_buffer_ + sample_buffer_last_ * channels * stream_data->sample_format_bytes_per_sample; + if(stream_data->has_replaygain && flac_cfg.output.replaygain.enable) { + FLAC__replaygain_synthesis__apply_gain( + sample_buffer_start, + !is_big_endian_host_, + stream_data->sample_format_bytes_per_sample == 1, /* unsigned_data_out */ + buffer, + wide_samples, + channels, + bits_per_sample, + stream_data->sample_format_bytes_per_sample * 8, + stream_data->replay_scale, + flac_cfg.output.replaygain.hard_limit, + flac_cfg.output.resolution.replaygain.dither, + &stream_data->dither_context + ); + } + else if(is_big_endian_host_) { + FLAC__plugin_common__pack_pcm_signed_big_endian( + sample_buffer_start, + buffer, + wide_samples, + channels, + bits_per_sample, + stream_data->sample_format_bytes_per_sample * 8 + ); + } + else { + FLAC__plugin_common__pack_pcm_signed_little_endian( + sample_buffer_start, + buffer, + wide_samples, + channels, + bits_per_sample, + stream_data->sample_format_bytes_per_sample * 8 + ); + } + + sample_buffer_last_ += wide_samples; + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct *)client_data; + (void)decoder; + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + stream_data->total_samples = metadata->data.stream_info.total_samples; + stream_data->bits_per_sample = metadata->data.stream_info.bits_per_sample; + stream_data->channels = metadata->data.stream_info.channels; + stream_data->sample_rate = metadata->data.stream_info.sample_rate; + { + FLAC__uint64 l = (FLAC__uint64)((double)stream_data->total_samples / (double)stream_data->sample_rate * 1000.0 + 0.5); + if (l > INT_MAX) + l = INT_MAX; + stream_data->length_in_msec = (int)l; + } + } + else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) { + double reference, gain, peak; + if(grabbag__replaygain_load_from_vorbiscomment(metadata, flac_cfg.output.replaygain.album_mode, /*strict=*/false, &reference, &gain, &peak)) { + stream_data->has_replaygain = true; + stream_data->replay_scale = grabbag__replaygain_compute_scale_factor(peak, gain, (double)flac_cfg.output.replaygain.preamp, /*prevent_clipping=*/!flac_cfg.output.replaygain.hard_limit); + } + } +} + +void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + stream_data_struct *stream_data = (stream_data_struct *)client_data; + (void)decoder; + if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC) + stream_data->abort_flag = true; +} diff --git a/flac/src/plugin_xmms/plugin.h b/flac/src/plugin_xmms/plugin.h new file mode 100644 index 0000000..7130a07 --- /dev/null +++ b/flac/src/plugin_xmms/plugin.h @@ -0,0 +1,24 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__PLUGIN_XMMS__PLUGIN_H +#define FLAC__PLUGIN_XMMS__PLUGIN_H + +void set_track_info(const char* title, int length_in_msec); + +#endif diff --git a/flac/src/plugin_xmms/tag.c b/flac/src/plugin_xmms/tag.c new file mode 100644 index 0000000..f86ab79 --- /dev/null +++ b/flac/src/plugin_xmms/tag.c @@ -0,0 +1,154 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * Based on FLAC plugin.c and mpg123 plugin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FLAC/metadata.h" +#include "plugin_common/tags.h" +#include "charset.h" +#include "configure.h" + +/* + * Function local__extname (filename) + * + * Return pointer within filename to its extenstion, or NULL if + * filename has no extension. + * + */ +static char *local__extname(const char *filename) +{ + char *ext = strrchr(filename, '.'); + + if (ext != NULL) + ++ext; + + return ext; +} + +static char *local__getstr(char* str) +{ + if (str && strlen(str) > 0) + return str; + return NULL; +} + +static int local__getnum(char* str) +{ + if (str && strlen(str) > 0) + return atoi(str); + return 0; +} + +static char *local__getfield(const FLAC__StreamMetadata *tags, const char *name) +{ + if (0 != tags) { + const char *utf8 = FLAC_plugin__tags_get_tag_utf8(tags, name); + if (0 != utf8) { + if(flac_cfg.title.convert_char_set) + return convert_from_utf8_to_user(utf8); + else + return strdup(utf8); + } + } + + return 0; +} + +static void local__safe_free(char *s) +{ + if (0 != s) + free(s); +} + +/* + * Function flac_format_song_title (tag, filename) + * + * Create song title according to `tag' and/or `filename' and + * return it. The title must be subsequently freed using g_free(). + * + */ +char *flac_format_song_title(char *filename) +{ + char *ret = NULL; + TitleInput *input = NULL; + FLAC__StreamMetadata *tags; + char *title, *artist, *performer, *album, *date, *tracknumber, *genre, *description; + + FLAC_plugin__tags_get(filename, &tags); + + title = local__getfield(tags, "TITLE"); + artist = local__getfield(tags, "ARTIST"); + performer = local__getfield(tags, "PERFORMER"); + album = local__getfield(tags, "ALBUM"); + date = local__getfield(tags, "DATE"); + tracknumber = local__getfield(tags, "TRACKNUMBER"); + genre = local__getfield(tags, "GENRE"); + description = local__getfield(tags, "DESCRIPTION"); + + XMMS_NEW_TITLEINPUT(input); + + input->performer = local__getstr(performer); + if(!input->performer) + input->performer = local__getstr(artist); + input->album_name = local__getstr(album); + input->track_name = local__getstr(title); + input->track_number = local__getnum(tracknumber); + input->year = local__getnum(date); + input->genre = local__getstr(genre); + input->comment = local__getstr(description); + + input->file_name = g_basename(filename); + input->file_path = filename; + input->file_ext = local__extname(filename); + ret = xmms_get_titlestring(flac_cfg.title.tag_override ? flac_cfg.title.tag_format : xmms_get_gentitle_format(), input); + g_free(input); + + if (!ret) { + /* + * Format according to filename. + */ + ret = g_strdup(g_basename(filename)); + if (local__extname(ret) != NULL) + *(local__extname(ret) - 1) = '\0'; /* removes period */ + } + + FLAC_plugin__tags_destroy(&tags); + local__safe_free(title); + local__safe_free(artist); + local__safe_free(performer); + local__safe_free(album); + local__safe_free(date); + local__safe_free(tracknumber); + local__safe_free(genre); + local__safe_free(description); + return ret; +} diff --git a/flac/src/plugin_xmms/tag.h b/flac/src/plugin_xmms/tag.h new file mode 100644 index 0000000..00de8de --- /dev/null +++ b/flac/src/plugin_xmms/tag.h @@ -0,0 +1,24 @@ +/* libxmms-flac - XMMS FLAC input plugin + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Daisuke Shimamura + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__PLUGIN_XMMS__TAG_H +#define FLAC__PLUGIN_XMMS__TAG_H + +gchar *flac_format_song_title(gchar * filename); + +#endif diff --git a/flac/src/share/Makefile.am b/flac/src/share/Makefile.am new file mode 100644 index 0000000..20d43d8 --- /dev/null +++ b/flac/src/share/Makefile.am @@ -0,0 +1,22 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = getopt replaygain_analysis replaygain_synthesis grabbag utf8 + +EXTRA_DIST = \ + Makefile.lite \ + README diff --git a/flac/src/share/Makefile.lite b/flac/src/share/Makefile.lite new file mode 100644 index 0000000..49d0994 --- /dev/null +++ b/flac/src/share/Makefile.lite @@ -0,0 +1,53 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +.PHONY: all getopt grabbag replaygain_analysis replaygain_synthesis utf8 +all: getopt grabbag replaygain_analysis replaygain_synthesis utf8 + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +debug : CONFIG = debug +valgrind: CONFIG = valgrind +release : CONFIG = release + +debug : all +valgrind: all +release : all + +getopt: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +grabbag: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +replaygain_analysis: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +replaygain_synthesis: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +utf8: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +clean: + -(cd getopt ; $(MAKE) -f Makefile.lite clean) + -(cd grabbag ; $(MAKE) -f Makefile.lite clean) + -(cd replaygain_analysis ; $(MAKE) -f Makefile.lite clean) + -(cd replaygain_synthesis ; $(MAKE) -f Makefile.lite clean) + -(cd utf8 ; $(MAKE) -f Makefile.lite clean) diff --git a/flac/src/share/README b/flac/src/share/README new file mode 100644 index 0000000..947ca7f --- /dev/null +++ b/flac/src/share/README @@ -0,0 +1,5 @@ +This directory contains several convenience libraries used by the rest of the +tools and plugins. Two of them (getopt and utf8) are shamelessly copied from +vorbistools, one for manipulating UTF-8 strings (GPL) and one for implementing +getopt (LGPL). libFLAC does not link to either; the only FLAC tools that do +are GPL'ed. diff --git a/flac/src/share/getopt/Makefile.am b/flac/src/share/getopt/Makefile.am new file mode 100644 index 0000000..93b6ed3 --- /dev/null +++ b/flac/src/share/getopt/Makefile.am @@ -0,0 +1,20 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I$(top_srcdir)/include/share + +noinst_LIBRARIES = libgetopt.a + +libgetopt_a_SOURCES = getopt.c getopt1.c + +EXTRA_DIST = \ + Makefile.lite \ + getopt_static.dsp \ + getopt_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/share/getopt/Makefile.lite b/flac/src/share/getopt/Makefile.lite new file mode 100644 index 0000000..4158ec3 --- /dev/null +++ b/flac/src/share/getopt/Makefile.lite @@ -0,0 +1,16 @@ +# +# GNU makefile +# + +topdir = ../../.. + +LIB_NAME = libgetopt +INCLUDES = -I$(topdir)/include -I$(topdir)/include/share + +SRCS_C = \ + getopt.c \ + getopt1.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/share/getopt/getopt.c b/flac/src/share/getopt/getopt.c new file mode 100644 index 0000000..b7e1ba0 --- /dev/null +++ b/flac/src/share/getopt/getopt.c @@ -0,0 +1,1065 @@ +/* + NOTE: + I cannot get the vanilla getopt code to work (i.e. compile only what + is needed and not duplicate symbols found in the standard library) + on all the platforms that FLAC supports. In particular the gating + of code with the ELIDE_CODE #define is not accurate enough on systems + that are POSIX but not glibc. If someone has a patch that works on + GNU/Linux, Darwin, AND Solaris please submit it on the project page: + http://sourceforge.net/projects/flac + + In the meantime I have munged the global symbols and removed gates + around code, while at the same time trying to touch the original as + little as possible. +*/ +/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + "Keep this file name-space clean" means, talk to drepper@gnu.org + before changing it! + + Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 + Free Software Foundation, Inc. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +/* This tells Alpha OSF/1 not to define a getopt prototype in . + Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#if HAVE_CONFIG_H +# include +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#if 1 +/*[JEC] was:#ifndef ELIDE_CODE*/ + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them + contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. + When compiling libc, the _ macro is predefined. */ +# ifdef HAVE_LIBINTL_H +# include +# define _(msgid) gettext (msgid) +# else +# define _(msgid) (msgid) +# endif +#endif + +/* This version of `share__getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `share__getopt' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable POSIXLY_CORRECT disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include "share/getopt.h" +/*[JEC] was:#include "getopt.h"*/ + +/* For communication from `share__getopt' to the caller. + When `share__getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *share__optarg = 0; /*[JEC] initialize to avoid being a 'Common' symbol */ + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `share__getopt'. + + On entry to `share__getopt', zero means this is the first call; initialize. + + When `share__getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `share__optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int share__optind = 1; + +/* Formerly, initialization of getopt depended on share__optind==0, which + causes problems with re-calling getopt as programs generally don't + know that. */ + +static int share____getopt_initialized = 0; + +/* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int share__opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int share__optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters. + + PERMUTE is the default. We permute the contents of ARGV as we scan, + so that eventually all the non-options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code 1. + Using `-' as the first character of the list of option characters + selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `share__getopt' to return -1 with `share__optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries + because there are many ways it can cause trouble. + On some systems, it contains special magic macros that don't work + in GCC. */ +# include +# define my_index strchr +#else + +#include + +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +#ifndef getenv +extern char *getenv (); +#endif + +static char * +my_index (str, chr) + const char *str; + int chr; +{ + while (*str) + { + if (*str == chr) + return (char *) str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. + If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. + That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, + and has done so at least since version 2.4.5. -- rms. */ +extern int strlen (const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; + +static int original_argc; +static char *const *original_argv; + +/* Make sure the environment variable bash 2.0 puts in the environment + is valid for the getopt call we must make sure that the ARGV passed + to getopt is that one passed to the process. */ +static void +__attribute__ ((unused)) +store_args_and_env (int argc, char *const *argv) +{ + /* XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ + original_argc = argc; + original_argv = argv; +} +# ifdef text_set_element +text_set_element (__libc_subinit, store_args_and_env); +# endif /* text_set_element */ + +# define SWAP_FLAGS(ch1, ch2) \ + if (nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,share__optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange (char **); +#endif + +static void +exchange (argv) + char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = share__optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#ifdef _LIBC + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (share__optind - last_nonopt); + last_nonopt = share__optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *share___getopt_initialize (int, char *const *, const char *); +#endif +static const char * +share___getopt_initialize (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = share__optind; + + nextchar = NULL; + + posixly_correct = getenv ("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#ifdef _LIBC + if (posixly_correct == NULL + && argc == original_argc && argv == original_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen (orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#else + (void)argc, (void)argv; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `share__getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `share__getopt' finds another option character, it returns that character, + updating `share__optind' and `nextchar' so that the next call to `share__getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `share__getopt' returns -1. + Then `share__optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `share__opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `share__optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `share__optarg', otherwise `share__optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `share__getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + The elements of ARGV aren't really const, because we permute them. + But we pretend they're const in the prototype to be compatible + with other systems. + + LONGOPTS is a vector of `struct share__option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. */ + +int +share___getopt_internal (argc, argv, optstring, longopts, longind, long_only) + int argc; + char *const *argv; + const char *optstring; + const struct share__option *longopts; + int *longind; + int long_only; +{ + share__optarg = NULL; + + if (share__optind == 0 || !share____getopt_initialized) + { + if (share__optind == 0) + share__optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = share___getopt_initialize (argc, argv, optstring); + share____getopt_initialized = 1; + } + + /* Test whether ARGV[share__optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#ifdef _LIBC +# define NONOPTION_P (argv[share__optind][0] != '-' || argv[share__optind][1] == '\0' \ + || (share__optind < nonoption_flags_len \ + && __getopt_nonoption_flags[share__optind] == '1')) +#else +# define NONOPTION_P (argv[share__optind][0] != '-' || argv[share__optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > share__optind) + last_nonopt = share__optind; + if (first_nonopt > share__optind) + first_nonopt = share__optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != share__optind) + exchange ((char **) argv); + else if (last_nonopt != share__optind) + first_nonopt = share__optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (share__optind < argc && NONOPTION_P) + share__optind++; + last_nonopt = share__optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (share__optind != argc && !strcmp (argv[share__optind], "--")) + { + share__optind++; + + if (first_nonopt != last_nonopt && last_nonopt != share__optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = share__optind; + last_nonopt = argc; + + share__optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (share__optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + share__optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + share__optarg = argv[share__optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[share__optind] + 1 + + (longopts != NULL && argv[share__optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[share__optind][1] == '-' + || (long_only && (argv[share__optind][2] || !my_index (optstring, argv[share__optind][1]))))) + { + char *nameend; + const struct share__option *p; + const struct share__option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (share__opterr) + fprintf (stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[share__optind]); + nextchar += strlen (nextchar); + share__optind++; + share__optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + share__optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + share__optarg = nameend + 1; + else + { + if (share__opterr) + { + if (argv[share__optind - 1][1] == '-') + /* --option */ + fprintf (stderr, + _("%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); + else + /* +option or -option */ + fprintf (stderr, + _("%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[share__optind - 1][0], pfound->name); + } + + nextchar += strlen (nextchar); + + share__optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (share__optind < argc) + share__optarg = argv[share__optind++]; + else + { + if (share__opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[share__optind - 1]); + nextchar += strlen (nextchar); + share__optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not share__getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[share__optind][1] == '-' + || my_index (optstring, *nextchar) == NULL) + { + if (share__opterr) + { + if (argv[share__optind][1] == '-') + /* --option */ + fprintf (stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); + else + /* +option or -option */ + fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[share__optind][0], nextchar); + } + nextchar = (char *) ""; + share__optind++; + share__optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index (optstring, c); + + /* Increment `share__optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++share__optind; + + if (temp == NULL || c == ':') + { + if (share__opterr) + { + if (posixly_correct) + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: illegal option -- %c\n"), + argv[0], c); + else + fprintf (stderr, _("%s: invalid option -- %c\n"), + argv[0], c); + } + share__optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct share__option *p; + const struct share__option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + share__optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + share__optind++; + } + else if (share__optind == argc) + { + if (share__opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + share__optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `share__optind' once; + increment it again when taking next ARGV-elt as argument. */ + share__optarg = argv[share__optind++]; + + /* share__optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = share__optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (share__opterr) + fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[share__optind]); + nextchar += strlen (nextchar); + share__optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + share__optarg = nameend + 1; + else + { + if (share__opterr) + fprintf (stderr, _("\ +%s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (share__optind < argc) + share__optarg = argv[share__optind++]; + else + { + if (share__opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[share__optind - 1]); + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + share__optarg = nextchar; + share__optind++; + } + else + share__optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + share__optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + share__optind++; + } + else if (share__optind == argc) + { + if (share__opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + share__optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `share__optind' once; + increment it again when taking next ARGV-elt as argument. */ + share__optarg = argv[share__optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +share__getopt (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + return share___getopt_internal (argc, argv, optstring, + (const struct share__option *) 0, + (int *) 0, + 0); +} + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `share__getopt'. */ + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = share__optind ? share__optind : 1; + + c = share__getopt (argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", share__optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (share__optind < argc) + { + printf ("non-option ARGV-elements: "); + while (share__optind < argc) + printf ("%s ", argv[share__optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/flac/src/share/getopt/getopt1.c b/flac/src/share/getopt/getopt1.c new file mode 100644 index 0000000..873df60 --- /dev/null +++ b/flac/src/share/getopt/getopt1.c @@ -0,0 +1,204 @@ +/* + NOTE: + I cannot get the vanilla getopt code to work (i.e. compile only what + is needed and not duplicate symbols found in the standard library) + on all the platforms that FLAC supports. In particular the gating + of code with the ELIDE_CODE #define is not accurate enough on systems + that are POSIX but not glibc. If someone has a patch that works on + GNU/Linux, Darwin, AND Solaris please submit it on the project page: + http://sourceforge.net/projects/flac + + In the meantime I have munged the global symbols and removed gates + around code, while at the same time trying to touch the original as + little as possible. +*/ +/* getopt_long and getopt_long_only entry points for GNU getopt. + Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "share/getopt.h" +/*[JEC] was:#include "getopt.h"*/ + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +#ifndef const +#define const +#endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +#include +#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +#define ELIDE_CODE +#endif +#endif + +#if 1 +/*[JEC] was:#ifndef ELIDE_CODE*/ + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +#include +#endif + +#ifndef NULL +#define NULL 0 +#endif + +int +share__getopt_long (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct share__option *long_options; + int *opt_index; +{ + return share___getopt_internal (argc, argv, options, long_options, opt_index, 0); +} + +/* Like share__getopt_long, but '-' as well as '--' can indicate a long option. + If an option that starts with '-' (not '--') doesn't match a long option, + but does match a short option, it is parsed as a short option + instead. */ + +int +share__getopt_long_only (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct share__option *long_options; + int *opt_index; +{ + return share___getopt_internal (argc, argv, options, long_options, opt_index, 1); +} + + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +#include + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = share__optind ? share__optind : 1; + int option_index = 0; + static struct share__option long_options[] = + { + {"add", 1, 0, 0}, + {"append", 0, 0, 0}, + {"delete", 1, 0, 0}, + {"verbose", 0, 0, 0}, + {"create", 0, 0, 0}, + {"file", 1, 0, 0}, + {0, 0, 0, 0} + }; + + c = share__getopt_long (argc, argv, "abc:d:0123456789", + long_options, &option_index); + if (c == -1) + break; + + switch (c) + { + case 0: + printf ("option %s", long_options[option_index].name); + if (share__optarg) + printf (" with arg %s", share__optarg); + printf ("\n"); + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", share__optarg); + break; + + case 'd': + printf ("option d with value `%s'\n", share__optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (share__optind < argc) + { + printf ("non-option ARGV-elements: "); + while (share__optind < argc) + printf ("%s ", argv[share__optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/flac/src/share/getopt/getopt_static.dsp b/flac/src/share/getopt/getopt_static.dsp new file mode 100644 index 0000000..2d69ba4 --- /dev/null +++ b/flac/src/share/getopt/getopt_static.dsp @@ -0,0 +1,112 @@ +# Microsoft Developer Studio Project File - Name="getopt_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=getopt_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "getopt_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "getopt_static.mak" CFG="getopt_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "getopt_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "getopt_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "getopt" +# PROP Scc_LocalPath "..\..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "getopt_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I ".\include" /I "..\..\..\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "getopt_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\..\include" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "getopt_static - Win32 Release" +# Name "getopt_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\getopt.c +# End Source File +# Begin Source File + +SOURCE=.\getopt1.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\getopt.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/share/getopt/getopt_static.vcproj b/flac/src/share/getopt/getopt_static.vcproj new file mode 100644 index 0000000..1830034 --- /dev/null +++ b/flac/src/share/getopt/getopt_static.vcproj @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/share/grabbag/Makefile.am b/flac/src/share/grabbag/Makefile.am new file mode 100644 index 0000000..3bc2d10 --- /dev/null +++ b/flac/src/share/grabbag/Makefile.am @@ -0,0 +1,25 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I$(top_srcdir)/include + +noinst_LTLIBRARIES = libgrabbag.la + +libgrabbag_la_SOURCES = \ + cuesheet.c \ + file.c \ + picture.c \ + replaygain.c \ + seektable.c + +EXTRA_DIST = \ + Makefile.lite \ + grabbag_static.dsp \ + grabbag_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/share/grabbag/Makefile.lite b/flac/src/share/grabbag/Makefile.lite new file mode 100644 index 0000000..557151d --- /dev/null +++ b/flac/src/share/grabbag/Makefile.lite @@ -0,0 +1,19 @@ +# +# GNU makefile +# + +topdir = ../../.. + +LIB_NAME = libgrabbag +INCLUDES = -I$(topdir)/include + +SRCS_C = \ + cuesheet.c \ + file.c \ + picture.c \ + replaygain.c \ + seektable.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/share/grabbag/cuesheet.c b/flac/src/share/grabbag/cuesheet.c new file mode 100644 index 0000000..c88b75a --- /dev/null +++ b/flac/src/share/grabbag/cuesheet.c @@ -0,0 +1,611 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "share/grabbag.h" +#include "FLAC/assert.h" +#include +#include +#include + +unsigned grabbag__cuesheet_msf_to_frame(unsigned minutes, unsigned seconds, unsigned frames) +{ + return ((minutes * 60) + seconds) * 75 + frames; +} + +void grabbag__cuesheet_frame_to_msf(unsigned frame, unsigned *minutes, unsigned *seconds, unsigned *frames) +{ + *frames = frame % 75; + frame /= 75; + *seconds = frame % 60; + frame /= 60; + *minutes = frame; +} + +/* since we only care about values >= 0 or error, returns < 0 for any illegal string, else value */ +static int local__parse_int_(const char *s) +{ + int ret = 0; + char c; + + if(*s == '\0') + return -1; + + while('\0' != (c = *s++)) + if(c >= '0' && c <= '9') + ret = ret * 10 + (c - '0'); + else + return -1; + + return ret; +} + +/* since we only care about values >= 0 or error, returns < 0 for any illegal string, else value */ +static FLAC__int64 local__parse_int64_(const char *s) +{ + FLAC__int64 ret = 0; + char c; + + if(*s == '\0') + return -1; + + while('\0' != (c = *s++)) + if(c >= '0' && c <= '9') + ret = ret * 10 + (c - '0'); + else + return -1; + + return ret; +} + +/* accept '[0-9]+:[0-9][0-9]?:[0-9][0-9]?', but max second of 59 and max frame of 74, e.g. 0:0:0, 123:45:67 + * return sample number or <0 for error + */ +static FLAC__int64 local__parse_msf_(const char *s) +{ + FLAC__int64 ret, field; + char c; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + while(':' != (c = *s++)) { + if(c >= '0' && c <= '9') + field = field * 10 + (c - '0'); + else + return -1; + } + + ret = field * 60 * 44100; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + if(':' != (c = *s++)) { + if(c >= '0' && c <= '9') { + field = field * 10 + (c - '0'); + c = *s++; + if(c != ':') + return -1; + } + else + return -1; + } + + if(field >= 60) + return -1; + + ret += field * 44100; + + c = *s++; + if(c >= '0' && c <= '9') + field = (c - '0'); + else + return -1; + if('\0' != (c = *s++)) { + if(c >= '0' && c <= '9') { + field = field * 10 + (c - '0'); + c = *s++; + } + else + return -1; + } + + if(c != '\0') + return -1; + + if(field >= 75) + return -1; + + ret += field * (44100 / 75); + + return ret; +} + +static char *local__get_field_(char **s, FLAC__bool allow_quotes) +{ + FLAC__bool has_quote = false; + char *p; + + FLAC__ASSERT(0 != s); + + if(0 == *s) + return 0; + + /* skip leading whitespace */ + while(**s && 0 != strchr(" \t\r\n", **s)) + (*s)++; + + if(**s == 0) { + *s = 0; + return 0; + } + + if(allow_quotes && (**s == '"')) { + has_quote = true; + (*s)++; + if(**s == 0) { + *s = 0; + return 0; + } + } + + p = *s; + + if(has_quote) { + *s = strchr(*s, '\"'); + /* if there is no matching end quote, it's an error */ + if(0 == *s) + p = *s = 0; + else { + **s = '\0'; + (*s)++; + } + } + else { + while(**s && 0 == strchr(" \t\r\n", **s)) + (*s)++; + if(**s) { + **s = '\0'; + (*s)++; + } + else + *s = 0; + } + + return p; +} + +static FLAC__bool local__cuesheet_parse_(FILE *file, const char **error_message, unsigned *last_line_read, FLAC__StreamMetadata *cuesheet, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset) +{ +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ +#define FLAC__STRCASECMP stricmp +#else +#define FLAC__STRCASECMP strcasecmp +#endif + char buffer[4096], *line, *field; + unsigned forced_leadout_track_num = 0; + FLAC__uint64 forced_leadout_track_offset = 0; + int in_track_num = -1, in_index_num = -1; + FLAC__bool disc_has_catalog = false, track_has_flags = false, track_has_isrc = false, has_forced_leadout = false; + FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet; + + cs->lead_in = is_cdda? 2 * 44100 /* The default lead-in size for CD-DA */ : 0; + cs->is_cd = is_cdda; + + while(0 != fgets(buffer, sizeof(buffer), file)) { + (*last_line_read)++; + line = buffer; + + { + size_t linelen = strlen(line); + if((linelen == sizeof(buffer)-1) && line[linelen-1] != '\n') { + *error_message = "line too long"; + return false; + } + } + + if(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == FLAC__STRCASECMP(field, "CATALOG")) { + if(disc_has_catalog) { + *error_message = "found multiple CATALOG commands"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/true))) { + *error_message = "CATALOG is missing catalog number"; + return false; + } + if(strlen(field) >= sizeof(cs->media_catalog_number)) { + *error_message = "CATALOG number is too long"; + return false; + } + if(is_cdda && (strlen(field) != 13 || strspn(field, "0123456789") != 13)) { + *error_message = "CD-DA CATALOG number must be 13 decimal digits"; + return false; + } + strcpy(cs->media_catalog_number, field); + disc_has_catalog = true; + } + else if(0 == FLAC__STRCASECMP(field, "FLAGS")) { + if(track_has_flags) { + *error_message = "found multiple FLAGS commands"; + return false; + } + if(in_track_num < 0 || in_index_num >= 0) { + *error_message = "FLAGS command must come after TRACK but before INDEX"; + return false; + } + while(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == FLAC__STRCASECMP(field, "PRE")) + cs->tracks[cs->num_tracks-1].pre_emphasis = 1; + } + track_has_flags = true; + } + else if(0 == FLAC__STRCASECMP(field, "INDEX")) { + FLAC__int64 xx; + FLAC__StreamMetadata_CueSheet_Track *track = &cs->tracks[cs->num_tracks-1]; + if(in_track_num < 0) { + *error_message = "found INDEX before any TRACK"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "INDEX is missing index number"; + return false; + } + in_index_num = local__parse_int_(field); + if(in_index_num < 0) { + *error_message = "INDEX has invalid index number"; + return false; + } + FLAC__ASSERT(cs->num_tracks > 0); + if(track->num_indices == 0) { + /* it's the first index point of the track */ + if(in_index_num > 1) { + *error_message = "first INDEX number of a TRACK must be 0 or 1"; + return false; + } + } + else { + if(in_index_num != track->indices[track->num_indices-1].number + 1) { + *error_message = "INDEX numbers must be sequential"; + return false; + } + } + if(is_cdda && in_index_num > 99) { + *error_message = "CD-DA INDEX number must be between 0 and 99, inclusive"; + return false; + } + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "INDEX is missing an offset after the index number"; + return false; + } + xx = local__parse_msf_(field); + if(xx < 0) { + if(is_cdda) { + *error_message = "illegal INDEX offset (not of the form MM:SS:FF)"; + return false; + } + xx = local__parse_int64_(field); + if(xx < 0) { + *error_message = "illegal INDEX offset"; + return false; + } + } + if(is_cdda && cs->num_tracks == 1 && cs->tracks[0].num_indices == 0 && xx != 0) { + *error_message = "first INDEX of first TRACK must have an offset of 00:00:00"; + return false; + } + if(is_cdda && track->num_indices > 0 && (FLAC__uint64)xx <= track->indices[track->num_indices-1].offset) { + *error_message = "CD-DA INDEX offsets must increase in time"; + return false; + } + /* fill in track offset if it's the first index of the track */ + if(track->num_indices == 0) + track->offset = (FLAC__uint64)xx; + if(is_cdda && cs->num_tracks > 1) { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-2]; + if((FLAC__uint64)xx <= prev->offset + prev->indices[prev->num_indices-1].offset) { + *error_message = "CD-DA INDEX offsets must increase in time"; + return false; + } + } + if(!FLAC__metadata_object_cuesheet_track_insert_blank_index(cuesheet, cs->num_tracks-1, track->num_indices)) { + *error_message = "memory allocation error"; + return false; + } + track->indices[track->num_indices-1].offset = (FLAC__uint64)xx - track->offset; + track->indices[track->num_indices-1].number = in_index_num; + } + else if(0 == FLAC__STRCASECMP(field, "ISRC")) { + char *l, *r; + if(track_has_isrc) { + *error_message = "found multiple ISRC commands"; + return false; + } + if(in_track_num < 0 || in_index_num >= 0) { + *error_message = "ISRC command must come after TRACK but before INDEX"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "ISRC is missing ISRC number"; + return false; + } + /* strip out dashes */ + for(l = r = field; *r; r++) { + if(*r != '-') + *l++ = *r; + } + *l = '\0'; + if(strlen(field) != 12 || strspn(field, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") < 5 || strspn(field+5, "1234567890") != 7) { + *error_message = "invalid ISRC number"; + return false; + } + strcpy(cs->tracks[cs->num_tracks-1].isrc, field); + track_has_isrc = true; + } + else if(0 == FLAC__STRCASECMP(field, "TRACK")) { + if(cs->num_tracks > 0) { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-1]; + if( + prev->num_indices == 0 || + ( + is_cdda && + ( + (prev->num_indices == 1 && prev->indices[0].number != 1) || + (prev->num_indices == 2 && prev->indices[0].number != 1 && prev->indices[1].number != 1) + ) + ) + ) { + *error_message = is_cdda? + "previous TRACK must specify at least one INDEX 01" : + "previous TRACK must specify at least one INDEX"; + return false; + } + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "TRACK is missing track number"; + return false; + } + in_track_num = local__parse_int_(field); + if(in_track_num < 0) { + *error_message = "TRACK has invalid track number"; + return false; + } + if(in_track_num == 0) { + *error_message = "TRACK number must be greater than 0"; + return false; + } + if(is_cdda) { + if(in_track_num > 99) { + *error_message = "CD-DA TRACK number must be between 1 and 99, inclusive"; + return false; + } + } + else { + if(in_track_num == 255) { + *error_message = "TRACK number 255 is reserved for the lead-out"; + return false; + } + else if(in_track_num > 255) { + *error_message = "TRACK number must be between 1 and 254, inclusive"; + return false; + } + } + if(is_cdda && cs->num_tracks > 0 && in_track_num != cs->tracks[cs->num_tracks-1].number + 1) { + *error_message = "CD-DA TRACK numbers must be sequential"; + return false; + } + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "TRACK is missing a track type after the track number"; + return false; + } + if(!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, cs->num_tracks)) { + *error_message = "memory allocation error"; + return false; + } + cs->tracks[cs->num_tracks-1].number = in_track_num; + cs->tracks[cs->num_tracks-1].type = (0 == FLAC__STRCASECMP(field, "AUDIO"))? 0 : 1; /*@@@ should we be more strict with the value here? */ + in_index_num = -1; + track_has_flags = false; + track_has_isrc = false; + } + else if(0 == FLAC__STRCASECMP(field, "REM")) { + if(0 != (field = local__get_field_(&line, /*allow_quotes=*/false))) { + if(0 == strcmp(field, "FLAC__lead-in")) { + FLAC__int64 xx; + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-in is missing offset"; + return false; + } + xx = local__parse_int64_(field); + if(xx < 0) { + *error_message = "illegal FLAC__lead-in offset"; + return false; + } + if(is_cdda && xx % 588 != 0) { + *error_message = "illegal CD-DA FLAC__lead-in offset, must be even multiple of 588 samples"; + return false; + } + cs->lead_in = (FLAC__uint64)xx; + } + else if(0 == strcmp(field, "FLAC__lead-out")) { + int track_num; + FLAC__int64 offset; + if(has_forced_leadout) { + *error_message = "multiple FLAC__lead-out commands"; + return false; + } + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-out is missing track number"; + return false; + } + track_num = local__parse_int_(field); + if(track_num < 0) { + *error_message = "illegal FLAC__lead-out track number"; + return false; + } + forced_leadout_track_num = (unsigned)track_num; + /*@@@ search for duplicate track number? */ + if(0 == (field = local__get_field_(&line, /*allow_quotes=*/false))) { + *error_message = "FLAC__lead-out is missing offset"; + return false; + } + offset = local__parse_int64_(field); + if(offset < 0) { + *error_message = "illegal FLAC__lead-out offset"; + return false; + } + forced_leadout_track_offset = (FLAC__uint64)offset; + if(forced_leadout_track_offset != lead_out_offset) { + *error_message = "FLAC__lead-out offset does not match end-of-stream offset"; + return false; + } + has_forced_leadout = true; + } + } + } + } + } + + if(cs->num_tracks == 0) { + *error_message = "there must be at least one TRACK command"; + return false; + } + else { + const FLAC__StreamMetadata_CueSheet_Track *prev = &cs->tracks[cs->num_tracks-1]; + if( + prev->num_indices == 0 || + ( + is_cdda && + ( + (prev->num_indices == 1 && prev->indices[0].number != 1) || + (prev->num_indices == 2 && prev->indices[0].number != 1 && prev->indices[1].number != 1) + ) + ) + ) { + *error_message = is_cdda? + "previous TRACK must specify at least one INDEX 01" : + "previous TRACK must specify at least one INDEX"; + return false; + } + } + + if(!has_forced_leadout) { + forced_leadout_track_num = is_cdda? 170 : 255; + forced_leadout_track_offset = lead_out_offset; + } + if(!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, cs->num_tracks)) { + *error_message = "memory allocation error"; + return false; + } + cs->tracks[cs->num_tracks-1].number = forced_leadout_track_num; + cs->tracks[cs->num_tracks-1].offset = forced_leadout_track_offset; + + if(!feof(file)) { + *error_message = "read error"; + return false; + } + return true; +#undef FLAC__STRCASECMP +} + +FLAC__StreamMetadata *grabbag__cuesheet_parse(FILE *file, const char **error_message, unsigned *last_line_read, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset) +{ + FLAC__StreamMetadata *cuesheet; + + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != error_message); + FLAC__ASSERT(0 != last_line_read); + + *last_line_read = 0; + cuesheet = FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET); + + if(0 == cuesheet) { + *error_message = "memory allocation error"; + return 0; + } + + if(!local__cuesheet_parse_(file, error_message, last_line_read, cuesheet, is_cdda, lead_out_offset)) { + FLAC__metadata_object_delete(cuesheet); + return 0; + } + + return cuesheet; +} + +void grabbag__cuesheet_emit(FILE *file, const FLAC__StreamMetadata *cuesheet, const char *file_reference) +{ + const FLAC__StreamMetadata_CueSheet *cs; + unsigned track_num, index_num; + + FLAC__ASSERT(0 != file); + FLAC__ASSERT(0 != cuesheet); + FLAC__ASSERT(cuesheet->type == FLAC__METADATA_TYPE_CUESHEET); + + cs = &cuesheet->data.cue_sheet; + + if(*(cs->media_catalog_number)) + fprintf(file, "CATALOG %s\n", cs->media_catalog_number); + fprintf(file, "FILE %s\n", file_reference); + + for(track_num = 0; track_num < cs->num_tracks-1; track_num++) { + const FLAC__StreamMetadata_CueSheet_Track *track = cs->tracks + track_num; + + fprintf(file, " TRACK %02u %s\n", (unsigned)track->number, track->type == 0? "AUDIO" : "DATA"); + + if(track->pre_emphasis) + fprintf(file, " FLAGS PRE\n"); + if(*(track->isrc)) + fprintf(file, " ISRC %s\n", track->isrc); + + for(index_num = 0; index_num < track->num_indices; index_num++) { + const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + index_num; + + fprintf(file, " INDEX %02u ", (unsigned)index->number); + if(cs->is_cd) { + const unsigned logical_frame = (unsigned)((track->offset + index->offset) / (44100 / 75)); + unsigned m, s, f; + grabbag__cuesheet_frame_to_msf(logical_frame, &m, &s, &f); + fprintf(file, "%02u:%02u:%02u\n", m, s, f); + } + else +#ifdef _MSC_VER + fprintf(file, "%I64u\n", track->offset + index->offset); +#else + fprintf(file, "%llu\n", (unsigned long long)(track->offset + index->offset)); +#endif + } + } + +#ifdef _MSC_VER + fprintf(file, "REM FLAC__lead-in %I64u\n", cs->lead_in); + fprintf(file, "REM FLAC__lead-out %u %I64u\n", (unsigned)cs->tracks[track_num].number, cs->tracks[track_num].offset); +#else + fprintf(file, "REM FLAC__lead-in %llu\n", (unsigned long long)cs->lead_in); + fprintf(file, "REM FLAC__lead-out %u %llu\n", (unsigned)cs->tracks[track_num].number, (unsigned long long)cs->tracks[track_num].offset); +#endif +} diff --git a/flac/src/share/grabbag/file.c b/flac/src/share/grabbag/file.c new file mode 100644 index 0000000..27ce775 --- /dev/null +++ b/flac/src/share/grabbag/file.c @@ -0,0 +1,192 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#include /* for utime() */ +#include /* for chmod(), _setmode(), unlink() */ +#include /* for _O_BINARY */ +#else +#include /* some flavors of BSD (like OS X) require this to get time_t */ +#include /* for utime() */ +#endif +#if defined __CYGWIN__ || defined __EMX__ +#include /* for setmode(), O_BINARY */ +#include /* for _O_BINARY */ +#endif +#include /* for stat(), maybe chmod() */ +#if defined _WIN32 && !defined __CYGWIN__ +#else +#include /* for unlink() */ +#endif +#include +#include +#include /* for strrchr() */ +#if defined _WIN32 && !defined __CYGWIN__ +// for GetFileInformationByHandle() etc +#include +#include +#endif +#include "share/grabbag.h" + + +void grabbag__file_copy_metadata(const char *srcpath, const char *destpath) +{ + struct stat srcstat; + struct utimbuf srctime; + + if(0 == stat(srcpath, &srcstat)) { + srctime.actime = srcstat.st_atime; + srctime.modtime = srcstat.st_mtime; + (void)chmod(destpath, srcstat.st_mode); + (void)utime(destpath, &srctime); + } +} + +off_t grabbag__file_get_filesize(const char *srcpath) +{ + struct stat srcstat; + + if(0 == stat(srcpath, &srcstat)) + return srcstat.st_size; + else + return -1; +} + +const char *grabbag__file_get_basename(const char *srcpath) +{ + const char *p; + + p = strrchr(srcpath, '/'); + if(0 == p) { + p = strrchr(srcpath, '\\'); + if(0 == p) + return srcpath; + } + return ++p; +} + +FLAC__bool grabbag__file_change_stats(const char *filename, FLAC__bool read_only) +{ + struct stat stats; + + if(0 == stat(filename, &stats)) { +#if !defined _MSC_VER && !defined __MINGW32__ + if(read_only) { + stats.st_mode &= ~S_IWUSR; + stats.st_mode &= ~S_IWGRP; + stats.st_mode &= ~S_IWOTH; + } + else { + stats.st_mode |= S_IWUSR; + } +#else + if(read_only) + stats.st_mode &= ~S_IWRITE; + else + stats.st_mode |= S_IWRITE; +#endif + if(0 != chmod(filename, stats.st_mode)) + return false; + } + else + return false; + + return true; +} + +FLAC__bool grabbag__file_are_same(const char *f1, const char *f2) +{ +#if defined _MSC_VER || defined __MINGW32__ + /* see + * http://www.hydrogenaudio.org/forums/index.php?showtopic=49439&pid=444300&st=0 + * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/getfileinformationbyhandle.asp + * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/by_handle_file_information_str.asp + * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/createfile.asp + * apparently both the files have to be open at the same time for the comparison to work + */ + FLAC__bool same = false; + BY_HANDLE_FILE_INFORMATION info1, info2; + HANDLE h1, h2; + BOOL ok = 1; + h1 = CreateFile(f1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + h2 = CreateFile(f2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if(h1 == INVALID_HANDLE_VALUE || h2 == INVALID_HANDLE_VALUE) + ok = 0; + ok &= GetFileInformationByHandle(h1, &info1); + ok &= GetFileInformationByHandle(h2, &info2); + if(ok) + same = + info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber && + info1.nFileIndexHigh == info2.nFileIndexHigh && + info1.nFileIndexLow == info2.nFileIndexLow + ; + if(h1 != INVALID_HANDLE_VALUE) + CloseHandle(h1); + if(h2 != INVALID_HANDLE_VALUE) + CloseHandle(h2); + return same; +#else + struct stat s1, s2; + return f1 && f2 && stat(f1, &s1) == 0 && stat(f2, &s2) == 0 && s1.st_ino == s2.st_ino && s1.st_dev == s2.st_dev; +#endif +} + +FLAC__bool grabbag__file_remove_file(const char *filename) +{ + return grabbag__file_change_stats(filename, /*read_only=*/false) && 0 == unlink(filename); +} + +FILE *grabbag__file_get_binary_stdin(void) +{ + /* if something breaks here it is probably due to the presence or + * absence of an underscore before the identifiers 'setmode', + * 'fileno', and/or 'O_BINARY'; check your system header files. + */ +#if defined _MSC_VER || defined __MINGW32__ + _setmode(_fileno(stdin), _O_BINARY); +#elif defined __CYGWIN__ + /* almost certainly not needed for any modern Cygwin, but let's be safe... */ + setmode(_fileno(stdin), _O_BINARY); +#elif defined __EMX__ + setmode(fileno(stdin), O_BINARY); +#endif + + return stdin; +} + +FILE *grabbag__file_get_binary_stdout(void) +{ + /* if something breaks here it is probably due to the presence or + * absence of an underscore before the identifiers 'setmode', + * 'fileno', and/or 'O_BINARY'; check your system header files. + */ +#if defined _MSC_VER || defined __MINGW32__ + _setmode(_fileno(stdout), _O_BINARY); +#elif defined __CYGWIN__ + /* almost certainly not needed for any modern Cygwin, but let's be safe... */ + setmode(_fileno(stdout), _O_BINARY); +#elif defined __EMX__ + setmode(fileno(stdout), O_BINARY); +#endif + + return stdout; +} diff --git a/flac/src/share/grabbag/grabbag_static.dsp b/flac/src/share/grabbag/grabbag_static.dsp new file mode 100644 index 0000000..ced3d03 --- /dev/null +++ b/flac/src/share/grabbag/grabbag_static.dsp @@ -0,0 +1,144 @@ +# Microsoft Developer Studio Project File - Name="grabbag_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=grabbag_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "grabbag_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "grabbag_static.mak" CFG="grabbag_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "grabbag_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "grabbag_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "grabbag" +# PROP Scc_LocalPath "..\..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "grabbag_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /Op /I ".\include" /I "..\..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "grabbag_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\..\include" /D "FLAC__NO_DLL" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "grabbag_static - Win32 Release" +# Name "grabbag_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\cuesheet.c +# End Source File +# Begin Source File + +SOURCE=.\file.c +# End Source File +# Begin Source File + +SOURCE=.\picture.c +# End Source File +# Begin Source File + +SOURCE=.\replaygain.c +# End Source File +# Begin Source File + +SOURCE=.\seektable.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag\cuesheet.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag\file.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag\picture.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag\replaygain.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag\seektable.h +# End Source File +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\grabbag.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/share/grabbag/grabbag_static.vcproj b/flac/src/share/grabbag/grabbag_static.vcproj new file mode 100644 index 0000000..b60e607 --- /dev/null +++ b/flac/src/share/grabbag/grabbag_static.vcproj @@ -0,0 +1,358 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/share/grabbag/picture.c b/flac/src/share/grabbag/picture.c new file mode 100644 index 0000000..f039caa --- /dev/null +++ b/flac/src/share/grabbag/picture.c @@ -0,0 +1,407 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "share/alloc.h" +#include "share/grabbag.h" +#include "FLAC/assert.h" +#include +#include +#include + +/* slightly different that strndup(): this always copies 'size' bytes starting from s into a NUL-terminated string. */ +static char *local__strndup_(const char *s, size_t size) +{ + char *x = (char*)safe_malloc_add_2op_(size, /*+*/1); + if(x) { + memcpy(x, s, size); + x[size] = '\0'; + } + return x; +} + +static FLAC__bool local__parse_type_(const char *s, size_t len, FLAC__StreamMetadata_Picture *picture) +{ + size_t i; + FLAC__uint32 val = 0; + + picture->type = FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER; + + if(len == 0) + return true; /* empty string implies default to 'front cover' */ + + for(i = 0; i < len; i++) { + if(s[i] >= '0' && s[i] <= '9') + val = 10*val + (FLAC__uint32)(s[i] - '0'); + else + return false; + } + + if(i == len) + picture->type = val; + else + return false; + + return true; +} + +static FLAC__bool local__parse_resolution_(const char *s, size_t len, FLAC__StreamMetadata_Picture *picture) +{ + int state = 0; + size_t i; + FLAC__uint32 val = 0; + + picture->width = picture->height = picture->depth = picture->colors = 0; + + if(len == 0) + return true; /* empty string implies client wants to get info from the file itself */ + + for(i = 0; i < len; i++) { + if(s[i] == 'x') { + if(state == 0) + picture->width = val; + else if(state == 1) + picture->height = val; + else + return false; + state++; + val = 0; + } + else if(s[i] == '/') { + if(state == 2) + picture->depth = val; + else + return false; + state++; + val = 0; + } + else if(s[i] >= '0' && s[i] <= '9') + val = 10*val + (FLAC__uint32)(s[i] - '0'); + else + return false; + } + + if(state < 2) + return false; + else if(state == 2) + picture->depth = val; + else if(state == 3) + picture->colors = val; + else + return false; + if(picture->depth < 32 && 1u<depth < picture->colors) + return false; + + return true; +} + +static FLAC__bool local__extract_mime_type_(FLAC__StreamMetadata *obj) +{ + if(obj->data.picture.data_length >= 8 && 0 == memcmp(obj->data.picture.data, "\x89PNG\x0d\x0a\x1a\x0a", 8)) + return FLAC__metadata_object_picture_set_mime_type(obj, "image/png", /*copy=*/true); + else if(obj->data.picture.data_length >= 6 && (0 == memcmp(obj->data.picture.data, "GIF87a", 6) || 0 == memcmp(obj->data.picture.data, "GIF89a", 6))) + return FLAC__metadata_object_picture_set_mime_type(obj, "image/gif", /*copy=*/true); + else if(obj->data.picture.data_length >= 2 && 0 == memcmp(obj->data.picture.data, "\xff\xd8", 2)) + return FLAC__metadata_object_picture_set_mime_type(obj, "image/jpeg", /*copy=*/true); + return false; +} + +static FLAC__bool local__extract_resolution_color_info_(FLAC__StreamMetadata_Picture *picture) +{ + const FLAC__byte *data = picture->data; + FLAC__uint32 len = picture->data_length; + + if(0 == strcmp(picture->mime_type, "image/png")) { + /* c.f. http://www.w3.org/TR/PNG/ */ + FLAC__bool need_palette = false; /* if IHDR has color_type=3, we need to also read the PLTE chunk to get the #colors */ + if(len < 8 || memcmp(data, "\x89PNG\x0d\x0a\x1a\x0a", 8)) + return false; + /* try to find IHDR chunk */ + data += 8; + len -= 8; + while(len > 12) { /* every PNG chunk must be at least 12 bytes long */ + const FLAC__uint32 clen = (FLAC__uint32)data[0] << 24 | (FLAC__uint32)data[1] << 16 | (FLAC__uint32)data[2] << 8 | (FLAC__uint32)data[3]; + if(0 == memcmp(data+4, "IHDR", 4) && clen == 13) { + unsigned color_type = data[17]; + picture->width = (FLAC__uint32)data[8] << 24 | (FLAC__uint32)data[9] << 16 | (FLAC__uint32)data[10] << 8 | (FLAC__uint32)data[11]; + picture->height = (FLAC__uint32)data[12] << 24 | (FLAC__uint32)data[13] << 16 | (FLAC__uint32)data[14] << 8 | (FLAC__uint32)data[15]; + if(color_type == 3) { + /* even though the bit depth for color_type==3 can be 1,2,4,or 8, + * the spec in 11.2.2 of http://www.w3.org/TR/PNG/ says that the + * sample depth is always 8 + */ + picture->depth = 8 * 3u; + need_palette = true; + data += 12 + clen; + len -= 12 + clen; + } + else { + if(color_type == 0) /* greyscale, 1 sample per pixel */ + picture->depth = (FLAC__uint32)data[16]; + if(color_type == 2) /* truecolor, 3 samples per pixel */ + picture->depth = (FLAC__uint32)data[16] * 3u; + if(color_type == 4) /* greyscale+alpha, 2 samples per pixel */ + picture->depth = (FLAC__uint32)data[16] * 2u; + if(color_type == 6) /* truecolor+alpha, 4 samples per pixel */ + picture->depth = (FLAC__uint32)data[16] * 4u; + picture->colors = 0; + return true; + } + } + else if(need_palette && 0 == memcmp(data+4, "PLTE", 4)) { + picture->colors = clen / 3u; + return true; + } + else if(clen + 12 > len) + return false; + else { + data += 12 + clen; + len -= 12 + clen; + } + } + } + else if(0 == strcmp(picture->mime_type, "image/jpeg")) { + /* c.f. http://www.w3.org/Graphics/JPEG/itu-t81.pdf and Q22 of http://www.faqs.org/faqs/jpeg-faq/part1/ */ + if(len < 2 || memcmp(data, "\xff\xd8", 2)) + return false; + data += 2; + len -= 2; + while(1) { + /* look for sync FF byte */ + for( ; len > 0; data++, len--) { + if(*data == 0xff) + break; + } + if(len == 0) + return false; + /* eat any extra pad FF bytes before marker */ + for( ; len > 0; data++, len--) { + if(*data != 0xff) + break; + } + if(len == 0) + return false; + /* if we hit SOS or EOI, bail */ + if(*data == 0xda || *data == 0xd9) + return false; + /* looking for some SOFn */ + else if(memchr("\xc0\xc1\xc2\xc3\xc5\xc6\xc7\xc9\xca\xcb\xcd\xce\xcf", *data, 13)) { + data++; len--; /* skip marker byte */ + if(len < 2) + return false; + else { + const FLAC__uint32 clen = (FLAC__uint32)data[0] << 8 | (FLAC__uint32)data[1]; + if(clen < 8 || len < clen) + return false; + picture->width = (FLAC__uint32)data[5] << 8 | (FLAC__uint32)data[6]; + picture->height = (FLAC__uint32)data[3] << 8 | (FLAC__uint32)data[4]; + picture->depth = (FLAC__uint32)data[2] * (FLAC__uint32)data[7]; + picture->colors = 0; + return true; + } + } + /* else skip it */ + else { + data++; len--; /* skip marker byte */ + if(len < 2) + return false; + else { + const FLAC__uint32 clen = (FLAC__uint32)data[0] << 8 | (FLAC__uint32)data[1]; + if(clen < 2 || len < clen) + return false; + data += clen; + len -= clen; + } + } + } + } + else if(0 == strcmp(picture->mime_type, "image/gif")) { + /* c.f. http://www.w3.org/Graphics/GIF/spec-gif89a.txt */ + if(len < 14) + return false; + if(memcmp(data, "GIF87a", 6) && memcmp(data, "GIF89a", 6)) + return false; +#if 0 + /* according to the GIF spec, even if the GCTF is 0, the low 3 bits should still tell the total # colors used */ + if(data[10] & 0x80 == 0) + return false; +#endif + picture->width = (FLAC__uint32)data[6] | ((FLAC__uint32)data[7] << 8); + picture->height = (FLAC__uint32)data[8] | ((FLAC__uint32)data[9] << 8); +#if 0 + /* this value doesn't seem to be reliable... */ + picture->depth = (((FLAC__uint32)(data[10] & 0x70) >> 4) + 1) * 3u; +#else + /* ...just pessimistically assume it's 24-bit color without scanning all the color tables */ + picture->depth = 8u * 3u; +#endif + picture->colors = 1u << ((FLAC__uint32)(data[10] & 0x07) + 1u); + return true; + } + return false; +} + +FLAC__StreamMetadata *grabbag__picture_parse_specification(const char *spec, const char **error_message) +{ + FLAC__StreamMetadata *obj; + int state = 0; + static const char *error_messages[] = { + "memory allocation error", + "invalid picture specification", + "invalid picture specification: can't parse resolution/color part", + "unable to extract resolution and color info from URL, user must set explicitly", + "unable to extract resolution and color info from file, user must set explicitly", + "error opening picture file", + "error reading picture file", + "invalid picture type", + "unable to guess MIME type from file, user must set explicitly", + "type 1 icon must be a 32x32 pixel PNG" + }; + + FLAC__ASSERT(0 != spec); + FLAC__ASSERT(0 != error_message); + + /* double protection */ + if(0 == spec) + return 0; + if(0 == error_message) + return 0; + + *error_message = 0; + + if(0 == (obj = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PICTURE))) + *error_message = error_messages[0]; + + if(strchr(spec, '|')) { /* full format */ + const char *p; + char *q; + for(p = spec; *error_message==0 && *p; ) { + if(*p == '|') { + switch(state) { + case 0: /* type */ + if(!local__parse_type_(spec, p-spec, &obj->data.picture)) + *error_message = error_messages[7]; + break; + case 1: /* mime type */ + if(p-spec) { /* if blank, we'll try to guess later from the picture data */ + if(0 == (q = local__strndup_(spec, p-spec))) + *error_message = error_messages[0]; + else if(!FLAC__metadata_object_picture_set_mime_type(obj, q, /*copy=*/false)) + *error_message = error_messages[0]; + } + break; + case 2: /* description */ + if(0 == (q = local__strndup_(spec, p-spec))) + *error_message = error_messages[0]; + else if(!FLAC__metadata_object_picture_set_description(obj, (FLAC__byte*)q, /*copy=*/false)) + *error_message = error_messages[0]; + break; + case 3: /* resolution/color (e.g. [300x300x16[/1234]] */ + if(!local__parse_resolution_(spec, p-spec, &obj->data.picture)) + *error_message = error_messages[2]; + break; + default: + *error_message = error_messages[1]; + break; + } + p++; + spec = p; + state++; + } + else + p++; + } + } + else { /* simple format, filename only, everything else guessed */ + if(!local__parse_type_("", 0, &obj->data.picture)) /* use default picture type */ + *error_message = error_messages[7]; + /* leave MIME type to be filled in later */ + /* leave description empty */ + /* leave the rest to be filled in later: */ + else if(!local__parse_resolution_("", 0, &obj->data.picture)) + *error_message = error_messages[2]; + else + state = 4; + } + + /* parse filename, read file, try to extract resolution/color info if needed */ + if(*error_message == 0) { + if(state != 4) + *error_message = error_messages[1]; + else { /* 'spec' points to filename/URL */ + if(0 == strcmp(obj->data.picture.mime_type, "-->")) { /* magic MIME type means URL */ + if(!FLAC__metadata_object_picture_set_data(obj, (FLAC__byte*)spec, strlen(spec), /*copy=*/true)) + *error_message = error_messages[0]; + else if(obj->data.picture.width == 0 || obj->data.picture.height == 0 || obj->data.picture.depth == 0) + *error_message = error_messages[3]; + } + else { /* regular picture file */ + const off_t size = grabbag__file_get_filesize(spec); + if(size < 0) + *error_message = error_messages[5]; + else { + FLAC__byte *buffer = (FLAC__byte*)safe_malloc_(size); + if(0 == buffer) + *error_message = error_messages[0]; + else { + FILE *f = fopen(spec, "rb"); + if(0 == f) + *error_message = error_messages[5]; + else { + if(fread(buffer, 1, size, f) != (size_t)size) + *error_message = error_messages[6]; + fclose(f); + if(0 == *error_message) { + if(!FLAC__metadata_object_picture_set_data(obj, buffer, size, /*copy=*/false)) + *error_message = error_messages[6]; + /* try to extract MIME type if user left it blank */ + else if(*obj->data.picture.mime_type == '\0' && !local__extract_mime_type_(obj)) + *error_message = error_messages[8]; + /* try to extract resolution/color info if user left it blank */ + else if((obj->data.picture.width == 0 || obj->data.picture.height == 0 || obj->data.picture.depth == 0) && !local__extract_resolution_color_info_(&obj->data.picture)) + *error_message = error_messages[4]; + } + } + } + } + } + } + } + + if(*error_message == 0) { + if( + obj->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD && + ( + (strcmp(obj->data.picture.mime_type, "image/png") && strcmp(obj->data.picture.mime_type, "-->")) || + obj->data.picture.width != 32 || + obj->data.picture.height != 32 + ) + ) + *error_message = error_messages[9]; + } + + if(*error_message && obj) { + FLAC__metadata_object_delete(obj); + obj = 0; + } + + return obj; +} diff --git a/flac/src/share/grabbag/replaygain.c b/flac/src/share/grabbag/replaygain.c new file mode 100644 index 0000000..9d35701 --- /dev/null +++ b/flac/src/share/grabbag/replaygain.c @@ -0,0 +1,668 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "share/grabbag.h" +#include "share/replaygain_analysis.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "FLAC/stream_decoder.h" +#include +#include +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#include /* for chmod() */ +#endif +#include /* for stat(), maybe chmod() */ + +#ifdef local_min +#undef local_min +#endif +#define local_min(a,b) ((a)<(b)?(a):(b)) + +#ifdef local_max +#undef local_max +#endif +#define local_max(a,b) ((a)>(b)?(a):(b)) + +static const char *reference_format_ = "%s=%2.1f dB"; +static const char *gain_format_ = "%s=%+2.2f dB"; +static const char *peak_format_ = "%s=%1.8f"; + +static double album_peak_, title_peak_; + +const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190; +/* + FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 + + FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 + + FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 + + FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 + + FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +*/ + +const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS"; +const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN"; +const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK"; +const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN"; +const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK"; + + +static FLAC__bool get_file_stats_(const char *filename, struct stat *stats) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + return (0 == stat(filename, stats)); +} + +static void set_file_stats_(const char *filename, struct stat *stats) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + + (void)chmod(filename, stats->st_mode); +} + +static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value) +{ + char buffer[256]; + char *saved_locale; + FLAC__StreamMetadata_VorbisComment_Entry entry; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + FLAC__ASSERT(0 != format); + FLAC__ASSERT(0 != name); + + buffer[sizeof(buffer)-1] = '\0'; + /* + * We need to save the old locale and switch to "C" because the locale + * influences the formatting of %f and we want it a certain way. + */ + saved_locale = strdup(setlocale(LC_ALL, 0)); + if (0 == saved_locale) + return false; + setlocale(LC_ALL, "C"); +#if defined _MSC_VER || defined __MINGW32__ + _snprintf(buffer, sizeof(buffer)-1, format, name, value); +#else + snprintf(buffer, sizeof(buffer)-1, format, name, value); +#endif + setlocale(LC_ALL, saved_locale); + free(saved_locale); + + entry.entry = (FLAC__byte *)buffer; + entry.length = strlen(buffer); + + return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true); +} + +FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency) +{ + static const unsigned valid_sample_rates[] = { + 8000, + 11025, + 12000, + 16000, + 22050, + 24000, + 32000, + 44100, + 48000 + }; + static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]); + + unsigned i; + + for(i = 0; i < n_valid_sample_rates; i++) + if(sample_frequency == valid_sample_rates[i]) + return true; + return false; +} + +FLAC__bool grabbag__replaygain_init(unsigned sample_frequency) +{ + title_peak_ = album_peak_ = 0.0; + return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK; +} + +FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples) +{ + /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */ + static Float_t lbuffer[2048], rbuffer[2048]; + static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]); + FLAC__int32 block_peak = 0, s; + unsigned i, j; + + FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE); + FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4); + /* + * We use abs() on a FLAC__int32 which is undefined for the most negative value. + * If the reference codec ever handles 32bps we will have to write a special + * case here. + */ + FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32); + + if(bps == 16) { + if(is_stereo) { + j = 0; + while(samples > 0) { + const unsigned n = local_min(samples, nbuffer); + for(i = 0; i < n; i++, j++) { + s = input[0][j]; + lbuffer[i] = (Float_t)s; + s = abs(s); + block_peak = local_max(block_peak, s); + + s = input[1][j]; + rbuffer[i] = (Float_t)s; + s = abs(s); + block_peak = local_max(block_peak, s); + } + samples -= n; + if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK) + return false; + } + } + else { + j = 0; + while(samples > 0) { + const unsigned n = local_min(samples, nbuffer); + for(i = 0; i < n; i++, j++) { + s = input[0][j]; + lbuffer[i] = (Float_t)s; + s = abs(s); + block_peak = local_max(block_peak, s); + } + samples -= n; + if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK) + return false; + } + } + } + else { /* bps must be < 32 according to above assertion */ + const double scale = ( + (bps > 16)? + (double)1. / (double)(1u << (bps - 16)) : + (double)(1u << (16 - bps)) + ); + + if(is_stereo) { + j = 0; + while(samples > 0) { + const unsigned n = local_min(samples, nbuffer); + for(i = 0; i < n; i++, j++) { + s = input[0][j]; + lbuffer[i] = (Float_t)(scale * (double)s); + s = abs(s); + block_peak = local_max(block_peak, s); + + s = input[1][j]; + rbuffer[i] = (Float_t)(scale * (double)s); + s = abs(s); + block_peak = local_max(block_peak, s); + } + samples -= n; + if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK) + return false; + } + } + else { + j = 0; + while(samples > 0) { + const unsigned n = local_min(samples, nbuffer); + for(i = 0; i < n; i++, j++) { + s = input[0][j]; + lbuffer[i] = (Float_t)(scale * (double)s); + s = abs(s); + block_peak = local_max(block_peak, s); + } + samples -= n; + if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK) + return false; + } + } + } + + { + const double peak_scale = (double)(1u << (bps - 1)); + double peak = (double)block_peak / peak_scale; + if(peak > title_peak_) + title_peak_ = peak; + if(peak > album_peak_) + album_peak_ = peak; + } + + return true; +} + +void grabbag__replaygain_get_album(float *gain, float *peak) +{ + *gain = (float)GetAlbumGain(); + *peak = (float)album_peak_; + album_peak_ = 0.0; +} + +void grabbag__replaygain_get_title(float *gain, float *peak) +{ + *gain = (float)GetTitleGain(); + *peak = (float)title_peak_; + title_peak_ = 0.0; +} + + +typedef struct { + unsigned channels; + unsigned bits_per_sample; + unsigned sample_rate; + FLAC__bool error; +} DecoderInstance; + +static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + DecoderInstance *instance = (DecoderInstance*)client_data; + const unsigned bits_per_sample = frame->header.bits_per_sample; + const unsigned channels = frame->header.channels; + const unsigned sample_rate = frame->header.sample_rate; + const unsigned samples = frame->header.blocksize; + + (void)decoder; + + if( + !instance->error && + (channels == 2 || channels == 1) && + bits_per_sample == instance->bits_per_sample && + channels == instance->channels && + sample_rate == instance->sample_rate + ) { + instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples); + } + else { + instance->error = true; + } + + if(!instance->error) + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; + else + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; +} + +static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + DecoderInstance *instance = (DecoderInstance*)client_data; + + (void)decoder; + + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + instance->bits_per_sample = metadata->data.stream_info.bits_per_sample; + instance->channels = metadata->data.stream_info.channels; + instance->sample_rate = metadata->data.stream_info.sample_rate; + + if(instance->channels != 1 && instance->channels != 2) { + instance->error = true; + return; + } + + if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) { + instance->error = true; + return; + } + } +} + +static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + DecoderInstance *instance = (DecoderInstance*)client_data; + + (void)decoder, (void)status; + + instance->error = true; +} + +const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak) +{ + DecoderInstance instance; + FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new(); + + if(0 == decoder) + return "memory allocation error"; + + instance.error = false; + + /* It does these three by default but lets be explicit: */ + FLAC__stream_decoder_set_md5_checking(decoder, false); + FLAC__stream_decoder_set_metadata_ignore_all(decoder); + FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO); + + if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + FLAC__stream_decoder_delete(decoder); + return "initializing decoder"; + } + + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) { + FLAC__stream_decoder_delete(decoder); + return "decoding file"; + } + + FLAC__stream_decoder_delete(decoder); + + grabbag__replaygain_get_title(title_gain, title_peak); + + return 0; +} + +const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak) +{ + const char *error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) + return error; + + return 0; +} + +const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block) +{ + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0) + return "memory allocation error"; + + if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness)) + return "memory allocation error"; + + return 0; +} + +const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak) +{ + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + if( + FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 || + FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0 + ) + return "memory allocation error"; + + if( + !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) || + !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak) + ) + return "memory allocation error"; + + return 0; +} + +const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak) +{ + FLAC__ASSERT(0 != block); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + if( + FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 || + FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0 + ) + return "memory allocation error"; + + if( + !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) || + !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak) + ) + return "memory allocation error"; + + return 0; +} + +static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block) +{ + FLAC__Metadata_Iterator *iterator; + const char *error; + FLAC__bool found_vc_block = false; + + if(0 == (*chain = FLAC__metadata_chain_new())) + return "memory allocation error"; + + if(!FLAC__metadata_chain_read(*chain, filename)) { + error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)]; + FLAC__metadata_chain_delete(*chain); + return error; + } + + if(0 == (iterator = FLAC__metadata_iterator_new())) { + FLAC__metadata_chain_delete(*chain); + return "memory allocation error"; + } + + FLAC__metadata_iterator_init(iterator, *chain); + + do { + *block = FLAC__metadata_iterator_get_block(iterator); + if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) + found_vc_block = true; + } while(!found_vc_block && FLAC__metadata_iterator_next(iterator)); + + if(!found_vc_block) { + /* create a new block */ + *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 == *block) { + FLAC__metadata_chain_delete(*chain); + FLAC__metadata_iterator_delete(iterator); + return "memory allocation error"; + } + while(FLAC__metadata_iterator_next(iterator)) + ; + if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) { + error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)]; + FLAC__metadata_chain_delete(*chain); + FLAC__metadata_iterator_delete(iterator); + return error; + } + /* iterator is left pointing to new block */ + FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block); + } + + FLAC__metadata_iterator_delete(iterator); + + FLAC__ASSERT(0 != *block); + FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + return 0; +} + +static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime) +{ + struct stat stats; + const FLAC__bool have_stats = get_file_stats_(filename, &stats); + + (void)grabbag__file_change_stats(filename, /*read_only=*/false); + + FLAC__metadata_chain_sort_padding(chain); + if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) { + FLAC__metadata_chain_delete(chain); + return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]; + } + + FLAC__metadata_chain_delete(chain); + + if(have_stats) + set_file_stats_(filename, &stats); + + return 0; +} + +const char *grabbag__replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak, FLAC__bool preserve_modtime) +{ + FLAC__Metadata_Chain *chain; + FLAC__StreamMetadata *block; + const char *error; + + if(0 != (error = store_to_file_pre_(filename, &chain, &block))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) { + FLAC__metadata_chain_delete(chain); + return error; + } + + if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime))) + return error; + + return 0; +} + +const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime) +{ + FLAC__Metadata_Chain *chain; + FLAC__StreamMetadata *block; + const char *error; + + if(0 != (error = store_to_file_pre_(filename, &chain, &block))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) { + FLAC__metadata_chain_delete(chain); + return error; + } + + if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime))) + return error; + + return 0; +} + +const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime) +{ + FLAC__Metadata_Chain *chain; + FLAC__StreamMetadata *block; + const char *error; + + if(0 != (error = store_to_file_pre_(filename, &chain, &block))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) { + FLAC__metadata_chain_delete(chain); + return error; + } + + if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime))) + return error; + + return 0; +} + +const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime) +{ + FLAC__Metadata_Chain *chain; + FLAC__StreamMetadata *block; + const char *error; + + if(0 != (error = store_to_file_pre_(filename, &chain, &block))) + return error; + + if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) { + FLAC__metadata_chain_delete(chain); + return error; + } + + if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime))) + return error; + + return 0; +} + +static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val) +{ + char s[32], *end; + const char *p, *q; + double v; + + FLAC__ASSERT(0 != entry); + FLAC__ASSERT(0 != val); + + p = (const char *)entry->entry; + q = strchr(p, '='); + if(0 == q) + return false; + q++; + memset(s, 0, sizeof(s)-1); + strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p))); + + v = strtod(s, &end); + if(end == s) + return false; + + *val = v; + return true; +} + +FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak) +{ + int reference_offset, gain_offset, peak_offset; + + FLAC__ASSERT(0 != block); + FLAC__ASSERT(0 != reference); + FLAC__ASSERT(0 != gain); + FLAC__ASSERT(0 != peak); + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); + + /* Default to current level until overridden by a detected tag; this + * will always be true until we change replaygain_analysis.c + */ + *reference = ReplayGainReferenceLoudness; + + if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS))) + (void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference); + + if(0 > (gain_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN : GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN)))) + return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak); + if(0 > (peak_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK : GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK)))) + return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak); + + if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain)) + return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak); + if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak)) + return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak); + + return true; +} + +double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping) +{ + double scale; + FLAC__ASSERT(peak >= 0.0); + gain += preamp; + scale = (float) pow(10.0, gain * 0.05); + if(prevent_clipping && peak > 0.0) { + const double max_scale = (float)(1.0 / peak); + if(scale > max_scale) + scale = max_scale; + } + return scale; +} diff --git a/flac/src/share/grabbag/seektable.c b/flac/src/share/grabbag/seektable.c new file mode 100644 index 0000000..4cbea49 --- /dev/null +++ b/flac/src/share/grabbag/seektable.c @@ -0,0 +1,132 @@ +/* grabbag - Convenience lib for various routines common to several tools + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "share/grabbag.h" +#include "FLAC/assert.h" +#include /* for atoi() */ +#include + +#ifdef _MSC_VER +/* There's no strtoll() in MSVC6 so we just write a specialized one */ +static FLAC__int64 local__strtoll(const char *src, char **endptr) +{ + FLAC__bool neg = false; + FLAC__int64 ret = 0; + int c; + FLAC__ASSERT(0 != src); + if(*src == '-') { + neg = true; + src++; + } + while(0 != (c = *src)) { + c -= '0'; + if(c >= 0 && c <= 9) + ret = (ret * 10) + c; + else + break; + src++; + } + if(endptr) + *endptr = (char*)src; + return neg? -ret : ret; +} +#endif + +FLAC__bool grabbag__seektable_convert_specification_to_template(const char *spec, FLAC__bool only_explicit_placeholders, FLAC__uint64 total_samples_to_encode, unsigned sample_rate, FLAC__StreamMetadata *seektable_template, FLAC__bool *spec_has_real_points) +{ + unsigned i; + const char *pt; + + FLAC__ASSERT(0 != spec); + FLAC__ASSERT(0 != seektable_template); + FLAC__ASSERT(seektable_template->type = FLAC__METADATA_TYPE_SEEKTABLE); + + if(0 != spec_has_real_points) + *spec_has_real_points = false; + + for(pt = spec, i = 0; pt && *pt; i++) { + const char *q = strchr(pt, ';'); + FLAC__ASSERT(0 != q); + + if(q > pt) { + if(0 == strncmp(pt, "X;", 2)) { /* -S X */ + if(!FLAC__metadata_object_seektable_template_append_placeholders(seektable_template, 1)) + return false; + } + else if(q[-1] == 'x') { /* -S #x */ + if(total_samples_to_encode > 0) { /* we can only do these if we know the number of samples to encode up front */ + if(0 != spec_has_real_points) + *spec_has_real_points = true; + if(!only_explicit_placeholders) { + const int n = (unsigned)atoi(pt); + if(n > 0) + if(!FLAC__metadata_object_seektable_template_append_spaced_points(seektable_template, (unsigned)n, total_samples_to_encode)) + return false; + } + } + } + else if(q[-1] == 's') { /* -S #s */ + if(total_samples_to_encode > 0) { /* we can only do these if we know the number of samples to encode up front */ + FLAC__ASSERT(sample_rate > 0); + if(0 != spec_has_real_points) + *spec_has_real_points = true; + if(!only_explicit_placeholders) { + const double sec = atof(pt); + if(sec > 0.0) { + unsigned samples = (unsigned)(sec * (double)sample_rate); + if(samples > 0) { + /* +1 for the initial point at sample 0 */ + if(!FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(seektable_template, samples, total_samples_to_encode)) + return false; + } + } + } + } + } + else { /* -S # */ + if(0 != spec_has_real_points) + *spec_has_real_points = true; + if(!only_explicit_placeholders) { + char *endptr; +#ifdef _MSC_VER + const FLAC__int64 n = local__strtoll(pt, &endptr); +#else + const FLAC__int64 n = (FLAC__int64)strtoll(pt, &endptr, 10); +#endif + if( + (n > 0 || (endptr > pt && *endptr == ';')) && /* is a valid number (extra check needed for "0") */ + (total_samples_to_encode == 0 || (FLAC__uint64)n < total_samples_to_encode) /* number is not >= the known total_samples_to_encode */ + ) + if(!FLAC__metadata_object_seektable_template_append_point(seektable_template, (FLAC__uint64)n)) + return false; + } + } + } + + pt = ++q; + } + + if(!FLAC__metadata_object_seektable_template_sort(seektable_template, /*compact=*/true)) + return false; + + return true; +} diff --git a/flac/src/share/replaygain_analysis/Makefile.am b/flac/src/share/replaygain_analysis/Makefile.am new file mode 100644 index 0000000..b1b79f5 --- /dev/null +++ b/flac/src/share/replaygain_analysis/Makefile.am @@ -0,0 +1,20 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I$(top_srcdir)/include/share + +noinst_LTLIBRARIES = libreplaygain_analysis.la + +libreplaygain_analysis_la_SOURCES = replaygain_analysis.c + +EXTRA_DIST = \ + Makefile.lite \ + replaygain_analysis_static.dsp \ + replaygain_analysis_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/share/replaygain_analysis/Makefile.lite b/flac/src/share/replaygain_analysis/Makefile.lite new file mode 100644 index 0000000..5da12f4 --- /dev/null +++ b/flac/src/share/replaygain_analysis/Makefile.lite @@ -0,0 +1,15 @@ +# +# GNU makefile +# + +topdir = ../../.. + +LIB_NAME = libreplaygain_analysis +INCLUDES = -I$(topdir)/include/share + +SRCS_C = \ + replaygain_analysis.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/share/replaygain_analysis/replaygain_analysis.c b/flac/src/share/replaygain_analysis/replaygain_analysis.c new file mode 100644 index 0000000..d397815 --- /dev/null +++ b/flac/src/share/replaygain_analysis/replaygain_analysis.c @@ -0,0 +1,430 @@ +/* + * ReplayGainAnalysis - analyzes input samples and give the recommended dB change + * Copyright (C) 2001 David Robinson and Glen Sawyer + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * concept and filter values by David Robinson (David@Robinson.org) + * -- blame him if you think the idea is flawed + * original coding by Glen Sawyer (glensawyer@hotmail.com) + * -- blame him if you think this runs too slowly, or the coding is otherwise flawed + * + * lots of code improvements by Frank Klemm ( http://www.uni-jena.de/~pfk/mpp/ ) + * -- credit him for all the _good_ programming ;) + * + * minor cosmetic tweaks to integrate with FLAC by Josh Coalson + * + * + * For an explanation of the concepts and the basic algorithms involved, go to: + * http://www.replaygain.org/ + */ + +/* + * Here's the deal. Call + * + * InitGainAnalysis ( long samplefreq ); + * + * to initialize everything. Call + * + * AnalyzeSamples ( const Float_t* left_samples, + * const Float_t* right_samples, + * size_t num_samples, + * int num_channels ); + * + * as many times as you want, with as many or as few samples as you want. + * If mono, pass the sample buffer in through left_samples, leave + * right_samples NULL, and make sure num_channels = 1. + * + * GetTitleGain() + * + * will return the recommended dB level change for all samples analyzed + * SINCE THE LAST TIME you called GetTitleGain() OR InitGainAnalysis(). + * + * GetAlbumGain() + * + * will return the recommended dB level change for all samples analyzed + * since InitGainAnalysis() was called and finalized with GetTitleGain(). + * + * Pseudo-code to process an album: + * + * Float_t l_samples [4096]; + * Float_t r_samples [4096]; + * size_t num_samples; + * unsigned int num_songs; + * unsigned int i; + * + * InitGainAnalysis ( 44100 ); + * for ( i = 1; i <= num_songs; i++ ) { + * while ( ( num_samples = getSongSamples ( song[i], left_samples, right_samples ) ) > 0 ) + * AnalyzeSamples ( left_samples, right_samples, num_samples, 2 ); + * fprintf ("Recommended dB change for song %2d: %+6.2f dB\n", i, GetTitleGain() ); + * } + * fprintf ("Recommended dB change for whole album: %+6.2f dB\n", GetAlbumGain() ); + */ + +/* + * So here's the main source of potential code confusion: + * + * The filters applied to the incoming samples are IIR filters, + * meaning they rely on up to number of previous samples + * AND up to number of previous filtered samples. + * + * I set up the AnalyzeSamples routine to minimize memory usage and interface + * complexity. The speed isn't compromised too much (I don't think), but the + * internal complexity is higher than it should be for such a relatively + * simple routine. + * + * Optimization/clarity suggestions are welcome. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +#include "replaygain_analysis.h" + +Float_t ReplayGainReferenceLoudness = 89.0; /* in dB SPL */ + +typedef unsigned short Uint16_t; +typedef signed short Int16_t; +typedef unsigned int Uint32_t; +typedef signed int Int32_t; + +#define YULE_ORDER 10 +#define BUTTER_ORDER 2 +#define RMS_PERCENTILE 0.95 /* percentile which is louder than the proposed level */ +#define MAX_SAMP_FREQ 48000. /* maximum allowed sample frequency [Hz] */ +#define RMS_WINDOW_TIME 0.050 /* Time slice size [s] */ +#define STEPS_per_dB 100. /* Table entries per dB */ +#define MAX_dB 120. /* Table entries for 0...MAX_dB (normal max. values are 70...80 dB) */ + +#define MAX_ORDER (BUTTER_ORDER > YULE_ORDER ? BUTTER_ORDER : YULE_ORDER) +/* [JEC] the following was originally #defined as: + * (size_t) (MAX_SAMP_FREQ * RMS_WINDOW_TIME) + * but that seemed to fail to take into account the ceil() part of the + * sampleWindow calculation in ResetSampleFrequency(), and was causing + * buffer overflows for 48kHz analysis, hence the +1. + */ +#ifndef __sun + #define MAX_SAMPLES_PER_WINDOW (size_t) (MAX_SAMP_FREQ * RMS_WINDOW_TIME + 1.) /* max. Samples per Time slice */ +#else + /* [JEC] Solaris Forte compiler doesn't like float calc in array indices */ + #define MAX_SAMPLES_PER_WINDOW (size_t) (2401) +#endif +#define PINK_REF 64.82 /* 298640883795 */ /* calibration value */ + +static Float_t linprebuf [MAX_ORDER * 2]; +static Float_t* linpre; /* left input samples, with pre-buffer */ +static Float_t lstepbuf [MAX_SAMPLES_PER_WINDOW + MAX_ORDER]; +static Float_t* lstep; /* left "first step" (i.e. post first filter) samples */ +static Float_t loutbuf [MAX_SAMPLES_PER_WINDOW + MAX_ORDER]; +static Float_t* lout; /* left "out" (i.e. post second filter) samples */ +static Float_t rinprebuf [MAX_ORDER * 2]; +static Float_t* rinpre; /* right input samples ... */ +static Float_t rstepbuf [MAX_SAMPLES_PER_WINDOW + MAX_ORDER]; +static Float_t* rstep; +static Float_t routbuf [MAX_SAMPLES_PER_WINDOW + MAX_ORDER]; +static Float_t* rout; +static unsigned int sampleWindow; /* number of samples required to reach number of milliseconds required for RMS window */ +static unsigned long totsamp; +static double lsum; +static double rsum; +static int freqindex; +#ifndef __sun +static Uint32_t A [(size_t)(STEPS_per_dB * MAX_dB)]; +static Uint32_t B [(size_t)(STEPS_per_dB * MAX_dB)]; +#else +/* [JEC] Solaris Forte compiler doesn't like float calc in array indices */ +static Uint32_t A [12000]; +static Uint32_t B [12000]; +#endif + +/* for each filter: + [0] 48 kHz, [1] 44.1 kHz, [2] 32 kHz, [3] 24 kHz, [4] 22050 Hz, [5] 16 kHz, [6] 12 kHz, [7] is 11025 Hz, [8] 8 kHz */ + +#ifdef WIN32 +#pragma warning ( disable : 4305 ) +#endif + +static const Float_t AYule [9] [11] = { + { 1., -3.84664617118067, 7.81501653005538,-11.34170355132042, 13.05504219327545,-12.28759895145294, 9.48293806319790, -5.87257861775999, 2.75465861874613, -0.86984376593551, 0.13919314567432 }, + { 1., -3.47845948550071, 6.36317777566148, -8.54751527471874, 9.47693607801280, -8.81498681370155, 6.85401540936998, -4.39470996079559, 2.19611684890774, -0.75104302451432, 0.13149317958808 }, + { 1., -2.37898834973084, 2.84868151156327, -2.64577170229825, 2.23697657451713, -1.67148153367602, 1.00595954808547, -0.45953458054983, 0.16378164858596, -0.05032077717131, 0.02347897407020 }, + { 1., -1.61273165137247, 1.07977492259970, -0.25656257754070, -0.16276719120440, -0.22638893773906, 0.39120800788284, -0.22138138954925, 0.04500235387352, 0.02005851806501, 0.00302439095741 }, + { 1., -1.49858979367799, 0.87350271418188, 0.12205022308084, -0.80774944671438, 0.47854794562326, -0.12453458140019, -0.04067510197014, 0.08333755284107, -0.04237348025746, 0.02977207319925 }, + { 1., -0.62820619233671, 0.29661783706366, -0.37256372942400, 0.00213767857124, -0.42029820170918, 0.22199650564824, 0.00613424350682, 0.06747620744683, 0.05784820375801, 0.03222754072173 }, + { 1., -1.04800335126349, 0.29156311971249, -0.26806001042947, 0.00819999645858, 0.45054734505008, -0.33032403314006, 0.06739368333110, -0.04784254229033, 0.01639907836189, 0.01807364323573 }, + { 1., -0.51035327095184, -0.31863563325245, -0.20256413484477, 0.14728154134330, 0.38952639978999, -0.23313271880868, -0.05246019024463, -0.02505961724053, 0.02442357316099, 0.01818801111503 }, + { 1., -0.25049871956020, -0.43193942311114, -0.03424681017675, -0.04678328784242, 0.26408300200955, 0.15113130533216, -0.17556493366449, -0.18823009262115, 0.05477720428674, 0.04704409688120 } +}; + +static const Float_t BYule [9] [11] = { + { 0.03857599435200, -0.02160367184185, -0.00123395316851, -0.00009291677959, -0.01655260341619, 0.02161526843274, -0.02074045215285, 0.00594298065125, 0.00306428023191, 0.00012025322027, 0.00288463683916 }, + { 0.05418656406430, -0.02911007808948, -0.00848709379851, -0.00851165645469, -0.00834990904936, 0.02245293253339, -0.02596338512915, 0.01624864962975, -0.00240879051584, 0.00674613682247, -0.00187763777362 }, + { 0.15457299681924, -0.09331049056315, -0.06247880153653, 0.02163541888798, -0.05588393329856, 0.04781476674921, 0.00222312597743, 0.03174092540049, -0.01390589421898, 0.00651420667831, -0.00881362733839 }, + { 0.30296907319327, -0.22613988682123, -0.08587323730772, 0.03282930172664, -0.00915702933434, -0.02364141202522, -0.00584456039913, 0.06276101321749, -0.00000828086748, 0.00205861885564, -0.02950134983287 }, + { 0.33642304856132, -0.25572241425570, -0.11828570177555, 0.11921148675203, -0.07834489609479, -0.00469977914380, -0.00589500224440, 0.05724228140351, 0.00832043980773, -0.01635381384540, -0.01760176568150 }, + { 0.44915256608450, -0.14351757464547, -0.22784394429749, -0.01419140100551, 0.04078262797139, -0.12398163381748, 0.04097565135648, 0.10478503600251, -0.01863887810927, -0.03193428438915, 0.00541907748707 }, + { 0.56619470757641, -0.75464456939302, 0.16242137742230, 0.16744243493672, -0.18901604199609, 0.30931782841830, -0.27562961986224, 0.00647310677246, 0.08647503780351, -0.03788984554840, -0.00588215443421 }, + { 0.58100494960553, -0.53174909058578, -0.14289799034253, 0.17520704835522, 0.02377945217615, 0.15558449135573, -0.25344790059353, 0.01628462406333, 0.06920467763959, -0.03721611395801, -0.00749618797172 }, + { 0.53648789255105, -0.42163034350696, -0.00275953611929, 0.04267842219415, -0.10214864179676, 0.14590772289388, -0.02459864859345, -0.11202315195388, -0.04060034127000, 0.04788665548180, -0.02217936801134 } +}; + +static const Float_t AButter [9] [3] = { + { 1., -1.97223372919527, 0.97261396931306 }, + { 1., -1.96977855582618, 0.97022847566350 }, + { 1., -1.95835380975398, 0.95920349965459 }, + { 1., -1.95002759149878, 0.95124613669835 }, + { 1., -1.94561023566527, 0.94705070426118 }, + { 1., -1.92783286977036, 0.93034775234268 }, + { 1., -1.91858953033784, 0.92177618768381 }, + { 1., -1.91542108074780, 0.91885558323625 }, + { 1., -1.88903307939452, 0.89487434461664 } +}; + +static const Float_t BButter [9] [3] = { + { 0.98621192462708, -1.97242384925416, 0.98621192462708 }, + { 0.98500175787242, -1.97000351574484, 0.98500175787242 }, + { 0.97938932735214, -1.95877865470428, 0.97938932735214 }, + { 0.97531843204928, -1.95063686409857, 0.97531843204928 }, + { 0.97316523498161, -1.94633046996323, 0.97316523498161 }, + { 0.96454515552826, -1.92909031105652, 0.96454515552826 }, + { 0.96009142950541, -1.92018285901082, 0.96009142950541 }, + { 0.95856916599601, -1.91713833199203, 0.95856916599601 }, + { 0.94597685600279, -1.89195371200558, 0.94597685600279 } +}; + +#ifdef WIN32 +#pragma warning ( default : 4305 ) +#endif + +/* When calling this procedure, make sure that ip[-order] and op[-order] point to real data! */ + +static void +filter ( const Float_t* input, Float_t* output, size_t nSamples, const Float_t* a, const Float_t* b, size_t order ) +{ + double y; + size_t i; + size_t k; + + for ( i = 0; i < nSamples; i++ ) { + y = input[i] * b[0]; + for ( k = 1; k <= order; k++ ) + y += input[i-k] * b[k] - output[i-k] * a[k]; + output[i] = (Float_t)y; + } +} + +/* returns a INIT_GAIN_ANALYSIS_OK if successful, INIT_GAIN_ANALYSIS_ERROR if not */ + +int +ResetSampleFrequency ( long samplefreq ) { + int i; + + /* zero out initial values */ + for ( i = 0; i < MAX_ORDER; i++ ) + linprebuf[i] = lstepbuf[i] = loutbuf[i] = rinprebuf[i] = rstepbuf[i] = routbuf[i] = 0.; + + switch ( (int)(samplefreq) ) { + case 48000: freqindex = 0; break; + case 44100: freqindex = 1; break; + case 32000: freqindex = 2; break; + case 24000: freqindex = 3; break; + case 22050: freqindex = 4; break; + case 16000: freqindex = 5; break; + case 12000: freqindex = 6; break; + case 11025: freqindex = 7; break; + case 8000: freqindex = 8; break; + default: return INIT_GAIN_ANALYSIS_ERROR; + } + + sampleWindow = (int) ceil (samplefreq * RMS_WINDOW_TIME); + + lsum = 0.; + rsum = 0.; + totsamp = 0; + + memset ( A, 0, sizeof(A) ); + + return INIT_GAIN_ANALYSIS_OK; +} + +int +InitGainAnalysis ( long samplefreq ) +{ + if (ResetSampleFrequency(samplefreq) != INIT_GAIN_ANALYSIS_OK) { + return INIT_GAIN_ANALYSIS_ERROR; + } + + linpre = linprebuf + MAX_ORDER; + rinpre = rinprebuf + MAX_ORDER; + lstep = lstepbuf + MAX_ORDER; + rstep = rstepbuf + MAX_ORDER; + lout = loutbuf + MAX_ORDER; + rout = routbuf + MAX_ORDER; + + memset ( B, 0, sizeof(B) ); + + return INIT_GAIN_ANALYSIS_OK; +} + +/* returns GAIN_ANALYSIS_OK if successful, GAIN_ANALYSIS_ERROR if not */ + +int +AnalyzeSamples ( const Float_t* left_samples, const Float_t* right_samples, size_t num_samples, int num_channels ) +{ + const Float_t* curleft; + const Float_t* curright; + long batchsamples; + long cursamples; + long cursamplepos; + int i; + + if ( num_samples == 0 ) + return GAIN_ANALYSIS_OK; + + cursamplepos = 0; + batchsamples = num_samples; + + switch ( num_channels) { + case 1: right_samples = left_samples; + case 2: break; + default: return GAIN_ANALYSIS_ERROR; + } + + if ( num_samples < MAX_ORDER ) { + memcpy ( linprebuf + MAX_ORDER, left_samples , num_samples * sizeof(Float_t) ); + memcpy ( rinprebuf + MAX_ORDER, right_samples, num_samples * sizeof(Float_t) ); + } + else { + memcpy ( linprebuf + MAX_ORDER, left_samples, MAX_ORDER * sizeof(Float_t) ); + memcpy ( rinprebuf + MAX_ORDER, right_samples, MAX_ORDER * sizeof(Float_t) ); + } + + while ( batchsamples > 0 ) { + cursamples = batchsamples > (long)(sampleWindow-totsamp) ? (long)(sampleWindow - totsamp) : batchsamples; + if ( cursamplepos < MAX_ORDER ) { + curleft = linpre+cursamplepos; + curright = rinpre+cursamplepos; + if (cursamples > MAX_ORDER - cursamplepos ) + cursamples = MAX_ORDER - cursamplepos; + } + else { + curleft = left_samples + cursamplepos; + curright = right_samples + cursamplepos; + } + + filter ( curleft , lstep + totsamp, cursamples, AYule[freqindex], BYule[freqindex], YULE_ORDER ); + filter ( curright, rstep + totsamp, cursamples, AYule[freqindex], BYule[freqindex], YULE_ORDER ); + + filter ( lstep + totsamp, lout + totsamp, cursamples, AButter[freqindex], BButter[freqindex], BUTTER_ORDER ); + filter ( rstep + totsamp, rout + totsamp, cursamples, AButter[freqindex], BButter[freqindex], BUTTER_ORDER ); + + for ( i = 0; i < cursamples; i++ ) { /* Get the squared values */ + lsum += lout [totsamp+i] * lout [totsamp+i]; + rsum += rout [totsamp+i] * rout [totsamp+i]; + } + + batchsamples -= cursamples; + cursamplepos += cursamples; + totsamp += cursamples; + if ( totsamp == sampleWindow ) { /* Get the Root Mean Square (RMS) for this set of samples */ + double val = STEPS_per_dB * 10. * log10 ( (lsum+rsum) / totsamp * 0.5 + 1.e-37 ); + int ival = (int) val; + if ( ival < 0 ) ival = 0; + if ( ival >= (int)(sizeof(A)/sizeof(*A)) ) ival = (int)(sizeof(A)/sizeof(*A)) - 1; + A [ival]++; + lsum = rsum = 0.; + memmove ( loutbuf , loutbuf + totsamp, MAX_ORDER * sizeof(Float_t) ); + memmove ( routbuf , routbuf + totsamp, MAX_ORDER * sizeof(Float_t) ); + memmove ( lstepbuf, lstepbuf + totsamp, MAX_ORDER * sizeof(Float_t) ); + memmove ( rstepbuf, rstepbuf + totsamp, MAX_ORDER * sizeof(Float_t) ); + totsamp = 0; + } + if ( totsamp > sampleWindow ) /* somehow I really screwed up: Error in programming! Contact author about totsamp > sampleWindow */ + return GAIN_ANALYSIS_ERROR; + } + if ( num_samples < MAX_ORDER ) { + memmove ( linprebuf, linprebuf + num_samples, (MAX_ORDER-num_samples) * sizeof(Float_t) ); + memmove ( rinprebuf, rinprebuf + num_samples, (MAX_ORDER-num_samples) * sizeof(Float_t) ); + memcpy ( linprebuf + MAX_ORDER - num_samples, left_samples, num_samples * sizeof(Float_t) ); + memcpy ( rinprebuf + MAX_ORDER - num_samples, right_samples, num_samples * sizeof(Float_t) ); + } + else { + memcpy ( linprebuf, left_samples + num_samples - MAX_ORDER, MAX_ORDER * sizeof(Float_t) ); + memcpy ( rinprebuf, right_samples + num_samples - MAX_ORDER, MAX_ORDER * sizeof(Float_t) ); + } + + return GAIN_ANALYSIS_OK; +} + + +static Float_t +analyzeResult ( Uint32_t* Array, size_t len ) +{ + Uint32_t elems; + Int32_t upper; + size_t i; + + elems = 0; + for ( i = 0; i < len; i++ ) + elems += Array[i]; + if ( elems == 0 ) + return GAIN_NOT_ENOUGH_SAMPLES; + + upper = (Int32_t) ceil (elems * (1. - RMS_PERCENTILE)); + for ( i = len; i-- > 0; ) { + if ( (upper -= Array[i]) <= 0 ) + break; + } + + return (Float_t) ((Float_t)PINK_REF - (Float_t)i / (Float_t)STEPS_per_dB); +} + + +Float_t +GetTitleGain ( void ) +{ + Float_t retval; + unsigned int i; + + retval = analyzeResult ( A, sizeof(A)/sizeof(*A) ); + + for ( i = 0; i < sizeof(A)/sizeof(*A); i++ ) { + B[i] += A[i]; + A[i] = 0; + } + + for ( i = 0; i < MAX_ORDER; i++ ) + linprebuf[i] = lstepbuf[i] = loutbuf[i] = rinprebuf[i] = rstepbuf[i] = routbuf[i] = 0.f; + + totsamp = 0; + lsum = rsum = 0.; + return retval; +} + + +Float_t +GetAlbumGain ( void ) +{ + return analyzeResult ( B, sizeof(B)/sizeof(*B) ); +} + +/* end of replaygain_analysis.c */ diff --git a/flac/src/share/replaygain_analysis/replaygain_analysis_static.dsp b/flac/src/share/replaygain_analysis/replaygain_analysis_static.dsp new file mode 100644 index 0000000..69c1da8 --- /dev/null +++ b/flac/src/share/replaygain_analysis/replaygain_analysis_static.dsp @@ -0,0 +1,108 @@ +# Microsoft Developer Studio Project File - Name="replaygain_analysis_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=replaygain_analysis_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "replaygain_analysis_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "replaygain_analysis_static.mak" CFG="replaygain_analysis_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "replaygain_analysis_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "replaygain_analysis_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "replaygain_analysis" +# PROP Scc_LocalPath "..\..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "replaygain_analysis_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /Op /I ".\include" /I "..\..\..\include\share" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "replaygain_analysis_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\..\include\share" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "replaygain_analysis_static - Win32 Release" +# Name "replaygain_analysis_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\replaygain_analysis.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\replaygain_analysis.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/share/replaygain_analysis/replaygain_analysis_static.vcproj b/flac/src/share/replaygain_analysis/replaygain_analysis_static.vcproj new file mode 100644 index 0000000..bd25ef0 --- /dev/null +++ b/flac/src/share/replaygain_analysis/replaygain_analysis_static.vcproj @@ -0,0 +1,318 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/share/replaygain_synthesis/Makefile.am b/flac/src/share/replaygain_synthesis/Makefile.am new file mode 100644 index 0000000..d7de1b7 --- /dev/null +++ b/flac/src/share/replaygain_synthesis/Makefile.am @@ -0,0 +1,22 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = include . + +INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/include/share + +noinst_LTLIBRARIES = libreplaygain_synthesis.la + +libreplaygain_synthesis_la_SOURCES = replaygain_synthesis.c + +EXTRA_DIST = \ + Makefile.lite \ + replaygain_synthesis_static.dsp \ + replaygain_synthesis_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/share/replaygain_synthesis/Makefile.lite b/flac/src/share/replaygain_synthesis/Makefile.lite new file mode 100644 index 0000000..717264c --- /dev/null +++ b/flac/src/share/replaygain_synthesis/Makefile.lite @@ -0,0 +1,15 @@ +# +# GNU makefile +# + +topdir = ../../.. + +LIB_NAME = libreplaygain_synthesis +INCLUDES = -I./include -I$(topdir)/include -I$(topdir)/include/share + +SRCS_C = \ + replaygain_synthesis.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/share/replaygain_synthesis/include/Makefile.am b/flac/src/share/replaygain_synthesis/include/Makefile.am new file mode 100644 index 0000000..8d7a237 --- /dev/null +++ b/flac/src/share/replaygain_synthesis/include/Makefile.am @@ -0,0 +1,18 @@ +# replaygain_synthesis - Routines for applying ReplayGain to a signal +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +SUBDIRS = private diff --git a/flac/src/share/replaygain_synthesis/include/private/Makefile.am b/flac/src/share/replaygain_synthesis/include/private/Makefile.am new file mode 100644 index 0000000..5b9952a --- /dev/null +++ b/flac/src/share/replaygain_synthesis/include/private/Makefile.am @@ -0,0 +1,19 @@ +# replaygain_synthesis - Routines for applying ReplayGain to a signal +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +noinst_HEADERS = \ + fast_float_math_hack.h diff --git a/flac/src/share/replaygain_synthesis/include/private/fast_float_math_hack.h b/flac/src/share/replaygain_synthesis/include/private/fast_float_math_hack.h new file mode 100644 index 0000000..e73fe41 --- /dev/null +++ b/flac/src/share/replaygain_synthesis/include/private/fast_float_math_hack.h @@ -0,0 +1,39 @@ +# ifdef __ICL /* only Intel C compiler has fmath ??? */ + + #include + +/* Nearest integer, absolute value, etc. */ + + #define ceil ceilf + #define fabs fabsf + #define floor floorf + #define fmod fmodf + #define rint rintf + #define hypot hypotf + +/* Power functions */ + + #define pow powf + #define sqrt sqrtf + +/* Exponential and logarithmic functions */ + + #define exp expf + #define log logf + #define log10 log10f + +/* Trigonometric functions */ + + #define acos acosf + #define asin asinf + #define atan atanf + #define cos cosf + #define sin sinf + #define tan tanf + +/* Hyperbolic functions */ + #define cosh coshf + #define sinh sinhf + #define tanh tanhf + +# endif diff --git a/flac/src/share/replaygain_synthesis/replaygain_synthesis.c b/flac/src/share/replaygain_synthesis/replaygain_synthesis.c new file mode 100644 index 0000000..cfa9985 --- /dev/null +++ b/flac/src/share/replaygain_synthesis/replaygain_synthesis.c @@ -0,0 +1,467 @@ +/* replaygain_synthesis - Routines for applying ReplayGain to a signal + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +/* + * This is an aggregation of pieces of code from John Edwards' WaveGain + * program. Mostly cosmetic changes were made; otherwise, the dithering + * code is almost untouched and the gain processing was converted from + * processing a whole file to processing chunks of samples. + * + * The original copyright notices for WaveGain's dither.c and wavegain.c + * appear below: + */ +/* + * (c) 2002 John Edwards + * mostly lifted from work by Frank Klemm + * random functions for dithering. + */ +/* + * Copyright (C) 2002 John Edwards + * Additional code by Magnus Holmgren and Gian-Carlo Pascutto + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include /* for memset() */ +#include +#include "private/fast_float_math_hack.h" +#include "replaygain_synthesis.h" +#include "FLAC/assert.h" + +#ifndef FLaC__INLINE +#define FLaC__INLINE +#endif + +/* adjust for compilers that can't understand using LL suffix for int64_t literals */ +#ifdef _MSC_VER +#define FLAC__I64L(x) x +#else +#define FLAC__I64L(x) x##LL +#endif + + +/* + * the following is based on parts of dither.c + */ + + +/* + * This is a simple random number generator with good quality for audio purposes. + * It consists of two polycounters with opposite rotation direction and different + * periods. The periods are coprime, so the total period is the product of both. + * + * ------------------------------------------------------------------------------------------------- + * +-> |31:30:29:28:27:26:25:24:23:22:21:20:19:18:17:16:15:14:13:12:11:10: 9: 8: 7: 6: 5: 4: 3: 2: 1: 0| + * | ------------------------------------------------------------------------------------------------- + * | | | | | | | + * | +--+--+--+-XOR-+--------+ + * | | + * +--------------------------------------------------------------------------------------+ + * + * ------------------------------------------------------------------------------------------------- + * |31:30:29:28:27:26:25:24:23:22:21:20:19:18:17:16:15:14:13:12:11:10: 9: 8: 7: 6: 5: 4: 3: 2: 1: 0| <-+ + * ------------------------------------------------------------------------------------------------- | + * | | | | | + * +--+----XOR----+--+ | + * | | + * +----------------------------------------------------------------------------------------+ + * + * + * The first has an period of 3*5*17*257*65537, the second of 7*47*73*178481, + * which gives a period of 18.410.713.077.675.721.215. The result is the + * XORed values of both generators. + */ + +static unsigned int random_int_(void) +{ + static const unsigned char parity_[256] = { + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0 + }; + static unsigned int r1_ = 1; + static unsigned int r2_ = 1; + + unsigned int t1, t2, t3, t4; + + /* Parity calculation is done via table lookup, this is also available + * on CPUs without parity, can be implemented in C and avoid unpredictable + * jumps and slow rotate through the carry flag operations. + */ + t3 = t1 = r1_; t4 = t2 = r2_; + t1 &= 0xF5; t2 >>= 25; + t1 = parity_[t1]; t2 &= 0x63; + t1 <<= 31; t2 = parity_[t2]; + + return (r1_ = (t3 >> 1) | t1 ) ^ (r2_ = (t4 + t4) | t2 ); +} + +/* gives a equal distributed random number */ +/* between -2^31*mult and +2^31*mult */ +static double random_equi_(double mult) +{ + return mult * (int) random_int_(); +} + +/* gives a triangular distributed random number */ +/* between -2^32*mult and +2^32*mult */ +static double random_triangular_(double mult) +{ + return mult * ( (double) (int) random_int_() + (double) (int) random_int_() ); +} + + +static const float F44_0 [16 + 32] = { + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, + + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, + + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, + (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0, (float)0 +}; + + +static const float F44_1 [16 + 32] = { /* SNR(w) = 4.843163 dB, SNR = -3.192134 dB */ + (float) 0.85018292704024355931, (float) 0.29089597350995344721, (float)-0.05021866022121039450, (float)-0.23545456294599161833, + (float)-0.58362726442227032096, (float)-0.67038978965193036429, (float)-0.38566861572833459221, (float)-0.15218663390367969967, + (float)-0.02577543084864530676, (float) 0.14119295297688728127, (float) 0.22398848581628781612, (float) 0.15401727203382084116, + (float) 0.05216161232906000929, (float)-0.00282237820999675451, (float)-0.03042794608323867363, (float)-0.03109780942998826024, + + (float) 0.85018292704024355931, (float) 0.29089597350995344721, (float)-0.05021866022121039450, (float)-0.23545456294599161833, + (float)-0.58362726442227032096, (float)-0.67038978965193036429, (float)-0.38566861572833459221, (float)-0.15218663390367969967, + (float)-0.02577543084864530676, (float) 0.14119295297688728127, (float) 0.22398848581628781612, (float) 0.15401727203382084116, + (float) 0.05216161232906000929, (float)-0.00282237820999675451, (float)-0.03042794608323867363, (float)-0.03109780942998826024, + + (float) 0.85018292704024355931, (float) 0.29089597350995344721, (float)-0.05021866022121039450, (float)-0.23545456294599161833, + (float)-0.58362726442227032096, (float)-0.67038978965193036429, (float)-0.38566861572833459221, (float)-0.15218663390367969967, + (float)-0.02577543084864530676, (float) 0.14119295297688728127, (float) 0.22398848581628781612, (float) 0.15401727203382084116, + (float) 0.05216161232906000929, (float)-0.00282237820999675451, (float)-0.03042794608323867363, (float)-0.03109780942998826024, +}; + + +static const float F44_2 [16 + 32] = { /* SNR(w) = 10.060213 dB, SNR = -12.766730 dB */ + (float) 1.78827593892108555290, (float) 0.95508210637394326553, (float)-0.18447626783899924429, (float)-0.44198126506275016437, + (float)-0.88404052492547413497, (float)-1.42218907262407452967, (float)-1.02037566838362314995, (float)-0.34861755756425577264, + (float)-0.11490230170431934434, (float) 0.12498899339968611803, (float) 0.38065885268563131927, (float) 0.31883491321310506562, + (float) 0.10486838686563442765, (float)-0.03105361685110374845, (float)-0.06450524884075370758, (float)-0.02939198261121969816, + + (float) 1.78827593892108555290, (float) 0.95508210637394326553, (float)-0.18447626783899924429, (float)-0.44198126506275016437, + (float)-0.88404052492547413497, (float)-1.42218907262407452967, (float)-1.02037566838362314995, (float)-0.34861755756425577264, + (float)-0.11490230170431934434, (float) 0.12498899339968611803, (float) 0.38065885268563131927, (float) 0.31883491321310506562, + (float) 0.10486838686563442765, (float)-0.03105361685110374845, (float)-0.06450524884075370758, (float)-0.02939198261121969816, + + (float) 1.78827593892108555290, (float) 0.95508210637394326553, (float)-0.18447626783899924429, (float)-0.44198126506275016437, + (float)-0.88404052492547413497, (float)-1.42218907262407452967, (float)-1.02037566838362314995, (float)-0.34861755756425577264, + (float)-0.11490230170431934434, (float) 0.12498899339968611803, (float) 0.38065885268563131927, (float) 0.31883491321310506562, + (float) 0.10486838686563442765, (float)-0.03105361685110374845, (float)-0.06450524884075370758, (float)-0.02939198261121969816, +}; + + +static const float F44_3 [16 + 32] = { /* SNR(w) = 15.382598 dB, SNR = -29.402334 dB */ + (float) 2.89072132015058161445, (float) 2.68932810943698754106, (float) 0.21083359339410251227, (float)-0.98385073324997617515, + (float)-1.11047823227097316719, (float)-2.18954076314139673147, (float)-2.36498032881953056225, (float)-0.95484132880101140785, + (float)-0.23924057925542965158, (float)-0.13865235703915925642, (float) 0.43587843191057992846, (float) 0.65903257226026665927, + (float) 0.24361815372443152787, (float)-0.00235974960154720097, (float) 0.01844166574603346289, (float) 0.01722945988740875099, + + (float) 2.89072132015058161445, (float) 2.68932810943698754106, (float) 0.21083359339410251227, (float)-0.98385073324997617515, + (float)-1.11047823227097316719, (float)-2.18954076314139673147, (float)-2.36498032881953056225, (float)-0.95484132880101140785, + (float)-0.23924057925542965158, (float)-0.13865235703915925642, (float) 0.43587843191057992846, (float) 0.65903257226026665927, + (float) 0.24361815372443152787, (float)-0.00235974960154720097, (float) 0.01844166574603346289, (float) 0.01722945988740875099, + + (float) 2.89072132015058161445, (float) 2.68932810943698754106, (float) 0.21083359339410251227, (float)-0.98385073324997617515, + (float)-1.11047823227097316719, (float)-2.18954076314139673147, (float)-2.36498032881953056225, (float)-0.95484132880101140785, + (float)-0.23924057925542965158, (float)-0.13865235703915925642, (float) 0.43587843191057992846, (float) 0.65903257226026665927, + (float) 0.24361815372443152787, (float)-0.00235974960154720097, (float) 0.01844166574603346289, (float) 0.01722945988740875099 +}; + + +static double scalar16_(const float* x, const float* y) +{ + return + x[ 0]*y[ 0] + x[ 1]*y[ 1] + x[ 2]*y[ 2] + x[ 3]*y[ 3] + + x[ 4]*y[ 4] + x[ 5]*y[ 5] + x[ 6]*y[ 6] + x[ 7]*y[ 7] + + x[ 8]*y[ 8] + x[ 9]*y[ 9] + x[10]*y[10] + x[11]*y[11] + + x[12]*y[12] + x[13]*y[13] + x[14]*y[14] + x[15]*y[15]; +} + + +void FLAC__replaygain_synthesis__init_dither_context(DitherContext *d, int bits, int shapingtype) +{ + static unsigned char default_dither [] = { 92, 92, 88, 84, 81, 78, 74, 67, 0, 0 }; + static const float* F [] = { F44_0, F44_1, F44_2, F44_3 }; + + int index; + + if (shapingtype < 0) shapingtype = 0; + if (shapingtype > 3) shapingtype = 3; + d->ShapingType = (NoiseShaping)shapingtype; + index = bits - 11 - shapingtype; + if (index < 0) index = 0; + if (index > 9) index = 9; + + memset ( d->ErrorHistory , 0, sizeof (d->ErrorHistory ) ); + memset ( d->DitherHistory, 0, sizeof (d->DitherHistory) ); + + d->FilterCoeff = F [shapingtype]; + d->Mask = ((FLAC__uint64)-1) << (32 - bits); + d->Add = 0.5 * ((1L << (32 - bits)) - 1); + d->Dither = 0.01f*default_dither[index] / (((FLAC__int64)1) << bits); + d->LastHistoryIndex = 0; +} + +/* + * the following is based on parts of wavegain.c + */ + +static FLaC__INLINE FLAC__int64 dither_output_(DitherContext *d, FLAC__bool do_dithering, int shapingtype, int i, double Sum, int k) +{ + union { + double d; + FLAC__int64 i; + } doubletmp; + double Sum2; + FLAC__int64 val; + +#define ROUND64(x) ( doubletmp.d = (x) + d->Add + (FLAC__int64)FLAC__I64L(0x001FFFFD80000000), doubletmp.i - (FLAC__int64)FLAC__I64L(0x433FFFFD80000000) ) + + if(do_dithering) { + if(shapingtype == 0) { + double tmp = random_equi_(d->Dither); + Sum2 = tmp - d->LastRandomNumber [k]; + d->LastRandomNumber [k] = (int)tmp; + Sum2 = Sum += Sum2; + val = ROUND64(Sum2) & d->Mask; + } + else { + Sum2 = random_triangular_(d->Dither) - scalar16_(d->DitherHistory[k], d->FilterCoeff + i); + Sum += d->DitherHistory [k] [(-1-i)&15] = (float)Sum2; + Sum2 = Sum + scalar16_(d->ErrorHistory [k], d->FilterCoeff + i); + val = ROUND64(Sum2) & d->Mask; + d->ErrorHistory [k] [(-1-i)&15] = (float)(Sum - val); + } + return val; + } + else + return ROUND64(Sum); + +#undef ROUND64 +} + +#if 0 + float peak = 0.f, + new_peak, + factor_clip + double scale, + dB; + + ... + + peak is in the range -32768.0 .. 32767.0 + + /* calculate factors for ReplayGain and ClippingPrevention */ + *track_gain = GetTitleGain() + settings->man_gain; + scale = (float) pow(10., *track_gain * 0.05); + if(settings->clip_prev) { + factor_clip = (float) (32767./( peak + 1)); + if(scale < factor_clip) + factor_clip = 1.f; + else + factor_clip /= scale; + scale *= factor_clip; + } + new_peak = (float) peak * scale; + + dB = 20. * log10(scale); + *track_gain = (float) dB; + + const double scale = pow(10., (double)gain * 0.05); +#endif + + +size_t FLAC__replaygain_synthesis__apply_gain(FLAC__byte *data_out, FLAC__bool little_endian_data_out, FLAC__bool unsigned_data_out, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, const unsigned source_bps, const unsigned target_bps, const double scale, const FLAC__bool hard_limit, FLAC__bool do_dithering, DitherContext *dither_context) +{ + static const FLAC__int32 conv_factors_[33] = { + -1, /* 0 bits-per-sample (not supported) */ + -1, /* 1 bits-per-sample (not supported) */ + -1, /* 2 bits-per-sample (not supported) */ + -1, /* 3 bits-per-sample (not supported) */ + 268435456, /* 4 bits-per-sample */ + 134217728, /* 5 bits-per-sample */ + 67108864, /* 6 bits-per-sample */ + 33554432, /* 7 bits-per-sample */ + 16777216, /* 8 bits-per-sample */ + 8388608, /* 9 bits-per-sample */ + 4194304, /* 10 bits-per-sample */ + 2097152, /* 11 bits-per-sample */ + 1048576, /* 12 bits-per-sample */ + 524288, /* 13 bits-per-sample */ + 262144, /* 14 bits-per-sample */ + 131072, /* 15 bits-per-sample */ + 65536, /* 16 bits-per-sample */ + 32768, /* 17 bits-per-sample */ + 16384, /* 18 bits-per-sample */ + 8192, /* 19 bits-per-sample */ + 4096, /* 20 bits-per-sample */ + 2048, /* 21 bits-per-sample */ + 1024, /* 22 bits-per-sample */ + 512, /* 23 bits-per-sample */ + 256, /* 24 bits-per-sample */ + 128, /* 25 bits-per-sample */ + 64, /* 26 bits-per-sample */ + 32, /* 27 bits-per-sample */ + 16, /* 28 bits-per-sample */ + 8, /* 29 bits-per-sample */ + 4, /* 30 bits-per-sample */ + 2, /* 31 bits-per-sample */ + 1 /* 32 bits-per-sample */ + }; + static const FLAC__int64 hard_clip_factors_[33] = { + 0, /* 0 bits-per-sample (not supported) */ + 0, /* 1 bits-per-sample (not supported) */ + 0, /* 2 bits-per-sample (not supported) */ + 0, /* 3 bits-per-sample (not supported) */ + -8, /* 4 bits-per-sample */ + -16, /* 5 bits-per-sample */ + -32, /* 6 bits-per-sample */ + -64, /* 7 bits-per-sample */ + -128, /* 8 bits-per-sample */ + -256, /* 9 bits-per-sample */ + -512, /* 10 bits-per-sample */ + -1024, /* 11 bits-per-sample */ + -2048, /* 12 bits-per-sample */ + -4096, /* 13 bits-per-sample */ + -8192, /* 14 bits-per-sample */ + -16384, /* 15 bits-per-sample */ + -32768, /* 16 bits-per-sample */ + -65536, /* 17 bits-per-sample */ + -131072, /* 18 bits-per-sample */ + -262144, /* 19 bits-per-sample */ + -524288, /* 20 bits-per-sample */ + -1048576, /* 21 bits-per-sample */ + -2097152, /* 22 bits-per-sample */ + -4194304, /* 23 bits-per-sample */ + -8388608, /* 24 bits-per-sample */ + -16777216, /* 25 bits-per-sample */ + -33554432, /* 26 bits-per-sample */ + -67108864, /* 27 bits-per-sample */ + -134217728, /* 28 bits-per-sample */ + -268435456, /* 29 bits-per-sample */ + -536870912, /* 30 bits-per-sample */ + -1073741824, /* 31 bits-per-sample */ + (FLAC__int64)(-1073741824) * 2 /* 32 bits-per-sample */ + }; + const FLAC__int32 conv_factor = conv_factors_[target_bps]; + const FLAC__int64 hard_clip_factor = hard_clip_factors_[target_bps]; + /* + * The integer input coming in has a varying range based on the + * source_bps. We want to normalize it to [-1.0, 1.0) so instead + * of doing two multiplies on each sample, we just multiple + * 'scale' by 1/(2^(source_bps-1)) + */ + const double multi_scale = scale / (double)(1u << (source_bps-1)); + + FLAC__byte * const start = data_out; + unsigned i, channel; + const FLAC__int32 *input_; + double sample; + const unsigned bytes_per_sample = target_bps / 8; + const unsigned last_history_index = dither_context->LastHistoryIndex; + NoiseShaping noise_shaping = dither_context->ShapingType; + FLAC__int64 val64; + FLAC__int32 val32; + FLAC__int32 uval32; + const FLAC__uint32 twiggle = 1u << (target_bps - 1); + + FLAC__ASSERT(channels > 0 && channels <= FLAC_SHARE__MAX_SUPPORTED_CHANNELS); + FLAC__ASSERT(source_bps >= 4); + FLAC__ASSERT(target_bps >= 4); + FLAC__ASSERT(source_bps <= 32); + FLAC__ASSERT(target_bps < 32); + FLAC__ASSERT((target_bps & 7) == 0); + + for(channel = 0; channel < channels; channel++) { + const unsigned incr = bytes_per_sample * channels; + data_out = start + bytes_per_sample * channel; + input_ = input[channel]; + for(i = 0; i < wide_samples; i++, data_out += incr) { + sample = (double)input_[i] * multi_scale; + + if(hard_limit) { + /* hard 6dB limiting */ + if(sample < -0.5) + sample = tanh((sample + 0.5) / (1-0.5)) * (1-0.5) - 0.5; + else if(sample > 0.5) + sample = tanh((sample - 0.5) / (1-0.5)) * (1-0.5) + 0.5; + } + sample *= 2147483647.f; + + val64 = dither_output_(dither_context, do_dithering, noise_shaping, (i + last_history_index) % 32, sample, channel) / conv_factor; + + val32 = (FLAC__int32)val64; + if(val64 >= -hard_clip_factor) + val32 = (FLAC__int32)(-(hard_clip_factor+1)); + else if(val64 < hard_clip_factor) + val32 = (FLAC__int32)hard_clip_factor; + + uval32 = (FLAC__uint32)val32; + if (unsigned_data_out) + uval32 ^= twiggle; + + if (little_endian_data_out) { + switch(target_bps) { + case 24: + data_out[2] = (FLAC__byte)(uval32 >> 16); + /* fall through */ + case 16: + data_out[1] = (FLAC__byte)(uval32 >> 8); + /* fall through */ + case 8: + data_out[0] = (FLAC__byte)uval32; + break; + } + } + else { + switch(target_bps) { + case 24: + data_out[0] = (FLAC__byte)(uval32 >> 16); + data_out[1] = (FLAC__byte)(uval32 >> 8); + data_out[2] = (FLAC__byte)uval32; + break; + case 16: + data_out[0] = (FLAC__byte)(uval32 >> 8); + data_out[1] = (FLAC__byte)uval32; + break; + case 8: + data_out[0] = (FLAC__byte)uval32; + break; + } + } + } + } + dither_context->LastHistoryIndex = (last_history_index + wide_samples) % 32; + + return wide_samples * channels * (target_bps/8); +} diff --git a/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.dsp b/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.dsp new file mode 100644 index 0000000..911356d --- /dev/null +++ b/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.dsp @@ -0,0 +1,108 @@ +# Microsoft Developer Studio Project File - Name="replaygain_synthesis_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=replaygain_synthesis_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "replaygain_synthesis_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "replaygain_synthesis_static.mak" CFG="replaygain_synthesis_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "replaygain_synthesis_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "replaygain_synthesis_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "replaygain_synthesis" +# PROP Scc_LocalPath "..\..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "replaygain_synthesis_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /Op /I ".\include" /I "..\..\..\include" /I "..\..\..\include\share" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "replaygain_synthesis_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\..\include" /I "..\..\..\include\share" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "replaygain_synthesis_static - Win32 Release" +# Name "replaygain_synthesis_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\replaygain_synthesis.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\include\private\fast_float_math_hack.h +# End Source File +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\replaygain_synthesis.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.vcproj b/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.vcproj new file mode 100644 index 0000000..ae32a8f --- /dev/null +++ b/flac/src/share/replaygain_synthesis/replaygain_synthesis_static.vcproj @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/share/utf8/Makefile.am b/flac/src/share/utf8/Makefile.am new file mode 100644 index 0000000..1c22822 --- /dev/null +++ b/flac/src/share/utf8/Makefile.am @@ -0,0 +1,25 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I$(top_srcdir)/include/share + +noinst_LTLIBRARIES = libutf8.la + +libutf8_la_SOURCES = charset.c charset.h iconvert.c utf8.c + +EXTRA_DIST = \ + Makefile.lite \ + charmaps.h \ + makemap.c \ + charset_test.c \ + charsetmap.h \ + iconvert.h \ + utf8_static.dsp \ + utf8_static.vcproj + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/flac/src/share/utf8/Makefile.lite b/flac/src/share/utf8/Makefile.lite new file mode 100644 index 0000000..66f1e55 --- /dev/null +++ b/flac/src/share/utf8/Makefile.lite @@ -0,0 +1,17 @@ +# +# GNU makefile +# + +topdir = ../../.. + +LIB_NAME = libutf8 +INCLUDES = -I$(topdir)/include -I$(topdir)/include/share + +SRCS_C = \ + charset.c \ + iconvert.c \ + utf8.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/share/utf8/charmaps.h b/flac/src/share/utf8/charmaps.h new file mode 100644 index 0000000..77b04f6 --- /dev/null +++ b/flac/src/share/utf8/charmaps.h @@ -0,0 +1,57 @@ + +/* + * If you need to generate more maps, use makemap.c on a system + * with a decent iconv. + */ + +static const unsigned short mapping_iso_8859_2[256] = { + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, + 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, + 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, + 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, + 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, + 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, + 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, + 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, + 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, + 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, + 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, + 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, + 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, + 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, + 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, + 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, + 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, + 0x00a0, 0x0104, 0x02d8, 0x0141, 0x00a4, 0x013d, 0x015a, 0x00a7, + 0x00a8, 0x0160, 0x015e, 0x0164, 0x0179, 0x00ad, 0x017d, 0x017b, + 0x00b0, 0x0105, 0x02db, 0x0142, 0x00b4, 0x013e, 0x015b, 0x02c7, + 0x00b8, 0x0161, 0x015f, 0x0165, 0x017a, 0x02dd, 0x017e, 0x017c, + 0x0154, 0x00c1, 0x00c2, 0x0102, 0x00c4, 0x0139, 0x0106, 0x00c7, + 0x010c, 0x00c9, 0x0118, 0x00cb, 0x011a, 0x00cd, 0x00ce, 0x010e, + 0x0110, 0x0143, 0x0147, 0x00d3, 0x00d4, 0x0150, 0x00d6, 0x00d7, + 0x0158, 0x016e, 0x00da, 0x0170, 0x00dc, 0x00dd, 0x0162, 0x00df, + 0x0155, 0x00e1, 0x00e2, 0x0103, 0x00e4, 0x013a, 0x0107, 0x00e7, + 0x010d, 0x00e9, 0x0119, 0x00eb, 0x011b, 0x00ed, 0x00ee, 0x010f, + 0x0111, 0x0144, 0x0148, 0x00f3, 0x00f4, 0x0151, 0x00f6, 0x00f7, + 0x0159, 0x016f, 0x00fa, 0x0171, 0x00fc, 0x00fd, 0x0163, 0x02d9 +}; + +static struct { + const char *name; + const unsigned short *map; + struct charset *charset; +} maps[] = { + { "ISO-8859-2", mapping_iso_8859_2, 0 }, + { 0, 0, 0 } +}; + +static const struct { + const char *bad; + const char *good; +} names[] = { + { "ANSI_X3.4-1968", "us-ascii" }, + { 0, 0 } +}; diff --git a/flac/src/share/utf8/charset.c b/flac/src/share/utf8/charset.c new file mode 100644 index 0000000..18fa13a --- /dev/null +++ b/flac/src/share/utf8/charset.c @@ -0,0 +1,532 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * See the corresponding header file for a description of the functions + * that this file provides. + * + * This was first written for Ogg Vorbis but could be of general use. + * + * The only deliberate assumption about data sizes is that a short has + * at least 16 bits, but this code has only been tested on systems with + * 8-bit char, 16-bit short and 32-bit int. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#ifndef HAVE_ICONV /* should be ifdef USE_CHARSET_CONVERT */ + +#include + +#include "share/alloc.h" +#include "charset.h" + +#include "charmaps.h" + +/* + * This is like the standard strcasecmp, but it does not depend + * on the locale. Locale-dependent functions can be dangerous: + * we once had a bug involving strcasecmp("iso", "ISO") in a + * Turkish locale! + * + * (I'm not really sure what the official standard says + * about the sign of strcasecmp("Z", "["), but usually + * we're only interested in whether it's zero.) + */ + +static int ascii_strcasecmp(const char *s1, const char *s2) +{ + char c1, c2; + + for (;; s1++, s2++) { + if (!*s1 || !*s1) + break; + if (*s1 == *s2) + continue; + c1 = *s1; + if ('a' <= c1 && c1 <= 'z') + c1 += 'A' - 'a'; + c2 = *s2; + if ('a' <= c2 && c2 <= 'z') + c2 += 'A' - 'a'; + if (c1 != c2) + break; + } + return (unsigned char)*s1 - (unsigned char)*s2; +} + +/* + * UTF-8 equivalents of the C library's wctomb() and mbtowc(). + */ + +int utf8_mbtowc(int *pwc, const char *s, size_t n) +{ + unsigned char c; + int wc, i, k; + + if (!n || !s) + return 0; + + c = *s; + if (c < 0x80) { + if (pwc) + *pwc = c; + return c ? 1 : 0; + } + else if (c < 0xc2) + return -1; + else if (c < 0xe0) { + if (n >= 2 && (s[1] & 0xc0) == 0x80) { + if (pwc) + *pwc = ((c & 0x1f) << 6) | (s[1] & 0x3f); + return 2; + } + else + return -1; + } + else if (c < 0xf0) + k = 3; + else if (c < 0xf8) + k = 4; + else if (c < 0xfc) + k = 5; + else if (c < 0xfe) + k = 6; + else + return -1; + + if (n < (size_t)k) + return -1; + wc = *s++ & ((1 << (7 - k)) - 1); + for (i = 1; i < k; i++) { + if ((*s & 0xc0) != 0x80) + return -1; + wc = (wc << 6) | (*s++ & 0x3f); + } + if (wc < (1 << (5 * k - 4))) + return -1; + if (pwc) + *pwc = wc; + return k; +} + +int utf8_wctomb(char *s, int wc1) +{ + unsigned int wc = wc1; + + if (!s) + return 0; + if (wc < (1u << 7)) { + *s++ = wc; + return 1; + } + else if (wc < (1u << 11)) { + *s++ = 0xc0 | (wc >> 6); + *s++ = 0x80 | (wc & 0x3f); + return 2; + } + else if (wc < (1u << 16)) { + *s++ = 0xe0 | (wc >> 12); + *s++ = 0x80 | ((wc >> 6) & 0x3f); + *s++ = 0x80 | (wc & 0x3f); + return 3; + } + else if (wc < (1u << 21)) { + *s++ = 0xf0 | (wc >> 18); + *s++ = 0x80 | ((wc >> 12) & 0x3f); + *s++ = 0x80 | ((wc >> 6) & 0x3f); + *s++ = 0x80 | (wc & 0x3f); + return 4; + } + else if (wc < (1u << 26)) { + *s++ = 0xf8 | (wc >> 24); + *s++ = 0x80 | ((wc >> 18) & 0x3f); + *s++ = 0x80 | ((wc >> 12) & 0x3f); + *s++ = 0x80 | ((wc >> 6) & 0x3f); + *s++ = 0x80 | (wc & 0x3f); + return 5; + } + else if (wc < (1u << 31)) { + *s++ = 0xfc | (wc >> 30); + *s++ = 0x80 | ((wc >> 24) & 0x3f); + *s++ = 0x80 | ((wc >> 18) & 0x3f); + *s++ = 0x80 | ((wc >> 12) & 0x3f); + *s++ = 0x80 | ((wc >> 6) & 0x3f); + *s++ = 0x80 | (wc & 0x3f); + return 6; + } + else + return -1; +} + +/* + * The charset "object" and methods. + */ + +struct charset { + int max; + int (*mbtowc)(void *table, int *pwc, const char *s, size_t n); + int (*wctomb)(void *table, char *s, int wc); + void *map; +}; + +int charset_mbtowc(struct charset *charset, int *pwc, const char *s, size_t n) +{ + return (*charset->mbtowc)(charset->map, pwc, s, n); +} + +int charset_wctomb(struct charset *charset, char *s, int wc) +{ + return (*charset->wctomb)(charset->map, s, wc); +} + +int charset_max(struct charset *charset) +{ + return charset->max; +} + +/* + * Implementation of UTF-8. + */ + +static int mbtowc_utf8(void *map, int *pwc, const char *s, size_t n) +{ + (void)map; + return utf8_mbtowc(pwc, s, n); +} + +static int wctomb_utf8(void *map, char *s, int wc) +{ + (void)map; + return utf8_wctomb(s, wc); +} + +/* + * Implementation of US-ASCII. + * Probably on most architectures this compiles to less than 256 bytes + * of code, so we can save space by not having a table for this one. + */ + +static int mbtowc_ascii(void *map, int *pwc, const char *s, size_t n) +{ + int wc; + + (void)map; + if (!n || !s) + return 0; + wc = (unsigned char)*s; + if (wc & ~0x7f) + return -1; + if (pwc) + *pwc = wc; + return wc ? 1 : 0; +} + +static int wctomb_ascii(void *map, char *s, int wc) +{ + (void)map; + if (!s) + return 0; + if (wc & ~0x7f) + return -1; + *s = wc; + return 1; +} + +/* + * Implementation of ISO-8859-1. + * Probably on most architectures this compiles to less than 256 bytes + * of code, so we can save space by not having a table for this one. + */ + +static int mbtowc_iso1(void *map, int *pwc, const char *s, size_t n) +{ + int wc; + + (void)map; + if (!n || !s) + return 0; + wc = (unsigned char)*s; + if (wc & ~0xff) + return -1; + if (pwc) + *pwc = wc; + return wc ? 1 : 0; +} + +static int wctomb_iso1(void *map, char *s, int wc) +{ + (void)map; + if (!s) + return 0; + if (wc & ~0xff) + return -1; + *s = wc; + return 1; +} + +/* + * Implementation of any 8-bit charset. + */ + +struct map { + const unsigned short *from; + struct inverse_map *to; +}; + +static int mbtowc_8bit(void *map1, int *pwc, const char *s, size_t n) +{ + struct map *map = map1; + unsigned short wc; + + if (!n || !s) + return 0; + wc = map->from[(unsigned char)*s]; + if (wc == 0xffff) + return -1; + if (pwc) + *pwc = (int)wc; + return wc ? 1 : 0; +} + +/* + * For the inverse map we use a hash table, which has the advantages + * of small constant memory requirement and simple memory allocation, + * but the disadvantage of slow conversion in the worst case. + * If you need real-time performance while letting a potentially + * malicious user define their own map, then the method used in + * linux/drivers/char/consolemap.c would be more appropriate. + */ + +struct inverse_map { + unsigned char first[256]; + unsigned char next[256]; +}; + +/* + * The simple hash is good enough for this application. + * Use the alternative trivial hashes for testing. + */ +#define HASH(i) ((i) & 0xff) +/* #define HASH(i) 0 */ +/* #define HASH(i) 99 */ + +static struct inverse_map *make_inverse_map(const unsigned short *from) +{ + struct inverse_map *to; + char used[256]; + int i, j, k; + + to = (struct inverse_map *)malloc(sizeof(struct inverse_map)); + if (!to) + return 0; + for (i = 0; i < 256; i++) + to->first[i] = to->next[i] = used[i] = 0; + for (i = 255; i >= 0; i--) + if (from[i] != 0xffff) { + k = HASH(from[i]); + to->next[i] = to->first[k]; + to->first[k] = i; + used[k] = 1; + } + + /* Point the empty buckets at an empty list. */ + for (i = 0; i < 256; i++) + if (!to->next[i]) + break; + if (i < 256) + for (j = 0; j < 256; j++) + if (!used[j]) + to->first[j] = i; + + return to; +} + +int wctomb_8bit(void *map1, char *s, int wc1) +{ + struct map *map = map1; + unsigned short wc = wc1; + int i; + + if (!s) + return 0; + + if (wc1 & ~0xffff) + return -1; + + if (1) /* Change 1 to 0 to test the case where malloc fails. */ + if (!map->to) + map->to = make_inverse_map(map->from); + + if (map->to) { + /* Use the inverse map. */ + i = map->to->first[HASH(wc)]; + for (;;) { + if (map->from[i] == wc) { + *s = i; + return 1; + } + if (!(i = map->to->next[i])) + break; + } + } + else { + /* We don't have an inverse map, so do a linear search. */ + for (i = 0; i < 256; i++) + if (map->from[i] == wc) { + *s = i; + return 1; + } + } + + return -1; +} + +/* + * The "constructor" charset_find(). + */ + +struct charset charset_utf8 = { + 6, + &mbtowc_utf8, + &wctomb_utf8, + 0 +}; + +struct charset charset_iso1 = { + 1, + &mbtowc_iso1, + &wctomb_iso1, + 0 +}; + +struct charset charset_ascii = { + 1, + &mbtowc_ascii, + &wctomb_ascii, + 0 +}; + +struct charset *charset_find(const char *code) +{ + int i; + + /* Find good (MIME) name. */ + for (i = 0; names[i].bad; i++) + if (!ascii_strcasecmp(code, names[i].bad)) { + code = names[i].good; + break; + } + + /* Recognise some charsets for which we avoid using a table. */ + if (!ascii_strcasecmp(code, "UTF-8")) + return &charset_utf8; + if (!ascii_strcasecmp(code, "US-ASCII")) + return &charset_ascii; + if (!ascii_strcasecmp(code, "ISO-8859-1")) + return &charset_iso1; + + /* Look for a mapping for a simple 8-bit encoding. */ + for (i = 0; maps[i].name; i++) + if (!ascii_strcasecmp(code, maps[i].name)) { + if (!maps[i].charset) { + maps[i].charset = (struct charset *)malloc(sizeof(struct charset)); + if (maps[i].charset) { + struct map *map = (struct map *)malloc(sizeof(struct map)); + if (!map) { + free(maps[i].charset); + maps[i].charset = 0; + } + else { + maps[i].charset->max = 1; + maps[i].charset->mbtowc = &mbtowc_8bit; + maps[i].charset->wctomb = &wctomb_8bit; + maps[i].charset->map = map; + map->from = maps[i].map; + map->to = 0; /* inverse mapping is created when required */ + } + } + } + return maps[i].charset; + } + + return 0; +} + +/* + * Function to convert a buffer from one encoding to another. + * Invalid bytes are replaced by '#', and characters that are + * not available in the target encoding are replaced by '?'. + * Each of TO and TOLEN may be zero, if the result is not needed. + * The output buffer is null-terminated, so it is all right to + * use charset_convert(fromcode, tocode, s, strlen(s), &t, 0). + */ + +int charset_convert(const char *fromcode, const char *tocode, + const char *from, size_t fromlen, + char **to, size_t *tolen) +{ + int ret = 0; + struct charset *charset1, *charset2; + char *tobuf, *p, *newbuf; + int i, j, wc; + + charset1 = charset_find(fromcode); + charset2 = charset_find(tocode); + if (!charset1 || !charset2 ) + return -1; + + tobuf = (char *)safe_malloc_mul2add_(fromlen, /*times*/charset2->max, /*+*/1); + if (!tobuf) + return -2; + + for (p = tobuf; fromlen; from += i, fromlen -= i, p += j) { + i = charset_mbtowc(charset1, &wc, from, fromlen); + if (!i) + i = 1; + else if (i == -1) { + i = 1; + wc = '#'; + ret = 2; + } + j = charset_wctomb(charset2, p, wc); + if (j == -1) { + if (!ret) + ret = 1; + j = charset_wctomb(charset2, p, '?'); + if (j == -1) + j = 0; + } + } + + if (tolen) + *tolen = p - tobuf; + *p++ = '\0'; + if (to) { + newbuf = realloc(tobuf, p - tobuf); + *to = newbuf ? newbuf : tobuf; + } + else + free(tobuf); + + return ret; +} + +#endif /* USE_CHARSET_ICONV */ diff --git a/flac/src/share/utf8/charset.h b/flac/src/share/utf8/charset.h new file mode 100644 index 0000000..8481b99 --- /dev/null +++ b/flac/src/share/utf8/charset.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include + +/* + * These functions are like the C library's mbtowc() and wctomb(), + * but instead of depending on the locale they always work in UTF-8, + * and they use int instead of wchar_t. + */ + +int utf8_mbtowc(int *pwc, const char *s, size_t n); +int utf8_wctomb(char *s, int wc); + +/* + * This is an object-oriented version of mbtowc() and wctomb(). + * The caller first uses charset_find() to get a pointer to struct + * charset, then uses the mbtowc() and wctomb() methods on it. + * The function charset_max() gives the maximum length of a + * multibyte character in that encoding. + * This API is only appropriate for stateless encodings like UTF-8 + * or ISO-8859-3, but I have no intention of implementing anything + * other than UTF-8 and 8-bit encodings. + * + * MINOR BUG: If there is no memory charset_find() may return 0 and + * there is no way to distinguish this case from an unknown encoding. + */ + +struct charset; + +struct charset *charset_find(const char *code); + +int charset_mbtowc(struct charset *charset, int *pwc, const char *s, size_t n); +int charset_wctomb(struct charset *charset, char *s, int wc); +int charset_max(struct charset *charset); + +/* + * Function to convert a buffer from one encoding to another. + * Invalid bytes are replaced by '#', and characters that are + * not available in the target encoding are replaced by '?'. + * Each of TO and TOLEN may be zero if the result is not wanted. + * The input or output may contain null bytes, but the output + * buffer is also null-terminated, so it is all right to + * use charset_convert(fromcode, tocode, s, strlen(s), &t, 0). + * + * Return value: + * + * -2 : memory allocation failed + * -1 : unknown encoding + * 0 : data was converted exactly + * 1 : valid data was converted approximately (using '?') + * 2 : input was invalid (but still converted, using '#') + */ + +int charset_convert(const char *fromcode, const char *tocode, + const char *from, size_t fromlen, + char **to, size_t *tolen); diff --git a/flac/src/share/utf8/charset_test.c b/flac/src/share/utf8/charset_test.c new file mode 100644 index 0000000..ecd42ff --- /dev/null +++ b/flac/src/share/utf8/charset_test.c @@ -0,0 +1,263 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include + +#include "charset.h" + +void test_any(struct charset *charset) +{ + int wc; + char s[2]; + + assert(charset); + + /* Decoder */ + + assert(charset_mbtowc(charset, 0, 0, 0) == 0); + assert(charset_mbtowc(charset, 0, 0, 1) == 0); + assert(charset_mbtowc(charset, 0, (char *)(-1), 0) == 0); + + assert(charset_mbtowc(charset, 0, "a", 0) == 0); + assert(charset_mbtowc(charset, 0, "", 1) == 0); + assert(charset_mbtowc(charset, 0, "b", 1) == 1); + assert(charset_mbtowc(charset, 0, "", 2) == 0); + assert(charset_mbtowc(charset, 0, "c", 2) == 1); + + wc = 'x'; + assert(charset_mbtowc(charset, &wc, "a", 0) == 0 && wc == 'x'); + assert(charset_mbtowc(charset, &wc, "", 1) == 0 && wc == 0); + assert(charset_mbtowc(charset, &wc, "b", 1) == 1 && wc == 'b'); + assert(charset_mbtowc(charset, &wc, "", 2) == 0 && wc == 0); + assert(charset_mbtowc(charset, &wc, "c", 2) == 1 && wc == 'c'); + + /* Encoder */ + + assert(charset_wctomb(charset, 0, 0) == 0); + + s[0] = s[1] = '.'; + assert(charset_wctomb(charset, s, 0) == 1 && + s[0] == '\0' && s[1] == '.'); + assert(charset_wctomb(charset, s, 'x') == 1 && + s[0] == 'x' && s[1] == '.'); +} + +void test_utf8() +{ + struct charset *charset; + int wc; + char s[8]; + + charset = charset_find("UTF-8"); + test_any(charset); + + /* Decoder */ + wc = 0; + assert(charset_mbtowc(charset, &wc, "\177", 1) == 1 && wc == 127); + assert(charset_mbtowc(charset, &wc, "\200", 2) == -1); + assert(charset_mbtowc(charset, &wc, "\301\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\302\200", 1) == -1); + assert(charset_mbtowc(charset, &wc, "\302\200", 2) == 2 && wc == 128); + assert(charset_mbtowc(charset, &wc, "\302\200", 3) == 2 && wc == 128); + assert(charset_mbtowc(charset, &wc, "\340\237\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\340\240\200", 9) == 3 && + wc == 1 << 11); + assert(charset_mbtowc(charset, &wc, "\360\217\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\220\200\200", 9) == 4 && + wc == 1 << 16); + assert(charset_mbtowc(charset, &wc, "\370\207\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\370\210\200\200\200", 9) == 5 && + wc == 1 << 21); + assert(charset_mbtowc(charset, &wc, "\374\203\277\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\374\204\200\200\200\200", 9) == 6 && + wc == 1 << 26); + assert(charset_mbtowc(charset, &wc, "\375\277\277\277\277\277", 9) == 6 && + wc == 0x7fffffff); + + assert(charset_mbtowc(charset, &wc, "\302\000", 2) == -1); + assert(charset_mbtowc(charset, &wc, "\302\300", 2) == -1); + assert(charset_mbtowc(charset, &wc, "\340\040\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\340\340\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\340\240\000", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\340\240\300", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\020\200\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\320\200\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\220\000\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\220\300\200", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\220\200\000", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\360\220\200\300", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\077\277\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\377\277\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\077\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\377\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\277\277\077\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\277\277\377\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\277\277\277\077", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\375\277\277\277\277\377", 9) == -1); + + assert(charset_mbtowc(charset, &wc, "\376\277\277\277\277\277", 9) == -1); + assert(charset_mbtowc(charset, &wc, "\377\277\277\277\277\277", 9) == -1); + + /* Encoder */ + strcpy(s, "......."); + assert(charset_wctomb(charset, s, 1 << 31) == -1 && + !strcmp(s, ".......")); + assert(charset_wctomb(charset, s, 127) == 1 && + !strcmp(s, "\177......")); + assert(charset_wctomb(charset, s, 128) == 2 && + !strcmp(s, "\302\200.....")); + assert(charset_wctomb(charset, s, 0x7ff) == 2 && + !strcmp(s, "\337\277.....")); + assert(charset_wctomb(charset, s, 0x800) == 3 && + !strcmp(s, "\340\240\200....")); + assert(charset_wctomb(charset, s, 0xffff) == 3 && + !strcmp(s, "\357\277\277....")); + assert(charset_wctomb(charset, s, 0x10000) == 4 && + !strcmp(s, "\360\220\200\200...")); + assert(charset_wctomb(charset, s, 0x1fffff) == 4 && + !strcmp(s, "\367\277\277\277...")); + assert(charset_wctomb(charset, s, 0x200000) == 5 && + !strcmp(s, "\370\210\200\200\200..")); + assert(charset_wctomb(charset, s, 0x3ffffff) == 5 && + !strcmp(s, "\373\277\277\277\277..")); + assert(charset_wctomb(charset, s, 0x4000000) == 6 && + !strcmp(s, "\374\204\200\200\200\200.")); + assert(charset_wctomb(charset, s, 0x7fffffff) == 6 && + !strcmp(s, "\375\277\277\277\277\277.")); +} + +void test_ascii() +{ + struct charset *charset; + int wc; + char s[3]; + + charset = charset_find("us-ascii"); + test_any(charset); + + /* Decoder */ + wc = 0; + assert(charset_mbtowc(charset, &wc, "\177", 2) == 1 && wc == 127); + assert(charset_mbtowc(charset, &wc, "\200", 2) == -1); + + /* Encoder */ + strcpy(s, ".."); + assert(charset_wctomb(charset, s, 256) == -1 && !strcmp(s, "..")); + assert(charset_wctomb(charset, s, 255) == -1); + assert(charset_wctomb(charset, s, 128) == -1); + assert(charset_wctomb(charset, s, 127) == 1 && !strcmp(s, "\177.")); +} + +void test_iso1() +{ + struct charset *charset; + int wc; + char s[3]; + + charset = charset_find("iso-8859-1"); + test_any(charset); + + /* Decoder */ + wc = 0; + assert(charset_mbtowc(charset, &wc, "\302\200", 9) == 1 && wc == 0xc2); + + /* Encoder */ + strcpy(s, ".."); + assert(charset_wctomb(charset, s, 256) == -1 && !strcmp(s, "..")); + assert(charset_wctomb(charset, s, 255) == 1 && !strcmp(s, "\377.")); + assert(charset_wctomb(charset, s, 128) == 1 && !strcmp(s, "\200.")); +} + +void test_iso2() +{ + struct charset *charset; + int wc; + char s[3]; + + charset = charset_find("iso-8859-2"); + test_any(charset); + + /* Decoder */ + wc = 0; + assert(charset_mbtowc(charset, &wc, "\302\200", 9) == 1 && wc == 0xc2); + assert(charset_mbtowc(charset, &wc, "\377", 2) == 1 && wc == 0x2d9); + + /* Encoder */ + strcpy(s, ".."); + assert(charset_wctomb(charset, s, 256) == -1 && !strcmp(s, "..")); + assert(charset_wctomb(charset, s, 255) == -1 && !strcmp(s, "..")); + assert(charset_wctomb(charset, s, 258) == 1 && !strcmp(s, "\303.")); + assert(charset_wctomb(charset, s, 128) == 1 && !strcmp(s, "\200.")); +} + +void test_convert() +{ + const char *p; + char *q, *r; + char s[256]; + size_t n, n2; + int i; + + p = "\000x\302\200\375\277\277\277\277\277"; + assert(charset_convert("UTF-8", "UTF-8", p, 10, &q, &n) == 0 && + n == 10 && !strcmp(p, q)); + assert(charset_convert("UTF-8", "UTF-8", "x\301\277y", 4, &q, &n) == 2 && + n == 4 && !strcmp(q, "x##y")); + assert(charset_convert("UTF-8", "UTF-8", "x\301\277y", 4, 0, &n) == 2 && + n == 4); + assert(charset_convert("UTF-8", "UTF-8", "x\301\277y", 4, &q, 0) == 2 && + !strcmp(q, "x##y")); + assert(charset_convert("UTF-8", "iso-8859-1", + "\302\200\304\200x", 5, &q, &n) == 1 && + n == 3 && !strcmp(q, "\200?x")); + assert(charset_convert("iso-8859-1", "UTF-8", + "\000\200\377", 3, &q, &n) == 0 && + n == 5 && !memcmp(q, "\000\302\200\303\277", 5)); + assert(charset_convert("iso-8859-1", "iso-8859-1", + "\000\200\377", 3, &q, &n) == 0 && + n == 3 && !memcmp(q, "\000\200\377", 3)); + + assert(charset_convert("iso-8859-2", "utf-8", "\300", 1, &q, &n) == 0 && + n == 2 && !strcmp(q, "\305\224")); + assert(charset_convert("utf-8", "iso-8859-2", "\305\224", 2, &q, &n) == 0 && + n == 1 && !strcmp(q, "\300")); + + for (i = 0; i < 256; i++) + s[i] = i; + + assert(charset_convert("iso-8859-2", "utf-8", s, 256, &q, &n) == 0); + assert(charset_convert("utf-8", "iso-8859-2", q, n, &r, &n2) == 0); + assert(n2 == 256 && !memcmp(r, s, n2)); +} + +int main() +{ + test_utf8(); + test_ascii(); + test_iso1(); + test_iso2(); + + test_convert(); + + return 0; +} diff --git a/flac/src/share/utf8/charsetmap.h b/flac/src/share/utf8/charsetmap.h new file mode 100644 index 0000000..b60ec7d --- /dev/null +++ b/flac/src/share/utf8/charsetmap.h @@ -0,0 +1,79 @@ +/* This file was automatically generated by make_code_map.pl + please don't edit directly + Daniel Resare +*/ +charset_map maps[] = { + {"ISO-8859-1", + { + 0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007, + 0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x000F, + 0x0010,0x0011,0x0012,0x0013,0x0014,0x0015,0x0016,0x0017, + 0x0018,0x0019,0x001A,0x001B,0x001C,0x001D,0x001E,0x001F, + 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027, + 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F, + 0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037, + 0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F, + 0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047, + 0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F, + 0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057, + 0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F, + 0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067, + 0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F, + 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077, + 0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x007F, + 0x0080,0x0081,0x0082,0x0083,0x0084,0x0085,0x0086,0x0087, + 0x0088,0x0089,0x008A,0x008B,0x008C,0x008D,0x008E,0x008F, + 0x0090,0x0091,0x0092,0x0093,0x0094,0x0095,0x0096,0x0097, + 0x0098,0x0099,0x009A,0x009B,0x009C,0x009D,0x009E,0x009F, + 0x00A0,0x00A1,0x00A2,0x00A3,0x00A4,0x00A5,0x00A6,0x00A7, + 0x00A8,0x00A9,0x00AA,0x00AB,0x00AC,0x00AD,0x00AE,0x00AF, + 0x00B0,0x00B1,0x00B2,0x00B3,0x00B4,0x00B5,0x00B6,0x00B7, + 0x00B8,0x00B9,0x00BA,0x00BB,0x00BC,0x00BD,0x00BE,0x00BF, + 0x00C0,0x00C1,0x00C2,0x00C3,0x00C4,0x00C5,0x00C6,0x00C7, + 0x00C8,0x00C9,0x00CA,0x00CB,0x00CC,0x00CD,0x00CE,0x00CF, + 0x00D0,0x00D1,0x00D2,0x00D3,0x00D4,0x00D5,0x00D6,0x00D7, + 0x00D8,0x00D9,0x00DA,0x00DB,0x00DC,0x00DD,0x00DE,0x00DF, + 0x00E0,0x00E1,0x00E2,0x00E3,0x00E4,0x00E5,0x00E6,0x00E7, + 0x00E8,0x00E9,0x00EA,0x00EB,0x00EC,0x00ED,0x00EE,0x00EF, + 0x00F0,0x00F1,0x00F2,0x00F3,0x00F4,0x00F5,0x00F6,0x00F7, + 0x00F8,0x00F9,0x00FA,0x00FB,0x00FC,0x00FD,0x00FE,0x00FF + } + }, + {"ISO-8859-2", + { + 0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007, + 0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x000F, + 0x0010,0x0011,0x0012,0x0013,0x0014,0x0015,0x0016,0x0017, + 0x0018,0x0019,0x001A,0x001B,0x001C,0x001D,0x001E,0x001F, + 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027, + 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F, + 0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037, + 0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F, + 0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047, + 0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F, + 0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057, + 0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F, + 0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067, + 0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F, + 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077, + 0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x007F, + 0x0080,0x0081,0x0082,0x0083,0x0084,0x0085,0x0086,0x0087, + 0x0088,0x0089,0x008A,0x008B,0x008C,0x008D,0x008E,0x008F, + 0x0090,0x0091,0x0092,0x0093,0x0094,0x0095,0x0096,0x0097, + 0x0098,0x0099,0x009A,0x009B,0x009C,0x009D,0x009E,0x009F, + 0x00A0,0x0104,0x02D8,0x0141,0x00A4,0x013D,0x015A,0x00A7, + 0x00A8,0x0160,0x015E,0x0164,0x0179,0x00AD,0x017D,0x017B, + 0x00B0,0x0105,0x02DB,0x0142,0x00B4,0x013E,0x015B,0x02C7, + 0x00B8,0x0161,0x015F,0x0165,0x017A,0x02DD,0x017E,0x017C, + 0x0154,0x00C1,0x00C2,0x0102,0x00C4,0x0139,0x0106,0x00C7, + 0x010C,0x00C9,0x0118,0x00CB,0x011A,0x00CD,0x00CE,0x010E, + 0x0110,0x0143,0x0147,0x00D3,0x00D4,0x0150,0x00D6,0x00D7, + 0x0158,0x016E,0x00DA,0x0170,0x00DC,0x00DD,0x0162,0x00DF, + 0x0155,0x00E1,0x00E2,0x0103,0x00E4,0x013A,0x0107,0x00E7, + 0x010D,0x00E9,0x0119,0x00EB,0x011B,0x00ED,0x00EE,0x010F, + 0x0111,0x0144,0x0148,0x00F3,0x00F4,0x0151,0x00F6,0x00F7, + 0x0159,0x016F,0x00FA,0x0171,0x00FC,0x00FD,0x0163,0x02D9 + } + }, + {NULL} +}; diff --git a/flac/src/share/utf8/iconvert.c b/flac/src/share/utf8/iconvert.c new file mode 100644 index 0000000..0378709 --- /dev/null +++ b/flac/src/share/utf8/iconvert.c @@ -0,0 +1,253 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#ifdef HAVE_ICONV + +#include +#include +#include +#include +#include + +#include "iconvert.h" +#include "share/alloc.h" + +/* + * Convert data from one encoding to another. Return: + * + * -2 : memory allocation failed + * -1 : unknown encoding + * 0 : data was converted exactly + * 1 : data was converted inexactly + * 2 : data was invalid (but still converted) + * + * We convert in two steps, via UTF-8, as this is the only + * reliable way of distinguishing between invalid input + * and valid input which iconv refuses to transliterate. + * We convert from UTF-8 twice, because we have no way of + * knowing whether the conversion was exact if iconv returns + * E2BIG (due to a bug in the specification of iconv). + * An alternative approach is to assume that the output of + * iconv is never more than 4 times as long as the input, + * but I prefer to avoid that assumption if possible. + */ + +int iconvert(const char *fromcode, const char *tocode, + const char *from, size_t fromlen, + char **to, size_t *tolen) +{ + int ret = 0; + iconv_t cd1, cd2; + char *ib; + char *ob; + char *utfbuf = 0, *outbuf, *newbuf; + size_t utflen, outlen, ibl, obl, k; + char tbuf[2048]; + + cd1 = iconv_open("UTF-8", fromcode); + if (cd1 == (iconv_t)(-1)) + return -1; + + cd2 = (iconv_t)(-1); + /* Don't use strcasecmp() as it's locale-dependent. */ + if (!strchr("Uu", tocode[0]) || + !strchr("Tt", tocode[1]) || + !strchr("Ff", tocode[2]) || + tocode[3] != '-' || + tocode[4] != '8' || + tocode[5] != '\0') { + char *tocode1; + + /* + * Try using this non-standard feature of glibc and libiconv. + * This is deliberately not a config option as people often + * change their iconv library without rebuilding applications. + */ + tocode1 = (char *)safe_malloc_add_2op_(strlen(tocode), /*+*/11); + if (!tocode1) + goto fail; + + strcpy(tocode1, tocode); + strcat(tocode1, "//TRANSLIT"); + cd2 = iconv_open(tocode1, "UTF-8"); + free(tocode1); + + if (cd2 == (iconv_t)(-1)) + cd2 = iconv_open(tocode, fromcode); + + if (cd2 == (iconv_t)(-1)) { + iconv_close(cd1); + return -1; + } + } + + utflen = 1; /*fromlen * 2 + 1; XXX */ + utfbuf = (char *)malloc(utflen); + if (!utfbuf) + goto fail; + + /* Convert to UTF-8 */ + ib = (char *)from; + ibl = fromlen; + ob = utfbuf; + obl = utflen; + for (;;) { + k = iconv(cd1, &ib, &ibl, &ob, &obl); + assert((!k && !ibl) || + (k == (size_t)(-1) && errno == E2BIG && ibl && obl < 6) || + (k == (size_t)(-1) && + (errno == EILSEQ || errno == EINVAL) && ibl)); + if (!ibl) + break; + if (obl < 6) { + /* Enlarge the buffer */ + if(utflen*2 < utflen) /* overflow check */ + goto fail; + utflen *= 2; + newbuf = (char *)realloc(utfbuf, utflen); + if (!newbuf) + goto fail; + ob = (ob - utfbuf) + newbuf; + obl = utflen - (ob - newbuf); + utfbuf = newbuf; + } + else { + /* Invalid input */ + ib++, ibl--; + *ob++ = '#', obl--; + ret = 2; + iconv(cd1, 0, 0, 0, 0); + } + } + + if (cd2 == (iconv_t)(-1)) { + /* The target encoding was UTF-8 */ + if (tolen) + *tolen = ob - utfbuf; + if (!to) { + free(utfbuf); + iconv_close(cd1); + return ret; + } + newbuf = (char *)safe_realloc_add_2op_(utfbuf, (ob - utfbuf), /*+*/1); + if (!newbuf) + goto fail; + ob = (ob - utfbuf) + newbuf; + *ob = '\0'; + *to = newbuf; + iconv_close(cd1); + return ret; + } + + /* Truncate the buffer to be tidy */ + utflen = ob - utfbuf; + newbuf = (char *)realloc(utfbuf, utflen); + if (!newbuf) + goto fail; + utfbuf = newbuf; + + /* Convert from UTF-8 to discover how long the output is */ + outlen = 0; + ib = utfbuf; + ibl = utflen; + while (ibl) { + ob = tbuf; + obl = sizeof(tbuf); + k = iconv(cd2, &ib, &ibl, &ob, &obl); + assert((k != (size_t)(-1) && !ibl) || + (k == (size_t)(-1) && errno == E2BIG && ibl) || + (k == (size_t)(-1) && errno == EILSEQ && ibl)); + if (ibl && !(k == (size_t)(-1) && errno == E2BIG)) { + /* Replace one character */ + char *tb = "?"; + size_t tbl = 1; + + outlen += ob - tbuf; + ob = tbuf; + obl = sizeof(tbuf); + k = iconv(cd2, &tb, &tbl, &ob, &obl); + assert((!k && !tbl) || + (k == (size_t)(-1) && errno == EILSEQ && tbl)); + for (++ib, --ibl; ibl && (*ib & 0x80); ib++, ibl--) + ; + } + outlen += ob - tbuf; + } + ob = tbuf; + obl = sizeof(tbuf); + k = iconv(cd2, 0, 0, &ob, &obl); + assert(!k); + outlen += ob - tbuf; + + /* Convert from UTF-8 for real */ + outbuf = (char *)safe_malloc_add_2op_(outlen, /*+*/1); + if (!outbuf) + goto fail; + ib = utfbuf; + ibl = utflen; + ob = outbuf; + obl = outlen; + while (ibl) { + k = iconv(cd2, &ib, &ibl, &ob, &obl); + assert((k != (size_t)(-1) && !ibl) || + (k == (size_t)(-1) && errno == EILSEQ && ibl)); + if (k && !ret) + ret = 1; + if (ibl && !(k == (size_t)(-1) && errno == E2BIG)) { + /* Replace one character */ + char *tb = "?"; + size_t tbl = 1; + + k = iconv(cd2, &tb, &tbl, &ob, &obl); + assert((!k && !tbl) || + (k == (size_t)(-1) && errno == EILSEQ && tbl)); + for (++ib, --ibl; ibl && (*ib & 0x80); ib++, ibl--) + ; + } + } + k = iconv(cd2, 0, 0, &ob, &obl); + assert(!k); + assert(!obl); + *ob = '\0'; + + free(utfbuf); + iconv_close(cd1); + iconv_close(cd2); + if (tolen) + *tolen = outlen; + if (!to) { + free(outbuf); + return ret; + } + *to = outbuf; + return ret; + + fail: + if(0 != utfbuf) + free(utfbuf); + iconv_close(cd1); + if (cd2 != (iconv_t)(-1)) + iconv_close(cd2); + return -2; +} + +#endif /* HAVE_ICONV */ diff --git a/flac/src/share/utf8/iconvert.h b/flac/src/share/utf8/iconvert.h new file mode 100644 index 0000000..a351c5d --- /dev/null +++ b/flac/src/share/utf8/iconvert.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#ifdef HAVE_ICONV + +/* + * Convert data from one encoding to another. Return: + * + * -2 : memory allocation failed + * -1 : unknown encoding + * 0 : data was converted exactly + * 1 : data was converted inexactly + * 2 : data was invalid (but still converted) + * + * We convert in two steps, via UTF-8, as this is the only + * reliable way of distinguishing between invalid input + * and valid input which iconv refuses to transliterate. + * We convert from UTF-8 twice, because we have no way of + * knowing whether the conversion was exact if iconv returns + * E2BIG (due to a bug in the specification of iconv). + * An alternative approach is to assume that the output of + * iconv is never more than 4 times as long as the input, + * but I prefer to avoid that assumption if possible. + */ + +int iconvert(const char *fromcode, const char *tocode, + const char *from, size_t fromlen, + char **to, size_t *tolen) ; + +#endif /* HAVE_ICONV */ diff --git a/flac/src/share/utf8/makemap.c b/flac/src/share/utf8/makemap.c new file mode 100644 index 0000000..46bcad2 --- /dev/null +++ b/flac/src/share/utf8/makemap.c @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2001 Edmund Grimley Evans + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +int main(int argc, char *argv[]) +{ + iconv_t cd; + const char *ib; + char *ob; + size_t ibl, obl, k; + unsigned char c, buf[4]; + int i, wc; + + if (argc != 2) { + printf("Usage: %s ENCODING\n", argv[0]); + printf("Output a charset map for the 8-bit ENCODING.\n"); + return 1; + } + + cd = iconv_open("UCS-4", argv[1]); + if (cd == (iconv_t)(-1)) { + perror("iconv_open"); + return 1; + } + + for (i = 0; i < 256; i++) { + c = i; + ib = &c; + ibl = 1; + ob = buf; + obl = 4; + k = iconv(cd, &ib, &ibl, &ob, &obl); + if (!k && !ibl && !obl) { + wc = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; + if (wc >= 0xffff) { + printf("Dodgy value.\n"); + return 1; + } + } + else if (k == (size_t)(-1) && errno == EILSEQ) + wc = 0xffff; + else { + printf("Non-standard iconv.\n"); + return 1; + } + + if (i % 8 == 0) + printf(" "); + printf("0x%04x", wc); + if (i == 255) + printf("\n"); + else if (i % 8 == 7) + printf(",\n"); + else + printf(", "); + } + + return 0; +} diff --git a/flac/src/share/utf8/utf8.c b/flac/src/share/utf8/utf8.c new file mode 100644 index 0000000..21179ae --- /dev/null +++ b/flac/src/share/utf8/utf8.c @@ -0,0 +1,319 @@ +/* + * Copyright (C) 2001 Peter Harris + * Copyright (C) 2001 Edmund Grimley Evans + * + * Buffer overflow checking added: Josh Coalson, 9/9/2007 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Convert a string between UTF-8 and the locale's charset. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include + +#include "share/alloc.h" +#include "utf8.h" +#include "charset.h" + + +#ifdef _WIN32 + + /* Thanks to Peter Harris for this win32 + * code. + */ + +#include +#include + +static unsigned char *make_utf8_string(const wchar_t *unicode) +{ + size_t size = 0, n; + int index = 0, out_index = 0; + unsigned char *out; + unsigned short c; + + /* first calculate the size of the target string */ + c = unicode[index++]; + while(c) { + if(c < 0x0080) { + n = 1; + } else if(c < 0x0800) { + n = 2; + } else { + n = 3; + } + if(size+n < size) /* overflow check */ + return NULL; + size += n; + c = unicode[index++]; + } + + out = safe_malloc_add_2op_(size, /*+*/1); + if (out == NULL) + return NULL; + index = 0; + + c = unicode[index++]; + while(c) + { + if(c < 0x080) { + out[out_index++] = (unsigned char)c; + } else if(c < 0x800) { + out[out_index++] = 0xc0 | (c >> 6); + out[out_index++] = 0x80 | (c & 0x3f); + } else { + out[out_index++] = 0xe0 | (c >> 12); + out[out_index++] = 0x80 | ((c >> 6) & 0x3f); + out[out_index++] = 0x80 | (c & 0x3f); + } + c = unicode[index++]; + } + out[out_index] = 0x00; + + return out; +} + +static wchar_t *make_unicode_string(const unsigned char *utf8) +{ + size_t size = 0; + int index = 0, out_index = 0; + wchar_t *out; + unsigned char c; + + /* first calculate the size of the target string */ + c = utf8[index++]; + while(c) { + if((c & 0x80) == 0) { + index += 0; + } else if((c & 0xe0) == 0xe0) { + index += 2; + } else { + index += 1; + } + if(size + 1 == 0) /* overflow check */ + return NULL; + size++; + c = utf8[index++]; + } + + if(size + 1 == 0) /* overflow check */ + return NULL; + out = safe_malloc_mul_2op_(size+1, /*times*/sizeof(wchar_t)); + if (out == NULL) + return NULL; + index = 0; + + c = utf8[index++]; + while(c) + { + if((c & 0x80) == 0) { + out[out_index++] = c; + } else if((c & 0xe0) == 0xe0) { + out[out_index] = (c & 0x1F) << 12; + c = utf8[index++]; + out[out_index] |= (c & 0x3F) << 6; + c = utf8[index++]; + out[out_index++] |= (c & 0x3F); + } else { + out[out_index] = (c & 0x3F) << 6; + c = utf8[index++]; + out[out_index++] |= (c & 0x3F); + } + c = utf8[index++]; + } + out[out_index] = 0; + + return out; +} + +int utf8_encode(const char *from, char **to) +{ + wchar_t *unicode; + int wchars, err; + + wchars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, from, + strlen(from), NULL, 0); + + if(wchars == 0) + { + fprintf(stderr, "Unicode translation error %d\n", GetLastError()); + return -1; + } + + if(wchars < 0) /* underflow check */ + return -1; + + unicode = safe_calloc_((size_t)wchars + 1, sizeof(unsigned short)); + if(unicode == NULL) + { + fprintf(stderr, "Out of memory processing string to UTF8\n"); + return -1; + } + + err = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, from, + strlen(from), unicode, wchars); + if(err != wchars) + { + free(unicode); + fprintf(stderr, "Unicode translation error %d\n", GetLastError()); + return -1; + } + + /* On NT-based windows systems, we could use WideCharToMultiByte(), but + * MS doesn't actually have a consistent API across win32. + */ + *to = make_utf8_string(unicode); + + free(unicode); + return 0; +} + +int utf8_decode(const char *from, char **to) +{ + wchar_t *unicode; + int chars, err; + + /* On NT-based windows systems, we could use MultiByteToWideChar(CP_UTF8), but + * MS doesn't actually have a consistent API across win32. + */ + unicode = make_unicode_string(from); + if(unicode == NULL) + { + fprintf(stderr, "Out of memory processing string from UTF8 to UNICODE16\n"); + return -1; + } + + chars = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, + -1, NULL, 0, NULL, NULL); + + if(chars < 0) /* underflow check */ + return -1; + + if(chars == 0) + { + fprintf(stderr, "Unicode translation error %d\n", GetLastError()); + free(unicode); + return -1; + } + + *to = safe_calloc_((size_t)chars + 1, sizeof(unsigned char)); + if(*to == NULL) + { + fprintf(stderr, "Out of memory processing string to local charset\n"); + free(unicode); + return -1; + } + + err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, + -1, *to, chars, NULL, NULL); + if(err != chars) + { + fprintf(stderr, "Unicode translation error %d\n", GetLastError()); + free(unicode); + free(*to); + *to = NULL; + return -1; + } + + free(unicode); + return 0; +} + +#else /* End win32. Rest is for real operating systems */ + + +#ifdef HAVE_LANGINFO_CODESET +#include +#endif + +#include "iconvert.h" + +static const char *current_charset(void) +{ + const char *c = 0; +#ifdef HAVE_LANGINFO_CODESET + c = nl_langinfo(CODESET); +#endif + + if (!c) + c = getenv("CHARSET"); + + return c? c : "US-ASCII"; +} + +static int convert_buffer(const char *fromcode, const char *tocode, + const char *from, size_t fromlen, + char **to, size_t *tolen) +{ + int ret = -1; + +#ifdef HAVE_ICONV + ret = iconvert(fromcode, tocode, from, fromlen, to, tolen); + if (ret != -1) + return ret; +#endif + +#ifndef HAVE_ICONV /* should be ifdef USE_CHARSET_CONVERT */ + ret = charset_convert(fromcode, tocode, from, fromlen, to, tolen); + if (ret != -1) + return ret; +#endif + + return ret; +} + +static int convert_string(const char *fromcode, const char *tocode, + const char *from, char **to, char replace) +{ + int ret; + size_t fromlen; + char *s; + + fromlen = strlen(from); + ret = convert_buffer(fromcode, tocode, from, fromlen, to, 0); + if (ret == -2) + return -1; + if (ret != -1) + return ret; + + s = safe_malloc_add_2op_(fromlen, /*+*/1); + if (!s) + return -1; + strcpy(s, from); + *to = s; + for (; *s; s++) + if (*s & ~0x7f) + *s = replace; + return 3; +} + +int utf8_encode(const char *from, char **to) +{ + return convert_string(current_charset(), "UTF-8", from, to, '#'); +} + +int utf8_decode(const char *from, char **to) +{ + return convert_string("UTF-8", current_charset(), from, to, '?'); +} + +#endif diff --git a/flac/src/share/utf8/utf8_static.dsp b/flac/src/share/utf8/utf8_static.dsp new file mode 100644 index 0000000..814284b --- /dev/null +++ b/flac/src/share/utf8/utf8_static.dsp @@ -0,0 +1,116 @@ +# Microsoft Developer Studio Project File - Name="utf8_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=utf8_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "utf8_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "utf8_static.mak" CFG="utf8_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "utf8_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "utf8_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "utf8" +# PROP Scc_LocalPath "..\..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "utf8_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I ".\include" /I "..\..\..\include" /I "..\..\..\include\share" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "utf8_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\..\include" /I "..\..\..\include\share" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "utf8_static - Win32 Release" +# Name "utf8_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\charset.c +# End Source File +# Begin Source File + +SOURCE=.\iconvert.c +# End Source File +# Begin Source File + +SOURCE=.\utf8.c +# End Source File +# End Group +# Begin Group "Private Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Protected Header Files" + +# PROP Default_Filter "" +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\include\share\utf8.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/share/utf8/utf8_static.vcproj b/flac/src/share/utf8/utf8_static.vcproj new file mode 100644 index 0000000..d7ad0eb --- /dev/null +++ b/flac/src/share/utf8/utf8_static.vcproj @@ -0,0 +1,338 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_grabbag/Makefile.am b/flac/src/test_grabbag/Makefile.am new file mode 100644 index 0000000..7fd0f4c --- /dev/null +++ b/flac/src/test_grabbag/Makefile.am @@ -0,0 +1,21 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +SUBDIRS = cuesheet picture + +EXTRA_DIST = \ + Makefile.lite diff --git a/flac/src/test_grabbag/Makefile.lite b/flac/src/test_grabbag/Makefile.lite new file mode 100644 index 0000000..28234ab --- /dev/null +++ b/flac/src/test_grabbag/Makefile.lite @@ -0,0 +1,40 @@ +# test_grabbag - Simple testers for the grabbag library +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +.PHONY: cuesheet picture +all: cuesheet picture + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +debug : CONFIG = debug +valgrind: CONFIG = valgrind +release : CONFIG = release + +debug : all +valgrind: all +release : all + +cuesheet: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) +picture: + (cd $@ ; $(MAKE) -f Makefile.lite $(CONFIG)) + +clean: + -(cd cuesheet ; $(MAKE) -f Makefile.lite clean) + -(cd picture ; $(MAKE) -f Makefile.lite clean) diff --git a/flac/src/test_grabbag/cuesheet/Makefile.am b/flac/src/test_grabbag/cuesheet/Makefile.am new file mode 100644 index 0000000..0bb3e6a --- /dev/null +++ b/flac/src/test_grabbag/cuesheet/Makefile.am @@ -0,0 +1,31 @@ +# test_cuesheet - Simple tester for cuesheet routines in grabbag +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_cuesheet.dsp \ + test_cuesheet.vcproj + +noinst_PROGRAMS = test_cuesheet +test_cuesheet_SOURCES = \ + main.c +test_cuesheet_LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + -lm diff --git a/flac/src/test_grabbag/cuesheet/Makefile.lite b/flac/src/test_grabbag/cuesheet/Makefile.lite new file mode 100644 index 0000000..29cfe09 --- /dev/null +++ b/flac/src/test_grabbag/cuesheet/Makefile.lite @@ -0,0 +1,40 @@ +# test_cuesheet - Simple tester for cuesheet routines in grabbag +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_cuesheet + +INCLUDES = -I./include -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libreplaygain_analysis.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lgrabbag -lreplaygain_analysis -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_grabbag/cuesheet/main.c b/flac/src/test_grabbag/cuesheet/main.c new file mode 100644 index 0000000..779f0f0 --- /dev/null +++ b/flac/src/test_grabbag/cuesheet/main.c @@ -0,0 +1,138 @@ +/* test_cuesheet - Simple tester for cuesheet routines in grabbag + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "share/grabbag.h" + +static int do_cuesheet(const char *infilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset) +{ + FILE *fin, *fout; + const char *error_message; + char tmpfilename[4096]; + unsigned last_line_read; + FLAC__StreamMetadata *cuesheet; + + FLAC__ASSERT(strlen(infilename) + 2 < sizeof(tmpfilename)); + + /* + * pass 1 + */ + if(0 == strcmp(infilename, "-")) { + fin = stdin; + } + else if(0 == (fin = fopen(infilename, "r"))) { + fprintf(stderr, "can't open file %s for reading: %s\n", infilename, strerror(errno)); + return 255; + } + if(0 != (cuesheet = grabbag__cuesheet_parse(fin, &error_message, &last_line_read, is_cdda, lead_out_offset))) { + if(fin != stdin) + fclose(fin); + } + else { + printf("pass1: parse error, line %u: \"%s\"\n", last_line_read, error_message); + if(fin != stdin) + fclose(fin); + return 1; + } + if(!FLAC__metadata_object_cuesheet_is_legal(cuesheet, is_cdda, &error_message)) { + printf("pass1: illegal cuesheet: \"%s\"\n", error_message); + FLAC__metadata_object_delete(cuesheet); + return 1; + } + sprintf(tmpfilename, "%s.1", infilename); + if(0 == (fout = fopen(tmpfilename, "w"))) { + fprintf(stderr, "can't open file %s for writing: %s\n", tmpfilename, strerror(errno)); + FLAC__metadata_object_delete(cuesheet); + return 255; + } + grabbag__cuesheet_emit(fout, cuesheet, "\"dummy.wav\" WAVE"); + FLAC__metadata_object_delete(cuesheet); + fclose(fout); + + /* + * pass 2 + */ + if(0 == (fin = fopen(tmpfilename, "r"))) { + fprintf(stderr, "can't open file %s for reading: %s\n", tmpfilename, strerror(errno)); + return 255; + } + if(0 != (cuesheet = grabbag__cuesheet_parse(fin, &error_message, &last_line_read, is_cdda, lead_out_offset))) { + if(fin != stdin) + fclose(fin); + } + else { + printf("pass2: parse error, line %u: \"%s\"\n", last_line_read, error_message); + if(fin != stdin) + fclose(fin); + return 1; + } + if(!FLAC__metadata_object_cuesheet_is_legal(cuesheet, is_cdda, &error_message)) { + printf("pass2: illegal cuesheet: \"%s\"\n", error_message); + FLAC__metadata_object_delete(cuesheet); + return 1; + } + sprintf(tmpfilename, "%s.2", infilename); + if(0 == (fout = fopen(tmpfilename, "w"))) { + fprintf(stderr, "can't open file %s for writing: %s\n", tmpfilename, strerror(errno)); + FLAC__metadata_object_delete(cuesheet); + return 255; + } + grabbag__cuesheet_emit(fout, cuesheet, "\"dummy.wav\" WAVE"); + FLAC__metadata_object_delete(cuesheet); + fclose(fout); + + return 0; +} + +int main(int argc, char *argv[]) +{ + FLAC__uint64 lead_out_offset; + FLAC__bool is_cdda = false; + const char *usage = "usage: test_cuesheet cuesheet_file lead_out_offset [ cdda ]\n"; + + if(argc > 1 && 0 == strcmp(argv[1], "-h")) { + printf(usage); + return 0; + } + + if(argc < 3 || argc > 4) { + fprintf(stderr, usage); + return 255; + } + + lead_out_offset = (FLAC__uint64)strtoul(argv[2], 0, 10); + if(argc == 4) { + if(0 == strcmp(argv[3], "cdda")) + is_cdda = true; + else { + fprintf(stderr, usage); + return 255; + } + } + + return do_cuesheet(argv[1], is_cdda, lead_out_offset); +} diff --git a/flac/src/test_grabbag/cuesheet/test_cuesheet.dsp b/flac/src/test_grabbag/cuesheet/test_cuesheet.dsp new file mode 100644 index 0000000..8769d0b --- /dev/null +++ b/flac/src/test_grabbag/cuesheet/test_cuesheet.dsp @@ -0,0 +1,96 @@ +# Microsoft Developer Studio Project File - Name="test_cuesheet" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_cuesheet - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_cuesheet.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_cuesheet.mak" CFG="test_cuesheet - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_cuesheet - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_cuesheet - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_cuesheet - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\obj\release\lib\grabbag_static.lib ..\..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\..\obj\release\lib\libFLAC_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_cuesheet - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\obj\debug\lib\grabbag_static.lib ..\..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\..\obj\debug\lib\libFLAC_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_cuesheet - Win32 Release" +# Name "test_cuesheet - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/test_grabbag/cuesheet/test_cuesheet.vcproj b/flac/src/test_grabbag/cuesheet/test_cuesheet.vcproj new file mode 100644 index 0000000..5fdb391 --- /dev/null +++ b/flac/src/test_grabbag/cuesheet/test_cuesheet.vcproj @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_grabbag/picture/Makefile.am b/flac/src/test_grabbag/picture/Makefile.am new file mode 100644 index 0000000..9a5ad6b --- /dev/null +++ b/flac/src/test_grabbag/picture/Makefile.am @@ -0,0 +1,30 @@ +# test_picture - Simple tester for picture routines in grabbag +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_picture.dsp \ + test_picture.vcproj + +noinst_PROGRAMS = test_picture +test_picture_SOURCES = \ + main.c +test_picture_LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + -lm diff --git a/flac/src/test_grabbag/picture/Makefile.lite b/flac/src/test_grabbag/picture/Makefile.lite new file mode 100644 index 0000000..102807f --- /dev/null +++ b/flac/src/test_grabbag/picture/Makefile.lite @@ -0,0 +1,40 @@ +# test_picture - Simple tester for picture routines in grabbag +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_picture + +INCLUDES = -I./include -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libreplaygain_analysis.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lgrabbag -lreplaygain_analysis -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_grabbag/picture/main.c b/flac/src/test_grabbag/picture/main.c new file mode 100644 index 0000000..09013c3 --- /dev/null +++ b/flac/src/test_grabbag/picture/main.c @@ -0,0 +1,224 @@ +/* test_picture - Simple tester for picture routines in grabbag + * Copyright (C) 2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include "FLAC/assert.h" +#include "share/grabbag.h" + +typedef struct { + const char *path; + const char *mime_type; + const char *description; + FLAC__uint32 width; + FLAC__uint32 height; + FLAC__uint32 depth; + FLAC__uint32 colors; + FLAC__StreamMetadata_Picture_Type type; +} PictureFile; + +PictureFile picturefiles[] = { + { "0.gif", "image/gif" , "", 24, 24, 24, 2, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "1.gif", "image/gif" , "", 12, 8, 24, 256, FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER }, + { "2.gif", "image/gif" , "", 16, 14, 24, 128, FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER }, + { "0.jpg", "image/jpeg", "", 30, 20, 8, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "4.jpg", "image/jpeg", "", 31, 47, 24, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "0.png", "image/png" , "", 30, 20, 8, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "1.png", "image/png" , "", 30, 20, 8, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "2.png", "image/png" , "", 30, 20, 24, 7, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "3.png", "image/png" , "", 30, 20, 24, 7, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "4.png", "image/png" , "", 31, 47, 24, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "5.png", "image/png" , "", 31, 47, 24, 0, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "6.png", "image/png" , "", 31, 47, 24, 23, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "7.png", "image/png" , "", 31, 47, 24, 23, FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER }, + { "8.png", "image/png" , "", 32, 32, 32, 0, 999 } +}; + +static FLAC__bool debug_ = false; + +static FLAC__bool failed_(const char *msg) +{ + if(msg) + printf("FAILED, %s\n", msg); + else + printf("FAILED\n"); + + return false; +} + +static FLAC__bool test_one_picture(const char *prefix, const PictureFile *pf, const char *res, FLAC__bool fn_only) +{ + FLAC__StreamMetadata *obj; + const char *error; + char s[4096]; + if(fn_only) +#if defined _MSC_VER || defined __MINGW32__ + _snprintf(s, sizeof(s)-1, "%s/%s", prefix, pf->path); +#else + snprintf(s, sizeof(s)-1, "%s/%s", prefix, pf->path); +#endif + else +#if defined _MSC_VER || defined __MINGW32__ + _snprintf(s, sizeof(s)-1, "%u|%s|%s|%s|%s/%s", (unsigned)pf->type, pf->mime_type, pf->description, res, prefix, pf->path); +#else + snprintf(s, sizeof(s)-1, "%u|%s|%s|%s|%s/%s", (unsigned)pf->type, pf->mime_type, pf->description, res, prefix, pf->path); +#endif + + printf("testing grabbag__picture_parse_specification(\"%s\")... ", s); + if(0 == (obj = grabbag__picture_parse_specification(s, &error))) + return failed_(error); + if(debug_) { + printf("\ntype=%u (%s)\nmime_type=%s\ndescription=%s\nwidth=%u\nheight=%u\ndepth=%u\ncolors=%u\ndata_length=%u\n", + obj->data.picture.type, + obj->data.picture.type < FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED? + FLAC__StreamMetadata_Picture_TypeString[obj->data.picture.type] : "UNDEFINED", + obj->data.picture.mime_type, + obj->data.picture.description, + obj->data.picture.width, + obj->data.picture.height, + obj->data.picture.depth, + obj->data.picture.colors, + obj->data.picture.data_length + ); + } + if(obj->data.picture.type != (fn_only? FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER : pf->type)) + return failed_("picture type mismatch"); + if(strcmp(obj->data.picture.mime_type, pf->mime_type)) + return failed_("picture MIME type mismatch"); + if(strcmp((const char *)obj->data.picture.description, (const char *)pf->description)) + return failed_("picture description mismatch"); + if(obj->data.picture.width != pf->width) + return failed_("picture width mismatch"); + if(obj->data.picture.height != pf->height) + return failed_("picture height mismatch"); + if(obj->data.picture.depth != pf->depth) + return failed_("picture depth mismatch"); + if(obj->data.picture.colors != pf->colors) + return failed_("picture colors mismatch"); + printf("OK\n"); + FLAC__metadata_object_delete(obj); + return true; +} + +static FLAC__bool do_picture(const char *prefix) +{ + FLAC__StreamMetadata *obj; + const char *error; + size_t i; + + printf("\n+++ grabbag unit test: picture\n\n"); + + /* invalid spec: no filename */ + printf("testing grabbag__picture_parse_specification(\"\")... "); + if(0 != (obj = grabbag__picture_parse_specification("", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected, error: %s)\n", error); + + /* invalid spec: no filename */ + printf("testing grabbag__picture_parse_specification(\"||||\")... "); + if(0 != (obj = grabbag__picture_parse_specification("||||", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: no filename */ + printf("testing grabbag__picture_parse_specification(\"|image/gif|||\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|image/gif|||", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: bad resolution */ + printf("testing grabbag__picture_parse_specification(\"|image/gif|desc|320|0.gif\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|image/gif|desc|320|0.gif", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: bad resolution */ + printf("testing grabbag__picture_parse_specification(\"|image/gif|desc|320x240|0.gif\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|image/gif|desc|320x240|0.gif", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: no filename */ + printf("testing grabbag__picture_parse_specification(\"|image/gif|desc|320x240x9|\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|image/gif|desc|320x240x9|", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: #colors exceeds color depth */ + printf("testing grabbag__picture_parse_specification(\"|image/gif|desc|320x240x9/2345|0.gif\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|image/gif|desc|320x240x9/2345|0.gif", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: standard icon has to be 32x32 PNG */ + printf("testing grabbag__picture_parse_specification(\"1|-->|desc|32x24x9|0.gif\")... "); + if(0 != (obj = grabbag__picture_parse_specification("1|-->|desc|32x24x9|0.gif", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + /* invalid spec: need resolution for linked URL */ + printf("testing grabbag__picture_parse_specification(\"|-->|desc||http://blah.blah.blah/z.gif\")... "); + if(0 != (obj = grabbag__picture_parse_specification("|-->|desc||http://blah.blah.blah/z.gif", &error))) + return failed_("expected error, got object"); + printf("OK (failed as expected: %s)\n", error); + + printf("testing grabbag__picture_parse_specification(\"|-->|desc|320x240x9|http://blah.blah.blah/z.gif\")... "); + if(0 == (obj = grabbag__picture_parse_specification("|-->|desc|320x240x9|http://blah.blah.blah/z.gif", &error))) + return failed_(error); + printf("OK\n"); + FLAC__metadata_object_delete(obj); + + /* test automatic parsing of picture files from only the file name */ + for(i = 0; i < sizeof(picturefiles)/sizeof(picturefiles[0]); i++) + if(!test_one_picture(prefix, picturefiles+i, "", /*fn_only=*/true)) + return false; + + /* test automatic parsing of picture files to get resolution/color info */ + for(i = 0; i < sizeof(picturefiles)/sizeof(picturefiles[0]); i++) + if(!test_one_picture(prefix, picturefiles+i, "", /*fn_only=*/false)) + return false; + + picturefiles[0].width = 320; + picturefiles[0].height = 240; + picturefiles[0].depth = 3; + picturefiles[0].colors = 2; + if(!test_one_picture(prefix, picturefiles+0, "320x240x3/2", /*fn_only=*/false)) + return false; + + return true; +} + +int main(int argc, char *argv[]) +{ + const char *usage = "usage: test_pictures path_prefix\n"; + + if(argc > 1 && 0 == strcmp(argv[1], "-h")) { + printf(usage); + return 0; + } + + if(argc != 2) { + fprintf(stderr, usage); + return 255; + } + + return do_picture(argv[1])? 0 : 1; +} diff --git a/flac/src/test_grabbag/picture/test_picture.dsp b/flac/src/test_grabbag/picture/test_picture.dsp new file mode 100644 index 0000000..3985aba --- /dev/null +++ b/flac/src/test_grabbag/picture/test_picture.dsp @@ -0,0 +1,96 @@ +# Microsoft Developer Studio Project File - Name="test_picture" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_picture - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_picture.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_picture.mak" CFG="test_picture - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_picture - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_picture - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_picture - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\obj\release\lib\grabbag_static.lib ..\..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\..\obj\release\lib\libFLAC_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_picture - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\obj\debug\lib\grabbag_static.lib ..\..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\..\obj\debug\lib\libFLAC_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_picture - Win32 Release" +# Name "test_picture - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/test_grabbag/picture/test_picture.vcproj b/flac/src/test_grabbag/picture/test_picture.vcproj new file mode 100644 index 0000000..42f312f --- /dev/null +++ b/flac/src/test_grabbag/picture/test_picture.vcproj @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_libFLAC++/Makefile.am b/flac/src/test_libFLAC++/Makefile.am new file mode 100644 index 0000000..919fb5c --- /dev/null +++ b/flac/src/test_libFLAC++/Makefile.am @@ -0,0 +1,42 @@ +# test_libFLAC++ - Unit tester for libFLAC++ +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_libFLAC++.dsp \ + test_libFLAC++.vcproj + +noinst_PROGRAMS = test_libFLAC++ +test_libFLAC___LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/test_libs_common/libtest_libs_common.la \ + $(top_builddir)/src/libFLAC++/libFLAC++.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +test_libFLAC___SOURCES = \ + decoders.cpp \ + encoders.cpp \ + main.cpp \ + metadata.cpp \ + metadata_manip.cpp \ + metadata_object.cpp \ + decoders.h \ + encoders.h \ + metadata.h diff --git a/flac/src/test_libFLAC++/Makefile.lite b/flac/src/test_libFLAC++/Makefile.lite new file mode 100644 index 0000000..2f43475 --- /dev/null +++ b/flac/src/test_libFLAC++/Makefile.lite @@ -0,0 +1,47 @@ +# test_libFLAC++ - Unit tester for libFLAC++ +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_libFLAC++ + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libreplaygain_analysis.a $(libdir)/libtest_libs_common.a $(libdir)/libFLAC++.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lgrabbag -lreplaygain_analysis -ltest_libs_common -lFLAC++ -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_CPP = \ + decoders.cpp \ + encoders.cpp \ + main.cpp \ + metadata.cpp \ + metadata_manip.cpp \ + metadata_object.cpp + +include $(topdir)/build/exe.mk + +LINK = $(CCC) $(LINKAGE) + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_libFLAC++/decoders.cpp b/flac/src/test_libFLAC++/decoders.cpp new file mode 100644 index 0000000..9474adc --- /dev/null +++ b/flac/src/test_libFLAC++/decoders.cpp @@ -0,0 +1,1179 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include "decoders.h" +#include "FLAC/assert.h" +#include "FLAC/metadata.h" // for ::FLAC__metadata_object_is_equal() +#include "FLAC++/decoder.h" +#include "share/grabbag.h" +extern "C" { +#include "test_libs_common/file_utils_flac.h" +#include "test_libs_common/metadata_utils.h" +} + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + +typedef enum { + LAYER_STREAM = 0, /* FLAC__stream_decoder_init_stream() without seeking */ + LAYER_SEEKABLE_STREAM, /* FLAC__stream_decoder_init_stream() with seeking */ + LAYER_FILE, /* FLAC__stream_decoder_init_FILE() */ + LAYER_FILENAME /* FLAC__stream_decoder_init_file() */ +} Layer; + +static const char * const LayerString[] = { + "Stream", + "Seekable Stream", + "FILE*", + "Filename" +}; + +static ::FLAC__StreamMetadata streaminfo_, padding_, seektable_, application1_, application2_, vorbiscomment_, cuesheet_, picture_, unknown_; +static ::FLAC__StreamMetadata *expected_metadata_sequence_[9]; +static unsigned num_expected_; +static off_t flacfilesize_; + +static const char *flacfilename(bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static FLAC__bool die_s_(const char *msg, const FLAC::Decoder::Stream *decoder) +{ + FLAC::Decoder::Stream::State state = decoder->get_state(); + + if(msg) + printf("FAILED, %s", msg); + else + printf("FAILED"); + + printf(", state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + + return false; +} + +static void init_metadata_blocks_() +{ + mutils__init_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static void free_metadata_blocks_() +{ + mutils__free_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static bool generate_file_(FLAC__bool is_ogg) +{ + printf("\n\ngenerating %sFLAC file for decoder tests...\n", is_ogg? "Ogg ":""); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + /* WATCHOUT: for Ogg FLAC the encoder should move the VORBIS_COMMENT block to the front, right after STREAMINFO */ + + if(!file_utils__generate_flacfile(is_ogg, flacfilename(is_ogg), &flacfilesize_, 512 * 1024, &streaminfo_, expected_metadata_sequence_, num_expected_)) + return die_("creating the encoded file"); + + return true; +} + + +class DecoderCommon { +public: + Layer layer_; + unsigned current_metadata_number_; + bool ignore_errors_; + bool error_occurred_; + + DecoderCommon(Layer layer): layer_(layer), current_metadata_number_(0), ignore_errors_(false), error_occurred_(false) { } + ::FLAC__StreamDecoderWriteStatus common_write_callback_(const ::FLAC__Frame *frame); + void common_metadata_callback_(const ::FLAC__StreamMetadata *metadata); + void common_error_callback_(::FLAC__StreamDecoderErrorStatus status); +}; + +::FLAC__StreamDecoderWriteStatus DecoderCommon::common_write_callback_(const ::FLAC__Frame *frame) +{ + if(error_occurred_) + return ::FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + if( + (frame->header.number_type == ::FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER && frame->header.number.frame_number == 0) || + (frame->header.number_type == ::FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER && frame->header.number.sample_number == 0) + ) { + printf("content... "); + fflush(stdout); + } + + return ::FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void DecoderCommon::common_metadata_callback_(const ::FLAC__StreamMetadata *metadata) +{ + if(error_occurred_) + return; + + printf("%d... ", current_metadata_number_); + fflush(stdout); + + if(current_metadata_number_ >= num_expected_) { + (void)die_("got more metadata blocks than expected"); + error_occurred_ = true; + } + else { + if(!::FLAC__metadata_object_is_equal(expected_metadata_sequence_[current_metadata_number_], metadata)) { + (void)die_("metadata block mismatch"); + error_occurred_ = true; + } + } + current_metadata_number_++; +} + +void DecoderCommon::common_error_callback_(::FLAC__StreamDecoderErrorStatus status) +{ + if(!ignore_errors_) { + printf("ERROR: got error callback: err = %u (%s)\n", (unsigned)status, ::FLAC__StreamDecoderErrorStatusString[status]); + error_occurred_ = true; + } +} + +class StreamDecoder : public FLAC::Decoder::Stream, public DecoderCommon { +public: + FILE *file_; + + StreamDecoder(Layer layer): FLAC::Decoder::Stream(), DecoderCommon(layer), file_(0) { } + ~StreamDecoder() { } + + // from FLAC::Decoder::Stream + ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes); + ::FLAC__StreamDecoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset); + ::FLAC__StreamDecoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset); + ::FLAC__StreamDecoderLengthStatus length_callback(FLAC__uint64 *stream_length); + bool eof_callback(); + ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]); + void metadata_callback(const ::FLAC__StreamMetadata *metadata); + void error_callback(::FLAC__StreamDecoderErrorStatus status); + + bool test_respond(bool is_ogg); +}; + +::FLAC__StreamDecoderReadStatus StreamDecoder::read_callback(FLAC__byte buffer[], size_t *bytes) +{ + const size_t requested_bytes = *bytes; + + if(error_occurred_) + return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; + + if(feof(file_)) { + *bytes = 0; + return ::FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + } + else if(requested_bytes > 0) { + *bytes = ::fread(buffer, 1, requested_bytes, file_); + if(*bytes == 0) { + if(feof(file_)) + return ::FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return ::FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + else { + return ::FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + } + else + return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */ +} + +::FLAC__StreamDecoderSeekStatus StreamDecoder::seek_callback(FLAC__uint64 absolute_byte_offset) +{ + if(layer_ == LAYER_STREAM) + return ::FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; + + if(error_occurred_) + return ::FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + + if(fseeko(file_, (off_t)absolute_byte_offset, SEEK_SET) < 0) { + error_occurred_ = true; + return ::FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + } + + return ::FLAC__STREAM_DECODER_SEEK_STATUS_OK; +} + +::FLAC__StreamDecoderTellStatus StreamDecoder::tell_callback(FLAC__uint64 *absolute_byte_offset) +{ + if(layer_ == LAYER_STREAM) + return ::FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; + + if(error_occurred_) + return ::FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + + off_t offset = ftello(file_); + *absolute_byte_offset = (FLAC__uint64)offset; + + if(offset < 0) { + error_occurred_ = true; + return ::FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + } + + return ::FLAC__STREAM_DECODER_TELL_STATUS_OK; +} + +::FLAC__StreamDecoderLengthStatus StreamDecoder::length_callback(FLAC__uint64 *stream_length) +{ + if(layer_ == LAYER_STREAM) + return ::FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; + + if(error_occurred_) + return ::FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + + *stream_length = (FLAC__uint64)flacfilesize_; + return ::FLAC__STREAM_DECODER_LENGTH_STATUS_OK; +} + +bool StreamDecoder::eof_callback() +{ + if(layer_ == LAYER_STREAM) + return false; + + if(error_occurred_) + return true; + + return (bool)feof(file_); +} + +::FLAC__StreamDecoderWriteStatus StreamDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) +{ + (void)buffer; + + return common_write_callback_(frame); +} + +void StreamDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) +{ + common_metadata_callback_(metadata); +} + +void StreamDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status) +{ + common_error_callback_(status); +} + +bool StreamDecoder::test_respond(bool is_ogg) +{ + ::FLAC__StreamDecoderInitStatus init_status; + + if(!set_md5_checking(true)) { + printf("FAILED at set_md5_checking(), returned false\n"); + return false; + } + + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? init_ogg() : init(); + if(init_status != ::FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, this); + printf("OK\n"); + + current_metadata_number_ = 0; + + if(fseeko(file_, 0, SEEK_SET) < 0) { + printf("FAILED rewinding input, errno = %d\n", errno); + return false; + } + + printf("testing process_until_end_of_stream()... "); + if(!process_until_end_of_stream()) { + State state = get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + printf("testing finish()... "); + if(!finish()) { + State state = get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + return true; +} + +class FileDecoder : public FLAC::Decoder::File, public DecoderCommon { +public: + FileDecoder(Layer layer): FLAC::Decoder::File(), DecoderCommon(layer) { } + ~FileDecoder() { } + + // from FLAC::Decoder::Stream + ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]); + void metadata_callback(const ::FLAC__StreamMetadata *metadata); + void error_callback(::FLAC__StreamDecoderErrorStatus status); + + bool test_respond(bool is_ogg); +}; + +::FLAC__StreamDecoderWriteStatus FileDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) +{ + (void)buffer; + return common_write_callback_(frame); +} + +void FileDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) +{ + common_metadata_callback_(metadata); +} + +void FileDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status) +{ + common_error_callback_(status); +} + +bool FileDecoder::test_respond(bool is_ogg) +{ + ::FLAC__StreamDecoderInitStatus init_status; + + if(!set_md5_checking(true)) { + printf("FAILED at set_md5_checking(), returned false\n"); + return false; + } + + switch(layer_) { + case LAYER_FILE: + { + printf("opening %sFLAC file... ", is_ogg? "Ogg ":""); + FILE *file = ::fopen(flacfilename(is_ogg), "rb"); + if(0 == file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? init_ogg(file) : init(file); + } + break; + case LAYER_FILENAME: + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? init_ogg(flacfilename(is_ogg)) : init(flacfilename(is_ogg)); + break; + default: + die_("internal error 001"); + return false; + } + if(init_status != ::FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, this); + printf("OK\n"); + + current_metadata_number_ = 0; + + printf("testing process_until_end_of_stream()... "); + if(!process_until_end_of_stream()) { + State state = get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + printf("testing finish()... "); + if(!finish()) { + State state = get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + return true; +} + + +static FLAC::Decoder::Stream *new_by_layer(Layer layer) +{ + if(layer < LAYER_FILE) + return new StreamDecoder(layer); + else + return new FileDecoder(layer); +} + +static bool test_stream_decoder(Layer layer, bool is_ogg) +{ + FLAC::Decoder::Stream *decoder; + ::FLAC__StreamDecoderInitStatus init_status; + bool expect; + + printf("\n+++ libFLAC++ unit test: FLAC::Decoder::%s (layer: %s, format: %s)\n\n", layer delete + // + printf("allocating decoder instance... "); + decoder = new_by_layer(layer); + if(0 == decoder) { + printf("FAILED, new returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing is_valid()... "); + if(!decoder->is_valid()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("freeing decoder instance... "); + delete decoder; + printf("OK\n"); + + // + // test new -> init -> delete + // + printf("allocating decoder instance... "); + decoder = new_by_layer(layer); + if(0 == decoder) { + printf("FAILED, new returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing is_valid()... "); + if(!decoder->is_valid()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing init%s()... ", is_ogg? "_ogg":""); + switch(layer) { + case LAYER_STREAM: + case LAYER_SEEKABLE_STREAM: + dynamic_cast(decoder)->file_ = stdin; + init_status = is_ogg? decoder->init_ogg() : decoder->init(); + break; + case LAYER_FILE: + init_status = is_ogg? + dynamic_cast(decoder)->init_ogg(stdin) : + dynamic_cast(decoder)->init(stdin); + break; + case LAYER_FILENAME: + init_status = is_ogg? + dynamic_cast(decoder)->init_ogg(flacfilename(is_ogg)) : + dynamic_cast(decoder)->init(flacfilename(is_ogg)); + break; + default: + die_("internal error 006"); + return false; + } + if(init_status != ::FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, decoder); + printf("OK\n"); + + printf("freeing decoder instance... "); + delete decoder; + printf("OK\n"); + + // + // test normal usage + // + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + + printf("allocating decoder instance... "); + decoder = new_by_layer(layer); + if(0 == decoder) { + printf("FAILED, new returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing is_valid()... "); + if(!decoder->is_valid()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + if(is_ogg) { + printf("testing set_ogg_serial_number()... "); + if(!decoder->set_ogg_serial_number(file_utils__ogg_serial_number)) + return die_s_("returned false", decoder); + printf("OK\n"); + } + + if(!decoder->set_md5_checking(true)) { + printf("FAILED at set_md5_checking(), returned false\n"); + return false; + } + + switch(layer) { + case LAYER_STREAM: + case LAYER_SEEKABLE_STREAM: + printf("opening %sFLAC file... ", is_ogg? "Ogg ":""); + dynamic_cast(decoder)->file_ = ::fopen(flacfilename(is_ogg), "rb"); + if(0 == dynamic_cast(decoder)->file_) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? decoder->init_ogg() : decoder->init(); + break; + case LAYER_FILE: + { + printf("opening FLAC file... "); + FILE *file = ::fopen(flacfilename(is_ogg), "rb"); + if(0 == file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? + dynamic_cast(decoder)->init_ogg(file) : + dynamic_cast(decoder)->init(file); + } + break; + case LAYER_FILENAME: + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? + dynamic_cast(decoder)->init_ogg(flacfilename(is_ogg)) : + dynamic_cast(decoder)->init(flacfilename(is_ogg)); + break; + default: + die_("internal error 009"); + return false; + } + if(init_status != ::FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, decoder); + printf("OK\n"); + + printf("testing get_state()... "); + FLAC::Decoder::Stream::State state = decoder->get_state(); + printf("returned state = %u (%s)... OK\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + + dynamic_cast(decoder)->current_metadata_number_ = 0; + dynamic_cast(decoder)->ignore_errors_ = false; + dynamic_cast(decoder)->error_occurred_ = false; + + printf("testing get_md5_checking()... "); + if(!decoder->get_md5_checking()) { + printf("FAILED, returned false, expected true\n"); + return false; + } + printf("OK\n"); + + printf("testing process_until_end_of_metadata()... "); + if(!decoder->process_until_end_of_metadata()) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing process_single()... "); + if(!decoder->process_single()) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing skip_single_frame()... "); + if(!decoder->skip_single_frame()) + return die_s_("returned false", decoder); + printf("OK\n"); + + if(layer < LAYER_FILE) { + printf("testing flush()... "); + if(!decoder->flush()) + return die_s_("returned false", decoder); + printf("OK\n"); + + dynamic_cast(decoder)->ignore_errors_ = true; + printf("testing process_single()... "); + if(!decoder->process_single()) + return die_s_("returned false", decoder); + printf("OK\n"); + dynamic_cast(decoder)->ignore_errors_ = false; + } + + expect = (layer != LAYER_STREAM); + printf("testing seek_absolute()... "); + if(decoder->seek_absolute(0) != expect) + return die_s_(expect? "returned false" : "returned true", decoder); + printf("OK\n"); + + printf("testing process_until_end_of_stream()... "); + if(!decoder->process_until_end_of_stream()) + return die_s_("returned false", decoder); + printf("OK\n"); + + expect = (layer != LAYER_STREAM); + printf("testing seek_absolute()... "); + if(decoder->seek_absolute(0) != expect) + return die_s_(expect? "returned false" : "returned true", decoder); + printf("OK\n"); + + printf("testing get_channels()... "); + { + unsigned channels = decoder->get_channels(); + if(channels != streaminfo_.data.stream_info.channels) { + printf("FAILED, returned %u, expected %u\n", channels, streaminfo_.data.stream_info.channels); + return false; + } + } + printf("OK\n"); + + printf("testing get_bits_per_sample()... "); + { + unsigned bits_per_sample = decoder->get_bits_per_sample(); + if(bits_per_sample != streaminfo_.data.stream_info.bits_per_sample) { + printf("FAILED, returned %u, expected %u\n", bits_per_sample, streaminfo_.data.stream_info.bits_per_sample); + return false; + } + } + printf("OK\n"); + + printf("testing get_sample_rate()... "); + { + unsigned sample_rate = decoder->get_sample_rate(); + if(sample_rate != streaminfo_.data.stream_info.sample_rate) { + printf("FAILED, returned %u, expected %u\n", sample_rate, streaminfo_.data.stream_info.sample_rate); + return false; + } + } + printf("OK\n"); + + printf("testing get_blocksize()... "); + { + unsigned blocksize = decoder->get_blocksize(); + /* value could be anything since we're at the last block, so accept any reasonable answer */ + printf("returned %u... %s\n", blocksize, blocksize>0? "OK" : "FAILED"); + if(blocksize == 0) + return false; + } + + printf("testing get_channel_assignment()... "); + { + ::FLAC__ChannelAssignment ca = decoder->get_channel_assignment(); + printf("returned %u (%s)... OK\n", (unsigned)ca, ::FLAC__ChannelAssignmentString[ca]); + } + + if(layer < LAYER_FILE) { + printf("testing reset()... "); + if(!decoder->reset()) + return die_s_("returned false", decoder); + printf("OK\n"); + + if(layer == LAYER_STREAM) { + /* after a reset() we have to rewind the input ourselves */ + printf("rewinding input... "); + if(fseeko(dynamic_cast(decoder)->file_, 0, SEEK_SET) < 0) { + printf("FAILED, errno = %d\n", errno); + return false; + } + printf("OK\n"); + } + + dynamic_cast(decoder)->current_metadata_number_ = 0; + + printf("testing process_until_end_of_stream()... "); + if(!decoder->process_until_end_of_stream()) + return die_s_("returned false", decoder); + printf("OK\n"); + } + + printf("testing finish()... "); + if(!decoder->finish()) { + FLAC::Decoder::Stream::State state = decoder->get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + /* + * respond all + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * respond all, ignore VORBIS_COMMENT + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore(VORBIS_COMMENT)... "); + if(!decoder->set_metadata_ignore(FLAC__METADATA_TYPE_VORBIS_COMMENT)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * respond all, ignore APPLICATION + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore(APPLICATION)... "); + if(!decoder->set_metadata_ignore(FLAC__METADATA_TYPE_APPLICATION)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * respond all, ignore APPLICATION id of app#1 + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore_application(of app block #1)... "); + if(!decoder->set_metadata_ignore_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * respond all, ignore APPLICATION id of app#1 & app#2 + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore_application(of app block #1)... "); + if(!decoder->set_metadata_ignore_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore_application(of app block #2)... "); + if(!decoder->set_metadata_ignore_application(application2_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all, respond VORBIS_COMMENT + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond(VORBIS_COMMENT)... "); + if(!decoder->set_metadata_respond(FLAC__METADATA_TYPE_VORBIS_COMMENT)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all, respond APPLICATION + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond(APPLICATION)... "); + if(!decoder->set_metadata_respond(FLAC__METADATA_TYPE_APPLICATION)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all, respond APPLICATION id of app#1 + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond_application(of app block #1)... "); + if(!decoder->set_metadata_respond_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all, respond APPLICATION id of app#1 & app#2 + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond_application(of app block #1)... "); + if(!decoder->set_metadata_respond_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond_application(of app block #2)... "); + if(!decoder->set_metadata_respond_application(application2_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * respond all, ignore APPLICATION, respond APPLICATION id of app#1 + */ + + printf("testing set_metadata_respond_all()... "); + if(!decoder->set_metadata_respond_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore(APPLICATION)... "); + if(!decoder->set_metadata_ignore(FLAC__METADATA_TYPE_APPLICATION)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond_application(of app block #1)... "); + if(!decoder->set_metadata_respond_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + /* + * ignore all, respond APPLICATION, ignore APPLICATION id of app#1 + */ + + printf("testing set_metadata_ignore_all()... "); + if(!decoder->set_metadata_ignore_all()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_respond(APPLICATION)... "); + if(!decoder->set_metadata_respond(FLAC__METADATA_TYPE_APPLICATION)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing set_metadata_ignore_application(of app block #1)... "); + if(!decoder->set_metadata_ignore_application(application1_.data.application.id)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!(layer < LAYER_FILE? dynamic_cast(decoder)->test_respond(is_ogg) : dynamic_cast(decoder)->test_respond(is_ogg))) + return false; + + if(layer < LAYER_FILE) /* for LAYER_FILE, FLAC__stream_decoder_finish() closes the file */ + ::fclose(dynamic_cast(decoder)->file_); + + printf("freeing decoder instance... "); + delete decoder; + printf("OK\n"); + + printf("\nPASSED!\n"); + + return true; +} + +bool test_decoders() +{ + FLAC__bool is_ogg = false; + + while(1) { + init_metadata_blocks_(); + + if(!generate_file_(is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_STREAM, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_SEEKABLE_STREAM, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_FILE, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_FILENAME, is_ogg)) + return false; + + (void) grabbag__file_remove_file(flacfilename(is_ogg)); + + free_metadata_blocks_(); + + if(!FLAC_API_SUPPORTS_OGG_FLAC || is_ogg) + break; + is_ogg = true; + } + + return true; +} diff --git a/flac/src/test_libFLAC++/decoders.h b/flac/src/test_libFLAC++/decoders.h new file mode 100644 index 0000000..639417b --- /dev/null +++ b/flac/src/test_libFLAC++/decoders.h @@ -0,0 +1,24 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLACPP_DECODERS_H +#define FLAC__TEST_LIBFLACPP_DECODERS_H + +bool test_decoders(); + +#endif diff --git a/flac/src/test_libFLAC++/encoders.cpp b/flac/src/test_libFLAC++/encoders.cpp new file mode 100644 index 0000000..b719d33 --- /dev/null +++ b/flac/src/test_libFLAC++/encoders.cpp @@ -0,0 +1,553 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "encoders.h" +#include "FLAC/assert.h" +#include "FLAC++/encoder.h" +#include "share/grabbag.h" +extern "C" { +#include "test_libs_common/file_utils_flac.h" +#include "test_libs_common/metadata_utils.h" +} +#include +#include +#include +#include + +typedef enum { + LAYER_STREAM = 0, /* FLAC__stream_encoder_init_stream() without seeking */ + LAYER_SEEKABLE_STREAM, /* FLAC__stream_encoder_init_stream() with seeking */ + LAYER_FILE, /* FLAC__stream_encoder_init_FILE() */ + LAYER_FILENAME /* FLAC__stream_encoder_init_file() */ +} Layer; + +static const char * const LayerString[] = { + "Stream", + "Seekable Stream", + "FILE*", + "Filename" +}; + +static ::FLAC__StreamMetadata streaminfo_, padding_, seektable_, application1_, application2_, vorbiscomment_, cuesheet_, picture_, unknown_; +static ::FLAC__StreamMetadata *metadata_sequence_[] = { &vorbiscomment_, &padding_, &seektable_, &application1_, &application2_, &cuesheet_, &picture_, &unknown_ }; +static const unsigned num_metadata_ = sizeof(metadata_sequence_) / sizeof(metadata_sequence_[0]); + +static const char *flacfilename(bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static bool die_s_(const char *msg, const FLAC::Encoder::Stream *encoder) +{ + FLAC::Encoder::Stream::State state = encoder->get_state(); + + if(msg) + printf("FAILED, %s", msg); + else + printf("FAILED"); + + printf(", state = %u (%s)\n", (unsigned)((::FLAC__StreamEncoderState)state), state.as_cstring()); + if(state == ::FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) { + FLAC::Decoder::Stream::State dstate = encoder->get_verify_decoder_state(); + printf(" verify decoder state = %u (%s)\n", (unsigned)((::FLAC__StreamDecoderState)dstate), dstate.as_cstring()); + } + + return false; +} + +static void init_metadata_blocks_() +{ + mutils__init_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static void free_metadata_blocks_() +{ + mutils__free_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +class StreamEncoder : public FLAC::Encoder::Stream { +public: + Layer layer_; + FILE *file_; + + StreamEncoder(Layer layer): FLAC::Encoder::Stream(), layer_(layer), file_(0) { } + ~StreamEncoder() { } + + // from FLAC::Encoder::Stream + ::FLAC__StreamEncoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes); + ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame); + ::FLAC__StreamEncoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset); + ::FLAC__StreamEncoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset); + void metadata_callback(const ::FLAC__StreamMetadata *metadata); +}; + +::FLAC__StreamEncoderReadStatus StreamEncoder::read_callback(FLAC__byte buffer[], size_t *bytes) +{ + if(*bytes > 0) { + *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file_); + if(ferror(file_)) + return ::FLAC__STREAM_ENCODER_READ_STATUS_ABORT; + else if(*bytes == 0) + return ::FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM; + else + return ::FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE; + } + else + return ::FLAC__STREAM_ENCODER_READ_STATUS_ABORT; +} + +::FLAC__StreamEncoderWriteStatus StreamEncoder::write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame) +{ + (void)samples, (void)current_frame; + + if(fwrite(buffer, 1, bytes, file_) != bytes) + return ::FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + else + return ::FLAC__STREAM_ENCODER_WRITE_STATUS_OK; +} + +::FLAC__StreamEncoderSeekStatus StreamEncoder::seek_callback(FLAC__uint64 absolute_byte_offset) +{ + if(layer_==LAYER_STREAM) + return ::FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED; + else if(fseek(file_, (long)absolute_byte_offset, SEEK_SET) < 0) + return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; + else + return FLAC__STREAM_ENCODER_SEEK_STATUS_OK; +} + +::FLAC__StreamEncoderTellStatus StreamEncoder::tell_callback(FLAC__uint64 *absolute_byte_offset) +{ + long pos; + if(layer_==LAYER_STREAM) + return ::FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED; + else if((pos = ftell(file_)) < 0) + return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR; + else { + *absolute_byte_offset = (FLAC__uint64)pos; + return FLAC__STREAM_ENCODER_TELL_STATUS_OK; + } +} + +void StreamEncoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) +{ + (void)metadata; +} + +class FileEncoder : public FLAC::Encoder::File { +public: + Layer layer_; + + FileEncoder(Layer layer): FLAC::Encoder::File(), layer_(layer) { } + ~FileEncoder() { } + + // from FLAC::Encoder::File + void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate); +}; + +void FileEncoder::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate) +{ + (void)bytes_written, (void)samples_written, (void)frames_written, (void)total_frames_estimate; +} + +static FLAC::Encoder::Stream *new_by_layer(Layer layer) +{ + if(layer < LAYER_FILE) + return new StreamEncoder(layer); + else + return new FileEncoder(layer); +} + +static bool test_stream_encoder(Layer layer, bool is_ogg) +{ + FLAC::Encoder::Stream *encoder; + ::FLAC__StreamEncoderInitStatus init_status; + FILE *file = 0; + FLAC__int32 samples[1024]; + FLAC__int32 *samples_array[1] = { samples }; + unsigned i; + + printf("\n+++ libFLAC++ unit test: FLAC::Encoder::%s (layer: %s, format: %s)\n\n", layeris_valid()) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + if(is_ogg) { + printf("testing set_ogg_serial_number()... "); + if(!encoder->set_ogg_serial_number(file_utils__ogg_serial_number)) + return die_s_("returned false", encoder); + printf("OK\n"); + } + + printf("testing set_verify()... "); + if(!encoder->set_verify(true)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_streamable_subset()... "); + if(!encoder->set_streamable_subset(true)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_channels()... "); + if(!encoder->set_channels(streaminfo_.data.stream_info.channels)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_bits_per_sample()... "); + if(!encoder->set_bits_per_sample(streaminfo_.data.stream_info.bits_per_sample)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_sample_rate()... "); + if(!encoder->set_sample_rate(streaminfo_.data.stream_info.sample_rate)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_compression_level()... "); + if(!encoder->set_compression_level((unsigned)(-1))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_blocksize()... "); + if(!encoder->set_blocksize(streaminfo_.data.stream_info.min_blocksize)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_do_mid_side_stereo()... "); + if(!encoder->set_do_mid_side_stereo(false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_loose_mid_side_stereo()... "); + if(!encoder->set_loose_mid_side_stereo(false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_max_lpc_order()... "); + if(!encoder->set_max_lpc_order(0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_qlp_coeff_precision()... "); + if(!encoder->set_qlp_coeff_precision(0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_do_qlp_coeff_prec_search()... "); + if(!encoder->set_do_qlp_coeff_prec_search(false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_do_escape_coding()... "); + if(!encoder->set_do_escape_coding(false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_do_exhaustive_model_search()... "); + if(!encoder->set_do_exhaustive_model_search(false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_min_residual_partition_order()... "); + if(!encoder->set_min_residual_partition_order(0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_max_residual_partition_order()... "); + if(!encoder->set_max_residual_partition_order(0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_rice_parameter_search_dist()... "); + if(!encoder->set_rice_parameter_search_dist(0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_total_samples_estimate()... "); + if(!encoder->set_total_samples_estimate(streaminfo_.data.stream_info.total_samples)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing set_metadata()... "); + if(!encoder->set_metadata(metadata_sequence_, num_metadata_)) + return die_s_("returned false", encoder); + printf("OK\n"); + + if(layer < LAYER_FILENAME) { + printf("opening file for FLAC output... "); + file = ::fopen(flacfilename(is_ogg), "w+b"); + if(0 == file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + if(layer < LAYER_FILE) + dynamic_cast(encoder)->file_ = file; + } + + switch(layer) { + case LAYER_STREAM: + case LAYER_SEEKABLE_STREAM: + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? encoder->init_ogg() : encoder->init(); + break; + case LAYER_FILE: + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? + dynamic_cast(encoder)->init_ogg(file) : + dynamic_cast(encoder)->init(file); + break; + case LAYER_FILENAME: + printf("testing init%s()... ", is_ogg? "_ogg":""); + init_status = is_ogg? + dynamic_cast(encoder)->init_ogg(flacfilename(is_ogg)) : + dynamic_cast(encoder)->init(flacfilename(is_ogg)); + break; + default: + die_("internal error 001"); + return false; + } + if(init_status != ::FLAC__STREAM_ENCODER_INIT_STATUS_OK) + return die_s_(0, encoder); + printf("OK\n"); + + printf("testing get_state()... "); + FLAC::Encoder::Stream::State state = encoder->get_state(); + printf("returned state = %u (%s)... OK\n", (unsigned)((::FLAC__StreamEncoderState)state), state.as_cstring()); + + printf("testing get_verify_decoder_state()... "); + FLAC::Decoder::Stream::State dstate = encoder->get_verify_decoder_state(); + printf("returned state = %u (%s)... OK\n", (unsigned)((::FLAC__StreamDecoderState)dstate), dstate.as_cstring()); + + { + FLAC__uint64 absolute_sample; + unsigned frame_number; + unsigned channel; + unsigned sample; + FLAC__int32 expected; + FLAC__int32 got; + + printf("testing get_verify_decoder_error_stats()... "); + encoder->get_verify_decoder_error_stats(&absolute_sample, &frame_number, &channel, &sample, &expected, &got); + printf("OK\n"); + } + + printf("testing get_verify()... "); + if(encoder->get_verify() != true) { + printf("FAILED, expected true, got false\n"); + return false; + } + printf("OK\n"); + + printf("testing get_streamable_subset()... "); + if(encoder->get_streamable_subset() != true) { + printf("FAILED, expected true, got false\n"); + return false; + } + printf("OK\n"); + + printf("testing get_do_mid_side_stereo()... "); + if(encoder->get_do_mid_side_stereo() != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing get_loose_mid_side_stereo()... "); + if(encoder->get_loose_mid_side_stereo() != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing get_channels()... "); + if(encoder->get_channels() != streaminfo_.data.stream_info.channels) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.channels, encoder->get_channels()); + return false; + } + printf("OK\n"); + + printf("testing get_bits_per_sample()... "); + if(encoder->get_bits_per_sample() != streaminfo_.data.stream_info.bits_per_sample) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.bits_per_sample, encoder->get_bits_per_sample()); + return false; + } + printf("OK\n"); + + printf("testing get_sample_rate()... "); + if(encoder->get_sample_rate() != streaminfo_.data.stream_info.sample_rate) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.sample_rate, encoder->get_sample_rate()); + return false; + } + printf("OK\n"); + + printf("testing get_blocksize()... "); + if(encoder->get_blocksize() != streaminfo_.data.stream_info.min_blocksize) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.min_blocksize, encoder->get_blocksize()); + return false; + } + printf("OK\n"); + + printf("testing get_max_lpc_order()... "); + if(encoder->get_max_lpc_order() != 0) { + printf("FAILED, expected %u, got %u\n", 0, encoder->get_max_lpc_order()); + return false; + } + printf("OK\n"); + + printf("testing get_qlp_coeff_precision()... "); + (void)encoder->get_qlp_coeff_precision(); + /* we asked the encoder to auto select this so we accept anything */ + printf("OK\n"); + + printf("testing get_do_qlp_coeff_prec_search()... "); + if(encoder->get_do_qlp_coeff_prec_search() != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing get_do_escape_coding()... "); + if(encoder->get_do_escape_coding() != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing get_do_exhaustive_model_search()... "); + if(encoder->get_do_exhaustive_model_search() != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing get_min_residual_partition_order()... "); + if(encoder->get_min_residual_partition_order() != 0) { + printf("FAILED, expected %u, got %u\n", 0, encoder->get_min_residual_partition_order()); + return false; + } + printf("OK\n"); + + printf("testing get_max_residual_partition_order()... "); + if(encoder->get_max_residual_partition_order() != 0) { + printf("FAILED, expected %u, got %u\n", 0, encoder->get_max_residual_partition_order()); + return false; + } + printf("OK\n"); + + printf("testing get_rice_parameter_search_dist()... "); + if(encoder->get_rice_parameter_search_dist() != 0) { + printf("FAILED, expected %u, got %u\n", 0, encoder->get_rice_parameter_search_dist()); + return false; + } + printf("OK\n"); + + printf("testing get_total_samples_estimate()... "); + if(encoder->get_total_samples_estimate() != streaminfo_.data.stream_info.total_samples) { +#ifdef _MSC_VER + printf("FAILED, expected %I64u, got %I64u\n", streaminfo_.data.stream_info.total_samples, encoder->get_total_samples_estimate()); +#else + printf("FAILED, expected %llu, got %llu\n", (unsigned long long)streaminfo_.data.stream_info.total_samples, (unsigned long long)encoder->get_total_samples_estimate()); +#endif + return false; + } + printf("OK\n"); + + /* init the dummy sample buffer */ + for(i = 0; i < sizeof(samples) / sizeof(FLAC__int32); i++) + samples[i] = i & 7; + + printf("testing process()... "); + if(!encoder->process(samples_array, sizeof(samples) / sizeof(FLAC__int32))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing process_interleaved()... "); + if(!encoder->process_interleaved(samples, sizeof(samples) / sizeof(FLAC__int32))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing finish()... "); + if(!encoder->finish()) { + FLAC::Encoder::Stream::State state = encoder->get_state(); + printf("FAILED, returned false, state = %u (%s)\n", (unsigned)((::FLAC__StreamEncoderState)state), state.as_cstring()); + return false; + } + printf("OK\n"); + + if(layer < LAYER_FILE) + ::fclose(dynamic_cast(encoder)->file_); + + printf("freeing encoder instance... "); + delete encoder; + printf("OK\n"); + + printf("\nPASSED!\n"); + + return true; +} + +bool test_encoders() +{ + FLAC__bool is_ogg = false; + + while(1) { + init_metadata_blocks_(); + + if(!test_stream_encoder(LAYER_STREAM, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_SEEKABLE_STREAM, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_FILE, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_FILENAME, is_ogg)) + return false; + + (void) grabbag__file_remove_file(flacfilename(is_ogg)); + + free_metadata_blocks_(); + + if(!FLAC_API_SUPPORTS_OGG_FLAC || is_ogg) + break; + is_ogg = true; + } + + return true; +} diff --git a/flac/src/test_libFLAC++/encoders.h b/flac/src/test_libFLAC++/encoders.h new file mode 100644 index 0000000..2c5d9f8 --- /dev/null +++ b/flac/src/test_libFLAC++/encoders.h @@ -0,0 +1,24 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLACPP_ENCODERS_H +#define FLAC__TEST_LIBFLACPP_ENCODERS_H + +bool test_encoders(); + +#endif diff --git a/flac/src/test_libFLAC++/main.cpp b/flac/src/test_libFLAC++/main.cpp new file mode 100644 index 0000000..8b9cd98 --- /dev/null +++ b/flac/src/test_libFLAC++/main.cpp @@ -0,0 +1,37 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "decoders.h" +#include "encoders.h" +#include "metadata.h" + +int main(int argc, char *argv[]) +{ + (void)argc, (void)argv; + + if(!test_encoders()) + return 1; + + if(!test_decoders()) + return 1; + + if(!test_metadata()) + return 1; + + return 0; +} diff --git a/flac/src/test_libFLAC++/metadata.cpp b/flac/src/test_libFLAC++/metadata.cpp new file mode 100644 index 0000000..13dc583 --- /dev/null +++ b/flac/src/test_libFLAC++/metadata.cpp @@ -0,0 +1,36 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "metadata.h" +#include + +extern bool test_metadata_object(); +extern bool test_metadata_file_manipulation(); + +bool test_metadata() +{ + if(!test_metadata_object()) + return false; + + if(!test_metadata_file_manipulation()) + return false; + + printf("\nPASSED!\n"); + + return true; +} diff --git a/flac/src/test_libFLAC++/metadata.h b/flac/src/test_libFLAC++/metadata.h new file mode 100644 index 0000000..2d230d3 --- /dev/null +++ b/flac/src/test_libFLAC++/metadata.h @@ -0,0 +1,24 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLACPP_METADATA_H +#define FLAC__TEST_LIBFLACPP_METADATA_H + +bool test_metadata(); + +#endif diff --git a/flac/src/test_libFLAC++/metadata_manip.cpp b/flac/src/test_libFLAC++/metadata_manip.cpp new file mode 100644 index 0000000..73965a1 --- /dev/null +++ b/flac/src/test_libFLAC++/metadata_manip.cpp @@ -0,0 +1,2210 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for malloc() */ +#include /* for memcpy()/memset() */ +#if defined _MSC_VER || defined __MINGW32__ +#include /* for utime() */ +#include /* for chmod() */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#else +#include /* some flavors of BSD (like OS X) require this to get time_t */ +#include /* for utime() */ +#include /* for chown(), unlink() */ +#endif +#include /* for stat(), maybe chmod() */ +#include "FLAC/assert.h" +#include "FLAC++/decoder.h" +#include "FLAC++/metadata.h" +#include "share/grabbag.h" +extern "C" { +#include "test_libs_common/file_utils_flac.h" +} + +/****************************************************************************** + The general strategy of these tests (for interface levels 1 and 2) is + to create a dummy FLAC file with a known set of initial metadata + blocks, then keep a mirror locally of what we expect the metadata to be + after each operation. Then testing becomes a simple matter of running + a FLAC::Decoder::File over the dummy file after each operation, comparing + the decoded metadata to what's in our local copy. If there are any + differences in the metadata, or the actual audio data is corrupted, we + will catch it while decoding. +******************************************************************************/ + +class OurFileDecoder: public FLAC::Decoder::File { +public: + inline OurFileDecoder(bool ignore_metadata): ignore_metadata_(ignore_metadata), error_occurred_(false) { } + + bool ignore_metadata_; + bool error_occurred_; +protected: + ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]); + void metadata_callback(const ::FLAC__StreamMetadata *metadata); + void error_callback(::FLAC__StreamDecoderErrorStatus status); +}; + +struct OurMetadata { + FLAC::Metadata::Prototype *blocks[64]; + unsigned num_blocks; +}; + +/* our copy of the metadata in flacfilename() */ +static OurMetadata our_metadata_; + +/* the current block number that corresponds to the position of the iterator we are testing */ +static unsigned mc_our_block_number_ = 0; + +static const char *flacfilename(bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static bool die_c_(const char *msg, FLAC::Metadata::Chain::Status status) +{ + printf("ERROR: %s\n", msg); + printf(" status=%u (%s)\n", (unsigned)((::FLAC__Metadata_ChainStatus)status), status.as_cstring()); + return false; +} + +static bool die_ss_(const char *msg, FLAC::Metadata::SimpleIterator &iterator) +{ + const FLAC::Metadata::SimpleIterator::Status status = iterator.status(); + printf("ERROR: %s\n", msg); + printf(" status=%u (%s)\n", (unsigned)((::FLAC__Metadata_SimpleIteratorStatus)status), status.as_cstring()); + return false; +} + +static void *malloc_or_die_(size_t size) +{ + void *x = malloc(size); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory allocating %u bytes\n", (unsigned)size); + exit(1); + } + return x; +} + +static char *strdup_or_die_(const char *s) +{ + char *x = strdup(s); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory copying string \"%s\"\n", s); + exit(1); + } + return x; +} + +/* functions for working with our metadata copy */ + +static bool replace_in_our_metadata_(FLAC::Metadata::Prototype *block, unsigned position, bool copy) +{ + unsigned i; + FLAC::Metadata::Prototype *obj = block; + FLAC__ASSERT(position < our_metadata_.num_blocks); + if(copy) { + if(0 == (obj = FLAC::Metadata::clone(block))) + return die_("during FLAC::Metadata::clone()"); + } + delete our_metadata_.blocks[position]; + our_metadata_.blocks[position] = obj; + + /* set the is_last flags */ + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->set_is_last(false); + our_metadata_.blocks[i]->set_is_last(true); + + return true; +} + +static bool insert_to_our_metadata_(FLAC::Metadata::Prototype *block, unsigned position, bool copy) +{ + unsigned i; + FLAC::Metadata::Prototype *obj = block; + if(copy) { + if(0 == (obj = FLAC::Metadata::clone(block))) + return die_("during FLAC::Metadata::clone()"); + } + if(position > our_metadata_.num_blocks) { + position = our_metadata_.num_blocks; + } + else { + for(i = our_metadata_.num_blocks; i > position; i--) + our_metadata_.blocks[i] = our_metadata_.blocks[i-1]; + } + our_metadata_.blocks[position] = obj; + our_metadata_.num_blocks++; + + /* set the is_last flags */ + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->set_is_last(false); + our_metadata_.blocks[i]->set_is_last(true); + + return true; +} + +static void delete_from_our_metadata_(unsigned position) +{ + unsigned i; + FLAC__ASSERT(position < our_metadata_.num_blocks); + delete our_metadata_.blocks[position]; + for(i = position; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i] = our_metadata_.blocks[i+1]; + our_metadata_.num_blocks--; + + /* set the is_last flags */ + if(our_metadata_.num_blocks > 0) { + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->set_is_last(false); + our_metadata_.blocks[i]->set_is_last(true); + } +} + +void add_to_padding_length_(unsigned index, int delta) +{ + FLAC::Metadata::Padding *padding = dynamic_cast(our_metadata_.blocks[index]); + FLAC__ASSERT(0 != padding); + padding->set_length((unsigned)((int)padding->get_length() + delta)); +} + +/* + * This wad of functions supports filename- and callback-based chain reading/writing. + * Everything up to set_file_stats_() is copied from libFLAC/metadata_iterators.c + */ +bool open_tempfile_(const char *filename, FILE **tempfile, char **tempfilename) +{ + static const char *tempfile_suffix = ".metadata_edit"; + + if(0 == (*tempfilename = (char*)malloc(strlen(filename) + strlen(tempfile_suffix) + 1))) + return false; + strcpy(*tempfilename, filename); + strcat(*tempfilename, tempfile_suffix); + + if(0 == (*tempfile = fopen(*tempfilename, "wb"))) + return false; + + return true; +} + +void cleanup_tempfile_(FILE **tempfile, char **tempfilename) +{ + if(0 != *tempfile) { + (void)fclose(*tempfile); + *tempfile = 0; + } + + if(0 != *tempfilename) { + (void)unlink(*tempfilename); + free(*tempfilename); + *tempfilename = 0; + } +} + +bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != tempfile); + FLAC__ASSERT(0 != tempfilename); + FLAC__ASSERT(0 != *tempfilename); + + if(0 != *tempfile) { + (void)fclose(*tempfile); + *tempfile = 0; + } + +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ + /* on some flavors of windows, rename() will fail if the destination already exists */ + if(unlink(filename) < 0) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } +#endif + + if(0 != rename(*tempfilename, filename)) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } + + cleanup_tempfile_(tempfile, tempfilename); + + return true; +} + +bool get_file_stats_(const char *filename, struct stat *stats) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + return (0 == stat(filename, stats)); +} + +void set_file_stats_(const char *filename, struct stat *stats) +{ + struct utimbuf srctime; + + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + + srctime.actime = stats->st_atime; + srctime.modtime = stats->st_mtime; + (void)chmod(filename, stats->st_mode); + (void)utime(filename, &srctime); +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__ + (void)chown(filename, stats->st_uid, (gid_t)(-1)); + (void)chown(filename, (uid_t)(-1), stats->st_gid); +#endif +} + +#ifdef FLAC__VALGRIND_TESTING +static size_t chain_write_cb_(const void *ptr, size_t size, size_t nmemb, ::FLAC__IOHandle handle) +{ + FILE *stream = (FILE*)handle; + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#endif + +static int chain_seek_cb_(::FLAC__IOHandle handle, FLAC__int64 offset, int whence) +{ + off_t o = (off_t)offset; + FLAC__ASSERT(offset == o); + return fseeko((FILE*)handle, o, whence); +} + +static FLAC__int64 chain_tell_cb_(::FLAC__IOHandle handle) +{ + return ftello((FILE*)handle); +} + +static int chain_eof_cb_(::FLAC__IOHandle handle) +{ + return feof((FILE*)handle); +} + +static bool write_chain_(FLAC::Metadata::Chain &chain, bool use_padding, bool preserve_file_stats, bool filename_based, const char *filename) +{ + if(filename_based) + return chain.write(use_padding, preserve_file_stats); + else { + ::FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (::FLAC__IOCallback_Read)fread; +#ifdef FLAC__VALGRIND_TESTING + callbacks.write = chain_write_cb_; +#else + callbacks.write = (::FLAC__IOCallback_Write)fwrite; +#endif + callbacks.seek = chain_seek_cb_; + callbacks.eof = chain_eof_cb_; + + if(chain.check_if_tempfile_needed(use_padding)) { + struct stat stats; + FILE *file, *tempfile; + char *tempfilename; + if(preserve_file_stats) { + if(!get_file_stats_(filename, &stats)) + return false; + } + if(0 == (file = fopen(filename, "rb"))) + return false; /*@@@@ chain status still says OK though */ + if(!open_tempfile_(filename, &tempfile, &tempfilename)) { + fclose(file); + cleanup_tempfile_(&tempfile, &tempfilename); + return false; /*@@@@ chain status still says OK though */ + } + if(!chain.write(use_padding, (::FLAC__IOHandle)file, callbacks, (::FLAC__IOHandle)tempfile, callbacks)) { + fclose(file); + fclose(tempfile); + return false; + } + fclose(file); + fclose(tempfile); + file = tempfile = 0; + if(!transport_tempfile_(filename, &tempfile, &tempfilename)) + return false; + if(preserve_file_stats) + set_file_stats_(filename, &stats); + } + else { + FILE *file = fopen(filename, "r+b"); + if(0 == file) + return false; /*@@@@ chain status still says OK though */ + if(!chain.write(use_padding, (::FLAC__IOHandle)file, callbacks)) + return false; + fclose(file); + } + } + + return true; +} + +static bool read_chain_(FLAC::Metadata::Chain &chain, const char *filename, bool filename_based, bool is_ogg) +{ + if(filename_based) + return chain.read(filename, is_ogg); + else { + ::FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (::FLAC__IOCallback_Read)fread; + callbacks.seek = chain_seek_cb_; + callbacks.tell = chain_tell_cb_; + + { + bool ret; + FILE *file = fopen(filename, "rb"); + if(0 == file) + return false; /*@@@@ chain status still says OK though */ + ret = chain.read((::FLAC__IOHandle)file, callbacks, is_ogg); + fclose(file); + return ret; + } + } +} + +/* function for comparing our metadata to a FLAC::Metadata::Chain */ + +static bool compare_chain_(FLAC::Metadata::Chain &chain, unsigned current_position, FLAC::Metadata::Prototype *current_block) +{ + unsigned i; + FLAC::Metadata::Iterator iterator; + bool next_ok = true; + + printf("\tcomparing chain... "); + fflush(stdout); + + if(!iterator.is_valid()) + return die_("allocating memory for iterator"); + + iterator.init(chain); + + i = 0; + do { + FLAC::Metadata::Prototype *block; + + printf("%u... ", i); + fflush(stdout); + + if(0 == (block = iterator.get_block())) + return die_("getting block from iterator"); + + if(*block != *our_metadata_.blocks[i]) + return die_("metadata block mismatch"); + + delete block; + i++; + next_ok = iterator.next(); + } while(i < our_metadata_.num_blocks && next_ok); + + if(next_ok) + return die_("chain has more blocks than expected"); + + if(i < our_metadata_.num_blocks) + return die_("short block count in chain"); + + if(0 != current_block) { + printf("CURRENT_POSITION... "); + fflush(stdout); + + if(*current_block != *our_metadata_.blocks[current_position]) + return die_("metadata block mismatch"); + } + + printf("PASSED\n"); + + return true; +} + +::FLAC__StreamDecoderWriteStatus OurFileDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) +{ + (void)buffer; + + if( + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER && frame->header.number.frame_number == 0) || + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER && frame->header.number.sample_number == 0) + ) { + printf("content... "); + fflush(stdout); + } + + return ::FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void OurFileDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) +{ + /* don't bother checking if we've already hit an error */ + if(error_occurred_) + return; + + printf("%d... ", mc_our_block_number_); + fflush(stdout); + + if(!ignore_metadata_) { + if(mc_our_block_number_ >= our_metadata_.num_blocks) { + (void)die_("got more metadata blocks than expected"); + error_occurred_ = true; + } + else { + if(*our_metadata_.blocks[mc_our_block_number_] != metadata) { + (void)die_("metadata block mismatch"); + error_occurred_ = true; + } + } + } + + mc_our_block_number_++; +} + +void OurFileDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status) +{ + error_occurred_ = true; + printf("ERROR: got error callback, status = %s (%u)\n", FLAC__StreamDecoderErrorStatusString[status], (unsigned)status); +} + +static bool generate_file_(bool include_extras, bool is_ogg) +{ + ::FLAC__StreamMetadata streaminfo, vorbiscomment, *cuesheet, picture, padding; + ::FLAC__StreamMetadata *metadata[4]; + unsigned i = 0, n = 0; + + printf("generating %sFLAC file for test\n", is_ogg? "Ogg " : ""); + + while(our_metadata_.num_blocks > 0) + delete_from_our_metadata_(0); + + streaminfo.is_last = false; + streaminfo.type = ::FLAC__METADATA_TYPE_STREAMINFO; + streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + streaminfo.data.stream_info.min_blocksize = 576; + streaminfo.data.stream_info.max_blocksize = 576; + streaminfo.data.stream_info.min_framesize = 0; + streaminfo.data.stream_info.max_framesize = 0; + streaminfo.data.stream_info.sample_rate = 44100; + streaminfo.data.stream_info.channels = 1; + streaminfo.data.stream_info.bits_per_sample = 8; + streaminfo.data.stream_info.total_samples = 0; + memset(streaminfo.data.stream_info.md5sum, 0, 16); + + { + const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING); + vorbiscomment.is_last = false; + vorbiscomment.type = ::FLAC__METADATA_TYPE_VORBIS_COMMENT; + vorbiscomment.length = (4 + vendor_string_length) + 4; + vorbiscomment.data.vorbis_comment.vendor_string.length = vendor_string_length; + vorbiscomment.data.vorbis_comment.vendor_string.entry = (FLAC__byte*)malloc_or_die_(vendor_string_length+1); + memcpy(vorbiscomment.data.vorbis_comment.vendor_string.entry, FLAC__VENDOR_STRING, vendor_string_length+1); + vorbiscomment.data.vorbis_comment.num_comments = 0; + vorbiscomment.data.vorbis_comment.comments = 0; + } + + { + if (0 == (cuesheet = ::FLAC__metadata_object_new(::FLAC__METADATA_TYPE_CUESHEET))) + return die_("priming our metadata"); + cuesheet->is_last = false; + strcpy(cuesheet->data.cue_sheet.media_catalog_number, "bogo-MCN"); + cuesheet->data.cue_sheet.lead_in = 123; + cuesheet->data.cue_sheet.is_cd = false; + if (!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, 0)) + return die_("priming our metadata"); + cuesheet->data.cue_sheet.tracks[0].number = 1; + if (!FLAC__metadata_object_cuesheet_track_insert_blank_index(cuesheet, 0, 0)) + return die_("priming our metadata"); + } + + { + picture.is_last = false; + picture.type = ::FLAC__METADATA_TYPE_PICTURE; + picture.length = + ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN /* will add the length for the data later */ + ) / 8 + ; + picture.data.picture.type = ::FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER; + picture.data.picture.mime_type = strdup_or_die_("image/jpeg"); + picture.length += strlen(picture.data.picture.mime_type); + picture.data.picture.description = (FLAC__byte*)strdup_or_die_("desc"); + picture.length += strlen((const char *)picture.data.picture.description); + picture.data.picture.width = 300; + picture.data.picture.height = 300; + picture.data.picture.depth = 24; + picture.data.picture.colors = 0; + picture.data.picture.data = (FLAC__byte*)strdup_or_die_("SOMEJPEGDATA"); + picture.data.picture.data_length = strlen((const char *)picture.data.picture.data); + picture.length += picture.data.picture.data_length; + } + + padding.is_last = true; + padding.type = ::FLAC__METADATA_TYPE_PADDING; + padding.length = 1234; + + metadata[n++] = &vorbiscomment; + if(include_extras) { + metadata[n++] = cuesheet; + metadata[n++] = &picture; + } + metadata[n++] = &padding; + + FLAC::Metadata::StreamInfo s(&streaminfo); + FLAC::Metadata::VorbisComment v(&vorbiscomment); + FLAC::Metadata::CueSheet c(cuesheet, /*copy=*/false); + FLAC::Metadata::Picture pi(&picture); + FLAC::Metadata::Padding p(&padding); + if( + !insert_to_our_metadata_(&s, i++, /*copy=*/true) || + !insert_to_our_metadata_(&v, i++, /*copy=*/true) || + (include_extras && !insert_to_our_metadata_(&c, i++, /*copy=*/true)) || + (include_extras && !insert_to_our_metadata_(&pi, i++, /*copy=*/true)) || + !insert_to_our_metadata_(&p, i++, /*copy=*/true) + ) + return die_("priming our metadata"); + + if(!file_utils__generate_flacfile(is_ogg, flacfilename(is_ogg), 0, 512 * 1024, &streaminfo, metadata, n)) + return die_("creating the encoded file"); + + free(vorbiscomment.data.vorbis_comment.vendor_string.entry); + free(picture.data.picture.mime_type); + free(picture.data.picture.description); + free(picture.data.picture.data); + + return true; +} + +static bool test_file_(bool is_ogg, bool ignore_metadata) +{ + const char *filename = flacfilename(is_ogg); + OurFileDecoder decoder(ignore_metadata); + + mc_our_block_number_ = 0; + decoder.error_occurred_ = false; + + printf("\ttesting '%s'... ", filename); + fflush(stdout); + + if(!decoder.is_valid()) + return die_("couldn't allocate decoder instance"); + + decoder.set_md5_checking(true); + decoder.set_metadata_respond_all(); + if((is_ogg? decoder.init_ogg(filename) : decoder.init(filename)) != ::FLAC__STREAM_DECODER_INIT_STATUS_OK) { + (void)decoder.finish(); + return die_("initializing decoder\n"); + } + if(!decoder.process_until_end_of_stream()) { + (void)decoder.finish(); + return die_("decoding file\n"); + } + + (void)decoder.finish(); + + if(decoder.error_occurred_) + return false; + + if(mc_our_block_number_ != our_metadata_.num_blocks) + return die_("short metadata block count"); + + printf("PASSED\n"); + return true; +} + +static bool change_stats_(const char *filename, bool read_only) +{ + if(!grabbag__file_change_stats(filename, read_only)) + return die_("during grabbag__file_change_stats()"); + + return true; +} + +static bool remove_file_(const char *filename) +{ + while(our_metadata_.num_blocks > 0) + delete_from_our_metadata_(0); + + if(!grabbag__file_remove_file(filename)) + return die_("removing file"); + + return true; +} + +static bool test_level_0_() +{ + FLAC::Metadata::StreamInfo streaminfo; + + printf("\n\n++++++ testing level 0 interface\n"); + + if(!generate_file_(/*include_extras=*/true, /*is_ogg=*/false)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/true)) + return false; + + printf("testing FLAC::Metadata::get_streaminfo()... "); + + if(!FLAC::Metadata::get_streaminfo(flacfilename(/*is_ogg=*/false), streaminfo)) + return die_("during FLAC::Metadata::get_streaminfo()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(streaminfo.get_channels() != 1) + return die_("mismatch in streaminfo.get_channels()"); + if(streaminfo.get_bits_per_sample() != 8) + return die_("mismatch in streaminfo.get_bits_per_sample()"); + if(streaminfo.get_sample_rate() != 44100) + return die_("mismatch in streaminfo.get_sample_rate()"); + if(streaminfo.get_min_blocksize() != 576) + return die_("mismatch in streaminfo.get_min_blocksize()"); + if(streaminfo.get_max_blocksize() != 576) + return die_("mismatch in streaminfo.get_max_blocksize()"); + + printf("OK\n"); + + { + printf("testing FLAC::Metadata::get_tags(VorbisComment *&)... "); + + FLAC::Metadata::VorbisComment *tags = 0; + + if(!FLAC::Metadata::get_tags(flacfilename(/*is_ogg=*/false), tags)) + return die_("during FLAC::Metadata::get_tags()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(tags->get_num_comments() != 0) + return die_("mismatch in tags->get_num_comments()"); + + printf("OK\n"); + + delete tags; + } + + { + printf("testing FLAC::Metadata::get_tags(VorbisComment &)... "); + + FLAC::Metadata::VorbisComment tags; + + if(!FLAC::Metadata::get_tags(flacfilename(/*is_ogg=*/false), tags)) + return die_("during FLAC::Metadata::get_tags()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(tags.get_num_comments() != 0) + return die_("mismatch in tags.get_num_comments()"); + + printf("OK\n"); + } + + { + printf("testing FLAC::Metadata::get_cuesheet(CueSheet *&)... "); + + FLAC::Metadata::CueSheet *cuesheet = 0; + + if(!FLAC::Metadata::get_cuesheet(flacfilename(/*is_ogg=*/false), cuesheet)) + return die_("during FLAC::Metadata::get_cuesheet()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(cuesheet->get_lead_in() != 123) + return die_("mismatch in cuesheet->get_lead_in()"); + + printf("OK\n"); + + delete cuesheet; + } + + { + printf("testing FLAC::Metadata::get_cuesheet(CueSheet &)... "); + + FLAC::Metadata::CueSheet cuesheet; + + if(!FLAC::Metadata::get_cuesheet(flacfilename(/*is_ogg=*/false), cuesheet)) + return die_("during FLAC::Metadata::get_cuesheet()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(cuesheet.get_lead_in() != 123) + return die_("mismatch in cuesheet.get_lead_in()"); + + printf("OK\n"); + } + + { + printf("testing FLAC::Metadata::get_picture(Picture *&)... "); + + FLAC::Metadata::Picture *picture = 0; + + if(!FLAC::Metadata::get_picture(flacfilename(/*is_ogg=*/false), picture, /*type=*/(::FLAC__StreamMetadata_Picture_Type)(-1), /*mime_type=*/0, /*description=*/0, /*max_width=*/(unsigned)(-1), /*max_height=*/(unsigned)(-1), /*max_depth=*/(unsigned)(-1), /*max_colors=*/(unsigned)(-1))) + return die_("during FLAC::Metadata::get_picture()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(picture->get_type () != ::FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER) + return die_("mismatch in picture->get_type ()"); + + printf("OK\n"); + + delete picture; + } + + { + printf("testing FLAC::Metadata::get_picture(Picture &)... "); + + FLAC::Metadata::Picture picture; + + if(!FLAC::Metadata::get_picture(flacfilename(/*is_ogg=*/false), picture, /*type=*/(::FLAC__StreamMetadata_Picture_Type)(-1), /*mime_type=*/0, /*description=*/0, /*max_width=*/(unsigned)(-1), /*max_height=*/(unsigned)(-1), /*max_depth=*/(unsigned)(-1), /*max_colors=*/(unsigned)(-1))) + return die_("during FLAC::Metadata::get_picture()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(picture.get_type () != ::FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER) + return die_("mismatch in picture->get_type ()"); + + printf("OK\n"); + } + + if(!remove_file_(flacfilename(/*is_ogg=*/false))) + return false; + + return true; +} + +static bool test_level_1_() +{ + FLAC::Metadata::Prototype *block; + FLAC::Metadata::StreamInfo *streaminfo; + FLAC::Metadata::Padding *padding; + FLAC::Metadata::Application *app; + FLAC__byte data[1000]; + unsigned our_current_position = 0; + + // initialize 'data' to avoid Valgrind errors + memset(data, 0, sizeof(data)); + + printf("\n\n++++++ testing level 1 interface\n"); + + /************************************************************/ + { + printf("simple iterator on read-only file\n"); + + if(!generate_file_(/*include_extras=*/false, /*is_ogg=*/false)) + return false; + + if(!change_stats_(flacfilename(/*is_ogg=*/false), /*read_only=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/true)) + return false; + + FLAC::Metadata::SimpleIterator iterator; + + if(!iterator.is_valid()) + return die_("iterator.is_valid() returned false"); + + if(!iterator.init(flacfilename(/*is_ogg=*/false), /*read_only=*/false, /*preserve_file_stats=*/false)) + return die_("iterator.init() returned false"); + + printf("is writable = %u\n", (unsigned)iterator.is_writable()); + if(iterator.is_writable()) + return die_("iterator claims file is writable when tester thinks it should not be; are you running as root?\n"); + + printf("iterate forwards\n"); + + if(iterator.get_block_type() != ::FLAC__METADATA_TYPE_STREAMINFO) + return die_("expected STREAMINFO type from iterator.get_block_type()"); + if(0 == (block = iterator.get_block())) + return die_("getting block 0"); + if(block->get_type() != ::FLAC__METADATA_TYPE_STREAMINFO) + return die_("expected STREAMINFO type"); + if(block->get_is_last()) + return die_("expected is_last to be false"); + if(block->get_length() != FLAC__STREAM_METADATA_STREAMINFO_LENGTH) + return die_("bad STREAMINFO length"); + /* check to see if some basic data matches (c.f. generate_file_()) */ + streaminfo = dynamic_cast(block); + FLAC__ASSERT(0 != streaminfo); + if(streaminfo->get_channels() != 1) + return die_("mismatch in channels"); + if(streaminfo->get_bits_per_sample() != 8) + return die_("mismatch in bits_per_sample"); + if(streaminfo->get_sample_rate() != 44100) + return die_("mismatch in sample_rate"); + if(streaminfo->get_min_blocksize() != 576) + return die_("mismatch in min_blocksize"); + if(streaminfo->get_max_blocksize() != 576) + return die_("mismatch in max_blocksize"); + // we will delete streaminfo a little later when we're really done with it... + + if(!iterator.next()) + return die_("forward iterator ended early"); + our_current_position++; + + if(!iterator.next()) + return die_("forward iterator ended early"); + our_current_position++; + + if(iterator.get_block_type() != ::FLAC__METADATA_TYPE_PADDING) + return die_("expected PADDING type from iterator.get_block_type()"); + if(0 == (block = iterator.get_block())) + return die_("getting block 1"); + if(block->get_type() != ::FLAC__METADATA_TYPE_PADDING) + return die_("expected PADDING type"); + if(!block->get_is_last()) + return die_("expected is_last to be true"); + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(block->get_length() != 1234) + return die_("bad PADDING length"); + delete block; + + if(iterator.next()) + return die_("forward iterator returned true but should have returned false"); + + printf("iterate backwards\n"); + if(!iterator.prev()) + return die_("reverse iterator ended early"); + if(!iterator.prev()) + return die_("reverse iterator ended early"); + if(iterator.prev()) + return die_("reverse iterator returned true but should have returned false"); + + printf("testing iterator.set_block() on read-only file...\n"); + + if(!iterator.set_block(streaminfo, false)) + printf("PASSED. iterator.set_block() returned false like it should\n"); + else + return die_("iterator.set_block() returned true but shouldn't have"); + delete streaminfo; + } + + /************************************************************/ + { + printf("simple iterator on writable file\n"); + + if(!change_stats_(flacfilename(/*is_ogg=*/false), /*read-only=*/false)) + return false; + + printf("creating APPLICATION block\n"); + + if(0 == (app = new FLAC::Metadata::Application())) + return die_("new FLAC::Metadata::Application()"); + app->set_id((const unsigned char *)"duh"); + + printf("creating PADDING block\n"); + + if(0 == (padding = new FLAC::Metadata::Padding())) + return die_("new FLAC::Metadata::Padding()"); + padding->set_length(20); + + FLAC::Metadata::SimpleIterator iterator; + + if(!iterator.is_valid()) + return die_("iterator.is_valid() returned false"); + + if(!iterator.init(flacfilename(/*is_ogg=*/false), /*read_only=*/false, /*preserve_file_stats=*/false)) + return die_("iterator.init() returned false"); + our_current_position = 0; + + printf("is writable = %u\n", (unsigned)iterator.is_writable()); + + printf("[S]VP\ttry to write over STREAMINFO block...\n"); + if(!iterator.set_block(app, false)) + printf("\titerator.set_block() returned false like it should\n"); + else + return die_("iterator.set_block() returned true but shouldn't have"); + + printf("[S]VP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tinsert PADDING after, don't expand into padding\n"); + padding->set_length(25); + if(!iterator.insert_block_after(padding, false)) + return die_ss_("iterator.insert_block_after(padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + printf("SVP[P]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[P]P\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PP\tinsert PADDING after, don't expand into padding\n"); + padding->set_length(30); + if(!iterator.insert_block_after(padding, false)) + return die_ss_("iterator.insert_block_after(padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[P]PP\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PPP\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VPPP\tdelete (STREAMINFO block), must fail\n"); + if(iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false) should have returned false", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("[S]VPPP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]PPP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]PP\tdelete (middle block), replace with padding\n"); + if(!iterator.delete_block(true)) + return die_ss_("iterator.delete_block(true)", iterator); + our_current_position--; + + printf("S[V]PPP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]PP\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]PP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]\tdelete (last block), replace with padding\n"); + if(!iterator.delete_block(true)) + return die_ss_("iterator.delete_block(false)", iterator); + our_current_position--; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[P]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]\tdelete (last block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[P]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]P\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VP\tset STREAMINFO (change sample rate)\n"); + FLAC__ASSERT(our_current_position == 0); + block = iterator.get_block(); + streaminfo = dynamic_cast(block); + FLAC__ASSERT(0 != streaminfo); + streaminfo->set_sample_rate(32000); + if(!replace_in_our_metadata_(block, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(block, false)) + return die_ss_("iterator.set_block(block, false)", iterator); + delete block; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("[S]VP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tinsert APPLICATION after, expand into padding of exceeding size\n"); + app->set_id((const unsigned char *)"euh"); /* twiddle the id so that our comparison doesn't miss transposition */ + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return false; + add_to_padding_length_(our_current_position+1, -((int)(FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) + (int)app->get_length())); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVA[P]\tset APPLICATION, expand into padding of exceeding size\n"); + app->set_id((const unsigned char *)"fuh"); /* twiddle the id */ + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + if(!insert_to_our_metadata_(app, our_current_position, /*copy=*/true)) + return false; + add_to_padding_length_(our_current_position+1, -((int)(FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) + (int)app->get_length())); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]P\tset APPLICATION (grow), don't expand into padding\n"); + app->set_id((const unsigned char *)"guh"); /* twiddle the id */ + if(!app->set_data(data, sizeof(data), true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app, false)) + return die_ss_("iterator.set_block(app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]P\tset APPLICATION (shrink), don't fill in with padding\n"); + app->set_id((const unsigned char *)"huh"); /* twiddle the id */ + if(!app->set_data(data, 12, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app, false)) + return die_ss_("iterator.set_block(app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]P\tset APPLICATION (grow), expand into padding of exceeding size\n"); + app->set_id((const unsigned char *)"iuh"); /* twiddle the id */ + if(!app->set_data(data, sizeof(data), true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + add_to_padding_length_(our_current_position+1, -((int)sizeof(data) - 12)); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]P\tset APPLICATION (shrink), fill in with padding\n"); + app->set_id((const unsigned char *)"juh"); /* twiddle the id */ + if(!app->set_data(data, 23, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!insert_to_our_metadata_(padding, our_current_position+1, /*copy=*/true)) + return die_("copying object"); + dynamic_cast(our_metadata_.blocks[our_current_position+1])->set_length(sizeof(data) - 23 - FLAC__STREAM_METADATA_HEADER_LENGTH); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]PP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVAA[P]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVAAP[P]\tset PADDING (shrink), don't fill in with padding\n"); + padding->set_length(5); + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(padding, false)) + return die_ss_("iterator.set_block(padding, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVAAP[P]\tset APPLICATION (grow)\n"); + app->set_id((const unsigned char *)"kuh"); /* twiddle the id */ + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app, false)) + return die_ss_("iterator.set_block(app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVAAP[A]\tset PADDING (equal)\n"); + padding->set_length(27); + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(padding, false)) + return die_ss_("iterator.set_block(padding, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVAAP[P]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVAA[P]P\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVA[A]P\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVA[P]\tinsert PADDING after\n"); + padding->set_length(5); + if(!iterator.insert_block_after(padding, false)) + return die_ss_("iterator.insert_block_after(padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVAP[P]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVA[P]P\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[A]PP\tset APPLICATION (grow), try to expand into padding which is too small\n"); + if(!app->set_data(data, 32, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), try to expand into padding which is 'close' but still too small\n"); + if(!app->set_data(data, 60, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), expand into padding which will leave 0-length pad\n"); + if(!app->set_data(data, 87, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + dynamic_cast(our_metadata_.blocks[our_current_position+1])->set_length(0); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), expand into padding which is exactly consumed\n"); + if(!app->set_data(data, 91, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tset APPLICATION (grow), expand into padding which is exactly consumed\n"); + if(!app->set_data(data, 100, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + our_metadata_.blocks[our_current_position]->set_is_last(true); + if(!iterator.set_block(app, true)) + return die_ss_("iterator.set_block(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tset PADDING (equal size)\n"); + padding->set_length(app->get_length()); + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(padding, true)) + return die_ss_("iterator.set_block(padding, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[P]\tinsert PADDING after\n"); + if(!iterator.insert_block_after(padding, false)) + return die_ss_("iterator.insert_block_after(padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVP[P]\tinsert PADDING after\n"); + padding->set_length(5); + if(!iterator.insert_block_after(padding, false)) + return die_ss_("iterator.insert_block_after(padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SVPP[P]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVP[P]P\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[P]PP\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PPP\tinsert APPLICATION after, try to expand into padding which is too small\n"); + if(!app->set_data(data, 101, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PPP\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]PPP\tinsert APPLICATION after, try to expand into padding which is 'close' but still too small\n"); + if(!app->set_data(data, 97, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PPP\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]PPP\tinsert APPLICATION after, expand into padding which is exactly consumed\n"); + if(!app->set_data(data, 100, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PP\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]PP\tinsert APPLICATION after, expand into padding which will leave 0-length pad\n"); + if(!app->set_data(data, 96, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + dynamic_cast(our_metadata_.blocks[our_current_position+1])->set_length(0); + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]PP\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]PP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tdelete (middle block), don't replace with padding\n"); + if(!iterator.delete_block(false)) + return die_ss_("iterator.delete_block(false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + + printf("S[V]P\tinsert APPLICATION after, expand into padding which is exactly consumed\n"); + if(!app->set_data(data, 1, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!iterator.insert_block_after(app, true)) + return die_ss_("iterator.insert_block_after(app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, /*ignore_metadata=*/false)) + return false; + } + + delete app; + delete padding; + + if(!remove_file_(flacfilename(/*is_ogg=*/false))) + return false; + + return true; +} + +static bool test_level_2_(bool filename_based, bool is_ogg) +{ + FLAC::Metadata::Prototype *block; + FLAC::Metadata::StreamInfo *streaminfo; + FLAC::Metadata::Application *app; + FLAC::Metadata::Padding *padding; + FLAC__byte data[2000]; + unsigned our_current_position; + + // initialize 'data' to avoid Valgrind errors + memset(data, 0, sizeof(data)); + + printf("\n\n++++++ testing level 2 interface (%s-based, %s FLAC)\n", filename_based? "filename":"callback", is_ogg? "Ogg":"native"); + + printf("generate read-only file\n"); + + if(!generate_file_(/*include_extras=*/false, is_ogg)) + return false; + + if(!change_stats_(flacfilename(is_ogg), /*read_only=*/true)) + return false; + + printf("create chain\n"); + FLAC::Metadata::Chain chain; + if(!chain.is_valid()) + return die_("allocating memory for chain"); + + printf("read chain\n"); + + if(!read_chain_(chain, flacfilename(is_ogg), filename_based, is_ogg)) + return die_c_("reading chain", chain.status()); + + printf("[S]VP\ttest initial metadata\n"); + + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + if(is_ogg) + goto end; + + printf("switch file to read-write\n"); + + if(!change_stats_(flacfilename(is_ogg), /*read-only=*/false)) + return false; + + printf("create iterator\n"); + { + FLAC::Metadata::Iterator iterator; + if(!iterator.is_valid()) + return die_("allocating memory for iterator"); + + our_current_position = 0; + + iterator.init(chain); + + if(0 == (block = iterator.get_block())) + return die_("getting block from iterator"); + + FLAC__ASSERT(block->get_type() == FLAC__METADATA_TYPE_STREAMINFO); + + printf("[S]VP\tmodify STREAMINFO, write\n"); + + streaminfo = dynamic_cast(block); + FLAC__ASSERT(0 != streaminfo); + streaminfo->set_sample_rate(32000); + if(!replace_in_our_metadata_(block, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete block; + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/true, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, true)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("[S]VP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\treplace PADDING with identical-size APPLICATION\n"); + if(0 == (block = iterator.get_block())) + return die_("getting block from iterator"); + if(0 == (app = new FLAC::Metadata::Application())) + return die_("new FLAC::Metadata::Application()"); + app->set_id((const unsigned char *)"duh"); + if(!app->set_data(data, block->get_length()-(FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), true)) + return die_("setting APPLICATION data"); + delete block; + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tshrink APPLICATION, don't use padding\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 26, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tgrow APPLICATION, don't use padding\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 28, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tgrow APPLICATION, use padding, but last block is not padding\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 36, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tshrink APPLICATION, use padding, last block is not padding, but delta is too small for new PADDING block\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 33, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tshrink APPLICATION, use padding, last block is not padding, delta is enough for new PADDING block\n"); + if(0 == (padding = new FLAC::Metadata::Padding())) + return die_("creating PADDING block"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 29, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + padding->set_length(0); + if(!insert_to_our_metadata_(padding, our_current_position+1, /*copy=*/false)) + return die_("internal error"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tshrink APPLICATION, use padding, last block is padding\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 16, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + dynamic_cast(our_metadata_.blocks[our_current_position+1])->set_length(13); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding, but delta is too small\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 50, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding of exceeding size\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 56, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + add_to_padding_length_(our_current_position+1, -(56 - 50)); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding of exact size\n"); + if(0 == (app = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("copying object"); + if(!app->set_data(data, 67, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!iterator.set_block(app)) + return die_c_("iterator.set_block(app)", chain.status()); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV[A]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]A\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VA\tinsert PADDING before STREAMINFO (should fail)\n"); + if(0 == (padding = new FLAC::Metadata::Padding())) + return die_("creating PADDING block"); + padding->set_length(30); + if(!iterator.insert_block_before(padding)) + printf("\titerator.insert_block_before() returned false like it should\n"); + else + return die_("iterator.insert_block_before() should have returned false"); + + printf("[S]VA\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]A\tinsert PADDING after\n"); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!iterator.insert_block_after(padding)) + return die_("iterator.insert_block_after(padding)"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("SV[P]A\tinsert PADDING before\n"); + if(0 == (padding = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("creating PADDING block"); + padding->set_length(17); + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!iterator.insert_block_before(padding)) + return die_("iterator.insert_block_before(padding)"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("SV[P]PA\tinsert PADDING before\n"); + if(0 == (padding = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[our_current_position])))) + return die_("creating PADDING block"); + padding->set_length(0); + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!iterator.insert_block_before(padding)) + return die_("iterator.insert_block_before(padding)"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("SV[P]PPA\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]PA\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVPP[P]A\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVPPP[A]\tinsert PADDING after\n"); + if(0 == (padding = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[2])))) + return die_("creating PADDING block"); + padding->set_length(57); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!iterator.insert_block_after(padding)) + return die_("iterator.insert_block_after(padding)"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("SVPPPA[P]\tinsert PADDING before\n"); + if(0 == (padding = dynamic_cast(FLAC::Metadata::clone(our_metadata_.blocks[2])))) + return die_("creating PADDING block"); + padding->set_length(99); + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!iterator.insert_block_before(padding)) + return die_("iterator.insert_block_before(padding)"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + } + our_current_position = 0; + + printf("SVPPPAPP\tmerge padding\n"); + chain.merge_padding(); + add_to_padding_length_(2, FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[3]->get_length()); + add_to_padding_length_(2, FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[4]->get_length()); + add_to_padding_length_(6, FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[7]->get_length()); + delete_from_our_metadata_(7); + delete_from_our_metadata_(4); + delete_from_our_metadata_(3); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SVPAP\tsort padding\n"); + chain.sort_padding(); + add_to_padding_length_(4, FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[2]->get_length()); + delete_from_our_metadata_(2); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(true, false)", chain.status()); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("create iterator\n"); + { + FLAC::Metadata::Iterator iterator; + if(!iterator.is_valid()) + return die_("allocating memory for iterator"); + + our_current_position = 0; + + iterator.init(chain); + + printf("[S]VAP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]AP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[A]P\tdelete middle block, replace with padding\n"); + if(0 == (padding = new FLAC::Metadata::Padding())) + return die_("creating PADDING block"); + padding->set_length(71); + if(!replace_in_our_metadata_(padding, our_current_position--, /*copy=*/false)) + return die_("copying object"); + if(!iterator.delete_block(/*replace_with_padding=*/true)) + return die_c_("iterator.delete_block(true)", chain.status()); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("S[V]PP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tdelete middle block, don't replace with padding\n"); + delete_from_our_metadata_(our_current_position--); + if(!iterator.delete_block(/*replace_with_padding=*/false)) + return die_c_("iterator.delete_block(false)", chain.status()); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("S[V]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tdelete last block, replace with padding\n"); + if(0 == (padding = new FLAC::Metadata::Padding())) + return die_("creating PADDING block"); + padding->set_length(219); + if(!replace_in_our_metadata_(padding, our_current_position--, /*copy=*/false)) + return die_("copying object"); + if(!iterator.delete_block(/*replace_with_padding=*/true)) + return die_c_("iterator.delete_block(true)", chain.status()); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("S[V]P\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tdelete last block, don't replace with padding\n"); + delete_from_our_metadata_(our_current_position--); + if(!iterator.delete_block(/*replace_with_padding=*/false)) + return die_c_("iterator.delete_block(false)", chain.status()); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + printf("S[V]\tprev\n"); + if(!iterator.prev()) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]V\tdelete STREAMINFO block, should fail\n"); + if(iterator.delete_block(/*replace_with_padding=*/false)) + return die_("iterator.delete_block() on STREAMINFO should have failed but didn't"); + + block = iterator.get_block(); + if(!compare_chain_(chain, our_current_position, block)) + return false; + delete block; + + } // delete iterator + our_current_position = 0; + + printf("SV\tmerge padding\n"); + chain.merge_padding(); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + + printf("SV\tsort padding\n"); + chain.sort_padding(); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during chain.write(false, false)", chain.status()); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, /*ignore_metadata=*/false)) + return false; + +end: + if(!remove_file_(flacfilename(is_ogg))) + return false; + + return true; +} + +static bool test_level_2_misc_(bool is_ogg) +{ + ::FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (::FLAC__IOCallback_Read)fread; +#ifdef FLAC__VALGRIND_TESTING + callbacks.write = chain_write_cb_; +#else + callbacks.write = (::FLAC__IOCallback_Write)fwrite; +#endif + callbacks.seek = chain_seek_cb_; + callbacks.tell = chain_tell_cb_; + callbacks.eof = chain_eof_cb_; + + printf("\n\n++++++ testing level 2 interface (mismatched read/write protections)\n"); + + printf("generate file\n"); + + if(!generate_file_(/*include_extras=*/false, is_ogg)) + return false; + + printf("create chain\n"); + FLAC::Metadata::Chain chain; + if(!chain.is_valid()) + return die_("allocating chain"); + + printf("read chain (filename-based)\n"); + + if(!chain.read(flacfilename(is_ogg))) + return die_c_("reading chain", chain.status()); + + printf("write chain with wrong method Chain::write(with callbacks)\n"); + { + if(chain.write(/*use_padding=*/false, 0, callbacks)) + return die_c_("mismatched write should have failed", chain.status()); + if(chain.status() != ::FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", chain.status()); + printf(" OK: Chain::write(with callbacks) returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (filename-based)\n"); + + if(!chain.read(flacfilename(is_ogg))) + return die_c_("reading chain", chain.status()); + + printf("write chain with wrong method Chain::write(with callbacks and tempfile)\n"); + { + if(chain.write(/*use_padding=*/false, 0, callbacks, 0, callbacks)) + return die_c_("mismatched write should have failed", chain.status()); + if(chain.status() != ::FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", chain.status()); + printf(" OK: Chain::write(with callbacks and tempfile) returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!chain.read((::FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", chain.status()); + } + fclose(file); + } + + printf("write chain with wrong method write()\n"); + { + if(chain.write(/*use_padding=*/false, /*preserve_file_stats=*/false)) + return die_c_("mismatched write should have failed", chain.status()); + if(chain.status() != ::FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", chain.status()); + printf(" OK: write() returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!chain.read((::FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", chain.status()); + } + fclose(file); + } + + printf("testing Chain::check_if_tempfile_needed()... "); + + if(!chain.check_if_tempfile_needed(/*use_padding=*/false)) + printf("OK: Chain::check_if_tempfile_needed() returned false like it should\n"); + else + return die_("Chain::check_if_tempfile_needed() returned true but shouldn't have"); + + printf("write chain with wrong method Chain::write(with callbacks and tempfile)\n"); + { + if(chain.write(/*use_padding=*/false, 0, callbacks, 0, callbacks)) + return die_c_("mismatched write should have failed", chain.status()); + if(chain.status() != ::FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL", chain.status()); + printf(" OK: Chain::write(with callbacks and tempfile) returned false,FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!chain.read((::FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", chain.status()); + } + fclose(file); + } + + printf("create iterator\n"); + { + FLAC::Metadata::Iterator iterator; + if(!iterator.is_valid()) + return die_("allocating memory for iterator"); + + iterator.init(chain); + + printf("[S]VP\tnext\n"); + if(!iterator.next()) + return die_("iterator ended early\n"); + + printf("S[V]P\tdelete VORBIS_COMMENT, write\n"); + if(!iterator.delete_block(/*replace_with_padding=*/false)) + return die_c_("block delete failed\n", chain.status()); + + printf("testing Chain::check_if_tempfile_needed()... "); + + if(chain.check_if_tempfile_needed(/*use_padding=*/false)) + printf("OK: Chain::check_if_tempfile_needed() returned true like it should\n"); + else + return die_("Chain::check_if_tempfile_needed() returned false but shouldn't have"); + + printf("write chain with wrong method Chain::write(with callbacks)\n"); + { + if(chain.write(/*use_padding=*/false, 0, callbacks)) + return die_c_("mismatched write should have failed", chain.status()); + if(chain.status() != ::FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL", chain.status()); + printf(" OK: Chain::write(with callbacks) returned false,FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL like it should\n"); + } + + } // delete iterator + + if(!remove_file_(flacfilename(is_ogg))) + return false; + + return true; +} + +bool test_metadata_file_manipulation() +{ + printf("\n+++ libFLAC++ unit test: metadata manipulation\n\n"); + + our_metadata_.num_blocks = 0; + + if(!test_level_0_()) + return false; + + if(!test_level_1_()) + return false; + + if(!test_level_2_(/*filename_based=*/true, /*is_ogg=*/false)) /* filename-based */ + return false; + if(!test_level_2_(/*filename_based=*/false, /*is_ogg=*/false)) /* callback-based */ + return false; + if(!test_level_2_misc_(/*is_ogg=*/false)) + return false; + + if(FLAC_API_SUPPORTS_OGG_FLAC) { + if(!test_level_2_(/*filename_based=*/true, /*is_ogg=*/true)) /* filename-based */ + return false; + if(!test_level_2_(/*filename_based=*/false, /*is_ogg=*/true)) /* callback-based */ + return false; +#if 0 + /* when ogg flac write is supported, will have to add this: */ + if(!test_level_2_misc_(/*is_ogg=*/true)) + return false; +#endif + } + + return true; +} diff --git a/flac/src/test_libFLAC++/metadata_object.cpp b/flac/src/test_libFLAC++/metadata_object.cpp new file mode 100644 index 0000000..978918a --- /dev/null +++ b/flac/src/test_libFLAC++/metadata_object.cpp @@ -0,0 +1,2093 @@ +/* test_libFLAC++ - Unit tester for libFLAC++ + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "FLAC/assert.h" +#include "FLAC++/metadata.h" +#include +#include /* for malloc() */ +#include /* for memcmp() */ + +static ::FLAC__StreamMetadata streaminfo_, padding_, seektable_, application_, vorbiscomment_, cuesheet_, picture_; + +static bool die_(const char *msg) +{ + printf("FAILED, %s\n", msg); + return false; +} + +static void *malloc_or_die_(size_t size) +{ + void *x = malloc(size); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory allocating %u bytes\n", (unsigned)size); + exit(1); + } + return x; +} + +static char *strdup_or_die_(const char *s) +{ + char *x = strdup(s); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory copying string \"%s\"\n", s); + exit(1); + } + return x; +} + +static bool index_is_equal_(const ::FLAC__StreamMetadata_CueSheet_Index &index, const ::FLAC__StreamMetadata_CueSheet_Index &indexcopy) +{ + if(indexcopy.offset != index.offset) + return false; + if(indexcopy.number != index.number) + return false; + return true; +} + +static bool track_is_equal_(const ::FLAC__StreamMetadata_CueSheet_Track *track, const ::FLAC__StreamMetadata_CueSheet_Track *trackcopy) +{ + unsigned i; + + if(trackcopy->offset != track->offset) + return false; + if(trackcopy->number != track->number) + return false; + if(0 != strcmp(trackcopy->isrc, track->isrc)) + return false; + if(trackcopy->type != track->type) + return false; + if(trackcopy->pre_emphasis != track->pre_emphasis) + return false; + if(trackcopy->num_indices != track->num_indices) + return false; + if(0 == track->indices || 0 == trackcopy->indices) { + if(track->indices != trackcopy->indices) + return false; + } + else { + for(i = 0; i < track->num_indices; i++) { + if(!index_is_equal_(trackcopy->indices[i], track->indices[i])) + return false; + } + } + return true; +} + +static void init_metadata_blocks_() +{ + streaminfo_.is_last = false; + streaminfo_.type = ::FLAC__METADATA_TYPE_STREAMINFO; + streaminfo_.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + streaminfo_.data.stream_info.min_blocksize = 576; + streaminfo_.data.stream_info.max_blocksize = 576; + streaminfo_.data.stream_info.min_framesize = 0; + streaminfo_.data.stream_info.max_framesize = 0; + streaminfo_.data.stream_info.sample_rate = 44100; + streaminfo_.data.stream_info.channels = 1; + streaminfo_.data.stream_info.bits_per_sample = 8; + streaminfo_.data.stream_info.total_samples = 0; + memset(streaminfo_.data.stream_info.md5sum, 0, 16); + + padding_.is_last = false; + padding_.type = ::FLAC__METADATA_TYPE_PADDING; + padding_.length = 1234; + + seektable_.is_last = false; + seektable_.type = ::FLAC__METADATA_TYPE_SEEKTABLE; + seektable_.data.seek_table.num_points = 2; + seektable_.length = seektable_.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; + seektable_.data.seek_table.points = (::FLAC__StreamMetadata_SeekPoint*)malloc_or_die_(seektable_.data.seek_table.num_points * sizeof(::FLAC__StreamMetadata_SeekPoint)); + seektable_.data.seek_table.points[0].sample_number = 0; + seektable_.data.seek_table.points[0].stream_offset = 0; + seektable_.data.seek_table.points[0].frame_samples = streaminfo_.data.stream_info.min_blocksize; + seektable_.data.seek_table.points[1].sample_number = ::FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seektable_.data.seek_table.points[1].stream_offset = 1000; + seektable_.data.seek_table.points[1].frame_samples = streaminfo_.data.stream_info.min_blocksize; + + application_.is_last = false; + application_.type = ::FLAC__METADATA_TYPE_APPLICATION; + application_.length = 8; + memcpy(application_.data.application.id, "\xfe\xdc\xba\x98", 4); + application_.data.application.data = (FLAC__byte*)malloc_or_die_(4); + memcpy(application_.data.application.data, "\xf0\xe1\xd2\xc3", 4); + + vorbiscomment_.is_last = false; + vorbiscomment_.type = ::FLAC__METADATA_TYPE_VORBIS_COMMENT; + vorbiscomment_.length = (4 + 5) + 4 + (4 + 12) + (4 + 12); + vorbiscomment_.data.vorbis_comment.vendor_string.length = 5; + vorbiscomment_.data.vorbis_comment.vendor_string.entry = (FLAC__byte*)malloc_or_die_(5+1); + memcpy(vorbiscomment_.data.vorbis_comment.vendor_string.entry, "name0", 5+1); + vorbiscomment_.data.vorbis_comment.num_comments = 2; + vorbiscomment_.data.vorbis_comment.comments = (::FLAC__StreamMetadata_VorbisComment_Entry*)malloc_or_die_(vorbiscomment_.data.vorbis_comment.num_comments * sizeof(::FLAC__StreamMetadata_VorbisComment_Entry)); + vorbiscomment_.data.vorbis_comment.comments[0].length = 12; + vorbiscomment_.data.vorbis_comment.comments[0].entry = (FLAC__byte*)malloc_or_die_(12+1); + memcpy(vorbiscomment_.data.vorbis_comment.comments[0].entry, "name2=value2", 12+1); + vorbiscomment_.data.vorbis_comment.comments[1].length = 12; + vorbiscomment_.data.vorbis_comment.comments[1].entry = (FLAC__byte*)malloc_or_die_(12+1); + memcpy(vorbiscomment_.data.vorbis_comment.comments[1].entry, "name3=value3", 12+1); + + cuesheet_.is_last = false; + cuesheet_.type = ::FLAC__METADATA_TYPE_CUESHEET; + cuesheet_.length = + /* cuesheet guts */ + ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8 + + /* 2 tracks */ + 2 * ( + FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN + ) / 8 + + /* 3 index points */ + 3 * ( + FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN + ) / 8 + ; + memset(cuesheet_.data.cue_sheet.media_catalog_number, 0, sizeof(cuesheet_.data.cue_sheet.media_catalog_number)); + cuesheet_.data.cue_sheet.media_catalog_number[0] = 'j'; + cuesheet_.data.cue_sheet.media_catalog_number[1] = 'C'; + cuesheet_.data.cue_sheet.lead_in = 159; + cuesheet_.data.cue_sheet.is_cd = true; + cuesheet_.data.cue_sheet.num_tracks = 2; + cuesheet_.data.cue_sheet.tracks = (FLAC__StreamMetadata_CueSheet_Track*)malloc_or_die_(cuesheet_.data.cue_sheet.num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track)); + cuesheet_.data.cue_sheet.tracks[0].offset = 1; + cuesheet_.data.cue_sheet.tracks[0].number = 1; + memcpy(cuesheet_.data.cue_sheet.tracks[0].isrc, "ACBDE1234567", sizeof(cuesheet_.data.cue_sheet.tracks[0].isrc)); + cuesheet_.data.cue_sheet.tracks[0].type = 0; + cuesheet_.data.cue_sheet.tracks[0].pre_emphasis = 1; + cuesheet_.data.cue_sheet.tracks[0].num_indices = 2; + cuesheet_.data.cue_sheet.tracks[0].indices = (FLAC__StreamMetadata_CueSheet_Index*)malloc_or_die_(cuesheet_.data.cue_sheet.tracks[0].num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index)); + cuesheet_.data.cue_sheet.tracks[0].indices[0].offset = 0; + cuesheet_.data.cue_sheet.tracks[0].indices[0].number = 0; + cuesheet_.data.cue_sheet.tracks[0].indices[1].offset = 1234567890; + cuesheet_.data.cue_sheet.tracks[0].indices[1].number = 1; + cuesheet_.data.cue_sheet.tracks[1].offset = 2345678901u; + cuesheet_.data.cue_sheet.tracks[1].number = 2; + memcpy(cuesheet_.data.cue_sheet.tracks[1].isrc, "ACBDE7654321", sizeof(cuesheet_.data.cue_sheet.tracks[1].isrc)); + cuesheet_.data.cue_sheet.tracks[1].type = 1; + cuesheet_.data.cue_sheet.tracks[1].pre_emphasis = 0; + cuesheet_.data.cue_sheet.tracks[1].num_indices = 1; + cuesheet_.data.cue_sheet.tracks[1].indices = (FLAC__StreamMetadata_CueSheet_Index*)malloc_or_die_(cuesheet_.data.cue_sheet.tracks[1].num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index)); + cuesheet_.data.cue_sheet.tracks[1].indices[0].offset = 0; + cuesheet_.data.cue_sheet.tracks[1].indices[0].number = 1; + + picture_.is_last = true; + picture_.type = FLAC__METADATA_TYPE_PICTURE; + picture_.length = + ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN /* will add the length for the data later */ + ) / 8 + ; + picture_.data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER; + picture_.data.picture.mime_type = strdup_or_die_("image/jpeg"); + picture_.length += strlen(picture_.data.picture.mime_type); + picture_.data.picture.description = (FLAC__byte*)strdup_or_die_("desc"); + picture_.length += strlen((const char *)picture_.data.picture.description); + picture_.data.picture.width = 300; + picture_.data.picture.height = 300; + picture_.data.picture.depth = 24; + picture_.data.picture.colors = 0; + picture_.data.picture.data = (FLAC__byte*)strdup_or_die_("SOMEJPEGDATA"); + picture_.data.picture.data_length = strlen((const char *)picture_.data.picture.data); + picture_.length += picture_.data.picture.data_length; +} + +static void free_metadata_blocks_() +{ + free(seektable_.data.seek_table.points); + free(application_.data.application.data); + free(vorbiscomment_.data.vorbis_comment.vendor_string.entry); + free(vorbiscomment_.data.vorbis_comment.comments[0].entry); + free(vorbiscomment_.data.vorbis_comment.comments[1].entry); + free(vorbiscomment_.data.vorbis_comment.comments); + free(cuesheet_.data.cue_sheet.tracks[0].indices); + free(cuesheet_.data.cue_sheet.tracks[1].indices); + free(cuesheet_.data.cue_sheet.tracks); + free(picture_.data.picture.mime_type); + free(picture_.data.picture.description); + free(picture_.data.picture.data); +} + +bool test_metadata_object_streaminfo() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::StreamInfo\n"); + + printf("testing StreamInfo::StreamInfo()... "); + FLAC::Metadata::StreamInfo block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing StreamInfo::StreamInfo(const StreamInfo &)... +\n"); + printf(" StreamInfo::operator!=(const StreamInfo &)... "); + { + FLAC::Metadata::StreamInfo blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing StreamInfo::~StreamInfo()... "); + } + printf("OK\n"); + + printf("testing StreamInfo::StreamInfo(const ::FLAC__StreamMetadata &)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::StreamInfo blockcopy(streaminfo_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::StreamInfo(const ::FLAC__StreamMetadata *)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::StreamInfo blockcopy(&streaminfo_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::StreamInfo(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::StreamInfo blockcopy(&streaminfo_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::StreamInfo(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&streaminfo_); + FLAC::Metadata::StreamInfo blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::StreamInfo blockcopy; + blockcopy.assign(&streaminfo_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" StreamInfo::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&streaminfo_); + FLAC::Metadata::StreamInfo blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != streaminfo_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::operator=(const StreamInfo &)... +\n"); + printf(" StreamInfo::operator==(const StreamInfo &)... "); + { + FLAC::Metadata::StreamInfo blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" StreamInfo::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::StreamInfo blockcopy = streaminfo_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == streaminfo_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" StreamInfo::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::StreamInfo blockcopy = &streaminfo_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == streaminfo_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing StreamInfo::set_min_blocksize()... "); + block.set_min_blocksize(streaminfo_.data.stream_info.min_blocksize); + printf("OK\n"); + + printf("testing StreamInfo::set_max_blocksize()... "); + block.set_max_blocksize(streaminfo_.data.stream_info.max_blocksize); + printf("OK\n"); + + printf("testing StreamInfo::set_min_framesize()... "); + block.set_min_framesize(streaminfo_.data.stream_info.min_framesize); + printf("OK\n"); + + printf("testing StreamInfo::set_max_framesize()... "); + block.set_max_framesize(streaminfo_.data.stream_info.max_framesize); + printf("OK\n"); + + printf("testing StreamInfo::set_sample_rate()... "); + block.set_sample_rate(streaminfo_.data.stream_info.sample_rate); + printf("OK\n"); + + printf("testing StreamInfo::set_channels()... "); + block.set_channels(streaminfo_.data.stream_info.channels); + printf("OK\n"); + + printf("testing StreamInfo::set_bits_per_sample()... "); + block.set_bits_per_sample(streaminfo_.data.stream_info.bits_per_sample); + printf("OK\n"); + + printf("testing StreamInfo::set_total_samples()... "); + block.set_total_samples(streaminfo_.data.stream_info.total_samples); + printf("OK\n"); + + printf("testing StreamInfo::set_md5sum()... "); + block.set_md5sum(streaminfo_.data.stream_info.md5sum); + printf("OK\n"); + + printf("testing StreamInfo::get_min_blocksize()... "); + if(block.get_min_blocksize() != streaminfo_.data.stream_info.min_blocksize) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_max_blocksize()... "); + if(block.get_max_blocksize() != streaminfo_.data.stream_info.max_blocksize) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_min_framesize()... "); + if(block.get_min_framesize() != streaminfo_.data.stream_info.min_framesize) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_max_framesize()... "); + if(block.get_max_framesize() != streaminfo_.data.stream_info.max_framesize) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_sample_rate()... "); + if(block.get_sample_rate() != streaminfo_.data.stream_info.sample_rate) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_channels()... "); + if(block.get_channels() != streaminfo_.data.stream_info.channels) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_bits_per_sample()... "); + if(block.get_bits_per_sample() != streaminfo_.data.stream_info.bits_per_sample) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_total_samples()... "); + if(block.get_total_samples() != streaminfo_.data.stream_info.total_samples) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing StreamInfo::get_md5sum()... "); + if(0 != memcmp(block.get_md5sum(), streaminfo_.data.stream_info.md5sum, 16)) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing StreamInfo::~StreamInfo()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_padding() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::Padding\n"); + + printf("testing Padding::Padding()... "); + FLAC::Metadata::Padding block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = 0; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing Padding::Padding(const Padding &)... +\n"); + printf(" Padding::operator!=(const Padding &)... "); + { + FLAC::Metadata::Padding blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing Padding::~Padding()... "); + } + printf("OK\n"); + + printf("testing Padding::Padding(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Padding blockcopy(padding_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::Padding(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Padding blockcopy(&padding_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::Padding(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Padding blockcopy(&padding_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::Padding(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&padding_); + FLAC::Metadata::Padding blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Padding blockcopy; + blockcopy.assign(&padding_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Padding::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&padding_); + FLAC::Metadata::Padding blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != padding_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::operator=(const Padding &)... +\n"); + printf(" Padding::operator==(const Padding &)... "); + { + FLAC::Metadata::Padding blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Padding::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Padding blockcopy = padding_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == padding_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Padding::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Padding blockcopy = &padding_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == padding_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Padding::set_length()... "); + block.set_length(padding_.length); + printf("OK\n"); + + printf("testing Prototype::get_length()... "); + if(block.get_length() != padding_.length) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing Padding::~Padding()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_application() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::Application\n"); + + printf("testing Application::Application()... "); + FLAC::Metadata::Application block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing Application::Application(const Application &)... +\n"); + printf(" Application::operator!=(const Application &)... "); + { + FLAC::Metadata::Application blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing Application::~Application()... "); + } + printf("OK\n"); + + printf("testing Application::Application(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Application blockcopy(application_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::Application(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Application blockcopy(&application_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::Application(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Application blockcopy(&application_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::Application(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&application_); + FLAC::Metadata::Application blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Application blockcopy; + blockcopy.assign(&application_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Application::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&application_); + FLAC::Metadata::Application blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != application_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::operator=(const Application &)... +\n"); + printf(" Application::operator==(const Application &)... "); + { + FLAC::Metadata::Application blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Application::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Application blockcopy = application_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == application_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Application::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Application blockcopy = &application_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == application_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Application::set_id()... "); + block.set_id(application_.data.application.id); + printf("OK\n"); + + printf("testing Application::set_data()... "); + block.set_data(application_.data.application.data, application_.length - sizeof(application_.data.application.id), /*copy=*/true); + printf("OK\n"); + + printf("testing Application::get_id()... "); + if(0 != memcmp(block.get_id(), application_.data.application.id, sizeof(application_.data.application.id))) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing Application::get_data()... "); + if(0 != memcmp(block.get_data(), application_.data.application.data, application_.length - sizeof(application_.data.application.id))) + return die_("value mismatch, doesn't match previously set value"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing Application::~Application()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_seektable() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::SeekTable\n"); + + printf("testing SeekTable::SeekTable()... "); + FLAC::Metadata::SeekTable block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = 0; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing SeekTable::SeekTable(const SeekTable &)... +\n"); + printf(" SeekTable::operator!=(const SeekTable &)... "); + { + FLAC::Metadata::SeekTable blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing SeekTable::~SeekTable()... "); + } + printf("OK\n"); + + printf("testing SeekTable::SeekTable(const ::FLAC__StreamMetadata &)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::SeekTable blockcopy(seektable_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::SeekTable(const ::FLAC__StreamMetadata *)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::SeekTable blockcopy(&seektable_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::SeekTable(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::SeekTable blockcopy(&seektable_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::SeekTable(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&seektable_); + FLAC::Metadata::SeekTable blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::SeekTable blockcopy; + blockcopy.assign(&seektable_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" SeekTable::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&seektable_); + FLAC::Metadata::SeekTable blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != seektable_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::operator=(const SeekTable &)... +\n"); + printf(" SeekTable::operator==(const SeekTable &)... "); + { + FLAC::Metadata::SeekTable blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" SeekTable::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::SeekTable blockcopy = seektable_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == seektable_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" SeekTable::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::SeekTable blockcopy = &seektable_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == seektable_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing SeekTable::insert_point() x 3... "); + if(!block.insert_point(0, seektable_.data.seek_table.points[1])) + return die_("returned false"); + if(!block.insert_point(0, seektable_.data.seek_table.points[1])) + return die_("returned false"); + if(!block.insert_point(1, seektable_.data.seek_table.points[0])) + return die_("returned false"); + printf("OK\n"); + + printf("testing SeekTable::is_legal()... "); + if(block.is_legal()) + return die_("returned true"); + printf("OK\n"); + + printf("testing SeekTable::set_point()... "); + block.set_point(0, seektable_.data.seek_table.points[0]); + printf("OK\n"); + + printf("testing SeekTable::delete_point()... "); + if(!block.delete_point(0)) + return die_("returned false"); + printf("OK\n"); + + printf("testing SeekTable::is_legal()... "); + if(!block.is_legal()) + return die_("returned false"); + printf("OK\n"); + + printf("testing SeekTable::get_num_points()... "); + if(block.get_num_points() != seektable_.data.seek_table.num_points) + return die_("number mismatch"); + printf("OK\n"); + + printf("testing SeekTable::operator!=(const ::FLAC__StreamMetadata &)... "); + if(block != seektable_) + return die_("data mismatch"); + printf("OK\n"); + + printf("testing SeekTable::get_point()... "); + if( + block.get_point(1).sample_number != seektable_.data.seek_table.points[1].sample_number || + block.get_point(1).stream_offset != seektable_.data.seek_table.points[1].stream_offset || + block.get_point(1).frame_samples != seektable_.data.seek_table.points[1].frame_samples + ) + return die_("point mismatch"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing SeekTable::~SeekTable()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_vorbiscomment() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::VorbisComment::Entry\n"); + + printf("testing Entry::Entry()... "); + { + FLAC::Metadata::VorbisComment::Entry entry1; + if(!entry1.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + printf("testing Entry::~Entry()... "); + } + printf("OK\n"); + + printf("testing Entry::Entry(const char *field, unsigned field_length)... "); + FLAC::Metadata::VorbisComment::Entry entry2("name2=value2", strlen("name2=value2")); + if(!entry2.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + { + printf("testing Entry::Entry(const char *field)... "); + FLAC::Metadata::VorbisComment::Entry entry2z("name2=value2"); + if(!entry2z.is_valid()) + return die_("!is_valid()"); + if(strcmp(entry2.get_field(), entry2z.get_field())) + return die_("bad value"); + printf("OK\n"); + } + + printf("testing Entry::Entry(const char *field_name, const char *field_value, unsigned field_value_length)... "); + FLAC::Metadata::VorbisComment::Entry entry3("name3", "value3", strlen("value3")); + if(!entry3.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + { + printf("testing Entry::Entry(const char *field_name, const char *field_value)... "); + FLAC::Metadata::VorbisComment::Entry entry3z("name3", "value3"); + if(!entry3z.is_valid()) + return die_("!is_valid()"); + if(strcmp(entry3.get_field(), entry3z.get_field())) + return die_("bad value"); + printf("OK\n"); + } + + printf("testing Entry::Entry(const Entry &entry)... "); + { + FLAC::Metadata::VorbisComment::Entry entry2copy(entry2); + if(!entry2copy.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + printf("testing Entry::~Entry()... "); + } + printf("OK\n"); + + printf("testing Entry::operator=(const Entry &entry)... "); + FLAC::Metadata::VorbisComment::Entry entry1 = entry2; + if(!entry2.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + printf("testing Entry::get_field_length()... "); + if(entry1.get_field_length() != strlen("name2=value2")) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::get_field_name_length()... "); + if(entry1.get_field_name_length() != strlen("name2")) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::get_field_value_length()... "); + if(entry1.get_field_value_length() != strlen("value2")) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::get_entry()... "); + { + ::FLAC__StreamMetadata_VorbisComment_Entry entry = entry1.get_entry(); + if(entry.length != strlen("name2=value2")) + return die_("entry length mismatch"); + if(0 != memcmp(entry.entry, "name2=value2", entry.length)) + return die_("entry value mismatch"); + } + printf("OK\n"); + + printf("testing Entry::get_field()... "); + if(0 != memcmp(entry1.get_field(), "name2=value2", strlen("name2=value2"))) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::get_field_name()... "); + if(0 != memcmp(entry1.get_field_name(), "name2", strlen("name2"))) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::get_field_value()... "); + if(0 != memcmp(entry1.get_field_value(), "value2", strlen("value2"))) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Entry::set_field_name()... "); + if(!entry1.set_field_name("name1")) + return die_("returned false"); + if(0 != memcmp(entry1.get_field_name(), "name1", strlen("name1"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field(), "name1=value2", strlen("name1=value2"))) + return die_("entry mismatch"); + printf("OK\n"); + + printf("testing Entry::set_field_value(const char *field_value, unsigned field_value_length)... "); + if(!entry1.set_field_value("value1", strlen("value1"))) + return die_("returned false"); + if(0 != memcmp(entry1.get_field_value(), "value1", strlen("value1"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field(), "name1=value1", strlen("name1=value1"))) + return die_("entry mismatch"); + printf("OK\n"); + + printf("testing Entry::set_field_value(const char *field_value)... "); + if(!entry1.set_field_value("value1")) + return die_("returned false"); + if(0 != memcmp(entry1.get_field_value(), "value1", strlen("value1"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field(), "name1=value1", strlen("name1=value1"))) + return die_("entry mismatch"); + printf("OK\n"); + + printf("testing Entry::set_field(const char *field, unsigned field_length)... "); + if(!entry1.set_field("name0=value0", strlen("name0=value0"))) + return die_("returned false"); + if(0 != memcmp(entry1.get_field_name(), "name0", strlen("name0"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field_value(), "value0", strlen("value0"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field(), "name0=value0", strlen("name0=value0"))) + return die_("entry mismatch"); + printf("OK\n"); + + printf("testing Entry::set_field(const char *field)... "); + if(!entry1.set_field("name0=value0")) + return die_("returned false"); + if(0 != memcmp(entry1.get_field_name(), "name0", strlen("name0"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field_value(), "value0", strlen("value0"))) + return die_("value mismatch"); + if(0 != memcmp(entry1.get_field(), "name0=value0", strlen("name0=value0"))) + return die_("entry mismatch"); + printf("OK\n"); + + printf("PASSED\n\n"); + + + printf("testing class FLAC::Metadata::VorbisComment\n"); + + printf("testing VorbisComment::VorbisComment()... "); + FLAC::Metadata::VorbisComment block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + strlen(::FLAC__VENDOR_STRING) + FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN/8); + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing VorbisComment::VorbisComment(const VorbisComment &)... +\n"); + printf(" VorbisComment::operator!=(const VorbisComment &)... "); + { + FLAC::Metadata::VorbisComment blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing VorbisComment::~VorbisComment()... "); + } + printf("OK\n"); + + printf("testing VorbisComment::VorbisComment(const ::FLAC__StreamMetadata &)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::VorbisComment blockcopy(vorbiscomment_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::VorbisComment(const ::FLAC__StreamMetadata *)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::VorbisComment blockcopy(&vorbiscomment_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::VorbisComment(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::VorbisComment blockcopy(&vorbiscomment_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::VorbisComment(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&vorbiscomment_); + FLAC::Metadata::VorbisComment blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::VorbisComment blockcopy; + blockcopy.assign(&vorbiscomment_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" VorbisComment::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&vorbiscomment_); + FLAC::Metadata::VorbisComment blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != vorbiscomment_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::operator=(const VorbisComment &)... +\n"); + printf(" VorbisComment::operator==(const VorbisComment &)... "); + { + FLAC::Metadata::VorbisComment blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" VorbisComment::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::VorbisComment blockcopy = vorbiscomment_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == vorbiscomment_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" VorbisComment::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::VorbisComment blockcopy = &vorbiscomment_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == vorbiscomment_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing VorbisComment::get_num_comments()... "); + if(block.get_num_comments() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing VorbisComment::set_vendor_string()... "); + if(!block.set_vendor_string((const FLAC__byte *)"mame0")) + return die_("returned false"); + printf("OK\n"); + vorbiscomment_.data.vorbis_comment.vendor_string.entry[0] = 'm'; + + printf("testing VorbisComment::get_vendor_string()... "); + if(strlen((const char *)block.get_vendor_string()) != vorbiscomment_.data.vorbis_comment.vendor_string.length) + return die_("length mismatch"); + if(0 != memcmp(block.get_vendor_string(), vorbiscomment_.data.vorbis_comment.vendor_string.entry, vorbiscomment_.data.vorbis_comment.vendor_string.length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::append_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.append_comment(entry3)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[1].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[1].entry, vorbiscomment_.data.vorbis_comment.comments[1].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::append_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.append_comment(entry2)) + return die_("returned false"); + if(block.get_comment(1).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[0].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(1).get_field(), vorbiscomment_.data.vorbis_comment.comments[0].entry, vorbiscomment_.data.vorbis_comment.comments[0].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::delete_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.delete_comment(0)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[0].length) + return die_("length[0] mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[0].entry, vorbiscomment_.data.vorbis_comment.comments[0].length)) + return die_("value[0] mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::delete_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.delete_comment(0)) + return die_("returned false"); + if(block.get_num_comments() != 0) + return die_("block mismatch, expected num_comments = 0"); + printf("OK\n"); + + printf("testing VorbisComment::insert_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.insert_comment(0, entry3)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[1].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[1].entry, vorbiscomment_.data.vorbis_comment.comments[1].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::insert_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.insert_comment(0, entry3)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[1].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[1].entry, vorbiscomment_.data.vorbis_comment.comments[1].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::insert_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.insert_comment(1, entry2)) + return die_("returned false"); + if(block.get_comment(1).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[0].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(1).get_field(), vorbiscomment_.data.vorbis_comment.comments[0].entry, vorbiscomment_.data.vorbis_comment.comments[0].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::set_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.set_comment(0, entry2)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[0].length) + return die_("length mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[0].entry, vorbiscomment_.data.vorbis_comment.comments[0].length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing VorbisComment::delete_comment()... +\n"); + printf(" VorbisComment::get_comment()... "); + if(!block.delete_comment(0)) + return die_("returned false"); + if(block.get_comment(0).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[0].length) + return die_("length[0] mismatch"); + if(0 != memcmp(block.get_comment(0).get_field(), vorbiscomment_.data.vorbis_comment.comments[0].entry, vorbiscomment_.data.vorbis_comment.comments[0].length)) + return die_("value[0] mismatch"); + if(block.get_comment(1).get_field_length() != vorbiscomment_.data.vorbis_comment.comments[1].length) + return die_("length[1] mismatch"); + if(0 != memcmp(block.get_comment(1).get_field(), vorbiscomment_.data.vorbis_comment.comments[1].entry, vorbiscomment_.data.vorbis_comment.comments[1].length)) + return die_("value[0] mismatch"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing VorbisComment::~VorbisComment()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_cuesheet() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::CueSheet::Track\n"); + + printf("testing Track::Track()... "); + FLAC::Metadata::CueSheet::Track track0; + if(!track0.is_valid()) + return die_("!is_valid()"); + printf("OK\n"); + + { + printf("testing Track::get_track()... "); + const ::FLAC__StreamMetadata_CueSheet_Track *trackp = track0.get_track(); + if(0 == trackp) + return die_("returned pointer is NULL"); + printf("OK\n"); + + printf("testing Track::Track(const ::FLAC__StreamMetadata_CueSheet_Track*)... "); + FLAC::Metadata::CueSheet::Track track2(trackp); + if(!track2.is_valid()) + return die_("!is_valid()"); + if(!track_is_equal_(track2.get_track(), trackp)) + return die_("copy is not equal"); + printf("OK\n"); + + printf("testing Track::~Track()... "); + } + printf("OK\n"); + + printf("testing Track::Track(const Track &track)... "); + { + FLAC::Metadata::CueSheet::Track track0copy(track0); + if(!track0copy.is_valid()) + return die_("!is_valid()"); + if(!track_is_equal_(track0copy.get_track(), track0.get_track())) + return die_("copy is not equal"); + printf("OK\n"); + + printf("testing Track::~Track()... "); + } + printf("OK\n"); + + printf("testing Track::operator=(const Track &track)... "); + FLAC::Metadata::CueSheet::Track track1 = track0; + if(!track0.is_valid()) + return die_("!is_valid()"); + if(!track_is_equal_(track1.get_track(), track0.get_track())) + return die_("copy is not equal"); + printf("OK\n"); + + printf("testing Track::get_offset()... "); + if(track1.get_offset() != 0) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::get_number()... "); + if(track1.get_number() != 0) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::get_isrc()... "); + if(0 != memcmp(track1.get_isrc(), "\0\0\0\0\0\0\0\0\0\0\0\0\0", 13)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::get_type()... "); + if(track1.get_type() != 0) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::get_pre_emphasis()... "); + if(track1.get_pre_emphasis() != 0) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::get_num_indices()... "); + if(track1.get_num_indices() != 0) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::set_offset()... "); + track1.set_offset(588); + if(track1.get_offset() != 588) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::set_number()... "); + track1.set_number(1); + if(track1.get_number() != 1) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::set_isrc()... "); + track1.set_isrc("ABCDE1234567"); + if(0 != memcmp(track1.get_isrc(), "ABCDE1234567", 13)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::set_type()... "); + track1.set_type(1); + if(track1.get_type() != 1) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Track::set_pre_emphasis()... "); + track1.set_pre_emphasis(1); + if(track1.get_pre_emphasis() != 1) + return die_("value mismatch"); + printf("OK\n"); + + printf("PASSED\n\n"); + + printf("testing class FLAC::Metadata::CueSheet\n"); + + printf("testing CueSheet::CueSheet()... "); + FLAC::Metadata::CueSheet block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing CueSheet::CueSheet(const CueSheet &)... +\n"); + printf(" CueSheet::operator!=(const CueSheet &)... "); + { + FLAC::Metadata::CueSheet blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing CueSheet::~CueSheet()... "); + } + printf("OK\n"); + + printf("testing CueSheet::CueSheet(const ::FLAC__StreamMetadata &)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::CueSheet blockcopy(cuesheet_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::CueSheet(const ::FLAC__StreamMetadata *)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::CueSheet blockcopy(&cuesheet_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::CueSheet(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::CueSheet blockcopy(&cuesheet_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::CueSheet(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&cuesheet_); + FLAC::Metadata::CueSheet blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::CueSheet blockcopy; + blockcopy.assign(&cuesheet_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" CueSheet::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&cuesheet_); + FLAC::Metadata::CueSheet blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != cuesheet_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::operator=(const CueSheet &)... +\n"); + printf(" CueSheet::operator==(const CueSheet &)... "); + { + FLAC::Metadata::CueSheet blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" CueSheet::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::CueSheet blockcopy = cuesheet_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == cuesheet_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" CueSheet::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::CueSheet blockcopy = &cuesheet_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == cuesheet_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing CueSheet::get_media_catalog_number()... "); + if(0 != strcmp(block.get_media_catalog_number(), "")) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::get_lead_in()... "); + if(block.get_lead_in() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing CueSheet::get_is_cd()... "); + if(block.get_is_cd()) + return die_("value mismatch, expected false"); + printf("OK\n"); + + printf("testing CueSheet::get_num_tracks()... "); + if(block.get_num_tracks() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing CueSheet::set_media_catalog_number()... "); + { + char mcn[129]; + memset(mcn, 0, sizeof(mcn)); + strcpy(mcn, "1234567890123"); + block.set_media_catalog_number(mcn); + if(0 != memcmp(block.get_media_catalog_number(), mcn, sizeof(mcn))) + return die_("value mismatch"); + } + printf("OK\n"); + + printf("testing CueSheet::set_lead_in()... "); + block.set_lead_in(588); + if(block.get_lead_in() != 588) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::set_is_cd()... "); + block.set_is_cd(true); + if(!block.get_is_cd()) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::insert_track()... +\n"); + printf(" CueSheet::get_track()... "); + if(!block.insert_track(0, track0)) + return die_("returned false"); + if(!track_is_equal_(block.get_track(0).get_track(), track0.get_track())) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::insert_track()... +\n"); + printf(" CueSheet::get_track()... "); + if(!block.insert_track(1, track1)) + return die_("returned false"); + if(!track_is_equal_(block.get_track(1).get_track(), track1.get_track())) + return die_("value mismatch"); + printf("OK\n"); + + ::FLAC__StreamMetadata_CueSheet_Index index0; + index0.offset = 588*4; + index0.number = 1; + + printf("testing CueSheet::insert_index(0)... +\n"); + printf(" CueSheet::get_track()... +\n"); + printf(" CueSheet::Track::get_index()... "); + if(!block.insert_index(0, 0, index0)) + return die_("returned false"); + if(!index_is_equal_(block.get_track(0).get_index(0), index0)) + return die_("value mismatch"); + printf("OK\n"); + + index0.offset = 588*5; + printf("testing CueSheet::Track::set_index()... "); + { + FLAC::Metadata::CueSheet::Track track_ = block.get_track(0); + track_.set_index(0, index0); + if(!index_is_equal_(track_.get_index(0), index0)) + return die_("value mismatch"); + } + printf("OK\n"); + + index0.offset = 588*6; + printf("testing CueSheet::set_index()... "); + block.set_index(0, 0, index0); + if(!index_is_equal_(block.get_track(0).get_index(0), index0)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::delete_index()... "); + if(!block.delete_index(0, 0)) + return die_("returned false"); + if(block.get_track(0).get_num_indices() != 0) + return die_("num_indices mismatch"); + printf("OK\n"); + + + printf("testing CueSheet::set_track()... +\n"); + printf(" CueSheet::get_track()... "); + if(!block.set_track(0, track1)) + return die_("returned false"); + if(!track_is_equal_(block.get_track(0).get_track(), track1.get_track())) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing CueSheet::delete_track()... "); + if(!block.delete_track(0)) + return die_("returned false"); + if(block.get_num_tracks() != 1) + return die_("num_tracks mismatch"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing CueSheet::~CueSheet()... "); + delete clone_; + printf("OK\n"); + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object_picture() +{ + unsigned expected_length; + + printf("testing class FLAC::Metadata::Picture\n"); + + printf("testing Picture::Picture()... "); + FLAC::Metadata::Picture block; + if(!block.is_valid()) + return die_("!block.is_valid()"); + expected_length = ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN + ) / 8; + if(block.get_length() != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block.get_length()); + return false; + } + printf("OK\n"); + + printf("testing Picture::Picture(const Picture &)... +\n"); + printf(" Picture::operator!=(const Picture &)... "); + { + FLAC::Metadata::Picture blockcopy(block); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != block) + return die_("copy is not identical to original"); + printf("OK\n"); + + printf("testing Picture::~Picture()... "); + } + printf("OK\n"); + + printf("testing Picture::Picture(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Picture blockcopy(picture_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::Picture(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Picture blockcopy(&picture_); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::Picture(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Picture blockcopy(&picture_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::Picture(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&picture_); + FLAC::Metadata::Picture blockcopy(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::assign(const ::FLAC__StreamMetadata *, copy=true)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Picture blockcopy; + blockcopy.assign(&picture_, /*copy=*/true); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::assign(const ::FLAC__StreamMetadata *, copy=false)... +\n"); + printf(" Picture::operator!=(const ::FLAC__StreamMetadata *)... "); + { + ::FLAC__StreamMetadata *copy = ::FLAC__metadata_object_clone(&picture_); + FLAC::Metadata::Picture blockcopy; + blockcopy.assign(copy, /*copy=*/false); + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(blockcopy != picture_) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::operator=(const Picture &)... +\n"); + printf(" Picture::operator==(const Picture &)... "); + { + FLAC::Metadata::Picture blockcopy = block; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == block)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::operator=(const ::FLAC__StreamMetadata &)... +\n"); + printf(" Picture::operator==(const ::FLAC__StreamMetadata &)... "); + { + FLAC::Metadata::Picture blockcopy = picture_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == picture_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::operator=(const ::FLAC__StreamMetadata *)... +\n"); + printf(" Picture::operator==(const ::FLAC__StreamMetadata *)... "); + { + FLAC::Metadata::Picture blockcopy = &picture_; + if(!blockcopy.is_valid()) + return die_("!blockcopy.is_valid()"); + if(!(blockcopy == picture_)) + return die_("copy is not identical to original"); + printf("OK\n"); + } + + printf("testing Picture::get_type()... "); + if(block.get_type() != ::FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER) + return die_("value mismatch, expected ::FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER"); + printf("OK\n"); + + printf("testing Picture::set_type()... +\n"); + printf(" Picture::get_type()... "); + block.set_type(::FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA); + if(block.get_type() != ::FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA) + return die_("value mismatch, expected ::FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA"); + printf("OK\n"); + + printf("testing Picture::set_mime_type()... "); + if(!block.set_mime_type("qmage/jpeg")) + return die_("returned false"); + printf("OK\n"); + picture_.data.picture.mime_type[0] = 'q'; + + printf("testing Picture::get_mime_type()... "); + if(0 != strcmp(block.get_mime_type(), picture_.data.picture.mime_type)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Picture::set_description()... "); + if(!block.set_description((const FLAC__byte*)"qesc")) + return die_("returned false"); + printf("OK\n"); + picture_.data.picture.description[0] = 'q'; + + printf("testing Picture::get_description()... "); + if(0 != strcmp((const char *)block.get_description(), (const char *)picture_.data.picture.description)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing Picture::get_width()... "); + if(block.get_width() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing Picture::set_width()... +\n"); + printf(" Picture::get_width()... "); + block.set_width(400); + if(block.get_width() != 400) + return die_("value mismatch, expected 400"); + printf("OK\n"); + + printf("testing Picture::get_height()... "); + if(block.get_height() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing Picture::set_height()... +\n"); + printf(" Picture::get_height()... "); + block.set_height(200); + if(block.get_height() != 200) + return die_("value mismatch, expected 200"); + printf("OK\n"); + + printf("testing Picture::get_depth()... "); + if(block.get_depth() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing Picture::set_depth()... +\n"); + printf(" Picture::get_depth()... "); + block.set_depth(16); + if(block.get_depth() != 16) + return die_("value mismatch, expected 16"); + printf("OK\n"); + + printf("testing Picture::get_colors()... "); + if(block.get_colors() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing Picture::set_colors()... +\n"); + printf(" Picture::get_colors()... "); + block.set_colors(1u>16); + if(block.get_colors() != 1u>16) + return die_("value mismatch, expected 2^16"); + printf("OK\n"); + + printf("testing Picture::get_data_length()... "); + if(block.get_data_length() != 0) + return die_("value mismatch, expected 0"); + printf("OK\n"); + + printf("testing Picture::set_data()... "); + if(!block.set_data((const FLAC__byte*)"qOMEJPEGDATA", strlen("qOMEJPEGDATA"))) + return die_("returned false"); + printf("OK\n"); + picture_.data.picture.data[0] = 'q'; + + printf("testing Picture::get_data()... "); + if(block.get_data_length() != picture_.data.picture.data_length) + return die_("length mismatch"); + if(0 != memcmp(block.get_data(), picture_.data.picture.data, picture_.data.picture.data_length)) + return die_("value mismatch"); + printf("OK\n"); + + printf("testing FLAC::Metadata::clone(const FLAC::Metadata::Prototype *)... "); + FLAC::Metadata::Prototype *clone_ = FLAC::Metadata::clone(&block); + if(0 == clone_) + return die_("returned NULL"); + if(0 == dynamic_cast(clone_)) + return die_("downcast is NULL"); + if(*dynamic_cast(clone_) != block) + return die_("clone is not identical"); + printf("OK\n"); + printf("testing Picture::~Picture()... "); + delete clone_; + printf("OK\n"); + + + printf("PASSED\n\n"); + return true; +} + +bool test_metadata_object() +{ + printf("\n+++ libFLAC++ unit test: metadata objects\n\n"); + + init_metadata_blocks_(); + + if(!test_metadata_object_streaminfo()) + return false; + + if(!test_metadata_object_padding()) + return false; + + if(!test_metadata_object_application()) + return false; + + if(!test_metadata_object_seektable()) + return false; + + if(!test_metadata_object_vorbiscomment()) + return false; + + if(!test_metadata_object_cuesheet()) + return false; + + if(!test_metadata_object_picture()) + return false; + + free_metadata_blocks_(); + + return true; +} diff --git a/flac/src/test_libFLAC++/test_libFLAC++.dsp b/flac/src/test_libFLAC++/test_libFLAC++.dsp new file mode 100644 index 0000000..36bfd56 --- /dev/null +++ b/flac/src/test_libFLAC++/test_libFLAC++.dsp @@ -0,0 +1,136 @@ +# Microsoft Developer Studio Project File - Name="test_libFLAC++" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_libFLAC++ - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_libFLAC++.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_libFLAC++.mak" CFG="test_libFLAC++ - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_libFLAC++ - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_libFLAC++ - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_libFLAC++ - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\grabbag_static.lib ..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\obj\release\lib\test_libs_common_static.lib ..\..\obj\release\lib\libFLAC++_static.lib ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_libFLAC++ - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\grabbag_static.lib ..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\obj\debug\lib\test_libs_common_static.lib ..\..\obj\debug\lib\libFLAC++_static.lib ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_libFLAC++ - Win32 Release" +# Name "test_libFLAC++ - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\decoders.cpp +# End Source File +# Begin Source File + +SOURCE=.\encoders.cpp +# End Source File +# Begin Source File + +SOURCE=.\main.cpp +# End Source File +# Begin Source File + +SOURCE=.\metadata.cpp +# End Source File +# Begin Source File + +SOURCE=.\metadata_manip.cpp +# End Source File +# Begin Source File + +SOURCE=.\metadata_object.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\decoders.h +# End Source File +# Begin Source File + +SOURCE=.\encoders.h +# End Source File +# Begin Source File + +SOURCE=.\metadata.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\README +# End Source File +# End Target +# End Project diff --git a/flac/src/test_libFLAC++/test_libFLAC++.vcproj b/flac/src/test_libFLAC++/test_libFLAC++.vcproj new file mode 100644 index 0000000..fc7baa1 --- /dev/null +++ b/flac/src/test_libFLAC++/test_libFLAC++.vcproj @@ -0,0 +1,400 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_libFLAC/Makefile.am b/flac/src/test_libFLAC/Makefile.am new file mode 100644 index 0000000..31ae34a --- /dev/null +++ b/flac/src/test_libFLAC/Makefile.am @@ -0,0 +1,47 @@ +# test_libFLAC - Unit tester for libFLAC +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_libFLAC.dsp \ + test_libFLAC.vcproj + +INCLUDES = -I$(top_srcdir)/src/libFLAC/include + +noinst_PROGRAMS = test_libFLAC +test_libFLAC_LDADD = \ + $(top_builddir)/src/share/grabbag/libgrabbag.la \ + $(top_builddir)/src/share/replaygain_analysis/libreplaygain_analysis.la \ + $(top_builddir)/src/test_libs_common/libtest_libs_common.la \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +test_libFLAC_SOURCES = \ + bitwriter.c \ + decoders.c \ + encoders.c \ + format.c \ + main.c \ + metadata.c \ + metadata_manip.c \ + metadata_object.c \ + bitwriter.h \ + decoders.h \ + encoders.h \ + format.h \ + metadata.h diff --git a/flac/src/test_libFLAC/Makefile.lite b/flac/src/test_libFLAC/Makefile.lite new file mode 100644 index 0000000..b5da3a5 --- /dev/null +++ b/flac/src/test_libFLAC/Makefile.lite @@ -0,0 +1,47 @@ +# test_libFLAC - Unit tester for libFLAC +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_libFLAC + +INCLUDES = -I../libFLAC/include -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libgrabbag.a $(libdir)/libreplaygain_analysis.a $(libdir)/libtest_libs_common.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lgrabbag -lreplaygain_analysis -ltest_libs_common -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + bitwriter.c \ + decoders.c \ + encoders.c \ + format.c \ + main.c \ + metadata.c \ + metadata_manip.c \ + metadata_object.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_libFLAC/bitwriter.c b/flac/src/test_libFLAC/bitwriter.c new file mode 100644 index 0000000..54cc41c --- /dev/null +++ b/flac/src/test_libFLAC/bitwriter.c @@ -0,0 +1,584 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" +#include "private/bitwriter.h" /* from the libFLAC private include area */ +#include "bitwriter.h" +#include +#include /* for memcmp() */ + +/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */ +#ifdef _MSC_VER +#define FLAC__U64L(x) x +#else +#define FLAC__U64L(x) x##LLU +#endif + +/* + * WATCHOUT! Since FLAC__BitWriter is a private structure, we use a copy of + * the definition here to get at the internals. Make sure this is kept up + * to date with what is in ../libFLAC/bitwriter.c + */ +typedef FLAC__uint32 bwword; + +struct FLAC__BitWriter { + bwword *buffer; + bwword accum; /* accumulator; when full, accum is appended to buffer */ + unsigned capacity; /* of buffer in words */ + unsigned words; /* # of complete words in buffer */ + unsigned bits; /* # of used bits in accum */ +}; + +#define TOTAL_BITS(bw) ((bw)->words*sizeof(bwword)*8 + (bw)->bits) + + +FLAC__bool test_bitwriter(void) +{ + FLAC__BitWriter *bw; + FLAC__bool ok; + unsigned i, j; +#if WORDS_BIGENDIAN + static bwword test_pattern1[5] = { 0xaaf0aabe, 0xaaaaaaa8, 0x300aaaaa, 0xaaadeadb, 0x00eeface }; +#else + static bwword test_pattern1[5] = { 0xbeaaf0aa, 0xa8aaaaaa, 0xaaaa0a30, 0xdbeaadaa, 0x00eeface }; +#endif + unsigned words, bits; /* what we think bw->words and bw->bits should be */ + + printf("\n+++ libFLAC unit test: bitwriter\n\n"); + + /* + * test new -> delete + */ + printf("testing new... "); + bw = FLAC__bitwriter_new(); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing delete... "); + FLAC__bitwriter_delete(bw); + printf("OK\n"); + + /* + * test new -> init -> delete + */ + printf("testing new... "); + bw = FLAC__bitwriter_new(); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing init... "); + FLAC__bitwriter_init(bw); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing delete... "); + FLAC__bitwriter_delete(bw); + printf("OK\n"); + + /* + * test new -> init -> clear -> delete + */ + printf("testing new... "); + bw = FLAC__bitwriter_new(); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing init... "); + FLAC__bitwriter_init(bw); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing clear... "); + FLAC__bitwriter_clear(bw); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing delete... "); + FLAC__bitwriter_delete(bw); + printf("OK\n"); + + /* + * test normal usage + */ + printf("testing new... "); + bw = FLAC__bitwriter_new(); + if(0 == bw) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing init... "); + ok = FLAC__bitwriter_init(bw); + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) + return false; + + printf("testing clear... "); + FLAC__bitwriter_clear(bw); + printf("OK\n"); + + words = bits = 0; + + printf("capacity = %u\n", bw->capacity); + + printf("testing zeroes, raw_uint32*... "); + ok = + FLAC__bitwriter_write_raw_uint32(bw, 0x1, 1) && + FLAC__bitwriter_write_raw_uint32(bw, 0x1, 2) && + FLAC__bitwriter_write_raw_uint32(bw, 0xa, 5) && + FLAC__bitwriter_write_raw_uint32(bw, 0xf0, 8) && + FLAC__bitwriter_write_raw_uint32(bw, 0x2aa, 10) && + FLAC__bitwriter_write_raw_uint32(bw, 0xf, 4) && + FLAC__bitwriter_write_raw_uint32(bw, 0xaaaaaaaa, 32) && + FLAC__bitwriter_write_zeroes(bw, 4) && + FLAC__bitwriter_write_raw_uint32(bw, 0x3, 2) && + FLAC__bitwriter_write_zeroes(bw, 8) && + FLAC__bitwriter_write_raw_uint64(bw, FLAC__U64L(0xaaaaaaaadeadbeef), 64) && + FLAC__bitwriter_write_raw_uint32(bw, 0xace, 12) + ; + if(!ok) { + printf("FAILED\n"); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + words = 4; + bits = 24; + if(bw->words != words) { + printf("FAILED byte count %u != %u\n", bw->words, words); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if(bw->bits != bits) { + printf("FAILED bit count %u != %u\n", bw->bits, bits); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if(memcmp(bw->buffer, test_pattern1, sizeof(bwword)*words) != 0) { + printf("FAILED pattern match (buffer)\n"); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if((bw->accum & 0x00ffffff) != test_pattern1[words]) { + printf("FAILED pattern match (bw->accum=%08X != %08X)\n", bw->accum&0x00ffffff, test_pattern1[words]); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + printf("OK\n"); + FLAC__bitwriter_dump(bw, stdout); + + printf("testing raw_uint32 some more... "); + ok = FLAC__bitwriter_write_raw_uint32(bw, 0x3d, 6); + if(!ok) { + printf("FAILED\n"); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + bits += 6; + test_pattern1[words] <<= 6; + test_pattern1[words] |= 0x3d; + if(bw->words != words) { + printf("FAILED byte count %u != %u\n", bw->words, words); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if(bw->bits != bits) { + printf("FAILED bit count %u != %u\n", bw->bits, bits); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if(memcmp(bw->buffer, test_pattern1, sizeof(bwword)*words) != 0) { + printf("FAILED pattern match (buffer)\n"); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + if((bw->accum & 0x3fffffff) != test_pattern1[words]) { + printf("FAILED pattern match (bw->accum=%08X != %08X)\n", bw->accum&0x3fffffff, test_pattern1[words]); + FLAC__bitwriter_dump(bw, stdout); + return false; + } + printf("OK\n"); + FLAC__bitwriter_dump(bw, stdout); + + printf("testing utf8_uint32(0x00000000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x00000000); + ok = TOTAL_BITS(bw) == 8 && (bw->accum & 0xff) == 0; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x0000007F)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x0000007F); + ok = TOTAL_BITS(bw) == 8 && (bw->accum & 0xff) == 0x7F; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x00000080)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x00000080); + ok = TOTAL_BITS(bw) == 16 && (bw->accum & 0xffff) == 0xC280; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x000007FF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x000007FF); + ok = TOTAL_BITS(bw) == 16 && (bw->accum & 0xffff) == 0xDFBF; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x00000800)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x00000800); + ok = TOTAL_BITS(bw) == 24 && (bw->accum & 0xffffff) == 0xE0A080; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x0000FFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x0000FFFF); + ok = TOTAL_BITS(bw) == 24 && (bw->accum & 0xffffff) == 0xEFBFBF; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x00010000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x00010000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xF0908080; +#else + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0x808090F0; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x001FFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x001FFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xF7BFBFBF; +#else + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xBFBFBFF7; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x00200000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x00200000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xF8888080 && (bw->accum & 0xff) == 0x80; +#else + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0x808088F8 && (bw->accum & 0xff) == 0x80; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x03FFFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x03FFFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xFBBFBFBF && (bw->accum & 0xff) == 0xBF; +#else + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xBFBFBFFB && (bw->accum & 0xff) == 0xBF; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x04000000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x04000000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xFC848080 && (bw->accum & 0xffff) == 0x8080; +#else + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0x808084FC && (bw->accum & 0xffff) == 0x8080; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint32(0x7FFFFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint32(bw, 0x7FFFFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xFDBFBFBF && (bw->accum & 0xffff) == 0xBFBF; +#else + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xBFBFBFFD && (bw->accum & 0xffff) == 0xBFBF; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000000000000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000000000000); + ok = TOTAL_BITS(bw) == 8 && (bw->accum & 0xff) == 0; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x000000000000007F)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x000000000000007F); + ok = TOTAL_BITS(bw) == 8 && (bw->accum & 0xff) == 0x7F; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000000000080)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000000000080); + ok = TOTAL_BITS(bw) == 16 && (bw->accum & 0xffff) == 0xC280; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x00000000000007FF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x00000000000007FF); + ok = TOTAL_BITS(bw) == 16 && (bw->accum & 0xffff) == 0xDFBF; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000000000800)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000000000800); + ok = TOTAL_BITS(bw) == 24 && (bw->accum & 0xffffff) == 0xE0A080; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x000000000000FFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x000000000000FFFF); + ok = TOTAL_BITS(bw) == 24 && (bw->accum & 0xffffff) == 0xEFBFBF; + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000000010000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000000010000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xF0908080; +#else + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0x808090F0; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x00000000001FFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x00000000001FFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xF7BFBFBF; +#else + ok = TOTAL_BITS(bw) == 32 && bw->buffer[0] == 0xBFBFBFF7; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000000200000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000000200000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xF8888080 && (bw->accum & 0xff) == 0x80; +#else + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0x808088F8 && (bw->accum & 0xff) == 0x80; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000003FFFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000003FFFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xFBBFBFBF && (bw->accum & 0xff) == 0xBF; +#else + ok = TOTAL_BITS(bw) == 40 && bw->buffer[0] == 0xBFBFBFFB && (bw->accum & 0xff) == 0xBF; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000004000000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000004000000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xFC848080 && (bw->accum & 0xffff) == 0x8080; +#else + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0x808084FC && (bw->accum & 0xffff) == 0x8080; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x000000007FFFFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x000000007FFFFFFF); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xFDBFBFBF && (bw->accum & 0xffff) == 0xBFBF; +#else + ok = TOTAL_BITS(bw) == 48 && bw->buffer[0] == 0xBFBFBFFD && (bw->accum & 0xffff) == 0xBFBF; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000080000000)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, 0x0000000080000000); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 56 && bw->buffer[0] == 0xFE828080 && (bw->accum & 0xffffff) == 0x808080; +#else + ok = TOTAL_BITS(bw) == 56 && bw->buffer[0] == 0x808082FE && (bw->accum & 0xffffff) == 0x808080; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing utf8_uint64(0x0000000FFFFFFFFF)... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_utf8_uint64(bw, FLAC__U64L(0x0000000FFFFFFFFF)); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == 56 && bw->buffer[0] == 0xFEBFBFBF && (bw->accum & 0xffffff) == 0xBFBFBF; +#else + ok = TOTAL_BITS(bw) == 56 && bw->buffer[0] == 0xBFBFBFFE && (bw->accum & 0xffffff) == 0xBFBFBF; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + + printf("testing grow... "); + FLAC__bitwriter_clear(bw); + FLAC__bitwriter_write_raw_uint32(bw, 0x5, 4); + j = bw->capacity; + for(i = 0; i < j; i++) + FLAC__bitwriter_write_raw_uint32(bw, 0xaaaaaaaa, 32); +#if WORDS_BIGENDIAN + ok = TOTAL_BITS(bw) == i*32+4 && bw->buffer[0] == 0x5aaaaaaa && (bw->accum & 0xf) == 0xa; +#else + ok = TOTAL_BITS(bw) == i*32+4 && bw->buffer[0] == 0xaaaaaa5a && (bw->accum & 0xf) == 0xa; +#endif + printf("%s\n", ok?"OK":"FAILED"); + if(!ok) { + FLAC__bitwriter_dump(bw, stdout); + return false; + } + printf("capacity = %u\n", bw->capacity); + + printf("testing free... "); + FLAC__bitwriter_free(bw); + printf("OK\n"); + + printf("testing delete... "); + FLAC__bitwriter_delete(bw); + printf("OK\n"); + + printf("\nPASSED!\n"); + return true; +} diff --git a/flac/src/test_libFLAC/bitwriter.h b/flac/src/test_libFLAC/bitwriter.h new file mode 100644 index 0000000..4363f99 --- /dev/null +++ b/flac/src/test_libFLAC/bitwriter.h @@ -0,0 +1,26 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_BITBUFFER_H +#define FLAC__TEST_LIBFLAC_BITBUFFER_H + +#include "FLAC/ordinals.h" + +FLAC__bool test_bitwriter(void); + +#endif diff --git a/flac/src/test_libFLAC/decoders.c b/flac/src/test_libFLAC/decoders.c new file mode 100644 index 0000000..c8aac10 --- /dev/null +++ b/flac/src/test_libFLAC/decoders.c @@ -0,0 +1,1048 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif +#include "decoders.h" +#include "FLAC/assert.h" +#include "FLAC/stream_decoder.h" +#include "share/grabbag.h" +#include "test_libs_common/file_utils_flac.h" +#include "test_libs_common/metadata_utils.h" + +typedef enum { + LAYER_STREAM = 0, /* FLAC__stream_decoder_init_[ogg_]stream() without seeking */ + LAYER_SEEKABLE_STREAM, /* FLAC__stream_decoder_init_[ogg_]stream() with seeking */ + LAYER_FILE, /* FLAC__stream_decoder_init_[ogg_]FILE() */ + LAYER_FILENAME /* FLAC__stream_decoder_init_[ogg_]file() */ +} Layer; + +static const char * const LayerString[] = { + "Stream", + "Seekable Stream", + "FILE*", + "Filename" +}; + +typedef struct { + Layer layer; + FILE *file; + unsigned current_metadata_number; + FLAC__bool ignore_errors; + FLAC__bool error_occurred; +} StreamDecoderClientData; + +static FLAC__StreamMetadata streaminfo_, padding_, seektable_, application1_, application2_, vorbiscomment_, cuesheet_, picture_, unknown_; +static FLAC__StreamMetadata *expected_metadata_sequence_[9]; +static unsigned num_expected_; +static off_t flacfilesize_; + +static const char *flacfilename(FLAC__bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static FLAC__bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static FLAC__bool die_s_(const char *msg, const FLAC__StreamDecoder *decoder) +{ + FLAC__StreamDecoderState state = FLAC__stream_decoder_get_state(decoder); + + if(msg) + printf("FAILED, %s", msg); + else + printf("FAILED"); + + printf(", state = %u (%s)\n", (unsigned)state, FLAC__StreamDecoderStateString[state]); + + return false; +} + +static void init_metadata_blocks_(void) +{ + mutils__init_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static void free_metadata_blocks_(void) +{ + mutils__free_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static FLAC__bool generate_file_(FLAC__bool is_ogg) +{ + printf("\n\ngenerating %sFLAC file for decoder tests...\n", is_ogg? "Ogg ":""); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + /* WATCHOUT: for Ogg FLAC the encoder should move the VORBIS_COMMENT block to the front, right after STREAMINFO */ + + if(!file_utils__generate_flacfile(is_ogg, flacfilename(is_ogg), &flacfilesize_, 512 * 1024, &streaminfo_, expected_metadata_sequence_, num_expected_)) + return die_("creating the encoded file"); + + return true; +} + +static FLAC__StreamDecoderReadStatus stream_decoder_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + const size_t requested_bytes = *bytes; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in read callback is NULL\n"); + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + + if(feof(dcd->file)) { + *bytes = 0; + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + } + else if(requested_bytes > 0) { + *bytes = fread(buffer, 1, requested_bytes, dcd->file); + if(*bytes == 0) { + if(feof(dcd->file)) + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + } + else { + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + } + else + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */ +} + +static FLAC__StreamDecoderSeekStatus stream_decoder_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in seek callback is NULL\n"); + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + + if(fseeko(dcd->file, (off_t)absolute_byte_offset, SEEK_SET) < 0) { + dcd->error_occurred = true; + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + } + + return FLAC__STREAM_DECODER_SEEK_STATUS_OK; +} + +static FLAC__StreamDecoderTellStatus stream_decoder_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + off_t offset; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in tell callback is NULL\n"); + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + + offset = ftello(dcd->file); + *absolute_byte_offset = (FLAC__uint64)offset; + + if(offset < 0) { + dcd->error_occurred = true; + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + } + + return FLAC__STREAM_DECODER_TELL_STATUS_OK; +} + +static FLAC__StreamDecoderLengthStatus stream_decoder_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in length callback is NULL\n"); + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + + *stream_length = (FLAC__uint64)flacfilesize_; + return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; +} + +static FLAC__bool stream_decoder_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in eof callback is NULL\n"); + return true; + } + + if(dcd->error_occurred) + return true; + + return feof(dcd->file); +} + +static FLAC__StreamDecoderWriteStatus stream_decoder_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder, (void)buffer; + + if(0 == dcd) { + printf("ERROR: client_data in write callback is NULL\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + if( + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER && frame->header.number.frame_number == 0) || + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER && frame->header.number.sample_number == 0) + ) { + printf("content... "); + fflush(stdout); + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +static void stream_decoder_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in metadata callback is NULL\n"); + return; + } + + if(dcd->error_occurred) + return; + + printf("%d... ", dcd->current_metadata_number); + fflush(stdout); + + if(dcd->current_metadata_number >= num_expected_) { + (void)die_("got more metadata blocks than expected"); + dcd->error_occurred = true; + } + else { + if(!mutils__compare_block(expected_metadata_sequence_[dcd->current_metadata_number], metadata)) { + (void)die_("metadata block mismatch"); + dcd->error_occurred = true; + } + } + dcd->current_metadata_number++; +} + +static void stream_decoder_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + StreamDecoderClientData *dcd = (StreamDecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in error callback is NULL\n"); + return; + } + + if(!dcd->ignore_errors) { + printf("ERROR: got error callback: err = %u (%s)\n", (unsigned)status, FLAC__StreamDecoderErrorStatusString[status]); + dcd->error_occurred = true; + } +} + +static FLAC__bool stream_decoder_test_respond_(FLAC__StreamDecoder *decoder, StreamDecoderClientData *dcd, FLAC__bool is_ogg) +{ + FLAC__StreamDecoderInitStatus init_status; + + if(!FLAC__stream_decoder_set_md5_checking(decoder, true)) + return die_s_("at FLAC__stream_decoder_set_md5_checking(), returned false", decoder); + + /* for FLAC__stream_encoder_init_FILE(), the FLAC__stream_encoder_finish() closes the file so we have to keep re-opening: */ + if(dcd->layer == LAYER_FILE) { + printf("opening %sFLAC file... ", is_ogg? "Ogg ":""); + dcd->file = fopen(flacfilename(is_ogg), "rb"); + if(0 == dcd->file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + } + + switch(dcd->layer) { + case LAYER_STREAM: + printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) : + FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) + ; + break; + case LAYER_SEEKABLE_STREAM: + printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) : + FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd); + break; + case LAYER_FILE: + printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_FILE(decoder, dcd->file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) : + FLAC__stream_decoder_init_FILE(decoder, dcd->file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd); + break; + case LAYER_FILENAME: + printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) : + FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd); + break; + default: + die_("internal error 000"); + return false; + } + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, decoder); + printf("OK\n"); + + dcd->current_metadata_number = 0; + + if(dcd->layer < LAYER_FILE && fseeko(dcd->file, 0, SEEK_SET) < 0) { + printf("FAILED rewinding input, errno = %d\n", errno); + return false; + } + + printf("testing FLAC__stream_decoder_process_until_end_of_stream()... "); + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_finish()... "); + if(!FLAC__stream_decoder_finish(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + return true; +} + +static FLAC__bool test_stream_decoder(Layer layer, FLAC__bool is_ogg) +{ + FLAC__StreamDecoder *decoder; + FLAC__StreamDecoderInitStatus init_status; + FLAC__StreamDecoderState state; + StreamDecoderClientData decoder_client_data; + FLAC__bool expect; + + decoder_client_data.layer = layer; + + printf("\n+++ libFLAC unit test: FLAC__StreamDecoder (layer: %s, format: %s)\n\n", LayerString[layer], is_ogg? "Ogg FLAC" : "FLAC"); + + printf("testing FLAC__stream_decoder_new()... "); + decoder = FLAC__stream_decoder_new(); + if(0 == decoder) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_decoder_delete()... "); + FLAC__stream_decoder_delete(decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_new()... "); + decoder = FLAC__stream_decoder_new(); + if(0 == decoder) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + switch(layer) { + case LAYER_STREAM: + case LAYER_SEEKABLE_STREAM: + printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_stream(decoder, 0, 0, 0, 0, 0, 0, 0, 0, 0) : + FLAC__stream_decoder_init_stream(decoder, 0, 0, 0, 0, 0, 0, 0, 0, 0); + break; + case LAYER_FILE: + printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_FILE(decoder, stdin, 0, 0, 0, 0) : + FLAC__stream_decoder_init_FILE(decoder, stdin, 0, 0, 0, 0); + break; + case LAYER_FILENAME: + printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), 0, 0, 0, 0) : + FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), 0, 0, 0, 0); + break; + default: + die_("internal error 003"); + return false; + } + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS) + return die_s_(0, decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_delete()... "); + FLAC__stream_decoder_delete(decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + + printf("testing FLAC__stream_decoder_new()... "); + decoder = FLAC__stream_decoder_new(); + if(0 == decoder) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + if(is_ogg) { + printf("testing FLAC__stream_decoder_set_ogg_serial_number()... "); + if(!FLAC__stream_decoder_set_ogg_serial_number(decoder, file_utils__ogg_serial_number)) + return die_s_("returned false", decoder); + printf("OK\n"); + } + + printf("testing FLAC__stream_decoder_set_md5_checking()... "); + if(!FLAC__stream_decoder_set_md5_checking(decoder, true)) + return die_s_("returned false", decoder); + printf("OK\n"); + + if(layer < LAYER_FILENAME) { + printf("opening %sFLAC file... ", is_ogg? "Ogg ":""); + decoder_client_data.file = fopen(flacfilename(is_ogg), "rb"); + if(0 == decoder_client_data.file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + } + + switch(layer) { + case LAYER_STREAM: + printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) : + FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data); + break; + case LAYER_SEEKABLE_STREAM: + printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) : + FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data); + break; + case LAYER_FILE: + printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_FILE(decoder, decoder_client_data.file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) : + FLAC__stream_decoder_init_FILE(decoder, decoder_client_data.file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data); + break; + case LAYER_FILENAME: + printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) : + FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data); + break; + default: + die_("internal error 009"); + return false; + } + if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_(0, decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_get_state()... "); + state = FLAC__stream_decoder_get_state(decoder); + printf("returned state = %u (%s)... OK\n", state, FLAC__StreamDecoderStateString[state]); + + decoder_client_data.current_metadata_number = 0; + decoder_client_data.ignore_errors = false; + decoder_client_data.error_occurred = false; + + printf("testing FLAC__stream_decoder_get_md5_checking()... "); + if(!FLAC__stream_decoder_get_md5_checking(decoder)) { + printf("FAILED, returned false, expected true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_decoder_process_until_end_of_metadata()... "); + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_process_single()... "); + if(!FLAC__stream_decoder_process_single(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_skip_single_frame()... "); + if(!FLAC__stream_decoder_skip_single_frame(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + if(layer < LAYER_FILE) { + printf("testing FLAC__stream_decoder_flush()... "); + if(!FLAC__stream_decoder_flush(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + decoder_client_data.ignore_errors = true; + printf("testing FLAC__stream_decoder_process_single()... "); + if(!FLAC__stream_decoder_process_single(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + decoder_client_data.ignore_errors = false; + } + + expect = (layer != LAYER_STREAM); + printf("testing FLAC__stream_decoder_seek_absolute()... "); + if(FLAC__stream_decoder_seek_absolute(decoder, 0) != expect) + return die_s_(expect? "returned false" : "returned true", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_process_until_end_of_stream()... "); + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + expect = (layer != LAYER_STREAM); + printf("testing FLAC__stream_decoder_seek_absolute()... "); + if(FLAC__stream_decoder_seek_absolute(decoder, 0) != expect) + return die_s_(expect? "returned false" : "returned true", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_get_channels()... "); + { + unsigned channels = FLAC__stream_decoder_get_channels(decoder); + if(channels != streaminfo_.data.stream_info.channels) { + printf("FAILED, returned %u, expected %u\n", channels, streaminfo_.data.stream_info.channels); + return false; + } + } + printf("OK\n"); + + printf("testing FLAC__stream_decoder_get_bits_per_sample()... "); + { + unsigned bits_per_sample = FLAC__stream_decoder_get_bits_per_sample(decoder); + if(bits_per_sample != streaminfo_.data.stream_info.bits_per_sample) { + printf("FAILED, returned %u, expected %u\n", bits_per_sample, streaminfo_.data.stream_info.bits_per_sample); + return false; + } + } + printf("OK\n"); + + printf("testing FLAC__stream_decoder_get_sample_rate()... "); + { + unsigned sample_rate = FLAC__stream_decoder_get_sample_rate(decoder); + if(sample_rate != streaminfo_.data.stream_info.sample_rate) { + printf("FAILED, returned %u, expected %u\n", sample_rate, streaminfo_.data.stream_info.sample_rate); + return false; + } + } + printf("OK\n"); + + printf("testing FLAC__stream_decoder_get_blocksize()... "); + { + unsigned blocksize = FLAC__stream_decoder_get_blocksize(decoder); + /* value could be anything since we're at the last block, so accept any reasonable answer */ + printf("returned %u... %s\n", blocksize, blocksize>0? "OK" : "FAILED"); + if(blocksize == 0) + return false; + } + + printf("testing FLAC__stream_decoder_get_channel_assignment()... "); + { + FLAC__ChannelAssignment ca = FLAC__stream_decoder_get_channel_assignment(decoder); + printf("returned %u (%s)... OK\n", (unsigned)ca, FLAC__ChannelAssignmentString[ca]); + } + + if(layer < LAYER_FILE) { + printf("testing FLAC__stream_decoder_reset()... "); + if(!FLAC__stream_decoder_reset(decoder)) { + state = FLAC__stream_decoder_get_state(decoder); + printf("FAILED, returned false, state = %u (%s)\n", state, FLAC__StreamDecoderStateString[state]); + return false; + } + printf("OK\n"); + + if(layer == LAYER_STREAM) { + /* after a reset() we have to rewind the input ourselves */ + printf("rewinding input... "); + if(fseeko(decoder_client_data.file, 0, SEEK_SET) < 0) { + printf("FAILED, errno = %d\n", errno); + return false; + } + printf("OK\n"); + } + + decoder_client_data.current_metadata_number = 0; + + printf("testing FLAC__stream_decoder_process_until_end_of_stream()... "); + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + } + + printf("testing FLAC__stream_decoder_finish()... "); + if(!FLAC__stream_decoder_finish(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + /* + * respond all + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * respond all, ignore VORBIS_COMMENT + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore(VORBIS_COMMENT)... "); + if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * respond all, ignore APPLICATION + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore(APPLICATION)... "); + if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_APPLICATION)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * respond all, ignore APPLICATION id of app#1 + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application2_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * respond all, ignore APPLICATION id of app#1 & app#2 + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #2)... "); + if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application2_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all, respond VORBIS_COMMENT + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond(VORBIS_COMMENT)... "); + if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all, respond APPLICATION + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond(APPLICATION)... "); + if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_APPLICATION)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all, respond APPLICATION id of app#1 + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all, respond APPLICATION id of app#1 & app#2 + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #2)... "); + if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application2_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * respond all, ignore APPLICATION, respond APPLICATION id of app#1 + */ + + printf("testing FLAC__stream_decoder_set_metadata_respond_all()... "); + if(!FLAC__stream_decoder_set_metadata_respond_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore(APPLICATION)... "); + if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_APPLICATION)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */ + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + else { + expected_metadata_sequence_[num_expected_++] = &streaminfo_; + expected_metadata_sequence_[num_expected_++] = &padding_; + expected_metadata_sequence_[num_expected_++] = &seektable_; + expected_metadata_sequence_[num_expected_++] = &application1_; + expected_metadata_sequence_[num_expected_++] = &vorbiscomment_; + expected_metadata_sequence_[num_expected_++] = &cuesheet_; + expected_metadata_sequence_[num_expected_++] = &picture_; + expected_metadata_sequence_[num_expected_++] = &unknown_; + } + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + /* + * ignore all, respond APPLICATION, ignore APPLICATION id of app#1 + */ + + printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... "); + if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_respond(APPLICATION)... "); + if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_APPLICATION)) + return die_s_("returned false", decoder); + printf("OK\n"); + + printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... "); + if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id)) + return die_s_("returned false", decoder); + printf("OK\n"); + + num_expected_ = 0; + expected_metadata_sequence_[num_expected_++] = &application2_; + + if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg)) + return false; + + if(layer < LAYER_FILE) /* for LAYER_FILE, FLAC__stream_decoder_finish() closes the file */ + fclose(decoder_client_data.file); + + printf("testing FLAC__stream_decoder_delete()... "); + FLAC__stream_decoder_delete(decoder); + printf("OK\n"); + + printf("\nPASSED!\n"); + + return true; +} + +FLAC__bool test_decoders(void) +{ + FLAC__bool is_ogg = false; + + while(1) { + init_metadata_blocks_(); + + if(!generate_file_(is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_STREAM, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_SEEKABLE_STREAM, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_FILE, is_ogg)) + return false; + + if(!test_stream_decoder(LAYER_FILENAME, is_ogg)) + return false; + + (void) grabbag__file_remove_file(flacfilename(is_ogg)); + + free_metadata_blocks_(); + + if(!FLAC_API_SUPPORTS_OGG_FLAC || is_ogg) + break; + is_ogg = true; + } + + return true; +} diff --git a/flac/src/test_libFLAC/decoders.h b/flac/src/test_libFLAC/decoders.h new file mode 100644 index 0000000..cbe421e --- /dev/null +++ b/flac/src/test_libFLAC/decoders.h @@ -0,0 +1,26 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_DECODERS_H +#define FLAC__TEST_LIBFLAC_DECODERS_H + +#include "FLAC/ordinals.h" + +FLAC__bool test_decoders(void); + +#endif diff --git a/flac/src/test_libFLAC/encoders.c b/flac/src/test_libFLAC/encoders.c new file mode 100644 index 0000000..798ba92 --- /dev/null +++ b/flac/src/test_libFLAC/encoders.c @@ -0,0 +1,521 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include "encoders.h" +#include "FLAC/assert.h" +#include "FLAC/stream_encoder.h" +#include "share/grabbag.h" +#include "test_libs_common/file_utils_flac.h" +#include "test_libs_common/metadata_utils.h" + +typedef enum { + LAYER_STREAM = 0, /* FLAC__stream_encoder_init_[ogg_]stream() without seeking */ + LAYER_SEEKABLE_STREAM, /* FLAC__stream_encoder_init_[ogg_]stream() with seeking */ + LAYER_FILE, /* FLAC__stream_encoder_init_[ogg_]FILE() */ + LAYER_FILENAME /* FLAC__stream_encoder_init_[ogg_]file() */ +} Layer; + +static const char * const LayerString[] = { + "Stream", + "Seekable Stream", + "FILE*", + "Filename" +}; + +static FLAC__StreamMetadata streaminfo_, padding_, seektable_, application1_, application2_, vorbiscomment_, cuesheet_, picture_, unknown_; +static FLAC__StreamMetadata *metadata_sequence_[] = { &vorbiscomment_, &padding_, &seektable_, &application1_, &application2_, &cuesheet_, &picture_, &unknown_ }; +static const unsigned num_metadata_ = sizeof(metadata_sequence_) / sizeof(metadata_sequence_[0]); + +static const char *flacfilename(FLAC__bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static FLAC__bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static FLAC__bool die_s_(const char *msg, const FLAC__StreamEncoder *encoder) +{ + FLAC__StreamEncoderState state = FLAC__stream_encoder_get_state(encoder); + + if(msg) + printf("FAILED, %s", msg); + else + printf("FAILED"); + + printf(", state = %u (%s)\n", (unsigned)state, FLAC__StreamEncoderStateString[state]); + if(state == FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) { + FLAC__StreamDecoderState dstate = FLAC__stream_encoder_get_verify_decoder_state(encoder); + printf(" verify decoder state = %u (%s)\n", (unsigned)dstate, FLAC__StreamDecoderStateString[dstate]); + } + + return false; +} + +static void init_metadata_blocks_(void) +{ + mutils__init_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static void free_metadata_blocks_(void) +{ + mutils__free_metadata_blocks(&streaminfo_, &padding_, &seektable_, &application1_, &application2_, &vorbiscomment_, &cuesheet_, &picture_, &unknown_); +} + +static FLAC__StreamEncoderReadStatus stream_encoder_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data) +{ + FILE *f = (FILE*)client_data; + (void)encoder; + if(*bytes > 0) { + *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, f); + if(ferror(f)) + return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; + else if(*bytes == 0) + return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM; + else + return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE; + } + else + return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; +} + +static FLAC__StreamEncoderWriteStatus stream_encoder_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) +{ + FILE *f = (FILE*)client_data; + (void)encoder, (void)samples, (void)current_frame; + if(fwrite(buffer, 1, bytes, f) != bytes) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + else + return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; +} + +static FLAC__StreamEncoderSeekStatus stream_encoder_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) +{ + FILE *f = (FILE*)client_data; + (void)encoder; + if(fseek(f, (long)absolute_byte_offset, SEEK_SET) < 0) + return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; + else + return FLAC__STREAM_ENCODER_SEEK_STATUS_OK; +} + +static FLAC__StreamEncoderTellStatus stream_encoder_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) +{ + FILE *f = (FILE*)client_data; + long pos; + (void)encoder; + if((pos = ftell(f)) < 0) + return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR; + else { + *absolute_byte_offset = (FLAC__uint64)pos; + return FLAC__STREAM_ENCODER_TELL_STATUS_OK; + } +} + +static void stream_encoder_metadata_callback_(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + (void)encoder, (void)metadata, (void)client_data; +} + +static void stream_encoder_progress_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data) +{ + (void)encoder, (void)bytes_written, (void)samples_written, (void)frames_written, (void)total_frames_estimate, (void)client_data; +} + +static FLAC__bool test_stream_encoder(Layer layer, FLAC__bool is_ogg) +{ + FLAC__StreamEncoder *encoder; + FLAC__StreamEncoderInitStatus init_status; + FLAC__StreamEncoderState state; + FLAC__StreamDecoderState dstate; + FILE *file = 0; + FLAC__int32 samples[1024]; + FLAC__int32 *samples_array[1]; + unsigned i; + + samples_array[0] = samples; + + printf("\n+++ libFLAC unit test: FLAC__StreamEncoder (layer: %s, format: %s)\n\n", LayerString[layer], is_ogg? "Ogg FLAC":"FLAC"); + + printf("testing FLAC__stream_encoder_new()... "); + encoder = FLAC__stream_encoder_new(); + if(0 == encoder) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + if(is_ogg) { + printf("testing FLAC__stream_encoder_set_ogg_serial_number()... "); + if(!FLAC__stream_encoder_set_ogg_serial_number(encoder, file_utils__ogg_serial_number)) + return die_s_("returned false", encoder); + printf("OK\n"); + } + + printf("testing FLAC__stream_encoder_set_verify()... "); + if(!FLAC__stream_encoder_set_verify(encoder, true)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_streamable_subset()... "); + if(!FLAC__stream_encoder_set_streamable_subset(encoder, true)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_channels()... "); + if(!FLAC__stream_encoder_set_channels(encoder, streaminfo_.data.stream_info.channels)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_bits_per_sample()... "); + if(!FLAC__stream_encoder_set_bits_per_sample(encoder, streaminfo_.data.stream_info.bits_per_sample)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_sample_rate()... "); + if(!FLAC__stream_encoder_set_sample_rate(encoder, streaminfo_.data.stream_info.sample_rate)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_compression_level()... "); + if(!FLAC__stream_encoder_set_compression_level(encoder, (unsigned)(-1))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_blocksize()... "); + if(!FLAC__stream_encoder_set_blocksize(encoder, streaminfo_.data.stream_info.min_blocksize)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_do_mid_side_stereo()... "); + if(!FLAC__stream_encoder_set_do_mid_side_stereo(encoder, false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_loose_mid_side_stereo()... "); + if(!FLAC__stream_encoder_set_loose_mid_side_stereo(encoder, false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_max_lpc_order()... "); + if(!FLAC__stream_encoder_set_max_lpc_order(encoder, 0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_qlp_coeff_precision()... "); + if(!FLAC__stream_encoder_set_qlp_coeff_precision(encoder, 0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_do_qlp_coeff_prec_search()... "); + if(!FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder, false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_do_escape_coding()... "); + if(!FLAC__stream_encoder_set_do_escape_coding(encoder, false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_do_exhaustive_model_search()... "); + if(!FLAC__stream_encoder_set_do_exhaustive_model_search(encoder, false)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_min_residual_partition_order()... "); + if(!FLAC__stream_encoder_set_min_residual_partition_order(encoder, 0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_max_residual_partition_order()... "); + if(!FLAC__stream_encoder_set_max_residual_partition_order(encoder, 0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_rice_parameter_search_dist()... "); + if(!FLAC__stream_encoder_set_rice_parameter_search_dist(encoder, 0)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_total_samples_estimate()... "); + if(!FLAC__stream_encoder_set_total_samples_estimate(encoder, streaminfo_.data.stream_info.total_samples)) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_set_metadata()... "); + if(!FLAC__stream_encoder_set_metadata(encoder, metadata_sequence_, num_metadata_)) + return die_s_("returned false", encoder); + printf("OK\n"); + + if(layer < LAYER_FILENAME) { + printf("opening file for FLAC output... "); + file = fopen(flacfilename(is_ogg), "w+b"); + if(0 == file) { + printf("ERROR (%s)\n", strerror(errno)); + return false; + } + printf("OK\n"); + } + + switch(layer) { + case LAYER_STREAM: + printf("testing FLAC__stream_encoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_encoder_init_ogg_stream(encoder, /*read_callback=*/0, stream_encoder_write_callback_, /*seek_callback=*/0, /*tell_callback=*/0, stream_encoder_metadata_callback_, /*client_data=*/file) : + FLAC__stream_encoder_init_stream(encoder, stream_encoder_write_callback_, /*seek_callback=*/0, /*tell_callback=*/0, stream_encoder_metadata_callback_, /*client_data=*/file); + break; + case LAYER_SEEKABLE_STREAM: + printf("testing FLAC__stream_encoder_init_%sstream()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_encoder_init_ogg_stream(encoder, stream_encoder_read_callback_, stream_encoder_write_callback_, stream_encoder_seek_callback_, stream_encoder_tell_callback_, /*metadata_callback=*/0, /*client_data=*/file) : + FLAC__stream_encoder_init_stream(encoder, stream_encoder_write_callback_, stream_encoder_seek_callback_, stream_encoder_tell_callback_, /*metadata_callback=*/0, /*client_data=*/file); + break; + case LAYER_FILE: + printf("testing FLAC__stream_encoder_init_%sFILE()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_encoder_init_ogg_FILE(encoder, file, stream_encoder_progress_callback_, /*client_data=*/0) : + FLAC__stream_encoder_init_FILE(encoder, file, stream_encoder_progress_callback_, /*client_data=*/0); + break; + case LAYER_FILENAME: + printf("testing FLAC__stream_encoder_init_%sfile()... ", is_ogg? "ogg_":""); + init_status = is_ogg? + FLAC__stream_encoder_init_ogg_file(encoder, flacfilename(is_ogg), stream_encoder_progress_callback_, /*client_data=*/0) : + FLAC__stream_encoder_init_file(encoder, flacfilename(is_ogg), stream_encoder_progress_callback_, /*client_data=*/0); + break; + default: + die_("internal error 001"); + return false; + } + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) + return die_s_(0, encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_state()... "); + state = FLAC__stream_encoder_get_state(encoder); + printf("returned state = %u (%s)... OK\n", (unsigned)state, FLAC__StreamEncoderStateString[state]); + + printf("testing FLAC__stream_encoder_get_verify_decoder_state()... "); + dstate = FLAC__stream_encoder_get_verify_decoder_state(encoder); + printf("returned state = %u (%s)... OK\n", (unsigned)dstate, FLAC__StreamDecoderStateString[dstate]); + + { + FLAC__uint64 absolute_sample; + unsigned frame_number; + unsigned channel; + unsigned sample; + FLAC__int32 expected; + FLAC__int32 got; + + printf("testing FLAC__stream_encoder_get_verify_decoder_error_stats()... "); + FLAC__stream_encoder_get_verify_decoder_error_stats(encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got); + printf("OK\n"); + } + + printf("testing FLAC__stream_encoder_get_verify()... "); + if(FLAC__stream_encoder_get_verify(encoder) != true) { + printf("FAILED, expected true, got false\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_streamable_subset()... "); + if(FLAC__stream_encoder_get_streamable_subset(encoder) != true) { + printf("FAILED, expected true, got false\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_do_mid_side_stereo()... "); + if(FLAC__stream_encoder_get_do_mid_side_stereo(encoder) != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_loose_mid_side_stereo()... "); + if(FLAC__stream_encoder_get_loose_mid_side_stereo(encoder) != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_channels()... "); + if(FLAC__stream_encoder_get_channels(encoder) != streaminfo_.data.stream_info.channels) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.channels, FLAC__stream_encoder_get_channels(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_bits_per_sample()... "); + if(FLAC__stream_encoder_get_bits_per_sample(encoder) != streaminfo_.data.stream_info.bits_per_sample) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.bits_per_sample, FLAC__stream_encoder_get_bits_per_sample(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_sample_rate()... "); + if(FLAC__stream_encoder_get_sample_rate(encoder) != streaminfo_.data.stream_info.sample_rate) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.sample_rate, FLAC__stream_encoder_get_sample_rate(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_blocksize()... "); + if(FLAC__stream_encoder_get_blocksize(encoder) != streaminfo_.data.stream_info.min_blocksize) { + printf("FAILED, expected %u, got %u\n", streaminfo_.data.stream_info.min_blocksize, FLAC__stream_encoder_get_blocksize(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_max_lpc_order()... "); + if(FLAC__stream_encoder_get_max_lpc_order(encoder) != 0) { + printf("FAILED, expected %u, got %u\n", 0, FLAC__stream_encoder_get_max_lpc_order(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_qlp_coeff_precision()... "); + (void)FLAC__stream_encoder_get_qlp_coeff_precision(encoder); + /* we asked the encoder to auto select this so we accept anything */ + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_do_qlp_coeff_prec_search()... "); + if(FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder) != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_do_escape_coding()... "); + if(FLAC__stream_encoder_get_do_escape_coding(encoder) != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_do_exhaustive_model_search()... "); + if(FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) != false) { + printf("FAILED, expected false, got true\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_min_residual_partition_order()... "); + if(FLAC__stream_encoder_get_min_residual_partition_order(encoder) != 0) { + printf("FAILED, expected %u, got %u\n", 0, FLAC__stream_encoder_get_min_residual_partition_order(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_max_residual_partition_order()... "); + if(FLAC__stream_encoder_get_max_residual_partition_order(encoder) != 0) { + printf("FAILED, expected %u, got %u\n", 0, FLAC__stream_encoder_get_max_residual_partition_order(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_rice_parameter_search_dist()... "); + if(FLAC__stream_encoder_get_rice_parameter_search_dist(encoder) != 0) { + printf("FAILED, expected %u, got %u\n", 0, FLAC__stream_encoder_get_rice_parameter_search_dist(encoder)); + return false; + } + printf("OK\n"); + + printf("testing FLAC__stream_encoder_get_total_samples_estimate()... "); + if(FLAC__stream_encoder_get_total_samples_estimate(encoder) != streaminfo_.data.stream_info.total_samples) { +#ifdef _MSC_VER + printf("FAILED, expected %I64u, got %I64u\n", streaminfo_.data.stream_info.total_samples, FLAC__stream_encoder_get_total_samples_estimate(encoder)); +#else + printf("FAILED, expected %llu, got %llu\n", (unsigned long long)streaminfo_.data.stream_info.total_samples, (unsigned long long)FLAC__stream_encoder_get_total_samples_estimate(encoder)); +#endif + return false; + } + printf("OK\n"); + + /* init the dummy sample buffer */ + for(i = 0; i < sizeof(samples) / sizeof(FLAC__int32); i++) + samples[i] = i & 7; + + printf("testing FLAC__stream_encoder_process()... "); + if(!FLAC__stream_encoder_process(encoder, (const FLAC__int32 * const *)samples_array, sizeof(samples) / sizeof(FLAC__int32))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_process_interleaved()... "); + if(!FLAC__stream_encoder_process_interleaved(encoder, samples, sizeof(samples) / sizeof(FLAC__int32))) + return die_s_("returned false", encoder); + printf("OK\n"); + + printf("testing FLAC__stream_encoder_finish()... "); + if(!FLAC__stream_encoder_finish(encoder)) + return die_s_("returned false", encoder); + printf("OK\n"); + + if(layer < LAYER_FILE) + fclose(file); + + printf("testing FLAC__stream_encoder_delete()... "); + FLAC__stream_encoder_delete(encoder); + printf("OK\n"); + + printf("\nPASSED!\n"); + + return true; +} + +FLAC__bool test_encoders(void) +{ + FLAC__bool is_ogg = false; + + while(1) { + init_metadata_blocks_(); + + if(!test_stream_encoder(LAYER_STREAM, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_SEEKABLE_STREAM, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_FILE, is_ogg)) + return false; + + if(!test_stream_encoder(LAYER_FILENAME, is_ogg)) + return false; + + (void) grabbag__file_remove_file(flacfilename(is_ogg)); + + free_metadata_blocks_(); + + if(!FLAC_API_SUPPORTS_OGG_FLAC || is_ogg) + break; + is_ogg = true; + } + + return true; +} diff --git a/flac/src/test_libFLAC/encoders.h b/flac/src/test_libFLAC/encoders.h new file mode 100644 index 0000000..d7e9077 --- /dev/null +++ b/flac/src/test_libFLAC/encoders.h @@ -0,0 +1,26 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_ENCODERS_H +#define FLAC__TEST_LIBFLAC_ENCODERS_H + +#include "FLAC/ordinals.h" + +FLAC__bool test_encoders(void); + +#endif diff --git a/flac/src/test_libFLAC/format.c b/flac/src/test_libFLAC/format.c new file mode 100644 index 0000000..eae5dd5 --- /dev/null +++ b/flac/src/test_libFLAC/format.c @@ -0,0 +1,256 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" +#include "FLAC/format.h" +#include "format.h" +#include + +static const char *true_false_string_[2] = { "false", "true" }; + +static struct { + unsigned rate; + FLAC__bool valid; + FLAC__bool subset; +} SAMPLE_RATES[] = { + { 0 , false, false }, + { 1 , true , true }, + { 9 , true , true }, + { 10 , true , true }, + { 4000 , true , true }, + { 8000 , true , true }, + { 11025 , true , true }, + { 12000 , true , true }, + { 16000 , true , true }, + { 22050 , true , true }, + { 24000 , true , true }, + { 32000 , true , true }, + { 32768 , true , true }, + { 44100 , true , true }, + { 48000 , true , true }, + { 65000 , true , true }, + { 65535 , true , true }, + { 65536 , true , false }, + { 65540 , true , true }, + { 65550 , true , true }, + { 65555 , true , false }, + { 66000 , true , true }, + { 66001 , true , false }, + { 96000 , true , true }, + { 100000 , true , true }, + { 100001 , true , false }, + { 192000 , true , true }, + { 500000 , true , true }, + { 500001 , true , false }, + { 500010 , true , true }, + { 655349 , true , false }, + { 655350 , true , true }, + { 655351 , false, false }, + { 655360 , false, false }, + { 700000 , false, false }, + { 700010 , false, false }, + { 1000000, false, false }, + { 1100000, false, false } +}; + +static struct { + const char *string; + FLAC__bool valid; +} VCENTRY_NAMES[] = { + { "" , true }, + { "a" , true }, + { "=" , false }, + { "a=" , false }, + { "\x01", false }, + { "\x1f", false }, + { "\x7d", true }, + { "\x7e", false }, + { "\xff", false } +}; + +static struct { + unsigned length; + const FLAC__byte *string; + FLAC__bool valid; +} VCENTRY_VALUES[] = { + { 0, (const FLAC__byte*)"" , true }, + { 1, (const FLAC__byte*)"" , true }, + { 1, (const FLAC__byte*)"\x01" , true }, + { 1, (const FLAC__byte*)"\x7f" , true }, + { 1, (const FLAC__byte*)"\x80" , false }, + { 1, (const FLAC__byte*)"\x81" , false }, + { 1, (const FLAC__byte*)"\xc0" , false }, + { 1, (const FLAC__byte*)"\xe0" , false }, + { 1, (const FLAC__byte*)"\xf0" , false }, + { 2, (const FLAC__byte*)"\xc0\x41" , false }, + { 2, (const FLAC__byte*)"\xc1\x41" , false }, + { 2, (const FLAC__byte*)"\xc0\x85" , false }, /* non-shortest form */ + { 2, (const FLAC__byte*)"\xc1\x85" , false }, /* non-shortest form */ + { 2, (const FLAC__byte*)"\xc2\x85" , true }, + { 2, (const FLAC__byte*)"\xe0\x41" , false }, + { 2, (const FLAC__byte*)"\xe1\x41" , false }, + { 2, (const FLAC__byte*)"\xe0\x85" , false }, + { 2, (const FLAC__byte*)"\xe1\x85" , false }, + { 3, (const FLAC__byte*)"\xe0\x85\x41", false }, + { 3, (const FLAC__byte*)"\xe1\x85\x41", false }, + { 3, (const FLAC__byte*)"\xe0\x85\x80", false }, /* non-shortest form */ + { 3, (const FLAC__byte*)"\xe0\x95\x80", false }, /* non-shortest form */ + { 3, (const FLAC__byte*)"\xe0\xa5\x80", true }, + { 3, (const FLAC__byte*)"\xe1\x85\x80", true }, + { 3, (const FLAC__byte*)"\xe1\x95\x80", true }, + { 3, (const FLAC__byte*)"\xe1\xa5\x80", true } +}; + +static struct { + const FLAC__byte *string; + FLAC__bool valid; +} VCENTRY_VALUES_NT[] = { + { (const FLAC__byte*)"" , true }, + { (const FLAC__byte*)"\x01" , true }, + { (const FLAC__byte*)"\x7f" , true }, + { (const FLAC__byte*)"\x80" , false }, + { (const FLAC__byte*)"\x81" , false }, + { (const FLAC__byte*)"\xc0" , false }, + { (const FLAC__byte*)"\xe0" , false }, + { (const FLAC__byte*)"\xf0" , false }, + { (const FLAC__byte*)"\xc0\x41" , false }, + { (const FLAC__byte*)"\xc1\x41" , false }, + { (const FLAC__byte*)"\xc0\x85" , false }, /* non-shortest form */ + { (const FLAC__byte*)"\xc1\x85" , false }, /* non-shortest form */ + { (const FLAC__byte*)"\xc2\x85" , true }, + { (const FLAC__byte*)"\xe0\x41" , false }, + { (const FLAC__byte*)"\xe1\x41" , false }, + { (const FLAC__byte*)"\xe0\x85" , false }, + { (const FLAC__byte*)"\xe1\x85" , false }, + { (const FLAC__byte*)"\xe0\x85\x41", false }, + { (const FLAC__byte*)"\xe1\x85\x41", false }, + { (const FLAC__byte*)"\xe0\x85\x80", false }, /* non-shortest form */ + { (const FLAC__byte*)"\xe0\x95\x80", false }, /* non-shortest form */ + { (const FLAC__byte*)"\xe0\xa5\x80", true }, + { (const FLAC__byte*)"\xe1\x85\x80", true }, + { (const FLAC__byte*)"\xe1\x95\x80", true }, + { (const FLAC__byte*)"\xe1\xa5\x80", true } +}; + +static struct { + unsigned length; + const FLAC__byte *string; + FLAC__bool valid; +} VCENTRIES[] = { + { 0, (const FLAC__byte*)"" , false }, + { 1, (const FLAC__byte*)"a" , false }, + { 1, (const FLAC__byte*)"=" , true }, + { 2, (const FLAC__byte*)"a=" , true }, + { 2, (const FLAC__byte*)"\x01=" , false }, + { 2, (const FLAC__byte*)"\x1f=" , false }, + { 2, (const FLAC__byte*)"\x7d=" , true }, + { 2, (const FLAC__byte*)"\x7e=" , false }, + { 2, (const FLAC__byte*)"\xff=" , false }, + { 3, (const FLAC__byte*)"a=\x01" , true }, + { 3, (const FLAC__byte*)"a=\x7f" , true }, + { 3, (const FLAC__byte*)"a=\x80" , false }, + { 3, (const FLAC__byte*)"a=\x81" , false }, + { 3, (const FLAC__byte*)"a=\xc0" , false }, + { 3, (const FLAC__byte*)"a=\xe0" , false }, + { 3, (const FLAC__byte*)"a=\xf0" , false }, + { 4, (const FLAC__byte*)"a=\xc0\x41" , false }, + { 4, (const FLAC__byte*)"a=\xc1\x41" , false }, + { 4, (const FLAC__byte*)"a=\xc0\x85" , false }, /* non-shortest form */ + { 4, (const FLAC__byte*)"a=\xc1\x85" , false }, /* non-shortest form */ + { 4, (const FLAC__byte*)"a=\xc2\x85" , true }, + { 4, (const FLAC__byte*)"a=\xe0\x41" , false }, + { 4, (const FLAC__byte*)"a=\xe1\x41" , false }, + { 4, (const FLAC__byte*)"a=\xe0\x85" , false }, + { 4, (const FLAC__byte*)"a=\xe1\x85" , false }, + { 5, (const FLAC__byte*)"a=\xe0\x85\x41", false }, + { 5, (const FLAC__byte*)"a=\xe1\x85\x41", false }, + { 5, (const FLAC__byte*)"a=\xe0\x85\x80", false }, /* non-shortest form */ + { 5, (const FLAC__byte*)"a=\xe0\x95\x80", false }, /* non-shortest form */ + { 5, (const FLAC__byte*)"a=\xe0\xa5\x80", true }, + { 5, (const FLAC__byte*)"a=\xe1\x85\x80", true }, + { 5, (const FLAC__byte*)"a=\xe1\x95\x80", true }, + { 5, (const FLAC__byte*)"a=\xe1\xa5\x80", true } +}; + +FLAC__bool test_format(void) +{ + unsigned i; + + printf("\n+++ libFLAC unit test: format\n\n"); + + for(i = 0; i < sizeof(SAMPLE_RATES)/sizeof(SAMPLE_RATES[0]); i++) { + printf("testing FLAC__format_sample_rate_is_valid(%u)... ", SAMPLE_RATES[i].rate); + if(FLAC__format_sample_rate_is_valid(SAMPLE_RATES[i].rate) != SAMPLE_RATES[i].valid) { + printf("FAILED, expected %s, got %s\n", true_false_string_[SAMPLE_RATES[i].valid], true_false_string_[!SAMPLE_RATES[i].valid]); + return false; + } + printf("OK\n"); + } + + for(i = 0; i < sizeof(SAMPLE_RATES)/sizeof(SAMPLE_RATES[0]); i++) { + printf("testing FLAC__format_sample_rate_is_subset(%u)... ", SAMPLE_RATES[i].rate); + if(FLAC__format_sample_rate_is_subset(SAMPLE_RATES[i].rate) != SAMPLE_RATES[i].subset) { + printf("FAILED, expected %s, got %s\n", true_false_string_[SAMPLE_RATES[i].subset], true_false_string_[!SAMPLE_RATES[i].subset]); + return false; + } + printf("OK\n"); + } + + for(i = 0; i < sizeof(VCENTRY_NAMES)/sizeof(VCENTRY_NAMES[0]); i++) { + printf("testing FLAC__format_vorbiscomment_entry_name_is_legal(\"%s\")... ", VCENTRY_NAMES[i].string); + if(FLAC__format_vorbiscomment_entry_name_is_legal(VCENTRY_NAMES[i].string) != VCENTRY_NAMES[i].valid) { + printf("FAILED, expected %s, got %s\n", true_false_string_[VCENTRY_NAMES[i].valid], true_false_string_[!VCENTRY_NAMES[i].valid]); + return false; + } + printf("OK\n"); + } + + for(i = 0; i < sizeof(VCENTRY_VALUES)/sizeof(VCENTRY_VALUES[0]); i++) { + printf("testing FLAC__format_vorbiscomment_entry_value_is_legal(\"%s\", %u)... ", VCENTRY_VALUES[i].string, VCENTRY_VALUES[i].length); + if(FLAC__format_vorbiscomment_entry_value_is_legal(VCENTRY_VALUES[i].string, VCENTRY_VALUES[i].length) != VCENTRY_VALUES[i].valid) { + printf("FAILED, expected %s, got %s\n", true_false_string_[VCENTRY_VALUES[i].valid], true_false_string_[!VCENTRY_VALUES[i].valid]); + return false; + } + printf("OK\n"); + } + + for(i = 0; i < sizeof(VCENTRY_VALUES_NT)/sizeof(VCENTRY_VALUES_NT[0]); i++) { + printf("testing FLAC__format_vorbiscomment_entry_value_is_legal(\"%s\", -1)... ", VCENTRY_VALUES_NT[i].string); + if(FLAC__format_vorbiscomment_entry_value_is_legal(VCENTRY_VALUES_NT[i].string, (unsigned)(-1)) != VCENTRY_VALUES_NT[i].valid) { + printf("FAILED, expected %s, got %s\n", true_false_string_[VCENTRY_VALUES_NT[i].valid], true_false_string_[!VCENTRY_VALUES_NT[i].valid]); + return false; + } + printf("OK\n"); + } + + for(i = 0; i < sizeof(VCENTRIES)/sizeof(VCENTRIES[0]); i++) { + printf("testing FLAC__format_vorbiscomment_entry_is_legal(\"%s\", %u)... ", VCENTRIES[i].string, VCENTRIES[i].length); + if(FLAC__format_vorbiscomment_entry_is_legal(VCENTRIES[i].string, VCENTRIES[i].length) != VCENTRIES[i].valid) { + printf("FAILED, expected %s, got %s\n", true_false_string_[VCENTRIES[i].valid], true_false_string_[!VCENTRIES[i].valid]); + return false; + } + printf("OK\n"); + } + + printf("\nPASSED!\n"); + return true; +} diff --git a/flac/src/test_libFLAC/format.h b/flac/src/test_libFLAC/format.h new file mode 100644 index 0000000..d3c820d --- /dev/null +++ b/flac/src/test_libFLAC/format.h @@ -0,0 +1,26 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_FORMAT_H +#define FLAC__TEST_LIBFLAC_FORMAT_H + +#include "FLAC/ordinals.h" + +FLAC__bool test_format(void); + +#endif diff --git a/flac/src/test_libFLAC/main.c b/flac/src/test_libFLAC/main.c new file mode 100644 index 0000000..02ac10b --- /dev/null +++ b/flac/src/test_libFLAC/main.c @@ -0,0 +1,49 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "bitwriter.h" +#include "decoders.h" +#include "encoders.h" +#include "format.h" +#include "metadata.h" + +int main(int argc, char *argv[]) +{ + (void)argc, (void)argv; + + if(!test_bitwriter()) + return 1; + + if(!test_format()) + return 1; + + if(!test_encoders()) + return 1; + + if(!test_decoders()) + return 1; + + if(!test_metadata()) + return 1; + + return 0; +} diff --git a/flac/src/test_libFLAC/matrix b/flac/src/test_libFLAC/matrix new file mode 100644 index 0000000..fe404d2 --- /dev/null +++ b/flac/src/test_libFLAC/matrix @@ -0,0 +1,69 @@ +#if 0 +level 1 + +4 delete middle block nopad +1 delete middle block pad +1 delete last block nopad +1 delete last block pad +1 insert middle block nopad +1 insert middle block equalpad +1 insert middle block smallpad +1 insert middle block smallpad+1 +1 insert middle block biggerpad +1 insert last block X +1 set middle block smaller nopad +1 set middle block smaller pad +1 set last block smaller nopad +1 set last block smaller pad +1 set middle block bigger nopad +1 set middle block bigger equalpad +1 set middle block bigger smallpad +1 set middle block bigger smallpad+1 +1 set middle block bigger biggerpad +1 set last block bigger nopad +1 set middle block equal X +2 set last block equal X + +level 2 + +FLAC__bool FLAC__metadata_chain_write() + +1 newsize==oldsize + newsize>oldsize +b no use_padding +c use_padding, last block is not padding +g use_padding, last block is padding of insufficient length +h use_padding, last block is padding, but padding header straddles border (can't do it) +j use_padding, last block is padding of exact sufficient length (padding totally consumed) +i use_padding, last block is padding of abundant length (padding is reduced) + newsize= 4 +f use_padding, last block is padding + +void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain); +void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain); + +S:34 A:1234 +a:shrink A->30 write nopad +S:34 A:30 +b:grow A->32 write nopad +S:34 A:32 +c:grow A->40 write pad +S:34 A:40 +d:shrink A->37 write pad +S:34 A:37 +e:shrink A->33 write pad +S:34 A:33 P:0 +f:shrink A->20 write pad +S:34 A:20 P:13 +g:grow A->40 write pad +S:34 A:40 P:13 +h:grow A->54 write pad +S:34 A:54 P:13 +i:grow A->60 write pad +S:34 A:60 P:7 +j:grow A->71 write pad +S:34 A:71 +#endif diff --git a/flac/src/test_libFLAC/metadata.c b/flac/src/test_libFLAC/metadata.c new file mode 100644 index 0000000..0a1ed56 --- /dev/null +++ b/flac/src/test_libFLAC/metadata.c @@ -0,0 +1,40 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "metadata.h" +#include + +extern FLAC__bool test_metadata_object(void); +extern FLAC__bool test_metadata_file_manipulation(void); + +FLAC__bool test_metadata(void) +{ + if(!test_metadata_object()) + return false; + + if(!test_metadata_file_manipulation()) + return false; + + printf("\nPASSED!\n"); + + return true; +} diff --git a/flac/src/test_libFLAC/metadata.h b/flac/src/test_libFLAC/metadata.h new file mode 100644 index 0000000..144edd8 --- /dev/null +++ b/flac/src/test_libFLAC/metadata.h @@ -0,0 +1,28 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef FLAC__TEST_LIBFLAC_METADATA_H +#define FLAC__TEST_LIBFLAC_METADATA_H + +#include "FLAC/ordinals.h" + +FLAC__bool test_metadata(void); +FLAC__bool test_metadata_file_manipulation(void); +FLAC__bool test_metadata_object(void); + +#endif diff --git a/flac/src/test_libFLAC/metadata_manip.c b/flac/src/test_libFLAC/metadata_manip.c new file mode 100644 index 0000000..9bf3794 --- /dev/null +++ b/flac/src/test_libFLAC/metadata_manip.c @@ -0,0 +1,2133 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include /* for malloc() */ +#include /* for memcpy()/memset() */ +#if defined _MSC_VER || defined __MINGW32__ +#include /* for utime() */ +#include /* for chmod() */ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#else +#include /* some flavors of BSD (like OS X) require this to get time_t */ +#include /* for utime() */ +#include /* for chown(), unlink() */ +#endif +#include /* for stat(), maybe chmod() */ +#include "FLAC/assert.h" +#include "FLAC/stream_decoder.h" +#include "FLAC/metadata.h" +#include "share/grabbag.h" +#include "test_libs_common/file_utils_flac.h" +#include "test_libs_common/metadata_utils.h" +#include "metadata.h" + + +/****************************************************************************** + The general strategy of these tests (for interface levels 1 and 2) is + to create a dummy FLAC file with a known set of initial metadata + blocks, then keep a mirror locally of what we expect the metadata to be + after each operation. Then testing becomes a simple matter of running + a FLAC__StreamDecoder over the dummy file after each operation, comparing + the decoded metadata to what's in our local copy. If there are any + differences in the metadata, or the actual audio data is corrupted, we + will catch it while decoding. +******************************************************************************/ + +typedef struct { + FLAC__bool error_occurred; +} decoder_client_struct; + +typedef struct { + FLAC__StreamMetadata *blocks[64]; + unsigned num_blocks; +} our_metadata_struct; + +/* our copy of the metadata in flacfilename() */ +static our_metadata_struct our_metadata_; + +/* the current block number that corresponds to the position of the iterator we are testing */ +static unsigned mc_our_block_number_ = 0; + +static const char *flacfilename(FLAC__bool is_ogg) +{ + return is_ogg? "metadata.oga" : "metadata.flac"; +} + +static FLAC__bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static FLAC__bool die_c_(const char *msg, FLAC__Metadata_ChainStatus status) +{ + printf("ERROR: %s\n", msg); + printf(" status=%s\n", FLAC__Metadata_ChainStatusString[status]); + return false; +} + +static FLAC__bool die_ss_(const char *msg, FLAC__Metadata_SimpleIterator *iterator) +{ + printf("ERROR: %s\n", msg); + printf(" status=%s\n", FLAC__Metadata_SimpleIteratorStatusString[FLAC__metadata_simple_iterator_status(iterator)]); + return false; +} + +static void *malloc_or_die_(size_t size) +{ + void *x = malloc(size); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory allocating %u bytes\n", (unsigned)size); + exit(1); + } + return x; +} + +static char *strdup_or_die_(const char *s) +{ + char *x = strdup(s); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory copying string \"%s\"\n", s); + exit(1); + } + return x; +} + +/* functions for working with our metadata copy */ + +static FLAC__bool replace_in_our_metadata_(FLAC__StreamMetadata *block, unsigned position, FLAC__bool copy) +{ + unsigned i; + FLAC__StreamMetadata *obj = block; + FLAC__ASSERT(position < our_metadata_.num_blocks); + if(copy) { + if(0 == (obj = FLAC__metadata_object_clone(block))) + return die_("during FLAC__metadata_object_clone()"); + } + FLAC__metadata_object_delete(our_metadata_.blocks[position]); + our_metadata_.blocks[position] = obj; + + /* set the is_last flags */ + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->is_last = false; + our_metadata_.blocks[i]->is_last = true; + + return true; +} + +static FLAC__bool insert_to_our_metadata_(FLAC__StreamMetadata *block, unsigned position, FLAC__bool copy) +{ + unsigned i; + FLAC__StreamMetadata *obj = block; + if(copy) { + if(0 == (obj = FLAC__metadata_object_clone(block))) + return die_("during FLAC__metadata_object_clone()"); + } + if(position > our_metadata_.num_blocks) { + position = our_metadata_.num_blocks; + } + else { + for(i = our_metadata_.num_blocks; i > position; i--) + our_metadata_.blocks[i] = our_metadata_.blocks[i-1]; + } + our_metadata_.blocks[position] = obj; + our_metadata_.num_blocks++; + + /* set the is_last flags */ + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->is_last = false; + our_metadata_.blocks[i]->is_last = true; + + return true; +} + +static void delete_from_our_metadata_(unsigned position) +{ + unsigned i; + FLAC__ASSERT(position < our_metadata_.num_blocks); + FLAC__metadata_object_delete(our_metadata_.blocks[position]); + for(i = position; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i] = our_metadata_.blocks[i+1]; + our_metadata_.num_blocks--; + + /* set the is_last flags */ + if(our_metadata_.num_blocks > 0) { + for(i = 0; i < our_metadata_.num_blocks - 1; i++) + our_metadata_.blocks[i]->is_last = false; + our_metadata_.blocks[i]->is_last = true; + } +} + +/* + * This wad of functions supports filename- and callback-based chain reading/writing. + * Everything up to set_file_stats_() is copied from libFLAC/metadata_iterators.c + */ +static FLAC__bool open_tempfile_(const char *filename, FILE **tempfile, char **tempfilename) +{ + static const char *tempfile_suffix = ".metadata_edit"; + + if(0 == (*tempfilename = (char*)malloc(strlen(filename) + strlen(tempfile_suffix) + 1))) + return false; + strcpy(*tempfilename, filename); + strcat(*tempfilename, tempfile_suffix); + + if(0 == (*tempfile = fopen(*tempfilename, "wb"))) + return false; + + return true; +} + +static void cleanup_tempfile_(FILE **tempfile, char **tempfilename) +{ + if(0 != *tempfile) { + (void)fclose(*tempfile); + *tempfile = 0; + } + + if(0 != *tempfilename) { + (void)unlink(*tempfilename); + free(*tempfilename); + *tempfilename = 0; + } +} + +static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != tempfile); + FLAC__ASSERT(0 != tempfilename); + FLAC__ASSERT(0 != *tempfilename); + + if(0 != *tempfile) { + (void)fclose(*tempfile); + *tempfile = 0; + } + +#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__ + /* on some flavors of windows, rename() will fail if the destination already exists */ + if(unlink(filename) < 0) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } +#endif + + if(0 != rename(*tempfilename, filename)) { + cleanup_tempfile_(tempfile, tempfilename); + return false; + } + + cleanup_tempfile_(tempfile, tempfilename); + + return true; +} + +static FLAC__bool get_file_stats_(const char *filename, struct stat *stats) +{ + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + return (0 == stat(filename, stats)); +} + +static void set_file_stats_(const char *filename, struct stat *stats) +{ + struct utimbuf srctime; + + FLAC__ASSERT(0 != filename); + FLAC__ASSERT(0 != stats); + + srctime.actime = stats->st_atime; + srctime.modtime = stats->st_mtime; + (void)chmod(filename, stats->st_mode); + (void)utime(filename, &srctime); +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__ + (void)chown(filename, stats->st_uid, -1); + (void)chown(filename, -1, stats->st_gid); +#endif +} + +#ifdef FLAC__VALGRIND_TESTING +static size_t chain_write_cb_(const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle) +{ + FILE *stream = (FILE*)handle; + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#endif + +static int chain_seek_cb_(FLAC__IOHandle handle, FLAC__int64 offset, int whence) +{ + off_t o = (off_t)offset; + FLAC__ASSERT(offset == o); + return fseeko((FILE*)handle, o, whence); +} + +static FLAC__int64 chain_tell_cb_(FLAC__IOHandle handle) +{ + return ftello((FILE*)handle); +} + +static int chain_eof_cb_(FLAC__IOHandle handle) +{ + return feof((FILE*)handle); +} + +static FLAC__bool write_chain_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats, FLAC__bool filename_based, const char *filename) +{ + if(filename_based) + return FLAC__metadata_chain_write(chain, use_padding, preserve_file_stats); + else { + FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (FLAC__IOCallback_Read)fread; +#ifdef FLAC__VALGRIND_TESTING + callbacks.write = chain_write_cb_; +#else + callbacks.write = (FLAC__IOCallback_Write)fwrite; +#endif + callbacks.seek = chain_seek_cb_; + callbacks.eof = chain_eof_cb_; + + if(FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) { + struct stat stats; + FILE *file, *tempfile = 0; + char *tempfilename; + if(preserve_file_stats) { + if(!get_file_stats_(filename, &stats)) + return false; + } + if(0 == (file = fopen(filename, "rb"))) + return false; /*@@@@ chain status still says OK though */ + if(!open_tempfile_(filename, &tempfile, &tempfilename)) { + fclose(file); + cleanup_tempfile_(&tempfile, &tempfilename); + return false; /*@@@@ chain status still says OK though */ + } + if(!FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain, use_padding, (FLAC__IOHandle)file, callbacks, (FLAC__IOHandle)tempfile, callbacks)) { + fclose(file); + fclose(tempfile); + return false; + } + fclose(file); + fclose(tempfile); + file = tempfile = 0; + if(!transport_tempfile_(filename, &tempfile, &tempfilename)) + return false; + if(preserve_file_stats) + set_file_stats_(filename, &stats); + } + else { + FILE *file = fopen(filename, "r+b"); + if(0 == file) + return false; /*@@@@ chain status still says OK though */ + if(!FLAC__metadata_chain_write_with_callbacks(chain, use_padding, (FLAC__IOHandle)file, callbacks)) + return false; + fclose(file); + } + } + + return true; +} + +static FLAC__bool read_chain_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool filename_based, FLAC__bool is_ogg) +{ + if(filename_based) + return is_ogg? + FLAC__metadata_chain_read_ogg(chain, flacfilename(is_ogg)) : + FLAC__metadata_chain_read(chain, flacfilename(is_ogg)) + ; + else { + FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (FLAC__IOCallback_Read)fread; + callbacks.seek = chain_seek_cb_; + callbacks.tell = chain_tell_cb_; + + { + FLAC__bool ret; + FILE *file = fopen(filename, "rb"); + if(0 == file) + return false; /*@@@@ chain status still says OK though */ + ret = is_ogg? + FLAC__metadata_chain_read_ogg_with_callbacks(chain, (FLAC__IOHandle)file, callbacks) : + FLAC__metadata_chain_read_with_callbacks(chain, (FLAC__IOHandle)file, callbacks) + ; + fclose(file); + return ret; + } + } +} + +/* function for comparing our metadata to a FLAC__Metadata_Chain */ + +static FLAC__bool compare_chain_(FLAC__Metadata_Chain *chain, unsigned current_position, FLAC__StreamMetadata *current_block) +{ + unsigned i; + FLAC__Metadata_Iterator *iterator; + FLAC__StreamMetadata *block; + FLAC__bool next_ok = true; + + FLAC__ASSERT(0 != chain); + + printf("\tcomparing chain... "); + fflush(stdout); + + if(0 == (iterator = FLAC__metadata_iterator_new())) + return die_("allocating memory for iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + i = 0; + do { + printf("%u... ", i); + fflush(stdout); + + if(0 == (block = FLAC__metadata_iterator_get_block(iterator))) { + FLAC__metadata_iterator_delete(iterator); + return die_("getting block from iterator"); + } + + if(!mutils__compare_block(our_metadata_.blocks[i], block)) { + FLAC__metadata_iterator_delete(iterator); + return die_("metadata block mismatch"); + } + + i++; + next_ok = FLAC__metadata_iterator_next(iterator); + } while(i < our_metadata_.num_blocks && next_ok); + + FLAC__metadata_iterator_delete(iterator); + + if(next_ok) + return die_("chain has more blocks than expected"); + + if(i < our_metadata_.num_blocks) + return die_("short block count in chain"); + + if(0 != current_block) { + printf("CURRENT_POSITION... "); + fflush(stdout); + + if(!mutils__compare_block(our_metadata_.blocks[current_position], current_block)) + return die_("metadata block mismatch"); + } + + printf("PASSED\n"); + + return true; +} + +/* decoder callbacks for checking the file */ + +static FLAC__StreamDecoderWriteStatus decoder_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + (void)decoder, (void)buffer, (void)client_data; + + if( + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER && frame->header.number.frame_number == 0) || + (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER && frame->header.number.sample_number == 0) + ) { + printf("content... "); + fflush(stdout); + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +/* this version pays no attention to the metadata */ +static void decoder_metadata_callback_null_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + (void)decoder, (void)metadata, (void)client_data; + + printf("%d... ", mc_our_block_number_); + fflush(stdout); + + mc_our_block_number_++; +} + +/* this version is used when we want to compare to our metadata copy */ +static void decoder_metadata_callback_compare_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + decoder_client_struct *dcd = (decoder_client_struct*)client_data; + + (void)decoder; + + /* don't bother checking if we've already hit an error */ + if(dcd->error_occurred) + return; + + printf("%d... ", mc_our_block_number_); + fflush(stdout); + + if(mc_our_block_number_ >= our_metadata_.num_blocks) { + (void)die_("got more metadata blocks than expected"); + dcd->error_occurred = true; + } + else { + if(!mutils__compare_block(our_metadata_.blocks[mc_our_block_number_], metadata)) { + (void)die_("metadata block mismatch"); + dcd->error_occurred = true; + } + } + mc_our_block_number_++; +} + +static void decoder_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + decoder_client_struct *dcd = (decoder_client_struct*)client_data; + (void)decoder; + + dcd->error_occurred = true; + printf("ERROR: got error callback, status = %s (%u)\n", FLAC__StreamDecoderErrorStatusString[status], (unsigned)status); +} + +static FLAC__bool generate_file_(FLAC__bool include_extras, FLAC__bool is_ogg) +{ + FLAC__StreamMetadata streaminfo, vorbiscomment, *cuesheet, picture, padding; + FLAC__StreamMetadata *metadata[4]; + unsigned i = 0, n = 0; + + printf("generating %sFLAC file for test\n", is_ogg? "Ogg " : ""); + + while(our_metadata_.num_blocks > 0) + delete_from_our_metadata_(0); + + streaminfo.is_last = false; + streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO; + streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + streaminfo.data.stream_info.min_blocksize = 576; + streaminfo.data.stream_info.max_blocksize = 576; + streaminfo.data.stream_info.min_framesize = 0; + streaminfo.data.stream_info.max_framesize = 0; + streaminfo.data.stream_info.sample_rate = 44100; + streaminfo.data.stream_info.channels = 1; + streaminfo.data.stream_info.bits_per_sample = 8; + streaminfo.data.stream_info.total_samples = 0; + memset(streaminfo.data.stream_info.md5sum, 0, 16); + + { + const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING); + vorbiscomment.is_last = false; + vorbiscomment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT; + vorbiscomment.length = (4 + vendor_string_length) + 4; + vorbiscomment.data.vorbis_comment.vendor_string.length = vendor_string_length; + vorbiscomment.data.vorbis_comment.vendor_string.entry = malloc_or_die_(vendor_string_length+1); + memcpy(vorbiscomment.data.vorbis_comment.vendor_string.entry, FLAC__VENDOR_STRING, vendor_string_length+1); + vorbiscomment.data.vorbis_comment.num_comments = 0; + vorbiscomment.data.vorbis_comment.comments = 0; + } + + { + if (0 == (cuesheet = FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET))) + return die_("priming our metadata"); + cuesheet->is_last = false; + strcpy(cuesheet->data.cue_sheet.media_catalog_number, "bogo-MCN"); + cuesheet->data.cue_sheet.lead_in = 123; + cuesheet->data.cue_sheet.is_cd = false; + if (!FLAC__metadata_object_cuesheet_insert_blank_track(cuesheet, 0)) + return die_("priming our metadata"); + cuesheet->data.cue_sheet.tracks[0].number = 1; + if (!FLAC__metadata_object_cuesheet_track_insert_blank_index(cuesheet, 0, 0)) + return die_("priming our metadata"); + } + + { + picture.is_last = false; + picture.type = FLAC__METADATA_TYPE_PICTURE; + picture.length = + ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN /* will add the length for the data later */ + ) / 8 + ; + picture.data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER; + picture.data.picture.mime_type = strdup_or_die_("image/jpeg"); + picture.length += strlen(picture.data.picture.mime_type); + picture.data.picture.description = (FLAC__byte*)strdup_or_die_("desc"); + picture.length += strlen((const char *)picture.data.picture.description); + picture.data.picture.width = 300; + picture.data.picture.height = 300; + picture.data.picture.depth = 24; + picture.data.picture.colors = 0; + picture.data.picture.data = (FLAC__byte*)strdup_or_die_("SOMEJPEGDATA"); + picture.data.picture.data_length = strlen((const char *)picture.data.picture.data); + picture.length += picture.data.picture.data_length; + } + + padding.is_last = true; + padding.type = FLAC__METADATA_TYPE_PADDING; + padding.length = 1234; + + metadata[n++] = &vorbiscomment; + if(include_extras) { + metadata[n++] = cuesheet; + metadata[n++] = &picture; + } + metadata[n++] = &padding; + + if( + !insert_to_our_metadata_(&streaminfo, i++, /*copy=*/true) || + !insert_to_our_metadata_(&vorbiscomment, i++, /*copy=*/true) || + (include_extras && !insert_to_our_metadata_(cuesheet, i++, /*copy=*/false)) || + (include_extras && !insert_to_our_metadata_(&picture, i++, /*copy=*/true)) || + !insert_to_our_metadata_(&padding, i++, /*copy=*/true) + ) + return die_("priming our metadata"); + + if(!file_utils__generate_flacfile(is_ogg, flacfilename(is_ogg), 0, 512 * 1024, &streaminfo, metadata, n)) + return die_("creating the encoded file"); + + free(vorbiscomment.data.vorbis_comment.vendor_string.entry); + free(picture.data.picture.mime_type); + free(picture.data.picture.description); + free(picture.data.picture.data); + if(!include_extras) + FLAC__metadata_object_delete(cuesheet); + + return true; +} + +static FLAC__bool test_file_(FLAC__bool is_ogg, FLAC__StreamDecoderMetadataCallback metadata_callback) +{ + const char *filename = flacfilename(is_ogg); + FLAC__StreamDecoder *decoder; + decoder_client_struct decoder_client_data; + + FLAC__ASSERT(0 != metadata_callback); + + mc_our_block_number_ = 0; + decoder_client_data.error_occurred = false; + + printf("\ttesting '%s'... ", filename); + fflush(stdout); + + if(0 == (decoder = FLAC__stream_decoder_new())) + return die_("couldn't allocate decoder instance"); + + FLAC__stream_decoder_set_md5_checking(decoder, true); + FLAC__stream_decoder_set_metadata_respond_all(decoder); + if( + (is_ogg? + FLAC__stream_decoder_init_ogg_file(decoder, filename, decoder_write_callback_, metadata_callback, decoder_error_callback_, &decoder_client_data) : + FLAC__stream_decoder_init_file(decoder, filename, decoder_write_callback_, metadata_callback, decoder_error_callback_, &decoder_client_data) + ) != FLAC__STREAM_DECODER_INIT_STATUS_OK + ) { + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + return die_("initializing decoder\n"); + } + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) { + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + return die_("decoding file\n"); + } + + (void)FLAC__stream_decoder_finish(decoder); + FLAC__stream_decoder_delete(decoder); + + if(decoder_client_data.error_occurred) + return false; + + if(mc_our_block_number_ != our_metadata_.num_blocks) + return die_("short metadata block count"); + + printf("PASSED\n"); + return true; +} + +static FLAC__bool change_stats_(const char *filename, FLAC__bool read_only) +{ + if(!grabbag__file_change_stats(filename, read_only)) + return die_("during grabbag__file_change_stats()"); + + return true; +} + +static FLAC__bool remove_file_(const char *filename) +{ + while(our_metadata_.num_blocks > 0) + delete_from_our_metadata_(0); + + if(!grabbag__file_remove_file(filename)) + return die_("removing file"); + + return true; +} + +static FLAC__bool test_level_0_(void) +{ + FLAC__StreamMetadata streaminfo; + FLAC__StreamMetadata *tags = 0; + FLAC__StreamMetadata *cuesheet = 0; + FLAC__StreamMetadata *picture = 0; + + printf("\n\n++++++ testing level 0 interface\n"); + + if(!generate_file_(/*include_extras=*/true, /*is_ogg=*/false)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_null_)) + return false; + + printf("testing FLAC__metadata_get_streaminfo()... "); + + if(!FLAC__metadata_get_streaminfo(flacfilename(/*is_ogg=*/false), &streaminfo)) + return die_("during FLAC__metadata_get_streaminfo()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(streaminfo.data.stream_info.channels != 1) + return die_("mismatch in streaminfo.data.stream_info.channels"); + if(streaminfo.data.stream_info.bits_per_sample != 8) + return die_("mismatch in streaminfo.data.stream_info.bits_per_sample"); + if(streaminfo.data.stream_info.sample_rate != 44100) + return die_("mismatch in streaminfo.data.stream_info.sample_rate"); + if(streaminfo.data.stream_info.min_blocksize != 576) + return die_("mismatch in streaminfo.data.stream_info.min_blocksize"); + if(streaminfo.data.stream_info.max_blocksize != 576) + return die_("mismatch in streaminfo.data.stream_info.max_blocksize"); + + printf("OK\n"); + + printf("testing FLAC__metadata_get_tags()... "); + + if(!FLAC__metadata_get_tags(flacfilename(/*is_ogg=*/false), &tags)) + return die_("during FLAC__metadata_get_tags()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(tags->data.vorbis_comment.num_comments != 0) + return die_("mismatch in tags->data.vorbis_comment.num_comments"); + + printf("OK\n"); + + FLAC__metadata_object_delete(tags); + + printf("testing FLAC__metadata_get_cuesheet()... "); + + if(!FLAC__metadata_get_cuesheet(flacfilename(/*is_ogg=*/false), &cuesheet)) + return die_("during FLAC__metadata_get_cuesheet()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(cuesheet->data.cue_sheet.lead_in != 123) + return die_("mismatch in cuesheet->data.cue_sheet.lead_in"); + + printf("OK\n"); + + FLAC__metadata_object_delete(cuesheet); + + printf("testing FLAC__metadata_get_picture()... "); + + if(!FLAC__metadata_get_picture(flacfilename(/*is_ogg=*/false), &picture, /*type=*/(FLAC__StreamMetadata_Picture_Type)(-1), /*mime_type=*/0, /*description=*/0, /*max_width=*/(unsigned)(-1), /*max_height=*/(unsigned)(-1), /*max_depth=*/(unsigned)(-1), /*max_colors=*/(unsigned)(-1))) + return die_("during FLAC__metadata_get_picture()"); + + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(picture->data.picture.type != FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER) + return die_("mismatch in picture->data.picture.type"); + + printf("OK\n"); + + FLAC__metadata_object_delete(picture); + + if(!remove_file_(flacfilename(/*is_ogg=*/false))) + return false; + + return true; +} + +static FLAC__bool test_level_1_(void) +{ + FLAC__Metadata_SimpleIterator *iterator; + FLAC__StreamMetadata *block, *app, *padding; + FLAC__byte data[1000]; + unsigned our_current_position = 0; + + /* initialize 'data' to avoid Valgrind errors */ + memset(data, 0, sizeof(data)); + + printf("\n\n++++++ testing level 1 interface\n"); + + /************************************************************/ + + printf("simple iterator on read-only file\n"); + + if(!generate_file_(/*include_extras=*/false, /*is_ogg=*/false)) + return false; + + if(!change_stats_(flacfilename(/*is_ogg=*/false), /*read_only=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_null_)) + return false; + + if(0 == (iterator = FLAC__metadata_simple_iterator_new())) + return die_("FLAC__metadata_simple_iterator_new()"); + + if(!FLAC__metadata_simple_iterator_init(iterator, flacfilename(/*is_ogg=*/false), /*read_only=*/false, /*preserve_file_stats=*/false)) + return die_("FLAC__metadata_simple_iterator_init() returned false"); + + printf("is writable = %u\n", (unsigned)FLAC__metadata_simple_iterator_is_writable(iterator)); + if(FLAC__metadata_simple_iterator_is_writable(iterator)) + return die_("iterator claims file is writable when tester thinks it should not be; are you running as root?\n"); + + printf("iterate forwards\n"); + + if(FLAC__metadata_simple_iterator_get_block_type(iterator) != FLAC__METADATA_TYPE_STREAMINFO) + return die_("expected STREAMINFO type from FLAC__metadata_simple_iterator_get_block_type()"); + if(0 == (block = FLAC__metadata_simple_iterator_get_block(iterator))) + return die_("getting block 0"); + if(block->type != FLAC__METADATA_TYPE_STREAMINFO) + return die_("expected STREAMINFO type"); + if(block->is_last) + return die_("expected is_last to be false"); + if(block->length != FLAC__STREAM_METADATA_STREAMINFO_LENGTH) + return die_("bad STREAMINFO length"); + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(block->data.stream_info.channels != 1) + return die_("mismatch in channels"); + if(block->data.stream_info.bits_per_sample != 8) + return die_("mismatch in bits_per_sample"); + if(block->data.stream_info.sample_rate != 44100) + return die_("mismatch in sample_rate"); + if(block->data.stream_info.min_blocksize != 576) + return die_("mismatch in min_blocksize"); + if(block->data.stream_info.max_blocksize != 576) + return die_("mismatch in max_blocksize"); + FLAC__metadata_object_delete(block); + + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("forward iterator ended early"); + our_current_position++; + + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("forward iterator ended early"); + our_current_position++; + + if(FLAC__metadata_simple_iterator_get_block_type(iterator) != FLAC__METADATA_TYPE_PADDING) + return die_("expected PADDING type from FLAC__metadata_simple_iterator_get_block_type()"); + if(0 == (block = FLAC__metadata_simple_iterator_get_block(iterator))) + return die_("getting block 2"); + if(block->type != FLAC__METADATA_TYPE_PADDING) + return die_("expected PADDING type"); + if(!block->is_last) + return die_("expected is_last to be true"); + /* check to see if some basic data matches (c.f. generate_file_()) */ + if(block->length != 1234) + return die_("bad PADDING length"); + FLAC__metadata_object_delete(block); + + if(FLAC__metadata_simple_iterator_next(iterator)) + return die_("forward iterator returned true but should have returned false"); + + printf("iterate backwards\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("reverse iterator ended early"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("reverse iterator ended early"); + if(FLAC__metadata_simple_iterator_prev(iterator)) + return die_("reverse iterator returned true but should have returned false"); + + printf("testing FLAC__metadata_simple_iterator_set_block() on read-only file...\n"); + + if(!FLAC__metadata_simple_iterator_set_block(iterator, (FLAC__StreamMetadata*)99, false)) + printf("OK: FLAC__metadata_simple_iterator_set_block() returned false like it should\n"); + else + return die_("FLAC__metadata_simple_iterator_set_block() returned true but shouldn't have"); + + FLAC__metadata_simple_iterator_delete(iterator); + + /************************************************************/ + + printf("simple iterator on writable file\n"); + + if(!change_stats_(flacfilename(/*is_ogg=*/false), /*read-only=*/false)) + return false; + + printf("creating APPLICATION block\n"); + + if(0 == (app = FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION))) + return die_("FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION)"); + memcpy(app->data.application.id, "duh", (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)); + + printf("creating PADDING block\n"); + + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return die_("FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)"); + padding->length = 20; + + if(0 == (iterator = FLAC__metadata_simple_iterator_new())) + return die_("FLAC__metadata_simple_iterator_new()"); + + if(!FLAC__metadata_simple_iterator_init(iterator, flacfilename(/*is_ogg=*/false), /*read_only=*/false, /*preserve_file_stats=*/false)) + return die_("FLAC__metadata_simple_iterator_init() returned false"); + our_current_position = 0; + + printf("is writable = %u\n", (unsigned)FLAC__metadata_simple_iterator_is_writable(iterator)); + + printf("[S]VP\ttry to write over STREAMINFO block...\n"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, false)) + printf("\tFLAC__metadata_simple_iterator_set_block() returned false like it should\n"); + else + return die_("FLAC__metadata_simple_iterator_set_block() returned true but shouldn't have"); + + printf("[S]VP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tinsert PADDING after, don't expand into padding\n"); + padding->length = 25; + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + printf("SVP[P]\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[P]P\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PP\tinsert PADDING after, don't expand into padding\n"); + padding->length = 30; + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[P]PP\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PPP\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VPPP\tdelete (STREAMINFO block), must fail\n"); + if(FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false) should have returned false", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("[S]VPPP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]PPP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]PP\tdelete (middle block), replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, true)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, true)", iterator); + our_current_position--; + + printf("S[V]PPP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]PP\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]PP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]\tdelete (last block), replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, true)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + our_current_position--; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[P]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]\tdelete (last block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[P]\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]P\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VP\tset STREAMINFO (change sample rate)\n"); + FLAC__ASSERT(our_current_position == 0); + block = FLAC__metadata_simple_iterator_get_block(iterator); + block->data.stream_info.sample_rate = 32000; + if(!replace_in_our_metadata_(block, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, block, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, block, false)", iterator); + FLAC__metadata_object_delete(block); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("[S]VP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tinsert APPLICATION after, expand into padding of exceeding size\n"); + app->data.application.id[0] = 'e'; /* twiddle the id so that our comparison doesn't miss transposition */ + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return false; + our_metadata_.blocks[our_current_position+1]->length -= (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) + app->length; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVA[P]\tset APPLICATION, expand into padding of exceeding size\n"); + app->data.application.id[0] = 'f'; /* twiddle the id */ + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + if(!insert_to_our_metadata_(app, our_current_position, /*copy=*/true)) + return false; + our_metadata_.blocks[our_current_position+1]->length -= (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) + app->length; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]P\tset APPLICATION (grow), don't expand into padding\n"); + app->data.application.id[0] = 'g'; /* twiddle the id */ + if(!FLAC__metadata_object_application_set_data(app, data, sizeof(data), true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]P\tset APPLICATION (shrink), don't fill in with padding\n"); + app->data.application.id[0] = 'h'; /* twiddle the id */ + if(!FLAC__metadata_object_application_set_data(app, data, 12, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]P\tset APPLICATION (grow), expand into padding of exceeding size\n"); + app->data.application.id[0] = 'i'; /* twiddle the id */ + if(!FLAC__metadata_object_application_set_data(app, data, sizeof(data), true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length -= (sizeof(data) - 12); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]P\tset APPLICATION (shrink), fill in with padding\n"); + app->data.application.id[0] = 'j'; /* twiddle the id */ + if(!FLAC__metadata_object_application_set_data(app, data, 23, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!insert_to_our_metadata_(padding, our_current_position+1, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length = sizeof(data) - 23 - FLAC__STREAM_METADATA_HEADER_LENGTH; + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]PP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVAA[P]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVAAP[P]\tset PADDING (shrink), don't fill in with padding\n"); + padding->length = 5; + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, padding, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVAAP[P]\tset APPLICATION (grow)\n"); + app->data.application.id[0] = 'k'; /* twiddle the id */ + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVAAP[A]\tset PADDING (equal)\n"); + padding->length = 27; + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, padding, false)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVAAP[P]\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVAA[P]P\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVA[A]P\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVA[P]\tinsert PADDING after\n"); + padding->length = 5; + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVAP[P]\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVA[P]P\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[A]PP\tset APPLICATION (grow), try to expand into padding which is too small\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 32, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), try to expand into padding which is 'close' but still too small\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 60, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), expand into padding which will leave 0-length pad\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 87, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length = 0; + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PP\tset APPLICATION (grow), expand into padding which is exactly consumed\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 91, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tset APPLICATION (grow), expand into padding which is exactly consumed\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 100, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + our_metadata_.blocks[our_current_position]->is_last = true; + if(!FLAC__metadata_simple_iterator_set_block(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tset PADDING (equal size)\n"); + padding->length = app->length; + if(!replace_in_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, true)) + return die_ss_("FLAC__metadata_simple_iterator_set_block(iterator, padding, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[P]\tinsert PADDING after\n"); + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVP[P]\tinsert PADDING after\n"); + padding->length = 5; + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, padding, false)", iterator); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return false; + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SVPP[P]\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SVP[P]P\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("SV[P]PP\tprev\n"); + if(!FLAC__metadata_simple_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]PPP\tinsert APPLICATION after, try to expand into padding which is too small\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 101, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PPP\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]PPP\tinsert APPLICATION after, try to expand into padding which is 'close' but still too small\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 97, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PPP\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]PPP\tinsert APPLICATION after, expand into padding which is exactly consumed\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 100, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PP\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]PP\tinsert APPLICATION after, expand into padding which will leave 0-length pad\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 96, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length = 0; + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]PP\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]PP\tnext\n"); + if(!FLAC__metadata_simple_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tdelete (middle block), don't replace with padding\n"); + if(!FLAC__metadata_simple_iterator_delete_block(iterator, false)) + return die_ss_("FLAC__metadata_simple_iterator_delete_block(iterator, false)", iterator); + delete_from_our_metadata_(our_current_position--); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("S[V]P\tinsert APPLICATION after, expand into padding which is exactly consumed\n"); + if(!FLAC__metadata_object_application_set_data(app, data, 1, true)) + return die_("setting APPLICATION data"); + if(!insert_to_our_metadata_(app, ++our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)) + return die_ss_("FLAC__metadata_simple_iterator_insert_block_after(iterator, app, true)", iterator); + + if(!test_file_(/*is_ogg=*/false, decoder_metadata_callback_compare_)) + return false; + + printf("delete simple iterator\n"); + + FLAC__metadata_simple_iterator_delete(iterator); + + FLAC__metadata_object_delete(app); + FLAC__metadata_object_delete(padding); + + if(!remove_file_(flacfilename(/*is_ogg=*/false))) + return false; + + return true; +} + +static FLAC__bool test_level_2_(FLAC__bool filename_based, FLAC__bool is_ogg) +{ + FLAC__Metadata_Iterator *iterator; + FLAC__Metadata_Chain *chain; + FLAC__StreamMetadata *block, *app, *padding; + FLAC__byte data[2000]; + unsigned our_current_position; + + /* initialize 'data' to avoid Valgrind errors */ + memset(data, 0, sizeof(data)); + + printf("\n\n++++++ testing level 2 interface (%s-based, %s FLAC)\n", filename_based? "filename":"callback", is_ogg? "Ogg":"native"); + + printf("generate read-only file\n"); + + if(!generate_file_(/*include_extras=*/false, is_ogg)) + return false; + + if(!change_stats_(flacfilename(is_ogg), /*read_only=*/true)) + return false; + + printf("create chain\n"); + + if(0 == (chain = FLAC__metadata_chain_new())) + return die_("allocating chain"); + + printf("read chain\n"); + + if(!read_chain_(chain, flacfilename(is_ogg), filename_based, is_ogg)) + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + + printf("[S]VP\ttest initial metadata\n"); + + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + if(is_ogg) + goto end; + + printf("switch file to read-write\n"); + + if(!change_stats_(flacfilename(is_ogg), /*read-only=*/false)) + return false; + + printf("create iterator\n"); + if(0 == (iterator = FLAC__metadata_iterator_new())) + return die_("allocating memory for iterator"); + + our_current_position = 0; + + FLAC__metadata_iterator_init(iterator, chain); + + if(0 == (block = FLAC__metadata_iterator_get_block(iterator))) + return die_("getting block from iterator"); + + FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_STREAMINFO); + + printf("[S]VP\tmodify STREAMINFO, write\n"); + + block->data.stream_info.sample_rate = 32000; + if(!replace_in_our_metadata_(block, our_current_position, /*copy=*/true)) + return die_("copying object"); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/true, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, true)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("[S]VP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]P\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\treplace PADDING with identical-size APPLICATION\n"); + if(0 == (block = FLAC__metadata_iterator_get_block(iterator))) + return die_("getting block from iterator"); + if(0 == (app = FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION))) + return die_("FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION)"); + memcpy(app->data.application.id, "duh", (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)); + if(!FLAC__metadata_object_application_set_data(app, data, block->length-(FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tshrink APPLICATION, don't use padding\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 26, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tgrow APPLICATION, don't use padding\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 28, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tgrow APPLICATION, use padding, but last block is not padding\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 36, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tshrink APPLICATION, use padding, last block is not padding, but delta is too small for new PADDING block\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 33, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tshrink APPLICATION, use padding, last block is not padding, delta is enough for new PADDING block\n"); + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return die_("creating PADDING block"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 29, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + padding->length = 0; + if(!insert_to_our_metadata_(padding, our_current_position+1, /*copy=*/false)) + return die_("internal error"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tshrink APPLICATION, use padding, last block is padding\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 16, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length = 13; + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding, but delta is too small\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 50, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding of exceeding size\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 56, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + our_metadata_.blocks[our_current_position+1]->length -= (56 - 50); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]P\tgrow APPLICATION, use padding, last block is padding of exact size\n"); + if(0 == (app = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("copying object"); + if(!FLAC__metadata_object_application_set_data(app, data, 67, true)) + return die_("setting APPLICATION data"); + if(!replace_in_our_metadata_(app, our_current_position, /*copy=*/true)) + return die_("copying object"); + delete_from_our_metadata_(our_current_position+1); + if(!FLAC__metadata_iterator_set_block(iterator, app)) + return die_c_("FLAC__metadata_iterator_set_block(iterator, app)", FLAC__metadata_chain_status(chain)); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV[A]\tprev\n"); + if(!FLAC__metadata_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("S[V]A\tprev\n"); + if(!FLAC__metadata_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]VA\tinsert PADDING before STREAMINFO (should fail)\n"); + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return die_("creating PADDING block"); + padding->length = 30; + if(!FLAC__metadata_iterator_insert_block_before(iterator, padding)) + printf("\tFLAC__metadata_iterator_insert_block_before() returned false like it should\n"); + else + return die_("FLAC__metadata_iterator_insert_block_before() should have returned false"); + + printf("[S]VP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]A\tinsert PADDING after\n"); + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) + return die_("FLAC__metadata_iterator_insert_block_after(iterator, padding)"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("SV[P]A\tinsert PADDING before\n"); + if(0 == (padding = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("creating PADDING block"); + padding->length = 17; + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!FLAC__metadata_iterator_insert_block_before(iterator, padding)) + return die_("FLAC__metadata_iterator_insert_block_before(iterator, padding)"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("SV[P]PA\tinsert PADDING before\n"); + if(0 == (padding = FLAC__metadata_object_clone(our_metadata_.blocks[our_current_position]))) + return die_("creating PADDING block"); + padding->length = 0; + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!FLAC__metadata_iterator_insert_block_before(iterator, padding)) + return die_("FLAC__metadata_iterator_insert_block_before(iterator, padding)"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("SV[P]PPA\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVP[P]PA\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVPP[P]A\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SVPPP[A]\tinsert PADDING after\n"); + if(0 == (padding = FLAC__metadata_object_clone(our_metadata_.blocks[2]))) + return die_("creating PADDING block"); + padding->length = 57; + if(!insert_to_our_metadata_(padding, ++our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) + return die_("FLAC__metadata_iterator_insert_block_after(iterator, padding)"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("SVPPPA[P]\tinsert PADDING before\n"); + if(0 == (padding = FLAC__metadata_object_clone(our_metadata_.blocks[2]))) + return die_("creating PADDING block"); + padding->length = 99; + if(!insert_to_our_metadata_(padding, our_current_position, /*copy=*/true)) + return die_("copying metadata"); + if(!FLAC__metadata_iterator_insert_block_before(iterator, padding)) + return die_("FLAC__metadata_iterator_insert_block_before(iterator, padding)"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("delete iterator\n"); + FLAC__metadata_iterator_delete(iterator); + our_current_position = 0; + + printf("SVPPPAPP\tmerge padding\n"); + FLAC__metadata_chain_merge_padding(chain); + our_metadata_.blocks[2]->length += (FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[3]->length); + our_metadata_.blocks[2]->length += (FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[4]->length); + our_metadata_.blocks[6]->length += (FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[7]->length); + delete_from_our_metadata_(7); + delete_from_our_metadata_(4); + delete_from_our_metadata_(3); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SVPAP\tsort padding\n"); + FLAC__metadata_chain_sort_padding(chain); + our_metadata_.blocks[4]->length += (FLAC__STREAM_METADATA_HEADER_LENGTH + our_metadata_.blocks[2]->length); + delete_from_our_metadata_(2); + + if(!write_chain_(chain, /*use_padding=*/true, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, true, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("create iterator\n"); + if(0 == (iterator = FLAC__metadata_iterator_new())) + return die_("allocating memory for iterator"); + + our_current_position = 0; + + FLAC__metadata_iterator_init(iterator, chain); + + printf("[S]VAP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("S[V]AP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[A]P\tdelete middle block, replace with padding\n"); + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return die_("creating PADDING block"); + padding->length = 71; + if(!replace_in_our_metadata_(padding, our_current_position--, /*copy=*/false)) + return die_("copying object"); + if(!FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/true)) + return die_c_("FLAC__metadata_iterator_delete_block(iterator, true)", FLAC__metadata_chain_status(chain)); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("S[V]PP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]P\tdelete middle block, don't replace with padding\n"); + delete_from_our_metadata_(our_current_position--); + if(!FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/false)) + return die_c_("FLAC__metadata_iterator_delete_block(iterator, false)", FLAC__metadata_chain_status(chain)); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("S[V]P\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tdelete last block, replace with padding\n"); + if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) + return die_("creating PADDING block"); + padding->length = 219; + if(!replace_in_our_metadata_(padding, our_current_position--, /*copy=*/false)) + return die_("copying object"); + if(!FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/true)) + return die_c_("FLAC__metadata_iterator_delete_block(iterator, true)", FLAC__metadata_chain_status(chain)); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("S[V]P\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + our_current_position++; + + printf("SV[P]\tdelete last block, don't replace with padding\n"); + delete_from_our_metadata_(our_current_position--); + if(!FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/false)) + return die_c_("FLAC__metadata_iterator_delete_block(iterator, false)", FLAC__metadata_chain_status(chain)); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("S[V]\tprev\n"); + if(!FLAC__metadata_iterator_prev(iterator)) + return die_("iterator ended early\n"); + our_current_position--; + + printf("[S]V\tdelete STREAMINFO block, should fail\n"); + if(FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/false)) + return die_("FLAC__metadata_iterator_delete_block() on STREAMINFO should have failed but didn't"); + + if(!compare_chain_(chain, our_current_position, FLAC__metadata_iterator_get_block(iterator))) + return false; + + printf("delete iterator\n"); + FLAC__metadata_iterator_delete(iterator); + our_current_position = 0; + + printf("SV\tmerge padding\n"); + FLAC__metadata_chain_merge_padding(chain); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + + printf("SV\tsort padding\n"); + FLAC__metadata_chain_sort_padding(chain); + + if(!write_chain_(chain, /*use_padding=*/false, /*preserve_file_stats=*/false, filename_based, flacfilename(is_ogg))) + return die_c_("during FLAC__metadata_chain_write(chain, false, false)", FLAC__metadata_chain_status(chain)); + if(!compare_chain_(chain, 0, 0)) + return false; + if(!test_file_(is_ogg, decoder_metadata_callback_compare_)) + return false; + +end: + printf("delete chain\n"); + + FLAC__metadata_chain_delete(chain); + + if(!remove_file_(flacfilename(is_ogg))) + return false; + + return true; +} + +static FLAC__bool test_level_2_misc_(FLAC__bool is_ogg) +{ + FLAC__Metadata_Iterator *iterator; + FLAC__Metadata_Chain *chain; + FLAC__IOCallbacks callbacks; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.read = (FLAC__IOCallback_Read)fread; +#ifdef FLAC__VALGRIND_TESTING + callbacks.write = chain_write_cb_; +#else + callbacks.write = (FLAC__IOCallback_Write)fwrite; +#endif + callbacks.seek = chain_seek_cb_; + callbacks.tell = chain_tell_cb_; + callbacks.eof = chain_eof_cb_; + + printf("\n\n++++++ testing level 2 interface (mismatched read/write protections)\n"); + + printf("generate file\n"); + + if(!generate_file_(/*include_extras=*/false, is_ogg)) + return false; + + printf("create chain\n"); + + if(0 == (chain = FLAC__metadata_chain_new())) + return die_("allocating chain"); + + printf("read chain (filename-based)\n"); + + if(!FLAC__metadata_chain_read(chain, flacfilename(is_ogg))) + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + + printf("write chain with wrong method FLAC__metadata_chain_write_with_callbacks()\n"); + { + if(FLAC__metadata_chain_write_with_callbacks(chain, /*use_padding=*/false, 0, callbacks)) + return die_c_("mismatched write should have failed", FLAC__metadata_chain_status(chain)); + if(FLAC__metadata_chain_status(chain) != FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", FLAC__metadata_chain_status(chain)); + printf(" OK: FLAC__metadata_chain_write_with_callbacks() returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (filename-based)\n"); + + if(!FLAC__metadata_chain_read(chain, flacfilename(is_ogg))) + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + + printf("write chain with wrong method FLAC__metadata_chain_write_with_callbacks_and_tempfile()\n"); + { + if(FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain, /*use_padding=*/false, 0, callbacks, 0, callbacks)) + return die_c_("mismatched write should have failed", FLAC__metadata_chain_status(chain)); + if(FLAC__metadata_chain_status(chain) != FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", FLAC__metadata_chain_status(chain)); + printf(" OK: FLAC__metadata_chain_write_with_callbacks_and_tempfile() returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!FLAC__metadata_chain_read_with_callbacks(chain, (FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + } + fclose(file); + } + + printf("write chain with wrong method FLAC__metadata_chain_write()\n"); + { + if(FLAC__metadata_chain_write(chain, /*use_padding=*/false, /*preserve_file_stats=*/false)) + return die_c_("mismatched write should have failed", FLAC__metadata_chain_status(chain)); + if(FLAC__metadata_chain_status(chain) != FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH", FLAC__metadata_chain_status(chain)); + printf(" OK: FLAC__metadata_chain_write() returned false,FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!FLAC__metadata_chain_read_with_callbacks(chain, (FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + } + fclose(file); + } + + printf("testing FLAC__metadata_chain_check_if_tempfile_needed()... "); + + if(!FLAC__metadata_chain_check_if_tempfile_needed(chain, /*use_padding=*/false)) + printf("OK: FLAC__metadata_chain_check_if_tempfile_needed() returned false like it should\n"); + else + return die_("FLAC__metadata_chain_check_if_tempfile_needed() returned true but shouldn't have"); + + printf("write chain with wrong method FLAC__metadata_chain_write_with_callbacks_and_tempfile()\n"); + { + if(FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain, /*use_padding=*/false, 0, callbacks, 0, callbacks)) + return die_c_("mismatched write should have failed", FLAC__metadata_chain_status(chain)); + if(FLAC__metadata_chain_status(chain) != FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL", FLAC__metadata_chain_status(chain)); + printf(" OK: FLAC__metadata_chain_write_with_callbacks_and_tempfile() returned false,FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL like it should\n"); + } + + printf("read chain (callback-based)\n"); + { + FILE *file = fopen(flacfilename(is_ogg), "rb"); + if(0 == file) + return die_("opening file"); + if(!FLAC__metadata_chain_read_with_callbacks(chain, (FLAC__IOHandle)file, callbacks)) { + fclose(file); + return die_c_("reading chain", FLAC__metadata_chain_status(chain)); + } + fclose(file); + } + + printf("create iterator\n"); + if(0 == (iterator = FLAC__metadata_iterator_new())) + return die_("allocating memory for iterator"); + + FLAC__metadata_iterator_init(iterator, chain); + + printf("[S]VP\tnext\n"); + if(!FLAC__metadata_iterator_next(iterator)) + return die_("iterator ended early\n"); + + printf("S[V]P\tdelete VORBIS_COMMENT, write\n"); + if(!FLAC__metadata_iterator_delete_block(iterator, /*replace_with_padding=*/false)) + return die_c_("block delete failed\n", FLAC__metadata_chain_status(chain)); + + printf("testing FLAC__metadata_chain_check_if_tempfile_needed()... "); + + if(FLAC__metadata_chain_check_if_tempfile_needed(chain, /*use_padding=*/false)) + printf("OK: FLAC__metadata_chain_check_if_tempfile_needed() returned true like it should\n"); + else + return die_("FLAC__metadata_chain_check_if_tempfile_needed() returned false but shouldn't have"); + + printf("write chain with wrong method FLAC__metadata_chain_write_with_callbacks()\n"); + { + if(FLAC__metadata_chain_write_with_callbacks(chain, /*use_padding=*/false, 0, callbacks)) + return die_c_("mismatched write should have failed", FLAC__metadata_chain_status(chain)); + if(FLAC__metadata_chain_status(chain) != FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL) + return die_c_("expected FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL", FLAC__metadata_chain_status(chain)); + printf(" OK: FLAC__metadata_chain_write_with_callbacks() returned false,FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL like it should\n"); + } + + printf("delete iterator\n"); + + FLAC__metadata_iterator_delete(iterator); + + printf("delete chain\n"); + + FLAC__metadata_chain_delete(chain); + + if(!remove_file_(flacfilename(is_ogg))) + return false; + + return true; +} + +FLAC__bool test_metadata_file_manipulation(void) +{ + printf("\n+++ libFLAC unit test: metadata manipulation\n\n"); + + our_metadata_.num_blocks = 0; + + if(!test_level_0_()) + return false; + + if(!test_level_1_()) + return false; + + if(!test_level_2_(/*filename_based=*/true, /*is_ogg=*/false)) /* filename-based */ + return false; + if(!test_level_2_(/*filename_based=*/false, /*is_ogg=*/false)) /* callback-based */ + return false; + if(!test_level_2_misc_(/*is_ogg=*/false)) + return false; + + if(FLAC_API_SUPPORTS_OGG_FLAC) { + if(!test_level_2_(/*filename_based=*/true, /*is_ogg=*/true)) /* filename-based */ + return false; + if(!test_level_2_(/*filename_based=*/false, /*is_ogg=*/true)) /* callback-based */ + return false; +#if 0 + /* when ogg flac write is supported, will have to add this: */ + if(!test_level_2_misc_(/*is_ogg=*/true)) + return false; +#endif + } + + return true; +} diff --git a/flac/src/test_libFLAC/metadata_object.c b/flac/src/test_libFLAC/metadata_object.c new file mode 100644 index 0000000..f4e1274 --- /dev/null +++ b/flac/src/test_libFLAC/metadata_object.c @@ -0,0 +1,2299 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "test_libs_common/metadata_utils.h" +#include "metadata.h" +#include +#include /* for malloc() */ +#include /* for memcmp() */ + +static FLAC__byte *make_dummydata_(FLAC__byte *dummydata, unsigned len) +{ + FLAC__byte *ret; + + if(0 == (ret = (FLAC__byte*)malloc(len))) { + printf("FAILED, malloc error\n"); + exit(1); + } + else + memcpy(ret, dummydata, len); + + return ret; +} + +static FLAC__bool compare_track_(const FLAC__StreamMetadata_CueSheet_Track *from, const FLAC__StreamMetadata_CueSheet_Track *to) +{ + unsigned i; + + if(from->offset != to->offset) { +#ifdef _MSC_VER + printf("FAILED, track offset mismatch, expected %I64u, got %I64u\n", to->offset, from->offset); +#else + printf("FAILED, track offset mismatch, expected %llu, got %llu\n", (unsigned long long)to->offset, (unsigned long long)from->offset); +#endif + return false; + } + if(from->number != to->number) { + printf("FAILED, track number mismatch, expected %u, got %u\n", (unsigned)to->number, (unsigned)from->number); + return false; + } + if(0 != strcmp(from->isrc, to->isrc)) { + printf("FAILED, track number mismatch, expected %s, got %s\n", to->isrc, from->isrc); + return false; + } + if(from->type != to->type) { + printf("FAILED, track type mismatch, expected %u, got %u\n", (unsigned)to->type, (unsigned)from->type); + return false; + } + if(from->pre_emphasis != to->pre_emphasis) { + printf("FAILED, track pre_emphasis mismatch, expected %u, got %u\n", (unsigned)to->pre_emphasis, (unsigned)from->pre_emphasis); + return false; + } + if(from->num_indices != to->num_indices) { + printf("FAILED, track num_indices mismatch, expected %u, got %u\n", (unsigned)to->num_indices, (unsigned)from->num_indices); + return false; + } + if(0 == to->indices || 0 == from->indices) { + if(to->indices != from->indices) { + printf("FAILED, track indices mismatch\n"); + return false; + } + } + else { + for(i = 0; i < to->num_indices; i++) { + if(from->indices[i].offset != to->indices[i].offset) { +#ifdef _MSC_VER + printf("FAILED, track indices[%u].offset mismatch, expected %I64u, got %I64u\n", i, to->indices[i].offset, from->indices[i].offset); +#else + printf("FAILED, track indices[%u].offset mismatch, expected %llu, got %llu\n", i, (unsigned long long)to->indices[i].offset, (unsigned long long)from->indices[i].offset); +#endif + return false; + } + if(from->indices[i].number != to->indices[i].number) { + printf("FAILED, track indices[%u].number mismatch, expected %u, got %u\n", i, (unsigned)to->indices[i].number, (unsigned)from->indices[i].number); + return false; + } + } + } + + return true; +} + +static FLAC__bool compare_seekpoint_array_(const FLAC__StreamMetadata_SeekPoint *from, const FLAC__StreamMetadata_SeekPoint *to, unsigned n) +{ + unsigned i; + + FLAC__ASSERT(0 != from); + FLAC__ASSERT(0 != to); + + for(i = 0; i < n; i++) { + if(from[i].sample_number != to[i].sample_number) { +#ifdef _MSC_VER + printf("FAILED, point[%u].sample_number mismatch, expected %I64u, got %I64u\n", i, to[i].sample_number, from[i].sample_number); +#else + printf("FAILED, point[%u].sample_number mismatch, expected %llu, got %llu\n", i, (unsigned long long)to[i].sample_number, (unsigned long long)from[i].sample_number); +#endif + return false; + } + if(from[i].stream_offset != to[i].stream_offset) { +#ifdef _MSC_VER + printf("FAILED, point[%u].stream_offset mismatch, expected %I64u, got %I64u\n", i, to[i].stream_offset, from[i].stream_offset); +#else + printf("FAILED, point[%u].stream_offset mismatch, expected %llu, got %llu\n", i, (unsigned long long)to[i].stream_offset, (unsigned long long)from[i].stream_offset); +#endif + return false; + } + if(from[i].frame_samples != to[i].frame_samples) { + printf("FAILED, point[%u].frame_samples mismatch, expected %u, got %u\n", i, to[i].frame_samples, from[i].frame_samples); + return false; + } + } + + return true; +} + +static FLAC__bool check_seektable_(const FLAC__StreamMetadata *block, unsigned num_points, const FLAC__StreamMetadata_SeekPoint *array) +{ + const unsigned expected_length = num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; + + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + if(block->data.seek_table.num_points != num_points) { + printf("FAILED, expected %u point, got %u\n", num_points, block->data.seek_table.num_points); + return false; + } + if(0 == array) { + if(0 != block->data.seek_table.points) { + printf("FAILED, 'points' pointer is not null\n"); + return false; + } + } + else { + if(!compare_seekpoint_array_(block->data.seek_table.points, array, num_points)) + return false; + } + printf("OK\n"); + + return true; +} + +static void entry_new_(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field) +{ + entry->length = strlen(field); + entry->entry = (FLAC__byte*)malloc(entry->length+1); + FLAC__ASSERT(0 != entry->entry); + memcpy(entry->entry, field, entry->length); + entry->entry[entry->length] = '\0'; +} + +static void entry_clone_(FLAC__StreamMetadata_VorbisComment_Entry *entry) +{ + FLAC__byte *x = (FLAC__byte*)malloc(entry->length+1); + FLAC__ASSERT(0 != x); + memcpy(x, entry->entry, entry->length); + x[entry->length] = '\0'; + entry->entry = x; +} + +static void vc_calc_len_(FLAC__StreamMetadata *block) +{ + const FLAC__StreamMetadata_VorbisComment *vc = &block->data.vorbis_comment; + unsigned i; + + block->length = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8; + block->length += vc->vendor_string.length; + block->length += FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8; + for(i = 0; i < vc->num_comments; i++) { + block->length += FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8; + block->length += vc->comments[i].length; + } +} + +static void vc_resize_(FLAC__StreamMetadata *block, unsigned num) +{ + FLAC__StreamMetadata_VorbisComment *vc = &block->data.vorbis_comment; + + if(vc->num_comments != 0) { + FLAC__ASSERT(0 != vc->comments); + if(num < vc->num_comments) { + unsigned i; + for(i = num; i < vc->num_comments; i++) { + if(0 != vc->comments[i].entry) + free(vc->comments[i].entry); + } + } + } + if(num == 0) { + if(0 != vc->comments) { + free(vc->comments); + vc->comments = 0; + } + } + else { + vc->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)realloc(vc->comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*num); + FLAC__ASSERT(0 != vc->comments); + if(num > vc->num_comments) + memset(vc->comments+vc->num_comments, 0, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(num-vc->num_comments)); + } + + vc->num_comments = num; + vc_calc_len_(block); +} + +static int vc_find_from_(FLAC__StreamMetadata *block, const char *name, unsigned start) +{ + const unsigned n = strlen(name); + unsigned i; + for(i = start; i < block->data.vorbis_comment.num_comments; i++) { + const FLAC__StreamMetadata_VorbisComment_Entry *entry = &block->data.vorbis_comment.comments[i]; + if(entry->length > n && 0 == strncmp((const char *)entry->entry, name, n) && entry->entry[n] == '=') + return (int)i; + } + return -1; +} + +static void vc_set_vs_new_(FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__StreamMetadata *block, const char *field) +{ + if(0 != block->data.vorbis_comment.vendor_string.entry) + free(block->data.vorbis_comment.vendor_string.entry); + entry_new_(entry, field); + block->data.vorbis_comment.vendor_string = *entry; + vc_calc_len_(block); +} + +static void vc_set_new_(FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__StreamMetadata *block, unsigned pos, const char *field) +{ + if(0 != block->data.vorbis_comment.comments[pos].entry) + free(block->data.vorbis_comment.comments[pos].entry); + entry_new_(entry, field); + block->data.vorbis_comment.comments[pos] = *entry; + vc_calc_len_(block); +} + +static void vc_insert_new_(FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__StreamMetadata *block, unsigned pos, const char *field) +{ + vc_resize_(block, block->data.vorbis_comment.num_comments+1); + memmove(&block->data.vorbis_comment.comments[pos+1], &block->data.vorbis_comment.comments[pos], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(block->data.vorbis_comment.num_comments-1-pos)); + memset(&block->data.vorbis_comment.comments[pos], 0, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)); + vc_set_new_(entry, block, pos, field); + vc_calc_len_(block); +} + +static void vc_delete_(FLAC__StreamMetadata *block, unsigned pos) +{ + if(0 != block->data.vorbis_comment.comments[pos].entry) + free(block->data.vorbis_comment.comments[pos].entry); + memmove(&block->data.vorbis_comment.comments[pos], &block->data.vorbis_comment.comments[pos+1], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(block->data.vorbis_comment.num_comments-pos-1)); + block->data.vorbis_comment.comments[block->data.vorbis_comment.num_comments-1].entry = 0; + block->data.vorbis_comment.comments[block->data.vorbis_comment.num_comments-1].length = 0; + vc_resize_(block, block->data.vorbis_comment.num_comments-1); + vc_calc_len_(block); +} + +static void vc_replace_new_(FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__StreamMetadata *block, const char *field, FLAC__bool all) +{ + int index; + char field_name[256]; + const char *eq = strchr(field, '='); + FLAC__ASSERT(eq>field && (unsigned)(eq-field) < sizeof(field_name)); + memcpy(field_name, field, eq-field); + field_name[eq-field]='\0'; + + index = vc_find_from_(block, field_name, 0); + if(index < 0) + vc_insert_new_(entry, block, block->data.vorbis_comment.num_comments, field); + else { + vc_set_new_(entry, block, (unsigned)index, field); + if(all) { + for(index = index+1; index >= 0 && (unsigned)index < block->data.vorbis_comment.num_comments; ) + if((index = vc_find_from_(block, field_name, (unsigned)index)) >= 0) + vc_delete_(block, (unsigned)index); + } + } + + vc_calc_len_(block); +} + +static void track_new_(FLAC__StreamMetadata_CueSheet_Track *track, FLAC__uint64 offset, FLAC__byte number, const char *isrc, FLAC__bool data, FLAC__bool pre_em) +{ + track->offset = offset; + track->number = number; + memcpy(track->isrc, isrc, sizeof(track->isrc)); + track->type = data; + track->pre_emphasis = pre_em; + track->num_indices = 0; + track->indices = 0; +} + +static void track_clone_(FLAC__StreamMetadata_CueSheet_Track *track) +{ + if(track->num_indices > 0) { + size_t bytes = sizeof(FLAC__StreamMetadata_CueSheet_Index) * track->num_indices; + FLAC__StreamMetadata_CueSheet_Index *x = (FLAC__StreamMetadata_CueSheet_Index*)malloc(bytes); + FLAC__ASSERT(0 != x); + memcpy(x, track->indices, bytes); + track->indices = x; + } +} + +static void cs_calc_len_(FLAC__StreamMetadata *block) +{ + const FLAC__StreamMetadata_CueSheet *cs = &block->data.cue_sheet; + unsigned i; + + block->length = ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8; + block->length += cs->num_tracks * ( + FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN + ) / 8; + for(i = 0; i < cs->num_tracks; i++) { + block->length += cs->tracks[i].num_indices * ( + FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN + ) / 8; + } +} + +static void tr_resize_(FLAC__StreamMetadata *block, unsigned track_num, unsigned num) +{ + FLAC__StreamMetadata_CueSheet_Track *tr; + + FLAC__ASSERT(track_num < block->data.cue_sheet.num_tracks); + + tr = &block->data.cue_sheet.tracks[track_num]; + + if(tr->num_indices != 0) { + FLAC__ASSERT(0 != tr->indices); + } + if(num == 0) { + if(0 != tr->indices) { + free(tr->indices); + tr->indices = 0; + } + } + else { + tr->indices = (FLAC__StreamMetadata_CueSheet_Index*)realloc(tr->indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)*num); + FLAC__ASSERT(0 != tr->indices); + if(num > tr->num_indices) + memset(tr->indices+tr->num_indices, 0, sizeof(FLAC__StreamMetadata_CueSheet_Index)*(num-tr->num_indices)); + } + + tr->num_indices = num; + cs_calc_len_(block); +} + +static void tr_set_new_(FLAC__StreamMetadata *block, unsigned track_num, unsigned pos, FLAC__StreamMetadata_CueSheet_Index index) +{ + FLAC__StreamMetadata_CueSheet_Track *tr; + + FLAC__ASSERT(track_num < block->data.cue_sheet.num_tracks); + + tr = &block->data.cue_sheet.tracks[track_num]; + + FLAC__ASSERT(pos < tr->num_indices); + + tr->indices[pos] = index; + + cs_calc_len_(block); +} + +static void tr_insert_new_(FLAC__StreamMetadata *block, unsigned track_num, unsigned pos, FLAC__StreamMetadata_CueSheet_Index index) +{ + FLAC__StreamMetadata_CueSheet_Track *tr; + + FLAC__ASSERT(track_num < block->data.cue_sheet.num_tracks); + + tr = &block->data.cue_sheet.tracks[track_num]; + + FLAC__ASSERT(pos <= tr->num_indices); + + tr_resize_(block, track_num, tr->num_indices+1); + memmove(&tr->indices[pos+1], &tr->indices[pos], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(tr->num_indices-1-pos)); + tr_set_new_(block, track_num, pos, index); + cs_calc_len_(block); +} + +static void tr_delete_(FLAC__StreamMetadata *block, unsigned track_num, unsigned pos) +{ + FLAC__StreamMetadata_CueSheet_Track *tr; + + FLAC__ASSERT(track_num < block->data.cue_sheet.num_tracks); + + tr = &block->data.cue_sheet.tracks[track_num]; + + FLAC__ASSERT(pos <= tr->num_indices); + + memmove(&tr->indices[pos], &tr->indices[pos+1], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(tr->num_indices-pos-1)); + tr_resize_(block, track_num, tr->num_indices-1); + cs_calc_len_(block); +} + +static void cs_resize_(FLAC__StreamMetadata *block, unsigned num) +{ + FLAC__StreamMetadata_CueSheet *cs = &block->data.cue_sheet; + + if(cs->num_tracks != 0) { + FLAC__ASSERT(0 != cs->tracks); + if(num < cs->num_tracks) { + unsigned i; + for(i = num; i < cs->num_tracks; i++) { + if(0 != cs->tracks[i].indices) + free(cs->tracks[i].indices); + } + } + } + if(num == 0) { + if(0 != cs->tracks) { + free(cs->tracks); + cs->tracks = 0; + } + } + else { + cs->tracks = (FLAC__StreamMetadata_CueSheet_Track*)realloc(cs->tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)*num); + FLAC__ASSERT(0 != cs->tracks); + if(num > cs->num_tracks) + memset(cs->tracks+cs->num_tracks, 0, sizeof(FLAC__StreamMetadata_CueSheet_Track)*(num-cs->num_tracks)); + } + + cs->num_tracks = num; + cs_calc_len_(block); +} + +static void cs_set_new_(FLAC__StreamMetadata_CueSheet_Track *track, FLAC__StreamMetadata *block, unsigned pos, FLAC__uint64 offset, FLAC__byte number, const char *isrc, FLAC__bool data, FLAC__bool pre_em) +{ + track_new_(track, offset, number, isrc, data, pre_em); + block->data.cue_sheet.tracks[pos] = *track; + cs_calc_len_(block); +} + +static void cs_insert_new_(FLAC__StreamMetadata_CueSheet_Track *track, FLAC__StreamMetadata *block, unsigned pos, FLAC__uint64 offset, FLAC__byte number, const char *isrc, FLAC__bool data, FLAC__bool pre_em) +{ + cs_resize_(block, block->data.cue_sheet.num_tracks+1); + memmove(&block->data.cue_sheet.tracks[pos+1], &block->data.cue_sheet.tracks[pos], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(block->data.cue_sheet.num_tracks-1-pos)); + cs_set_new_(track, block, pos, offset, number, isrc, data, pre_em); + cs_calc_len_(block); +} + +static void cs_delete_(FLAC__StreamMetadata *block, unsigned pos) +{ + if(0 != block->data.cue_sheet.tracks[pos].indices) + free(block->data.cue_sheet.tracks[pos].indices); + memmove(&block->data.cue_sheet.tracks[pos], &block->data.cue_sheet.tracks[pos+1], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(block->data.cue_sheet.num_tracks-pos-1)); + block->data.cue_sheet.tracks[block->data.cue_sheet.num_tracks-1].indices = 0; + block->data.cue_sheet.tracks[block->data.cue_sheet.num_tracks-1].num_indices = 0; + cs_resize_(block, block->data.cue_sheet.num_tracks-1); + cs_calc_len_(block); +} + +static void pi_set_mime_type(FLAC__StreamMetadata *block, const char *s) +{ + if(block->data.picture.mime_type) { + block->length -= strlen(block->data.picture.mime_type); + free(block->data.picture.mime_type); + } + block->data.picture.mime_type = strdup(s); + FLAC__ASSERT(block->data.picture.mime_type); + block->length += strlen(block->data.picture.mime_type); +} + +static void pi_set_description(FLAC__StreamMetadata *block, const FLAC__byte *s) +{ + if(block->data.picture.description) { + block->length -= strlen((const char *)block->data.picture.description); + free(block->data.picture.description); + } + block->data.picture.description = (FLAC__byte*)strdup((const char *)s); + FLAC__ASSERT(block->data.picture.description); + block->length += strlen((const char *)block->data.picture.description); +} + +static void pi_set_data(FLAC__StreamMetadata *block, const FLAC__byte *data, FLAC__uint32 len) +{ + if(block->data.picture.data) { + block->length -= block->data.picture.data_length; + free(block->data.picture.data); + } + block->data.picture.data = (FLAC__byte*)strdup((const char *)data); + FLAC__ASSERT(block->data.picture.data); + block->data.picture.data_length = len; + block->length += len; +} + +FLAC__bool test_metadata_object(void) +{ + FLAC__StreamMetadata *block, *blockcopy, *vorbiscomment, *cuesheet, *picture; + FLAC__StreamMetadata_SeekPoint seekpoint_array[14]; + FLAC__StreamMetadata_VorbisComment_Entry entry; + FLAC__StreamMetadata_CueSheet_Index index; + FLAC__StreamMetadata_CueSheet_Track track; + unsigned i, expected_length, seekpoints; + int j; + static FLAC__byte dummydata[4] = { 'a', 'b', 'c', 'd' }; + + printf("\n+++ libFLAC unit test: metadata objects\n\n"); + + + printf("testing STREAMINFO\n"); + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_STREAMINFO); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing PADDING\n"); + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = 0; + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing APPLICATION\n"); + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8; + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_application_set_data(copy)... "); + if(!FLAC__metadata_object_application_set_data(block, dummydata, sizeof(dummydata), true/*copy*/)) { + printf("FAILED, returned false\n"); + return false; + } + expected_length = (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8) + sizeof(dummydata); + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + if(0 != memcmp(block->data.application.data, dummydata, sizeof(dummydata))) { + printf("FAILED, data mismatch\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_application_set_data(own)... "); + if(!FLAC__metadata_object_application_set_data(block, make_dummydata_(dummydata, sizeof(dummydata)), sizeof(dummydata), false/*own*/)) { + printf("FAILED, returned false\n"); + return false; + } + expected_length = (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8) + sizeof(dummydata); + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + if(0 != memcmp(block->data.application.data, dummydata, sizeof(dummydata))) { + printf("FAILED, data mismatch\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing SEEKTABLE\n"); + + for(i = 0; i < sizeof(seekpoint_array) / sizeof(FLAC__StreamMetadata_SeekPoint); i++) { + seekpoint_array[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seekpoint_array[i].stream_offset = 0; + seekpoint_array[i].frame_samples = 0; + } + + seekpoints = 0; + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!check_seektable_(block, seekpoints, 0)) + return false; + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + seekpoints = 2; + printf("testing FLAC__metadata_object_seektable_resize_points(grow to %u)...", seekpoints); + if(!FLAC__metadata_object_seektable_resize_points(block, seekpoints)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoints = 1; + printf("testing FLAC__metadata_object_seektable_resize_points(shrink to %u)...", seekpoints); + if(!FLAC__metadata_object_seektable_resize_points(block, seekpoints)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + printf("testing FLAC__metadata_object_seektable_is_legal()..."); + if(!FLAC__metadata_object_seektable_is_legal(block)) { + printf("FAILED, returned false\n"); + return false; + } + printf("OK\n"); + + seekpoints = 0; + printf("testing FLAC__metadata_object_seektable_resize_points(shrink to %u)...", seekpoints); + if(!FLAC__metadata_object_seektable_resize_points(block, seekpoints)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, 0)) + return false; + + seekpoints++; + printf("testing FLAC__metadata_object_seektable_insert_point() on empty array..."); + if(!FLAC__metadata_object_seektable_insert_point(block, 0, seekpoint_array[0])) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[0].sample_number = 1; + seekpoints++; + printf("testing FLAC__metadata_object_seektable_insert_point() on beginning of non-empty array..."); + if(!FLAC__metadata_object_seektable_insert_point(block, 0, seekpoint_array[0])) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[1].sample_number = 2; + seekpoints++; + printf("testing FLAC__metadata_object_seektable_insert_point() on middle of non-empty array..."); + if(!FLAC__metadata_object_seektable_insert_point(block, 1, seekpoint_array[1])) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[3].sample_number = 3; + seekpoints++; + printf("testing FLAC__metadata_object_seektable_insert_point() on end of non-empty array..."); + if(!FLAC__metadata_object_seektable_insert_point(block, 3, seekpoint_array[3])) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + seekpoint_array[2].sample_number = seekpoint_array[3].sample_number; + seekpoints--; + printf("testing FLAC__metadata_object_seektable_delete_point() on middle of array..."); + if(!FLAC__metadata_object_seektable_delete_point(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoints--; + printf("testing FLAC__metadata_object_seektable_delete_point() on end of array..."); + if(!FLAC__metadata_object_seektable_delete_point(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoints--; + printf("testing FLAC__metadata_object_seektable_delete_point() on beginning of array..."); + if(!FLAC__metadata_object_seektable_delete_point(block, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array+1)) + return false; + + printf("testing FLAC__metadata_object_seektable_set_point()..."); + FLAC__metadata_object_seektable_set_point(block, 0, seekpoint_array[0]); + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + /* seektable template functions */ + + for(i = 0; i < sizeof(seekpoint_array) / sizeof(FLAC__StreamMetadata_SeekPoint); i++) { + seekpoint_array[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seekpoint_array[i].stream_offset = 0; + seekpoint_array[i].frame_samples = 0; + } + + seekpoints = 0; + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!check_seektable_(block, seekpoints, 0)) + return false; + + seekpoints += 2; + printf("testing FLAC__metadata_object_seekpoint_template_append_placeholders()... "); + if(!FLAC__metadata_object_seektable_template_append_placeholders(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[seekpoints++].sample_number = 7; + printf("testing FLAC__metadata_object_seekpoint_template_append_point()... "); + if(!FLAC__metadata_object_seektable_template_append_point(block, 7)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + { + FLAC__uint64 nums[2] = { 3, 7 }; + seekpoint_array[seekpoints++].sample_number = nums[0]; + seekpoint_array[seekpoints++].sample_number = nums[1]; + printf("testing FLAC__metadata_object_seekpoint_template_append_points()... "); + if(!FLAC__metadata_object_seektable_template_append_points(block, nums, sizeof(nums)/sizeof(FLAC__uint64))) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + } + + seekpoint_array[seekpoints++].sample_number = 0; + seekpoint_array[seekpoints++].sample_number = 10; + seekpoint_array[seekpoints++].sample_number = 20; + printf("testing FLAC__metadata_object_seekpoint_template_append_spaced_points()... "); + if(!FLAC__metadata_object_seektable_template_append_spaced_points(block, 3, 30)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoints--; + seekpoint_array[0].sample_number = 0; + seekpoint_array[1].sample_number = 3; + seekpoint_array[2].sample_number = 7; + seekpoint_array[3].sample_number = 10; + seekpoint_array[4].sample_number = 20; + seekpoint_array[5].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seekpoint_array[6].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + printf("testing FLAC__metadata_object_seekpoint_template_sort(compact=true)... "); + if(!FLAC__metadata_object_seektable_template_sort(block, /*compact=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!FLAC__metadata_object_seektable_is_legal(block)) { + printf("FAILED, seek table is illegal\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + printf("testing FLAC__metadata_object_seekpoint_template_sort(compact=false)... "); + if(!FLAC__metadata_object_seektable_template_sort(block, /*compact=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!FLAC__metadata_object_seektable_is_legal(block)) { + printf("FAILED, seek table is illegal\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[seekpoints++].sample_number = 0; + seekpoint_array[seekpoints++].sample_number = 10; + seekpoint_array[seekpoints++].sample_number = 20; + printf("testing FLAC__metadata_object_seekpoint_template_append_spaced_points_by_samples()... "); + if(!FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(block, 10, 30)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + seekpoint_array[seekpoints++].sample_number = 0; + seekpoint_array[seekpoints++].sample_number = 11; + seekpoint_array[seekpoints++].sample_number = 22; + printf("testing FLAC__metadata_object_seekpoint_template_append_spaced_points_by_samples()... "); + if(!FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(block, 11, 30)) { + printf("FAILED, returned false\n"); + return false; + } + if(!check_seektable_(block, seekpoints, seekpoint_array)) + return false; + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing VORBIS_COMMENT\n"); + + { + FLAC__StreamMetadata_VorbisComment_Entry entry_; + char *field_name, *field_value; + + printf("testing FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair()... "); + if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry_, "name", "value")) { + printf("FAILED, returned false\n"); + return false; + } + if(strcmp((const char *)entry_.entry, "name=value")) { + printf("FAILED, field mismatch\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair()... "); + if(!FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(entry_, &field_name, &field_value)) { + printf("FAILED, returned false\n"); + return false; + } + if(strcmp(field_name, "name")) { + printf("FAILED, field name mismatch\n"); + return false; + } + if(strcmp(field_value, "value")) { + printf("FAILED, field value mismatch\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_entry_matches()... "); + if(!FLAC__metadata_object_vorbiscomment_entry_matches(entry_, field_name, strlen(field_name))) { + printf("FAILED, expected true, returned false\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_entry_matches()... "); + if(FLAC__metadata_object_vorbiscomment_entry_matches(entry_, "blah", strlen("blah"))) { + printf("FAILED, expected false, returned true\n"); + return false; + } + printf("OK\n"); + + free(entry_.entry); + free(field_name); + free(field_value); + } + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + strlen(FLAC__VENDOR_STRING) + FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN/8); + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + vorbiscomment = FLAC__metadata_object_clone(block); + if(0 == vorbiscomment) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + vc_resize_(vorbiscomment, 2); + printf("testing FLAC__metadata_object_vorbiscomment_resize_comments(grow to %u)...", vorbiscomment->data.vorbis_comment.num_comments); + if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, vorbiscomment->data.vorbis_comment.num_comments)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + vc_resize_(vorbiscomment, 1); + printf("testing FLAC__metadata_object_vorbiscomment_resize_comments(shrink to %u)...", vorbiscomment->data.vorbis_comment.num_comments); + if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, vorbiscomment->data.vorbis_comment.num_comments)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + vc_resize_(vorbiscomment, 0); + printf("testing FLAC__metadata_object_vorbiscomment_resize_comments(shrink to %u)...", vorbiscomment->data.vorbis_comment.num_comments); + if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, vorbiscomment->data.vorbis_comment.num_comments)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(copy) on empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name1=field1"); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(copy) on non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 1, "name2=field2"); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + vc_resize_(vorbiscomment, 0); + printf("testing FLAC__metadata_object_vorbiscomment_resize_comments(shrink to %u)...", vorbiscomment->data.vorbis_comment.num_comments); + if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, vorbiscomment->data.vorbis_comment.num_comments)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name1=field1"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 0, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on beginning of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name2=field2"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 0, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on middle of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 1, "name3=field3"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 1, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 3, "name4=field4"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 3, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 4, "name3=field3dup1"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 4, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(copy) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 5, "name3=field3dup1"); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 5, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, 0, "name3")) != 1) { + printf("FAILED, expected 1, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, j+1, "name3")) != 4) { + printf("FAILED, expected 4, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, j+1, "name3")) != 5) { + printf("FAILED, expected 5, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, 0, "name2")) != 0) { + printf("FAILED, expected 0, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, j+1, "name2")) != -1) { + printf("FAILED, expected -1, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_find_entry_from()..."); + if((j = FLAC__metadata_object_vorbiscomment_find_entry_from(block, 0, "blah")) != -1) { + printf("FAILED, expected -1, got %d\n", j); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_replace_comment(first, copy)..."); + vc_replace_new_(&entry, vorbiscomment, "name3=field3new1", /*all=*/false); + if(!FLAC__metadata_object_vorbiscomment_replace_comment(block, entry, /*all=*/false, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + if(block->data.vorbis_comment.num_comments != 6) { + printf("FAILED, expected 6 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_replace_comment(all, copy)..."); + vc_replace_new_(&entry, vorbiscomment, "name3=field3new2", /*all=*/true); + if(!FLAC__metadata_object_vorbiscomment_replace_comment(block, entry, /*all=*/true, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + if(block->data.vorbis_comment.num_comments != 4) { + printf("FAILED, expected 4 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on middle of array..."); + vc_delete_(vorbiscomment, 2); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on end of array..."); + vc_delete_(vorbiscomment, 2); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on beginning of array..."); + vc_delete_(vorbiscomment, 0); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(copy) on non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 1, "rem0=val0"); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(copy) on non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 2, "rem0=val1"); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(copy) on non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 3, "rem0=val2"); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_remove_entry_matching(\"blah\")..."); + if((j = FLAC__metadata_object_vorbiscomment_remove_entry_matching(block, "blah")) != 0) { + printf("FAILED, expected 0, got %d\n", j); + return false; + } + if(block->data.vorbis_comment.num_comments != 4) { + printf("FAILED, expected 4 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_remove_entry_matching(\"rem0\")..."); + vc_delete_(vorbiscomment, 1); + if((j = FLAC__metadata_object_vorbiscomment_remove_entry_matching(block, "rem0")) != 1) { + printf("FAILED, expected 1, got %d\n", j); + return false; + } + if(block->data.vorbis_comment.num_comments != 3) { + printf("FAILED, expected 3 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_remove_entries_matching(\"blah\")..."); + if((j = FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, "blah")) != 0) { + printf("FAILED, expected 0, got %d\n", j); + return false; + } + if(block->data.vorbis_comment.num_comments != 3) { + printf("FAILED, expected 3 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_remove_entries_matching(\"rem0\")..."); + vc_delete_(vorbiscomment, 1); + vc_delete_(vorbiscomment, 1); + if((j = FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, "rem0")) != 2) { + printf("FAILED, expected 2, got %d\n", j); + return false; + } + if(block->data.vorbis_comment.num_comments != 1) { + printf("FAILED, expected 1 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_set_comment(copy)..."); + vc_set_new_(&entry, vorbiscomment, 0, "name5=field5"); + FLAC__metadata_object_vorbiscomment_set_comment(block, 0, entry, /*copy=*/true); + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_set_vendor_string(copy)..."); + vc_set_vs_new_(&entry, vorbiscomment, "name6=field6"); + FLAC__metadata_object_vorbiscomment_set_vendor_string(block, entry, /*copy=*/true); + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(vorbiscomment); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + vorbiscomment = FLAC__metadata_object_clone(block); + if(0 == vorbiscomment) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(own) on empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name1=field1"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_append_comment(own) on non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 1, "name2=field2"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(vorbiscomment); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + vorbiscomment = FLAC__metadata_object_clone(block); + if(0 == vorbiscomment) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name1=field1"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 0, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on beginning of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 0, "name2=field2"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 0, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on middle of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 1, "name3=field3"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 1, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 3, "name4=field4"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 3, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 4, "name3=field3dup1"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 4, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_insert_comment(own) on end of non-empty array..."); + vc_insert_new_(&entry, vorbiscomment, 5, "name3=field3dup1"); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, 5, entry, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_replace_comment(first, own)..."); + vc_replace_new_(&entry, vorbiscomment, "name3=field3new1", /*all=*/false); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_replace_comment(block, entry, /*all=*/false, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + if(block->data.vorbis_comment.num_comments != 6) { + printf("FAILED, expected 6 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_replace_comment(all, own)..."); + vc_replace_new_(&entry, vorbiscomment, "name3=field3new2", /*all=*/true); + entry_clone_(&entry); + if(!FLAC__metadata_object_vorbiscomment_replace_comment(block, entry, /*all=*/true, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + if(block->data.vorbis_comment.num_comments != 4) { + printf("FAILED, expected 4 comments, got %u\n", block->data.vorbis_comment.num_comments); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on middle of array..."); + vc_delete_(vorbiscomment, 2); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on end of array..."); + vc_delete_(vorbiscomment, 2); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_delete_comment() on beginning of array..."); + vc_delete_(vorbiscomment, 0); + if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_set_comment(own)..."); + vc_set_new_(&entry, vorbiscomment, 0, "name5=field5"); + entry_clone_(&entry); + FLAC__metadata_object_vorbiscomment_set_comment(block, 0, entry, /*copy=*/false); + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_vorbiscomment_set_vendor_string(own)..."); + vc_set_vs_new_(&entry, vorbiscomment, "name6=field6"); + entry_clone_(&entry); + FLAC__metadata_object_vorbiscomment_set_vendor_string(block, entry, /*copy=*/false); + if(!mutils__compare_block(vorbiscomment, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(vorbiscomment); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing CUESHEET\n"); + + { + FLAC__StreamMetadata_CueSheet_Track *track_, *trackcopy_; + + printf("testing FLAC__metadata_object_cuesheet_track_new()... "); + track_ = FLAC__metadata_object_cuesheet_track_new(); + if(0 == track_) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_clone()... "); + trackcopy_ = FLAC__metadata_object_cuesheet_track_clone(track_); + if(0 == trackcopy_) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!compare_track_(trackcopy_, track_)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_delete()... "); + FLAC__metadata_object_cuesheet_track_delete(trackcopy_); + FLAC__metadata_object_cuesheet_track_delete(track_); + printf("OK\n"); + } + + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8; + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + cuesheet = FLAC__metadata_object_clone(block); + if(0 == cuesheet) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + cs_resize_(cuesheet, 2); + printf("testing FLAC__metadata_object_cuesheet_resize_tracks(grow to %u)...", cuesheet->data.cue_sheet.num_tracks); + if(!FLAC__metadata_object_cuesheet_resize_tracks(block, cuesheet->data.cue_sheet.num_tracks)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + cs_resize_(cuesheet, 1); + printf("testing FLAC__metadata_object_cuesheet_resize_tracks(shrink to %u)...", cuesheet->data.cue_sheet.num_tracks); + if(!FLAC__metadata_object_cuesheet_resize_tracks(block, cuesheet->data.cue_sheet.num_tracks)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + cs_resize_(cuesheet, 0); + printf("testing FLAC__metadata_object_cuesheet_resize_tracks(shrink to %u)...", cuesheet->data.cue_sheet.num_tracks); + if(!FLAC__metadata_object_cuesheet_resize_tracks(block, cuesheet->data.cue_sheet.num_tracks)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(copy) on empty array..."); + cs_insert_new_(&track, cuesheet, 0, 0, 1, "ABCDE1234567", false, false); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 0, &track, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(copy) on beginning of non-empty array..."); + cs_insert_new_(&track, cuesheet, 0, 10, 2, "BBCDE1234567", false, false); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 0, &track, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(copy) on middle of non-empty array..."); + cs_insert_new_(&track, cuesheet, 1, 20, 3, "CBCDE1234567", false, false); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 1, &track, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(copy) on end of non-empty array..."); + cs_insert_new_(&track, cuesheet, 3, 30, 4, "DBCDE1234567", false, false); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 3, &track, /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_blank_track() on end of non-empty array..."); + cs_insert_new_(&track, cuesheet, 4, 0, 0, "\0\0\0\0\0\0\0\0\0\0\0\0", false, false); + if(!FLAC__metadata_object_cuesheet_insert_blank_track(block, 4)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on end of array..."); + cs_delete_(cuesheet, 4); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 4)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on middle of array..."); + cs_delete_(cuesheet, 2); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on end of array..."); + cs_delete_(cuesheet, 2); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on beginning of array..."); + cs_delete_(cuesheet, 0); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_set_track(copy)..."); + cs_set_new_(&track, cuesheet, 0, 40, 5, "EBCDE1234567", false, false); + FLAC__metadata_object_cuesheet_set_track(block, 0, &track, /*copy=*/true); + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + tr_resize_(cuesheet, 0, 2); + printf("testing FLAC__metadata_object_cuesheet_track_resize_indices(grow to %u)...", cuesheet->data.cue_sheet.tracks[0].num_indices); + if(!FLAC__metadata_object_cuesheet_track_resize_indices(block, 0, cuesheet->data.cue_sheet.tracks[0].num_indices)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + tr_resize_(cuesheet, 0, 1); + printf("testing FLAC__metadata_object_cuesheet_track_resize_indices(shrink to %u)...", cuesheet->data.cue_sheet.tracks[0].num_indices); + if(!FLAC__metadata_object_cuesheet_track_resize_indices(block, 0, cuesheet->data.cue_sheet.tracks[0].num_indices)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + tr_resize_(cuesheet, 0, 0); + printf("testing FLAC__metadata_object_cuesheet_track_resize_indices(shrink to %u)...", cuesheet->data.cue_sheet.tracks[0].num_indices); + if(!FLAC__metadata_object_cuesheet_track_resize_indices(block, 0, cuesheet->data.cue_sheet.tracks[0].num_indices)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + index.offset = 0; + index.number = 1; + printf("testing FLAC__metadata_object_cuesheet_track_insert_index() on empty array..."); + tr_insert_new_(cuesheet, 0, 0, index); + if(!FLAC__metadata_object_cuesheet_track_insert_index(block, 0, 0, index)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + index.offset = 10; + index.number = 2; + printf("testing FLAC__metadata_object_cuesheet_track_insert_index() on beginning of non-empty array..."); + tr_insert_new_(cuesheet, 0, 0, index); + if(!FLAC__metadata_object_cuesheet_track_insert_index(block, 0, 0, index)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + index.offset = 20; + index.number = 3; + printf("testing FLAC__metadata_object_cuesheet_track_insert_index() on middle of non-empty array..."); + tr_insert_new_(cuesheet, 0, 1, index); + if(!FLAC__metadata_object_cuesheet_track_insert_index(block, 0, 1, index)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + index.offset = 30; + index.number = 4; + printf("testing FLAC__metadata_object_cuesheet_track_insert_index() on end of non-empty array..."); + tr_insert_new_(cuesheet, 0, 3, index); + if(!FLAC__metadata_object_cuesheet_track_insert_index(block, 0, 3, index)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + index.offset = 0; + index.number = 0; + printf("testing FLAC__metadata_object_cuesheet_track_insert_blank_index() on end of non-empty array..."); + tr_insert_new_(cuesheet, 0, 4, index); + if(!FLAC__metadata_object_cuesheet_track_insert_blank_index(block, 0, 4)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_delete_index() on end of array..."); + tr_delete_(cuesheet, 0, 4); + if(!FLAC__metadata_object_cuesheet_track_delete_index(block, 0, 4)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_delete_index() on middle of array..."); + tr_delete_(cuesheet, 0, 2); + if(!FLAC__metadata_object_cuesheet_track_delete_index(block, 0, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_delete_index() on end of array..."); + tr_delete_(cuesheet, 0, 2); + if(!FLAC__metadata_object_cuesheet_track_delete_index(block, 0, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_track_delete_index() on beginning of array..."); + tr_delete_(cuesheet, 0, 0); + if(!FLAC__metadata_object_cuesheet_track_delete_index(block, 0, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(cuesheet); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + cuesheet = FLAC__metadata_object_clone(block); + if(0 == cuesheet) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(own) on empty array..."); + cs_insert_new_(&track, cuesheet, 0, 60, 7, "GBCDE1234567", false, false); + track_clone_(&track); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 0, &track, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(own) on beginning of non-empty array..."); + cs_insert_new_(&track, cuesheet, 0, 70, 8, "HBCDE1234567", false, false); + track_clone_(&track); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 0, &track, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(own) on middle of non-empty array..."); + cs_insert_new_(&track, cuesheet, 1, 80, 9, "IBCDE1234567", false, false); + track_clone_(&track); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 1, &track, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_insert_track(own) on end of non-empty array..."); + cs_insert_new_(&track, cuesheet, 3, 90, 10, "JBCDE1234567", false, false); + track_clone_(&track); + if(!FLAC__metadata_object_cuesheet_insert_track(block, 3, &track, /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on middle of array..."); + cs_delete_(cuesheet, 2); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on end of array..."); + cs_delete_(cuesheet, 2); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 2)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_delete_track() on beginning of array..."); + cs_delete_(cuesheet, 0); + if(!FLAC__metadata_object_cuesheet_delete_track(block, 0)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_set_track(own)..."); + cs_set_new_(&track, cuesheet, 0, 100, 11, "KBCDE1234567", false, false); + track_clone_(&track); + FLAC__metadata_object_cuesheet_set_track(block, 0, &track, /*copy=*/false); + if(!mutils__compare_block(cuesheet, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_cuesheet_is_legal()..."); + { + const char *violation; + if(FLAC__metadata_object_cuesheet_is_legal(block, /*check_cd_da_subset=*/true, &violation)) { + printf("FAILED, returned true when expecting false\n"); + return false; + } + printf("returned false as expected, violation=\"%s\" OK\n", violation); + } + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(cuesheet); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + printf("testing PICTURE\n"); + + printf("testing FLAC__metadata_object_new()... "); + block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PICTURE); + if(0 == block) { + printf("FAILED, returned NULL\n"); + return false; + } + expected_length = ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN + ) / 8; + if(block->length != expected_length) { + printf("FAILED, bad length, expected %u, got %u\n", expected_length, block->length); + return false; + } + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + picture = FLAC__metadata_object_clone(block); + if(0 == picture) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + pi_set_mime_type(picture, "image/png\t"); + printf("testing FLAC__metadata_object_picture_set_mime_type(copy)..."); + if(!FLAC__metadata_object_picture_set_mime_type(block, "image/png\t", /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned true when expecting false\n"); + return false; + } + printf("returned false as expected, violation=\"%s\" OK\n", violation); + } + + pi_set_mime_type(picture, "image/png"); + printf("testing FLAC__metadata_object_picture_set_mime_type(copy)..."); + if(!FLAC__metadata_object_picture_set_mime_type(block, "image/png", /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(!FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned false, violation=\"%s\"\n", violation); + return false; + } + printf("OK\n"); + } + + pi_set_description(picture, (const FLAC__byte *)"DESCRIPTION\xff"); + printf("testing FLAC__metadata_object_picture_set_description(copy)..."); + if(!FLAC__metadata_object_picture_set_description(block, (FLAC__byte *)"DESCRIPTION\xff", /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned true when expecting false\n"); + return false; + } + printf("returned false as expected, violation=\"%s\" OK\n", violation); + } + + pi_set_description(picture, (const FLAC__byte *)"DESCRIPTION"); + printf("testing FLAC__metadata_object_picture_set_description(copy)..."); + if(!FLAC__metadata_object_picture_set_description(block, (FLAC__byte *)"DESCRIPTION", /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(!FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned false, violation=\"%s\"\n", violation); + return false; + } + printf("OK\n"); + } + + + pi_set_data(picture, (const FLAC__byte*)"PNGDATA", strlen("PNGDATA")); + printf("testing FLAC__metadata_object_picture_set_data(copy)..."); + if(!FLAC__metadata_object_picture_set_data(block, (FLAC__byte*)"PNGDATA", strlen("PNGDATA"), /*copy=*/true)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + pi_set_mime_type(picture, "image/png\t"); + printf("testing FLAC__metadata_object_picture_set_mime_type(own)..."); + if(!FLAC__metadata_object_picture_set_mime_type(block, strdup("image/png\t"), /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned true when expecting false\n"); + return false; + } + printf("returned false as expected, violation=\"%s\" OK\n", violation); + } + + pi_set_mime_type(picture, "image/png"); + printf("testing FLAC__metadata_object_picture_set_mime_type(own)..."); + if(!FLAC__metadata_object_picture_set_mime_type(block, strdup("image/png"), /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(!FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned false, violation=\"%s\"\n", violation); + return false; + } + printf("OK\n"); + } + + pi_set_description(picture, (const FLAC__byte *)"DESCRIPTION\xff"); + printf("testing FLAC__metadata_object_picture_set_description(own)..."); + if(!FLAC__metadata_object_picture_set_description(block, (FLAC__byte *)strdup("DESCRIPTION\xff"), /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned true when expecting false\n"); + return false; + } + printf("returned false as expected, violation=\"%s\" OK\n", violation); + } + + pi_set_description(picture, (const FLAC__byte *)"DESCRIPTION"); + printf("testing FLAC__metadata_object_picture_set_description(own)..."); + if(!FLAC__metadata_object_picture_set_description(block, (FLAC__byte *)strdup("DESCRIPTION"), /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_picture_is_legal()..."); + { + const char *violation; + if(!FLAC__metadata_object_picture_is_legal(block, &violation)) { + printf("FAILED, returned false, violation=\"%s\"\n", violation); + return false; + } + printf("OK\n"); + } + + pi_set_data(picture, (const FLAC__byte*)"PNGDATA", strlen("PNGDATA")); + printf("testing FLAC__metadata_object_picture_set_data(own)..."); + if(!FLAC__metadata_object_picture_set_data(block, (FLAC__byte*)strdup("PNGDATA"), strlen("PNGDATA"), /*copy=*/false)) { + printf("FAILED, returned false\n"); + return false; + } + if(!mutils__compare_block(picture, block)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_clone()... "); + blockcopy = FLAC__metadata_object_clone(block); + if(0 == blockcopy) { + printf("FAILED, returned NULL\n"); + return false; + } + if(!mutils__compare_block(block, blockcopy)) + return false; + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(blockcopy); + printf("OK\n"); + + printf("testing FLAC__metadata_object_delete()... "); + FLAC__metadata_object_delete(picture); + FLAC__metadata_object_delete(block); + printf("OK\n"); + + + return true; +} diff --git a/flac/src/test_libFLAC/test_libFLAC.dsp b/flac/src/test_libFLAC/test_libFLAC.dsp new file mode 100644 index 0000000..9563c12 --- /dev/null +++ b/flac/src/test_libFLAC/test_libFLAC.dsp @@ -0,0 +1,148 @@ +# Microsoft Developer Studio Project File - Name="test_libFLAC" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_libFLAC - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_libFLAC.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_libFLAC.mak" CFG="test_libFLAC - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_libFLAC - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_libFLAC - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_libFLAC - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\libFLAC\include" /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\grabbag_static.lib ..\..\obj\release\lib\replaygain_analysis_static.lib ..\..\obj\release\lib\test_libs_common_static.lib ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_libFLAC - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\libFLAC\include" /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\grabbag_static.lib ..\..\obj\debug\lib\replaygain_analysis_static.lib ..\..\obj\debug\lib\test_libs_common_static.lib ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_libFLAC - Win32 Release" +# Name "test_libFLAC - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\bitwriter.c +# End Source File +# Begin Source File + +SOURCE=.\decoders.c +# End Source File +# Begin Source File + +SOURCE=.\encoders.c +# End Source File +# Begin Source File + +SOURCE=.\format.c +# End Source File +# Begin Source File + +SOURCE=.\main.c +# End Source File +# Begin Source File + +SOURCE=.\metadata.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_manip.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_object.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\bitwriter.h +# End Source File +# Begin Source File + +SOURCE=.\decoders.h +# End Source File +# Begin Source File + +SOURCE=.\encoders.h +# End Source File +# Begin Source File + +SOURCE=.\format.h +# End Source File +# Begin Source File + +SOURCE=.\metadata.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/test_libFLAC/test_libFLAC.vcproj b/flac/src/test_libFLAC/test_libFLAC.vcproj new file mode 100644 index 0000000..79ab58b --- /dev/null +++ b/flac/src/test_libFLAC/test_libFLAC.vcproj @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_libs_common/Makefile.am b/flac/src/test_libs_common/Makefile.am new file mode 100644 index 0000000..bfc192e --- /dev/null +++ b/flac/src/test_libs_common/Makefile.am @@ -0,0 +1,30 @@ +# test_libs_common - Common code to library unit tests +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +INCLUDES = -I$(top_srcdir)/include + +noinst_LTLIBRARIES = libtest_libs_common.la + +libtest_libs_common_la_SOURCES = \ + file_utils_flac.c \ + metadata_utils.c + +EXTRA_DIST = \ + Makefile.lite \ + README \ + test_libs_common_static.dsp \ + test_libs_common_static.vcproj diff --git a/flac/src/test_libs_common/Makefile.lite b/flac/src/test_libs_common/Makefile.lite new file mode 100644 index 0000000..52b8317 --- /dev/null +++ b/flac/src/test_libs_common/Makefile.lite @@ -0,0 +1,35 @@ +# test_libs_common - Common code to library unit tests +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +LIB_NAME = libtest_libs_common + +INCLUDES = -I$(topdir)/include + +SRCS_C = \ + file_utils_flac.c \ + metadata_utils.c + +include $(topdir)/build/lib.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_libs_common/README b/flac/src/test_libs_common/README new file mode 100644 index 0000000..0f95d35 --- /dev/null +++ b/flac/src/test_libs_common/README @@ -0,0 +1,2 @@ +This directory contains a convenience library of routines that are +common to the library unit testers. diff --git a/flac/src/test_libs_common/file_utils_flac.c b/flac/src/test_libs_common/file_utils_flac.c new file mode 100644 index 0000000..1b14263 --- /dev/null +++ b/flac/src/test_libs_common/file_utils_flac.c @@ -0,0 +1,153 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/assert.h" +#include "FLAC/stream_encoder.h" +#include "test_libs_common/file_utils_flac.h" +#include +#include +#include /* for stat() */ + +#ifdef min +#undef min +#endif +#define min(a,b) ((a)<(b)?(a):(b)) + +const long file_utils__ogg_serial_number = 12345; + +#ifdef FLAC__VALGRIND_TESTING +static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + size_t ret = fwrite(ptr, size, nmemb, stream); + if(!ferror(stream)) + fflush(stream); + return ret; +} +#else +#define local__fwrite fwrite +#endif + +typedef struct { + FILE *file; +} encoder_client_struct; + +static FLAC__StreamEncoderWriteStatus encoder_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) +{ + encoder_client_struct *ecd = (encoder_client_struct*)client_data; + + (void)encoder, (void)samples, (void)current_frame; + + if(local__fwrite(buffer, 1, bytes, ecd->file) != bytes) + return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; + else + return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; +} + +static void encoder_metadata_callback_(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + (void)encoder, (void)metadata, (void)client_data; +} + +FLAC__bool file_utils__generate_flacfile(FLAC__bool is_ogg, const char *output_filename, off_t *output_filesize, unsigned length, const FLAC__StreamMetadata *streaminfo, FLAC__StreamMetadata **metadata, unsigned num_metadata) +{ + FLAC__int32 samples[1024]; + FLAC__StreamEncoder *encoder; + FLAC__StreamEncoderInitStatus init_status; + encoder_client_struct encoder_client_data; + unsigned i, n; + + FLAC__ASSERT(0 != output_filename); + FLAC__ASSERT(0 != streaminfo); + FLAC__ASSERT(streaminfo->type == FLAC__METADATA_TYPE_STREAMINFO); + FLAC__ASSERT((streaminfo->is_last && num_metadata == 0) || (!streaminfo->is_last && num_metadata > 0)); + + if(0 == (encoder_client_data.file = fopen(output_filename, "wb"))) + return false; + + encoder = FLAC__stream_encoder_new(); + if(0 == encoder) { + fclose(encoder_client_data.file); + return false; + } + + FLAC__stream_encoder_set_ogg_serial_number(encoder, file_utils__ogg_serial_number); + FLAC__stream_encoder_set_verify(encoder, true); + FLAC__stream_encoder_set_streamable_subset(encoder, true); + FLAC__stream_encoder_set_do_mid_side_stereo(encoder, false); + FLAC__stream_encoder_set_loose_mid_side_stereo(encoder, false); + FLAC__stream_encoder_set_channels(encoder, streaminfo->data.stream_info.channels); + FLAC__stream_encoder_set_bits_per_sample(encoder, streaminfo->data.stream_info.bits_per_sample); + FLAC__stream_encoder_set_sample_rate(encoder, streaminfo->data.stream_info.sample_rate); + FLAC__stream_encoder_set_blocksize(encoder, streaminfo->data.stream_info.min_blocksize); + FLAC__stream_encoder_set_max_lpc_order(encoder, 0); + FLAC__stream_encoder_set_qlp_coeff_precision(encoder, 0); + FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder, false); + FLAC__stream_encoder_set_do_escape_coding(encoder, false); + FLAC__stream_encoder_set_do_exhaustive_model_search(encoder, false); + FLAC__stream_encoder_set_min_residual_partition_order(encoder, 0); + FLAC__stream_encoder_set_max_residual_partition_order(encoder, 0); + FLAC__stream_encoder_set_rice_parameter_search_dist(encoder, 0); + FLAC__stream_encoder_set_total_samples_estimate(encoder, streaminfo->data.stream_info.total_samples); + FLAC__stream_encoder_set_metadata(encoder, metadata, num_metadata); + + if(is_ogg) + init_status = FLAC__stream_encoder_init_ogg_stream(encoder, /*read_callback=*/0, encoder_write_callback_, /*seek_callback=*/0, /*tell_callback=*/0, encoder_metadata_callback_, &encoder_client_data); + else + init_status = FLAC__stream_encoder_init_stream(encoder, encoder_write_callback_, /*seek_callback=*/0, /*tell_callback=*/0, encoder_metadata_callback_, &encoder_client_data); + + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + fclose(encoder_client_data.file); + return false; + } + + /* init the dummy sample buffer */ + for(i = 0; i < sizeof(samples) / sizeof(FLAC__int32); i++) + samples[i] = i & 7; + + while(length > 0) { + n = min(length, sizeof(samples) / sizeof(FLAC__int32)); + + if(!FLAC__stream_encoder_process_interleaved(encoder, samples, n)) { + fclose(encoder_client_data.file); + return false; + } + + length -= n; + } + + (void)FLAC__stream_encoder_finish(encoder); + + fclose(encoder_client_data.file); + + FLAC__stream_encoder_delete(encoder); + + if(0 != output_filesize) { + struct stat filestats; + + if(stat(output_filename, &filestats) != 0) + return false; + else + *output_filesize = filestats.st_size; + } + + return true; +} diff --git a/flac/src/test_libs_common/metadata_utils.c b/flac/src/test_libs_common/metadata_utils.c new file mode 100644 index 0000000..a9076ac --- /dev/null +++ b/flac/src/test_libs_common/metadata_utils.c @@ -0,0 +1,657 @@ +/* test_libFLAC - Unit tester for libFLAC + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * These are not tests, just utility functions used by the metadata tests + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include "FLAC/metadata.h" +#include "test_libs_common/metadata_utils.h" +#include +#include /* for malloc() */ +#include /* for memcmp() */ + +FLAC__bool mutils__compare_block_data_streaminfo(const FLAC__StreamMetadata_StreamInfo *block, const FLAC__StreamMetadata_StreamInfo *blockcopy) +{ + if(blockcopy->min_blocksize != block->min_blocksize) { + printf("FAILED, min_blocksize mismatch, expected %u, got %u\n", block->min_blocksize, blockcopy->min_blocksize); + return false; + } + if(blockcopy->max_blocksize != block->max_blocksize) { + printf("FAILED, max_blocksize mismatch, expected %u, got %u\n", block->max_blocksize, blockcopy->max_blocksize); + return false; + } + if(blockcopy->min_framesize != block->min_framesize) { + printf("FAILED, min_framesize mismatch, expected %u, got %u\n", block->min_framesize, blockcopy->min_framesize); + return false; + } + if(blockcopy->max_framesize != block->max_framesize) { + printf("FAILED, max_framesize mismatch, expected %u, got %u\n", block->max_framesize, blockcopy->max_framesize); + return false; + } + if(blockcopy->sample_rate != block->sample_rate) { + printf("FAILED, sample_rate mismatch, expected %u, got %u\n", block->sample_rate, blockcopy->sample_rate); + return false; + } + if(blockcopy->channels != block->channels) { + printf("FAILED, channels mismatch, expected %u, got %u\n", block->channels, blockcopy->channels); + return false; + } + if(blockcopy->bits_per_sample != block->bits_per_sample) { + printf("FAILED, bits_per_sample mismatch, expected %u, got %u\n", block->bits_per_sample, blockcopy->bits_per_sample); + return false; + } + if(blockcopy->total_samples != block->total_samples) { +#ifdef _MSC_VER + printf("FAILED, total_samples mismatch, expected %I64u, got %I64u\n", block->total_samples, blockcopy->total_samples); +#else + printf("FAILED, total_samples mismatch, expected %llu, got %llu\n", (unsigned long long)block->total_samples, (unsigned long long)blockcopy->total_samples); +#endif + return false; + } + if(0 != memcmp(blockcopy->md5sum, block->md5sum, sizeof(block->md5sum))) { + printf("FAILED, md5sum mismatch, expected %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X, got %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n", + (unsigned)block->md5sum[0], + (unsigned)block->md5sum[1], + (unsigned)block->md5sum[2], + (unsigned)block->md5sum[3], + (unsigned)block->md5sum[4], + (unsigned)block->md5sum[5], + (unsigned)block->md5sum[6], + (unsigned)block->md5sum[7], + (unsigned)block->md5sum[8], + (unsigned)block->md5sum[9], + (unsigned)block->md5sum[10], + (unsigned)block->md5sum[11], + (unsigned)block->md5sum[12], + (unsigned)block->md5sum[13], + (unsigned)block->md5sum[14], + (unsigned)block->md5sum[15], + (unsigned)blockcopy->md5sum[0], + (unsigned)blockcopy->md5sum[1], + (unsigned)blockcopy->md5sum[2], + (unsigned)blockcopy->md5sum[3], + (unsigned)blockcopy->md5sum[4], + (unsigned)blockcopy->md5sum[5], + (unsigned)blockcopy->md5sum[6], + (unsigned)blockcopy->md5sum[7], + (unsigned)blockcopy->md5sum[8], + (unsigned)blockcopy->md5sum[9], + (unsigned)blockcopy->md5sum[10], + (unsigned)blockcopy->md5sum[11], + (unsigned)blockcopy->md5sum[12], + (unsigned)blockcopy->md5sum[13], + (unsigned)blockcopy->md5sum[14], + (unsigned)blockcopy->md5sum[15] + ); + return false; + } + return true; +} + +FLAC__bool mutils__compare_block_data_padding(const FLAC__StreamMetadata_Padding *block, const FLAC__StreamMetadata_Padding *blockcopy, unsigned block_length) +{ + /* we don't compare the padding guts */ + (void)block, (void)blockcopy, (void)block_length; + return true; +} + +FLAC__bool mutils__compare_block_data_application(const FLAC__StreamMetadata_Application *block, const FLAC__StreamMetadata_Application *blockcopy, unsigned block_length) +{ + if(block_length < sizeof(block->id)) { + printf("FAILED, bad block length = %u\n", block_length); + return false; + } + if(0 != memcmp(blockcopy->id, block->id, sizeof(block->id))) { + printf("FAILED, id mismatch, expected %02X%02X%02X%02X, got %02X%02X%02X%02X\n", + (unsigned)block->id[0], + (unsigned)block->id[1], + (unsigned)block->id[2], + (unsigned)block->id[3], + (unsigned)blockcopy->id[0], + (unsigned)blockcopy->id[1], + (unsigned)blockcopy->id[2], + (unsigned)blockcopy->id[3] + ); + return false; + } + if(0 == block->data || 0 == blockcopy->data) { + if(block->data != blockcopy->data) { + printf("FAILED, data mismatch (%s's data pointer is null)\n", 0==block->data?"original":"copy"); + return false; + } + else if(block_length - sizeof(block->id) > 0) { + printf("FAILED, data pointer is null but block length is not 0\n"); + return false; + } + } + else { + if(block_length - sizeof(block->id) == 0) { + printf("FAILED, data pointer is not null but block length is 0\n"); + return false; + } + else if(0 != memcmp(blockcopy->data, block->data, block_length - sizeof(block->id))) { + printf("FAILED, data mismatch\n"); + return false; + } + } + return true; +} + +FLAC__bool mutils__compare_block_data_seektable(const FLAC__StreamMetadata_SeekTable *block, const FLAC__StreamMetadata_SeekTable *blockcopy) +{ + unsigned i; + if(blockcopy->num_points != block->num_points) { + printf("FAILED, num_points mismatch, expected %u, got %u\n", block->num_points, blockcopy->num_points); + return false; + } + for(i = 0; i < block->num_points; i++) { + if(blockcopy->points[i].sample_number != block->points[i].sample_number) { +#ifdef _MSC_VER + printf("FAILED, points[%u].sample_number mismatch, expected %I64u, got %I64u\n", i, block->points[i].sample_number, blockcopy->points[i].sample_number); +#else + printf("FAILED, points[%u].sample_number mismatch, expected %llu, got %llu\n", i, (unsigned long long)block->points[i].sample_number, (unsigned long long)blockcopy->points[i].sample_number); +#endif + return false; + } + if(blockcopy->points[i].stream_offset != block->points[i].stream_offset) { +#ifdef _MSC_VER + printf("FAILED, points[%u].stream_offset mismatch, expected %I64u, got %I64u\n", i, block->points[i].stream_offset, blockcopy->points[i].stream_offset); +#else + printf("FAILED, points[%u].stream_offset mismatch, expected %llu, got %llu\n", i, (unsigned long long)block->points[i].stream_offset, (unsigned long long)blockcopy->points[i].stream_offset); +#endif + return false; + } + if(blockcopy->points[i].frame_samples != block->points[i].frame_samples) { + printf("FAILED, points[%u].frame_samples mismatch, expected %u, got %u\n", i, block->points[i].frame_samples, blockcopy->points[i].frame_samples); + return false; + } + } + return true; +} + +FLAC__bool mutils__compare_block_data_vorbiscomment(const FLAC__StreamMetadata_VorbisComment *block, const FLAC__StreamMetadata_VorbisComment *blockcopy) +{ + unsigned i; + if(blockcopy->vendor_string.length != block->vendor_string.length) { + printf("FAILED, vendor_string.length mismatch, expected %u, got %u\n", block->vendor_string.length, blockcopy->vendor_string.length); + return false; + } + if(0 == block->vendor_string.entry || 0 == blockcopy->vendor_string.entry) { + if(block->vendor_string.entry != blockcopy->vendor_string.entry) { + printf("FAILED, vendor_string.entry mismatch\n"); + return false; + } + } + else if(0 != memcmp(blockcopy->vendor_string.entry, block->vendor_string.entry, block->vendor_string.length)) { + printf("FAILED, vendor_string.entry mismatch\n"); + return false; + } + if(blockcopy->num_comments != block->num_comments) { + printf("FAILED, num_comments mismatch, expected %u, got %u\n", block->num_comments, blockcopy->num_comments); + return false; + } + for(i = 0; i < block->num_comments; i++) { + if(blockcopy->comments[i].length != block->comments[i].length) { + printf("FAILED, comments[%u].length mismatch, expected %u, got %u\n", i, block->comments[i].length, blockcopy->comments[i].length); + return false; + } + if(0 == block->comments[i].entry || 0 == blockcopy->comments[i].entry) { + if(block->comments[i].entry != blockcopy->comments[i].entry) { + printf("FAILED, comments[%u].entry mismatch\n", i); + return false; + } + } + else { + if(0 != memcmp(blockcopy->comments[i].entry, block->comments[i].entry, block->comments[i].length)) { + printf("FAILED, comments[%u].entry mismatch\n", i); + return false; + } + } + } + return true; +} + +FLAC__bool mutils__compare_block_data_cuesheet(const FLAC__StreamMetadata_CueSheet *block, const FLAC__StreamMetadata_CueSheet *blockcopy) +{ + unsigned i, j; + + if(0 != strcmp(blockcopy->media_catalog_number, block->media_catalog_number)) { + printf("FAILED, media_catalog_number mismatch, expected %s, got %s\n", block->media_catalog_number, blockcopy->media_catalog_number); + return false; + } + if(blockcopy->lead_in != block->lead_in) { +#ifdef _MSC_VER + printf("FAILED, lead_in mismatch, expected %I64u, got %I64u\n", block->lead_in, blockcopy->lead_in); +#else + printf("FAILED, lead_in mismatch, expected %llu, got %llu\n", (unsigned long long)block->lead_in, (unsigned long long)blockcopy->lead_in); +#endif + return false; + } + if(blockcopy->is_cd != block->is_cd) { + printf("FAILED, is_cd mismatch, expected %u, got %u\n", (unsigned)block->is_cd, (unsigned)blockcopy->is_cd); + return false; + } + if(blockcopy->num_tracks != block->num_tracks) { + printf("FAILED, num_tracks mismatch, expected %u, got %u\n", block->num_tracks, blockcopy->num_tracks); + return false; + } + for(i = 0; i < block->num_tracks; i++) { + if(blockcopy->tracks[i].offset != block->tracks[i].offset) { +#ifdef _MSC_VER + printf("FAILED, tracks[%u].offset mismatch, expected %I64u, got %I64u\n", i, block->tracks[i].offset, blockcopy->tracks[i].offset); +#else + printf("FAILED, tracks[%u].offset mismatch, expected %llu, got %llu\n", i, (unsigned long long)block->tracks[i].offset, (unsigned long long)blockcopy->tracks[i].offset); +#endif + return false; + } + if(blockcopy->tracks[i].number != block->tracks[i].number) { + printf("FAILED, tracks[%u].number mismatch, expected %u, got %u\n", i, (unsigned)block->tracks[i].number, (unsigned)blockcopy->tracks[i].number); + return false; + } + if(blockcopy->tracks[i].num_indices != block->tracks[i].num_indices) { + printf("FAILED, tracks[%u].num_indices mismatch, expected %u, got %u\n", i, (unsigned)block->tracks[i].num_indices, (unsigned)blockcopy->tracks[i].num_indices); + return false; + } + /* num_indices == 0 means lead-out track so only the track offset and number are valid */ + if(block->tracks[i].num_indices > 0) { + if(0 != strcmp(blockcopy->tracks[i].isrc, block->tracks[i].isrc)) { + printf("FAILED, tracks[%u].isrc mismatch, expected %s, got %s\n", i, block->tracks[i].isrc, blockcopy->tracks[i].isrc); + return false; + } + if(blockcopy->tracks[i].type != block->tracks[i].type) { + printf("FAILED, tracks[%u].type mismatch, expected %u, got %u\n", i, (unsigned)block->tracks[i].type, (unsigned)blockcopy->tracks[i].type); + return false; + } + if(blockcopy->tracks[i].pre_emphasis != block->tracks[i].pre_emphasis) { + printf("FAILED, tracks[%u].pre_emphasis mismatch, expected %u, got %u\n", i, (unsigned)block->tracks[i].pre_emphasis, (unsigned)blockcopy->tracks[i].pre_emphasis); + return false; + } + if(0 == block->tracks[i].indices || 0 == blockcopy->tracks[i].indices) { + if(block->tracks[i].indices != blockcopy->tracks[i].indices) { + printf("FAILED, tracks[%u].indices mismatch\n", i); + return false; + } + } + else { + for(j = 0; j < block->tracks[i].num_indices; j++) { + if(blockcopy->tracks[i].indices[j].offset != block->tracks[i].indices[j].offset) { +#ifdef _MSC_VER + printf("FAILED, tracks[%u].indices[%u].offset mismatch, expected %I64u, got %I64u\n", i, j, block->tracks[i].indices[j].offset, blockcopy->tracks[i].indices[j].offset); +#else + printf("FAILED, tracks[%u].indices[%u].offset mismatch, expected %llu, got %llu\n", i, j, (unsigned long long)block->tracks[i].indices[j].offset, (unsigned long long)blockcopy->tracks[i].indices[j].offset); +#endif + return false; + } + if(blockcopy->tracks[i].indices[j].number != block->tracks[i].indices[j].number) { + printf("FAILED, tracks[%u].indices[%u].number mismatch, expected %u, got %u\n", i, j, (unsigned)block->tracks[i].indices[j].number, (unsigned)blockcopy->tracks[i].indices[j].number); + return false; + } + } + } + } + } + return true; +} + +FLAC__bool mutils__compare_block_data_picture(const FLAC__StreamMetadata_Picture *block, const FLAC__StreamMetadata_Picture *blockcopy) +{ + size_t len, lencopy; + if(blockcopy->type != block->type) { + printf("FAILED, type mismatch, expected %u, got %u\n", (unsigned)block->type, (unsigned)blockcopy->type); + return false; + } + len = strlen(block->mime_type); + lencopy = strlen(blockcopy->mime_type); + if(lencopy != len) { + printf("FAILED, mime_type length mismatch, expected %u, got %u\n", (unsigned)len, (unsigned)lencopy); + return false; + } + if(strcmp(blockcopy->mime_type, block->mime_type)) { + printf("FAILED, mime_type mismatch, expected %s, got %s\n", block->mime_type, blockcopy->mime_type); + return false; + } + len = strlen((const char *)block->description); + lencopy = strlen((const char *)blockcopy->description); + if(lencopy != len) { + printf("FAILED, description length mismatch, expected %u, got %u\n", (unsigned)len, (unsigned)lencopy); + return false; + } + if(strcmp((const char *)blockcopy->description, (const char *)block->description)) { + printf("FAILED, description mismatch, expected %s, got %s\n", block->description, blockcopy->description); + return false; + } + if(blockcopy->width != block->width) { + printf("FAILED, width mismatch, expected %u, got %u\n", block->width, blockcopy->width); + return false; + } + if(blockcopy->height != block->height) { + printf("FAILED, height mismatch, expected %u, got %u\n", block->height, blockcopy->height); + return false; + } + if(blockcopy->depth != block->depth) { + printf("FAILED, depth mismatch, expected %u, got %u\n", block->depth, blockcopy->depth); + return false; + } + if(blockcopy->colors != block->colors) { + printf("FAILED, colors mismatch, expected %u, got %u\n", block->colors, blockcopy->colors); + return false; + } + if(blockcopy->data_length != block->data_length) { + printf("FAILED, data_length mismatch, expected %u, got %u\n", block->data_length, blockcopy->data_length); + return false; + } + if(memcmp(blockcopy->data, block->data, block->data_length)) { + printf("FAILED, data mismatch\n"); + return false; + } + return true; +} + +FLAC__bool mutils__compare_block_data_unknown(const FLAC__StreamMetadata_Unknown *block, const FLAC__StreamMetadata_Unknown *blockcopy, unsigned block_length) +{ + if(0 == block->data || 0 == blockcopy->data) { + if(block->data != blockcopy->data) { + printf("FAILED, data mismatch (%s's data pointer is null)\n", 0==block->data?"original":"copy"); + return false; + } + else if(block_length > 0) { + printf("FAILED, data pointer is null but block length is not 0\n"); + return false; + } + } + else { + if(block_length == 0) { + printf("FAILED, data pointer is not null but block length is 0\n"); + return false; + } + else if(0 != memcmp(blockcopy->data, block->data, block_length)) { + printf("FAILED, data mismatch\n"); + return false; + } + } + return true; +} + +FLAC__bool mutils__compare_block(const FLAC__StreamMetadata *block, const FLAC__StreamMetadata *blockcopy) +{ + if(blockcopy->type != block->type) { + printf("FAILED, type mismatch, expected %s, got %s\n", FLAC__MetadataTypeString[block->type], FLAC__MetadataTypeString[blockcopy->type]); + return false; + } + if(blockcopy->is_last != block->is_last) { + printf("FAILED, is_last mismatch, expected %u, got %u\n", (unsigned)block->is_last, (unsigned)blockcopy->is_last); + return false; + } + if(blockcopy->length != block->length) { + printf("FAILED, length mismatch, expected %u, got %u\n", block->length, blockcopy->length); + return false; + } + switch(block->type) { + case FLAC__METADATA_TYPE_STREAMINFO: + return mutils__compare_block_data_streaminfo(&block->data.stream_info, &blockcopy->data.stream_info); + case FLAC__METADATA_TYPE_PADDING: + return mutils__compare_block_data_padding(&block->data.padding, &blockcopy->data.padding, block->length); + case FLAC__METADATA_TYPE_APPLICATION: + return mutils__compare_block_data_application(&block->data.application, &blockcopy->data.application, block->length); + case FLAC__METADATA_TYPE_SEEKTABLE: + return mutils__compare_block_data_seektable(&block->data.seek_table, &blockcopy->data.seek_table); + case FLAC__METADATA_TYPE_VORBIS_COMMENT: + return mutils__compare_block_data_vorbiscomment(&block->data.vorbis_comment, &blockcopy->data.vorbis_comment); + case FLAC__METADATA_TYPE_CUESHEET: + return mutils__compare_block_data_cuesheet(&block->data.cue_sheet, &blockcopy->data.cue_sheet); + case FLAC__METADATA_TYPE_PICTURE: + return mutils__compare_block_data_picture(&block->data.picture, &blockcopy->data.picture); + default: + return mutils__compare_block_data_unknown(&block->data.unknown, &blockcopy->data.unknown, block->length); + } +} + +static void *malloc_or_die_(size_t size) +{ + void *x = malloc(size); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory allocating %u bytes\n", (unsigned)size); + exit(1); + } + return x; +} + +static void *calloc_or_die_(size_t n, size_t size) +{ + void *x = calloc(n, size); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory allocating %u bytes\n", (unsigned)n * (unsigned)size); + exit(1); + } + return x; +} + +static char *strdup_or_die_(const char *s) +{ + char *x = strdup(s); + if(0 == x) { + fprintf(stderr, "ERROR: out of memory copying string \"%s\"\n", s); + exit(1); + } + return x; +} + +void mutils__init_metadata_blocks( + FLAC__StreamMetadata *streaminfo, + FLAC__StreamMetadata *padding, + FLAC__StreamMetadata *seektable, + FLAC__StreamMetadata *application1, + FLAC__StreamMetadata *application2, + FLAC__StreamMetadata *vorbiscomment, + FLAC__StreamMetadata *cuesheet, + FLAC__StreamMetadata *picture, + FLAC__StreamMetadata *unknown +) +{ + /* + most of the actual numbers and data in the blocks don't matter, + we just want to make sure the decoder parses them correctly + + remember, the metadata interface gets tested after the decoders, + so we do all the metadata manipulation here without it. + */ + + /* min/max_framesize and md5sum don't get written at first, so we have to leave them 0 */ + streaminfo->is_last = false; + streaminfo->type = FLAC__METADATA_TYPE_STREAMINFO; + streaminfo->length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH; + streaminfo->data.stream_info.min_blocksize = 576; + streaminfo->data.stream_info.max_blocksize = 576; + streaminfo->data.stream_info.min_framesize = 0; + streaminfo->data.stream_info.max_framesize = 0; + streaminfo->data.stream_info.sample_rate = 44100; + streaminfo->data.stream_info.channels = 1; + streaminfo->data.stream_info.bits_per_sample = 8; + streaminfo->data.stream_info.total_samples = 0; + memset(streaminfo->data.stream_info.md5sum, 0, 16); + + padding->is_last = false; + padding->type = FLAC__METADATA_TYPE_PADDING; + padding->length = 1234; + + seektable->is_last = false; + seektable->type = FLAC__METADATA_TYPE_SEEKTABLE; + seektable->data.seek_table.num_points = 2; + seektable->length = seektable->data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH; + seektable->data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)malloc_or_die_(seektable->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint)); + seektable->data.seek_table.points[0].sample_number = 0; + seektable->data.seek_table.points[0].stream_offset = 0; + seektable->data.seek_table.points[0].frame_samples = streaminfo->data.stream_info.min_blocksize; + seektable->data.seek_table.points[1].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; + seektable->data.seek_table.points[1].stream_offset = 1000; + seektable->data.seek_table.points[1].frame_samples = streaminfo->data.stream_info.min_blocksize; + + application1->is_last = false; + application1->type = FLAC__METADATA_TYPE_APPLICATION; + application1->length = 8; + memcpy(application1->data.application.id, "\xfe\xdc\xba\x98", 4); + application1->data.application.data = (FLAC__byte*)malloc_or_die_(4); + memcpy(application1->data.application.data, "\xf0\xe1\xd2\xc3", 4); + + application2->is_last = false; + application2->type = FLAC__METADATA_TYPE_APPLICATION; + application2->length = 4; + memcpy(application2->data.application.id, "\x76\x54\x32\x10", 4); + application2->data.application.data = 0; + + { + const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING); + vorbiscomment->is_last = false; + vorbiscomment->type = FLAC__METADATA_TYPE_VORBIS_COMMENT; + vorbiscomment->length = (4 + vendor_string_length) + 4 + (4 + 5) + (4 + 0); + vorbiscomment->data.vorbis_comment.vendor_string.length = vendor_string_length; + vorbiscomment->data.vorbis_comment.vendor_string.entry = (FLAC__byte*)malloc_or_die_(vendor_string_length+1); + memcpy(vorbiscomment->data.vorbis_comment.vendor_string.entry, FLAC__VENDOR_STRING, vendor_string_length+1); + vorbiscomment->data.vorbis_comment.num_comments = 2; + vorbiscomment->data.vorbis_comment.comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc_or_die_(vorbiscomment->data.vorbis_comment.num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)); + vorbiscomment->data.vorbis_comment.comments[0].length = 5; + vorbiscomment->data.vorbis_comment.comments[0].entry = (FLAC__byte*)malloc_or_die_(5+1); + memcpy(vorbiscomment->data.vorbis_comment.comments[0].entry, "ab=cd", 5+1); + vorbiscomment->data.vorbis_comment.comments[1].length = 0; + vorbiscomment->data.vorbis_comment.comments[1].entry = 0; + } + + cuesheet->is_last = false; + cuesheet->type = FLAC__METADATA_TYPE_CUESHEET; + cuesheet->length = + /* cuesheet guts */ + ( + FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN + + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN + ) / 8 + + /* 2 tracks */ + 3 * ( + FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN + + FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN + ) / 8 + + /* 3 index points */ + 3 * ( + FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN + + FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN + ) / 8 + ; + memset(cuesheet->data.cue_sheet.media_catalog_number, 0, sizeof(cuesheet->data.cue_sheet.media_catalog_number)); + cuesheet->data.cue_sheet.media_catalog_number[0] = 'j'; + cuesheet->data.cue_sheet.media_catalog_number[1] = 'C'; + cuesheet->data.cue_sheet.lead_in = 2 * 44100; + cuesheet->data.cue_sheet.is_cd = true; + cuesheet->data.cue_sheet.num_tracks = 3; + cuesheet->data.cue_sheet.tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc_or_die_(cuesheet->data.cue_sheet.num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)); + cuesheet->data.cue_sheet.tracks[0].offset = 0; + cuesheet->data.cue_sheet.tracks[0].number = 1; + memcpy(cuesheet->data.cue_sheet.tracks[0].isrc, "ACBDE1234567", sizeof(cuesheet->data.cue_sheet.tracks[0].isrc)); + cuesheet->data.cue_sheet.tracks[0].type = 0; + cuesheet->data.cue_sheet.tracks[0].pre_emphasis = 1; + cuesheet->data.cue_sheet.tracks[0].num_indices = 2; + cuesheet->data.cue_sheet.tracks[0].indices = (FLAC__StreamMetadata_CueSheet_Index*)malloc_or_die_(cuesheet->data.cue_sheet.tracks[0].num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index)); + cuesheet->data.cue_sheet.tracks[0].indices[0].offset = 0; + cuesheet->data.cue_sheet.tracks[0].indices[0].number = 0; + cuesheet->data.cue_sheet.tracks[0].indices[1].offset = 123 * 588; + cuesheet->data.cue_sheet.tracks[0].indices[1].number = 1; + cuesheet->data.cue_sheet.tracks[1].offset = 1234 * 588; + cuesheet->data.cue_sheet.tracks[1].number = 2; + memcpy(cuesheet->data.cue_sheet.tracks[1].isrc, "ACBDE7654321", sizeof(cuesheet->data.cue_sheet.tracks[1].isrc)); + cuesheet->data.cue_sheet.tracks[1].type = 1; + cuesheet->data.cue_sheet.tracks[1].pre_emphasis = 0; + cuesheet->data.cue_sheet.tracks[1].num_indices = 1; + cuesheet->data.cue_sheet.tracks[1].indices = (FLAC__StreamMetadata_CueSheet_Index*)malloc_or_die_(cuesheet->data.cue_sheet.tracks[1].num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index)); + cuesheet->data.cue_sheet.tracks[1].indices[0].offset = 0; + cuesheet->data.cue_sheet.tracks[1].indices[0].number = 1; + cuesheet->data.cue_sheet.tracks[2].offset = 12345 * 588; + cuesheet->data.cue_sheet.tracks[2].number = 170; + cuesheet->data.cue_sheet.tracks[2].num_indices = 0; + + picture->is_last = false; + picture->type = FLAC__METADATA_TYPE_PICTURE; + picture->length = + ( + FLAC__STREAM_METADATA_PICTURE_TYPE_LEN + + FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* will add the length for the string later */ + FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN + + FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN + + FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN + + FLAC__STREAM_METADATA_PICTURE_COLORS_LEN + + FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN /* will add the length for the data later */ + ) / 8 + ; + picture->data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER; + picture->data.picture.mime_type = strdup_or_die_("image/jpeg"); + picture->length += strlen(picture->data.picture.mime_type); + picture->data.picture.description = (FLAC__byte*)strdup_or_die_("desc"); + picture->length += strlen((const char *)picture->data.picture.description); + picture->data.picture.width = 300; + picture->data.picture.height = 300; + picture->data.picture.depth = 24; + picture->data.picture.colors = 0; + picture->data.picture.data = (FLAC__byte*)strdup_or_die_("SOMEJPEGDATA"); + picture->data.picture.data_length = strlen((const char *)picture->data.picture.data); + picture->length += picture->data.picture.data_length; + + unknown->is_last = true; + unknown->type = 126; + unknown->length = 8; + unknown->data.unknown.data = (FLAC__byte*)malloc_or_die_(unknown->length); + memcpy(unknown->data.unknown.data, "\xfe\xdc\xba\x98\xf0\xe1\xd2\xc3", unknown->length); +} + +void mutils__free_metadata_blocks( + FLAC__StreamMetadata *streaminfo, + FLAC__StreamMetadata *padding, + FLAC__StreamMetadata *seektable, + FLAC__StreamMetadata *application1, + FLAC__StreamMetadata *application2, + FLAC__StreamMetadata *vorbiscomment, + FLAC__StreamMetadata *cuesheet, + FLAC__StreamMetadata *picture, + FLAC__StreamMetadata *unknown +) +{ + (void)streaminfo, (void)padding, (void)application2; + free(seektable->data.seek_table.points); + free(application1->data.application.data); + free(vorbiscomment->data.vorbis_comment.vendor_string.entry); + free(vorbiscomment->data.vorbis_comment.comments[0].entry); + free(vorbiscomment->data.vorbis_comment.comments); + free(cuesheet->data.cue_sheet.tracks[0].indices); + free(cuesheet->data.cue_sheet.tracks[1].indices); + free(cuesheet->data.cue_sheet.tracks); + free(picture->data.picture.mime_type); + free(picture->data.picture.description); + free(picture->data.picture.data); + free(unknown->data.unknown.data); +} diff --git a/flac/src/test_libs_common/test_libs_common_static.dsp b/flac/src/test_libs_common/test_libs_common_static.dsp new file mode 100644 index 0000000..531cfa5 --- /dev/null +++ b/flac/src/test_libs_common/test_libs_common_static.dsp @@ -0,0 +1,108 @@ +# Microsoft Developer Studio Project File - Name="test_libs_common_static" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=test_libs_common_static - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_libs_common_static.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_libs_common_static.mak" CFG="test_libs_common_static - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_libs_common_static - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "test_libs_common_static - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "test_libs_common" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_libs_common_static - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\lib" +# PROP Intermediate_Dir "Release_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /Op /I ".\include" /I "..\..\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ELSEIF "$(CFG)" == "test_libs_common_static - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\lib" +# PROP Intermediate_Dir "Debug_static" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I ".\include" /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo /nodefaultlib + +!ENDIF + +# Begin Target + +# Name "test_libs_common_static - Win32 Release" +# Name "test_libs_common_static - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\file_utils_flac.c +# End Source File +# Begin Source File + +SOURCE=.\metadata_utils.c +# End Source File +# End Group +# Begin Group "Public Header Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\include\test_libs_common\file_utils_flac.h +# End Source File +# Begin Source File + +SOURCE=..\..\include\test_libs_common\metadata_utils.h +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/test_libs_common/test_libs_common_static.vcproj b/flac/src/test_libs_common/test_libs_common_static.vcproj new file mode 100644 index 0000000..c200b20 --- /dev/null +++ b/flac/src/test_libs_common/test_libs_common_static.vcproj @@ -0,0 +1,314 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_seeking/Makefile.am b/flac/src/test_seeking/Makefile.am new file mode 100644 index 0000000..2b4dd2e --- /dev/null +++ b/flac/src/test_seeking/Makefile.am @@ -0,0 +1,34 @@ +# test_seeking - Seeking tester for libFLAC +# Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_seeking.dsp \ + test_seeking.vcproj + +AM_CFLAGS = @OGG_CFLAGS@ + +INCLUDES = + +noinst_PROGRAMS = test_seeking +test_seeking_LDADD = \ + $(top_builddir)/src/libFLAC/libFLAC.la \ + @OGG_LIBS@ \ + @MINGW_WINSOCK_LIBS@ \ + -lm +test_seeking_SOURCES = \ + main.c diff --git a/flac/src/test_seeking/Makefile.lite b/flac/src/test_seeking/Makefile.lite new file mode 100644 index 0000000..4d630ac --- /dev/null +++ b/flac/src/test_seeking/Makefile.lite @@ -0,0 +1,40 @@ +# test_seeking - Seeking tester for libFLAC +# Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_seeking + +INCLUDES = -I../libFLAC/include -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_C = \ + main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_seeking/main.c b/flac/src/test_seeking/main.c new file mode 100644 index 0000000..68b39f2 --- /dev/null +++ b/flac/src/test_seeking/main.c @@ -0,0 +1,501 @@ +/* test_seeking - Seeking tester for libFLAC + * Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#include +#else +#include +#endif +#include /* for stat() */ +#include "FLAC/assert.h" +#include "FLAC/metadata.h" +#include "FLAC/stream_decoder.h" + +typedef struct { + FLAC__int32 **pcm; + FLAC__bool got_data; + FLAC__uint64 total_samples; + unsigned channels; + unsigned bits_per_sample; + FLAC__bool quiet; + FLAC__bool ignore_errors; + FLAC__bool error_occurred; +} DecoderClientData; + +static FLAC__bool stop_signal_ = false; + +static void our_sigint_handler_(int signal) +{ + (void)signal; + printf("(caught SIGINT) "); + fflush(stdout); + stop_signal_ = true; +} + +static FLAC__bool die_(const char *msg) +{ + printf("ERROR: %s\n", msg); + return false; +} + +static FLAC__bool die_s_(const char *msg, const FLAC__StreamDecoder *decoder) +{ + FLAC__StreamDecoderState state = FLAC__stream_decoder_get_state(decoder); + + if(msg) + printf("FAILED, %s", msg); + else + printf("FAILED"); + + printf(", state = %u (%s)\n", (unsigned)state, FLAC__StreamDecoderStateString[state]); + + return false; +} + +static unsigned local_rand_(void) +{ +#if !defined _MSC_VER && !defined __MINGW32__ +#define RNDFUNC random +#else +#define RNDFUNC rand +#endif + /* every RAND_MAX I've ever seen is 2^15-1 or 2^31-1, so a little hackery here: */ + if (RAND_MAX > 32767) + return RNDFUNC(); + else /* usually MSVC, some solaris */ + return (RNDFUNC()<<15) | RNDFUNC(); +#undef RNDFUNC +} + +static off_t get_filesize_(const char *srcpath) +{ + struct stat srcstat; + + if(0 == stat(srcpath, &srcstat)) + return srcstat.st_size; + else + return -1; +} + +static FLAC__bool read_pcm_(FLAC__int32 *pcm[], const char *rawfilename, const char *flacfilename) +{ + FILE *f; + unsigned channels = 0, bps = 0, samples, i, j; + + off_t rawfilesize = get_filesize_(rawfilename); + if (rawfilesize < 0) { + fprintf(stderr, "ERROR: can't determine filesize for %s\n", rawfilename); + return false; + } + /* get sample format from flac file; would just use FLAC__metadata_get_streaminfo() except it doesn't work for Ogg FLAC yet */ + { +#if 0 + FLAC__StreamMetadata streaminfo; + if(!FLAC__metadata_get_streaminfo(flacfilename, &streaminfo)) { + printf("ERROR: getting STREAMINFO from %s\n", flacfilename); + return false; + } + channels = streaminfo.data.stream_info.channels; + bps = streaminfo.data.stream_info.bits_per_sample; +#else + FLAC__bool ok = true; + FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new(); + FLAC__Metadata_Iterator *it = 0; + ok = ok && chain && (FLAC__metadata_chain_read(chain, flacfilename) || FLAC__metadata_chain_read_ogg(chain, flacfilename)); + ok = ok && (it = FLAC__metadata_iterator_new()); + if(ok) FLAC__metadata_iterator_init(it, chain); + ok = ok && (FLAC__metadata_iterator_get_block(it)->type == FLAC__METADATA_TYPE_STREAMINFO); + ok = ok && (channels = FLAC__metadata_iterator_get_block(it)->data.stream_info.channels); + ok = ok && (bps = FLAC__metadata_iterator_get_block(it)->data.stream_info.bits_per_sample); + if(it) FLAC__metadata_iterator_delete(it); + if(chain) FLAC__metadata_chain_delete(chain); + if(!ok) { + printf("ERROR: getting STREAMINFO from %s\n", flacfilename); + return false; + } +#endif + } + if(channels > 2) { + printf("ERROR: PCM verification requires 1 or 2 channels, got %u\n", channels); + return false; + } + if(bps != 8 && bps != 16) { + printf("ERROR: PCM verification requires 8 or 16 bps, got %u\n", bps); + return false; + } + samples = rawfilesize / channels / (bps>>3); + if (samples > 10000000) { + fprintf(stderr, "ERROR: %s is too big\n", rawfilename); + return false; + } + for(i = 0; i < channels; i++) { + if(0 == (pcm[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32)*samples))) { + printf("ERROR: allocating space for PCM samples\n"); + return false; + } + } + if(0 == (f = fopen(rawfilename, "rb"))) { + printf("ERROR: opening %s for reading\n", rawfilename); + return false; + } + /* assumes signed big-endian data */ + if(bps == 8) { + signed char c; + for(i = 0; i < samples; i++) { + for(j = 0; j < channels; j++) { + fread(&c, 1, 1, f); + pcm[j][i] = c; + } + } + } + else { /* bps == 16 */ + unsigned char c[2]; + for(i = 0; i < samples; i++) { + for(j = 0; j < channels; j++) { + fread(&c, 1, 2, f); + pcm[j][i] = ((int)((signed char)c[0])) << 8 | (int)c[1]; + } + } + } + fclose(f); + return true; +} + +static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) +{ + DecoderClientData *dcd = (DecoderClientData*)client_data; + + (void)decoder, (void)buffer; + + if(0 == dcd) { + printf("ERROR: client_data in write callback is NULL\n"); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + + if(dcd->error_occurred) + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + + FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); /* decoder guarantees this */ + if (!dcd->quiet) +#ifdef _MSC_VER + printf("frame@%I64u(%u)... ", frame->header.number.sample_number, frame->header.blocksize); +#else + printf("frame@%llu(%u)... ", (unsigned long long)frame->header.number.sample_number, frame->header.blocksize); +#endif + fflush(stdout); + + /* check against PCM data if we have it */ + if (dcd->pcm) { + unsigned c, i, j; + for (c = 0; c < frame->header.channels; c++) + for (i = (unsigned)frame->header.number.sample_number, j = 0; j < frame->header.blocksize; i++, j++) + if (buffer[c][j] != dcd->pcm[c][i]) { + printf("ERROR: sample mismatch at sample#%u(%u), channel=%u, expected %d, got %d\n", i, j, c, buffer[c][j], dcd->pcm[c][i]); + return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) +{ + DecoderClientData *dcd = (DecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in metadata callback is NULL\n"); + return; + } + + if(dcd->error_occurred) + return; + + if (!dcd->got_data && metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { + dcd->got_data = true; + dcd->total_samples = metadata->data.stream_info.total_samples; + dcd->channels = metadata->data.stream_info.channels; + dcd->bits_per_sample = metadata->data.stream_info.bits_per_sample; + } +} + +static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) +{ + DecoderClientData *dcd = (DecoderClientData*)client_data; + + (void)decoder; + + if(0 == dcd) { + printf("ERROR: client_data in error callback is NULL\n"); + return; + } + + if(!dcd->ignore_errors) { + printf("ERROR: got error callback: err = %u (%s)\n", (unsigned)status, FLAC__StreamDecoderErrorStatusString[status]); + dcd->error_occurred = true; + } +} + +/* read mode: + * 0 - no read after seek + * 1 - read 2 frames + * 2 - read until end + */ +static FLAC__bool seek_barrage(FLAC__bool is_ogg, const char *filename, off_t filesize, unsigned count, FLAC__int64 total_samples, unsigned read_mode, FLAC__int32 **pcm) +{ + FLAC__StreamDecoder *decoder; + DecoderClientData decoder_client_data; + unsigned i; + long int n; + + decoder_client_data.pcm = pcm; + decoder_client_data.got_data = false; + decoder_client_data.total_samples = 0; + decoder_client_data.quiet = false; + decoder_client_data.ignore_errors = false; + decoder_client_data.error_occurred = false; + + printf("\n+++ seek test: FLAC__StreamDecoder (%s FLAC, read_mode=%u)\n\n", is_ogg? "Ogg":"native", read_mode); + + decoder = FLAC__stream_decoder_new(); + if(0 == decoder) + return die_("FLAC__stream_decoder_new() FAILED, returned NULL\n"); + + if(is_ogg) { + if(FLAC__stream_decoder_init_ogg_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &decoder_client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_("FLAC__stream_decoder_init_file() FAILED", decoder); + } + else { + if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &decoder_client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) + return die_s_("FLAC__stream_decoder_init_file() FAILED", decoder); + } + + if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) + return die_s_("FLAC__stream_decoder_process_until_end_of_metadata() FAILED", decoder); + + if(!is_ogg) { /* not necessary to do this for Ogg because of its seeking method */ + /* process until end of stream to make sure we can still seek in that state */ + decoder_client_data.quiet = true; + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) + return die_s_("FLAC__stream_decoder_process_until_end_of_stream() FAILED", decoder); + decoder_client_data.quiet = false; + + printf("stream decoder state is %s\n", FLAC__stream_decoder_get_resolved_state_string(decoder)); + if(FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_END_OF_STREAM) + return die_s_("expected FLAC__STREAM_DECODER_END_OF_STREAM", decoder); + } + +#ifdef _MSC_VER + printf("file's total_samples is %I64u\n", decoder_client_data.total_samples); +#else + printf("file's total_samples is %llu\n", (unsigned long long)decoder_client_data.total_samples); +#endif + n = (long int)decoder_client_data.total_samples; + + if(n == 0 && total_samples >= 0) + n = (long int)total_samples; + + /* if we don't have a total samples count, just guess based on the file size */ + /* @@@ for is_ogg we should get it from last page's granulepos */ + if(n == 0) { + /* 8 would imply no compression, 9 guarantees that we will get some samples off the end of the stream to test that case */ + n = 9 * filesize / (decoder_client_data.channels * decoder_client_data.bits_per_sample); + } + + printf("Begin seek barrage, count=%u\n", count); + + for (i = 0; !stop_signal_ && (count == 0 || i < count); i++) { + FLAC__uint64 pos; + + /* for the first 10, seek to the first 10 samples */ + if (n >= 10 && i < 10) { + pos = i; + } + /* for the second 10, seek to the last 10 samples */ + else if (n >= 10 && i < 20) { + pos = n - 1 - (i-10); + } + /* for the third 10, seek past the end and make sure we fail properly as expected */ + else if (i < 30) { + pos = n + (i-20); + } + else { + pos = (FLAC__uint64)(local_rand_() % n); + } + +#ifdef _MSC_VER + printf("#%u:seek(%I64u)... ", i, pos); +#else + printf("#%u:seek(%llu)... ", i, (unsigned long long)pos); +#endif + fflush(stdout); + if(!FLAC__stream_decoder_seek_absolute(decoder, pos)) { + if(pos >= (FLAC__uint64)n) + printf("seek past end failed as expected... "); + else if(decoder_client_data.total_samples == 0 && total_samples <= 0) + printf("seek failed, assuming it was past EOF... "); + else + return die_s_("FLAC__stream_decoder_seek_absolute() FAILED", decoder); + if(!FLAC__stream_decoder_flush(decoder)) + return die_s_("FLAC__stream_decoder_flush() FAILED", decoder); + } + else if(read_mode == 1) { + printf("decode_frame... "); + fflush(stdout); + if(!FLAC__stream_decoder_process_single(decoder)) + return die_s_("FLAC__stream_decoder_process_single() FAILED", decoder); + + printf("decode_frame... "); + fflush(stdout); + if(!FLAC__stream_decoder_process_single(decoder)) + return die_s_("FLAC__stream_decoder_process_single() FAILED", decoder); + } + else if(read_mode == 2) { + printf("decode_all... "); + fflush(stdout); + decoder_client_data.quiet = true; + if(!FLAC__stream_decoder_process_until_end_of_stream(decoder)) + return die_s_("FLAC__stream_decoder_process_until_end_of_stream() FAILED", decoder); + decoder_client_data.quiet = false; + } + + printf("OK\n"); + fflush(stdout); + } + stop_signal_ = false; + + if(FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED) { + if(!FLAC__stream_decoder_finish(decoder)) + return die_s_("FLAC__stream_decoder_finish() FAILED", decoder); + } + + FLAC__stream_decoder_delete(decoder); + printf("\nPASSED!\n"); + + return true; +} + +#ifdef _MSC_VER +/* There's no strtoull() in MSVC6 so we just write a specialized one */ +static FLAC__uint64 local__strtoull(const char *src) +{ + FLAC__uint64 ret = 0; + int c; + FLAC__ASSERT(0 != src); + while(0 != (c = *src++)) { + c -= '0'; + if(c >= 0 && c <= 9) + ret = (ret * 10) + c; + else + break; + } + return ret; +} +#endif + +int main(int argc, char *argv[]) +{ + const char *flacfilename, *rawfilename = 0; + unsigned count = 0, read_mode; + FLAC__int64 samples = -1; + off_t flacfilesize; + FLAC__int32 *pcm[2] = { 0, 0 }; + FLAC__bool ok = true; + + static const char * const usage = "usage: test_seeking file.flac [#seeks] [#samples-in-file.flac] [file.raw]\n"; + + if (argc < 2 || argc > 5) { + fprintf(stderr, usage); + return 1; + } + + flacfilename = argv[1]; + + if (argc > 2) + count = strtoul(argv[2], 0, 10); + if (argc > 3) +#ifdef _MSC_VER + samples = local__strtoull(argv[3]); +#else + samples = strtoull(argv[3], 0, 10); +#endif + if (argc > 4) + rawfilename = argv[4]; + + if (count < 30) + fprintf(stderr, "WARNING: random seeks don't kick in until after 30 preprogrammed ones\n"); + +#if !defined _MSC_VER && !defined __MINGW32__ + { + struct timeval tv; + + if (gettimeofday(&tv, 0) < 0) { + fprintf(stderr, "WARNING: couldn't seed RNG with time\n"); + tv.tv_usec = 4321; + } + srandom(tv.tv_usec); + } +#else + srand((unsigned)time(0)); +#endif + + flacfilesize = get_filesize_(flacfilename); + if (flacfilesize < 0) { + fprintf(stderr, "ERROR: can't determine filesize for %s\n", flacfilename); + return 1; + } + + if (rawfilename && !read_pcm_(pcm, rawfilename, flacfilename)) { + free(pcm[0]); + free(pcm[1]); + return 1; + } + + (void) signal(SIGINT, our_sigint_handler_); + + for (read_mode = 0; ok && read_mode <= 2; read_mode++) { + /* no need to do "decode all" read_mode if PCM checking is available */ + if (rawfilename && read_mode > 1) + continue; + if (strlen(flacfilename) > 4 && (0 == strcmp(flacfilename+strlen(flacfilename)-4, ".oga") || 0 == strcmp(flacfilename+strlen(flacfilename)-4, ".ogg"))) { +#if FLAC__HAS_OGG + ok = seek_barrage(/*is_ogg=*/true, flacfilename, flacfilesize, count, samples, read_mode, rawfilename? pcm : 0); +#else + fprintf(stderr, "ERROR: Ogg FLAC not supported\n"); + ok = false; +#endif + } + else { + ok = seek_barrage(/*is_ogg=*/false, flacfilename, flacfilesize, count, samples, read_mode, rawfilename? pcm : 0); + } + } + + free(pcm[0]); + free(pcm[1]); + + return ok? 0 : 2; +} diff --git a/flac/src/test_seeking/test_seeking.dsp b/flac/src/test_seeking/test_seeking.dsp new file mode 100644 index 0000000..db1c234 --- /dev/null +++ b/flac/src/test_seeking/test_seeking.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="test_seeking" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_seeking - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_seeking.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_seeking.mak" CFG="test_seeking - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_seeking - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_seeking - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_seeking - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\obj\release\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_seeking - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "FLAC__HAS_OGG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\obj\debug\lib\libFLAC_static.lib ..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_seeking - Win32 Release" +# Name "test_seeking - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/src/test_seeking/test_seeking.vcproj b/flac/src/test_seeking/test_seeking.vcproj new file mode 100644 index 0000000..82c5f39 --- /dev/null +++ b/flac/src/test_seeking/test_seeking.vcproj @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/test_streams/Makefile.am b/flac/src/test_streams/Makefile.am new file mode 100644 index 0000000..c91646b --- /dev/null +++ b/flac/src/test_streams/Makefile.am @@ -0,0 +1,26 @@ +# test_streams - Simple test pattern generator +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +EXTRA_DIST = \ + Makefile.lite \ + test_streams.dsp \ + test_streams.vcproj + +noinst_PROGRAMS = test_streams +test_streams_SOURCES = \ + main.c +test_streams_LDADD = -lm diff --git a/flac/src/test_streams/Makefile.lite b/flac/src/test_streams/Makefile.lite new file mode 100644 index 0000000..b9ca65e --- /dev/null +++ b/flac/src/test_streams/Makefile.lite @@ -0,0 +1,36 @@ +# test_streams - Simple test pattern generator +# Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = test_streams + +INCLUDES = -I./include -I$(topdir)/include + +LIBS = -lm + +SRCS_C = \ + main.c + +include $(topdir)/build/exe.mk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/test_streams/main.c b/flac/src/test_streams/main.c new file mode 100644 index 0000000..8714281 --- /dev/null +++ b/flac/src/test_streams/main.c @@ -0,0 +1,1115 @@ +/* test_streams - Simple test pattern generator + * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#if defined _MSC_VER || defined __MINGW32__ +#include +#else +#include +#endif +#include "FLAC/assert.h" +#include "FLAC/ordinals.h" + +#ifndef M_PI +/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */ +#define M_PI 3.14159265358979323846 +#endif + +#if !defined _MSC_VER && !defined __MINGW32__ +#define GET_RANDOM_BYTE (((unsigned)random()) & 0xff) +#else +#define GET_RANDOM_BYTE (((unsigned)rand()) & 0xff) +#endif + +static FLAC__bool is_big_endian_host; + + +static FLAC__bool write_little_endian(FILE *f, FLAC__int32 x, size_t bytes) +{ + while(bytes) { + if(fputc(x, f) == EOF) + return false; + x >>= 8; + bytes--; + } + return true; +} + +static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF + ; +} + +static FLAC__bool write_little_endian_int16(FILE *f, FLAC__int16 x) +{ + return write_little_endian_uint16(f, (FLAC__uint16)x); +} + +static FLAC__bool write_little_endian_uint24(FILE *f, FLAC__uint32 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x >> 16, f) != EOF + ; +} + +static FLAC__bool write_little_endian_int24(FILE *f, FLAC__int32 x) +{ + return write_little_endian_uint24(f, (FLAC__uint32)x); +} + +static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x >> 16, f) != EOF && + fputc(x >> 24, f) != EOF + ; +} + +#if 0 +/* @@@ not used (yet) */ +static FLAC__bool write_little_endian_int32(FILE *f, FLAC__int32 x) +{ + return write_little_endian_uint32(f, (FLAC__uint32)x); +} +#endif + +static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 x) +{ + return + fputc(x, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x >> 16, f) != EOF && + fputc(x >> 24, f) != EOF && + fputc(x >> 32, f) != EOF && + fputc(x >> 40, f) != EOF && + fputc(x >> 48, f) != EOF && + fputc(x >> 56, f) != EOF + ; +} + +static FLAC__bool write_big_endian(FILE *f, FLAC__int32 x, size_t bytes) +{ + if(bytes < 4) + x <<= 8*(4-bytes); + while(bytes) { + if(fputc(x>>24, f) == EOF) + return false; + x <<= 8; + bytes--; + } + return true; +} + +static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 x) +{ + return + fputc(x >> 8, f) != EOF && + fputc(x, f) != EOF + ; +} + +#if 0 +/* @@@ not used (yet) */ +static FLAC__bool write_big_endian_int16(FILE *f, FLAC__int16 x) +{ + return write_big_endian_uint16(f, (FLAC__uint16)x); +} +#endif + +#if 0 +/* @@@ not used (yet) */ +static FLAC__bool write_big_endian_uint24(FILE *f, FLAC__uint32 x) +{ + return + fputc(x >> 16, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x, f) != EOF + ; +} +#endif + +#if 0 +/* @@@ not used (yet) */ +static FLAC__bool write_big_endian_int24(FILE *f, FLAC__int32 x) +{ + return write_big_endian_uint24(f, (FLAC__uint32)x); +} +#endif + +static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 x) +{ + return + fputc(x >> 24, f) != EOF && + fputc(x >> 16, f) != EOF && + fputc(x >> 8, f) != EOF && + fputc(x, f) != EOF + ; +} + +#if 0 +/* @@@ not used (yet) */ +static FLAC__bool write_big_endian_int32(FILE *f, FLAC__int32 x) +{ + return write_big_endian_uint32(f, (FLAC__uint32)x); +} +#endif + +static FLAC__bool write_sane_extended(FILE *f, unsigned val) + /* Write to 'f' a SANE extended representation of 'val'. Return false if + * the write succeeds; return true otherwise. + * + * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits + * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754 + * representations, it does not imply a 1 above the MSB of the significand. + * + * Preconditions: + * val!=0U + */ +{ + unsigned int shift, exponent; + + FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */ + + for(shift= 0U; (val>>(31-shift))==0U; ++shift) + ; + val<<= shift; + exponent= 63U-(shift+32U); /* add 32 for unused second word */ + + if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF))) + return false; + if(!write_big_endian_uint32(f, val)) + return false; + if(!write_big_endian_uint32(f, 0)) /* unused second word */ + return false; + + return true; +} + +/* a mono one-sample 16bps stream */ +static FLAC__bool generate_01(void) +{ + FILE *f; + FLAC__int16 x = -32768; + + if(0 == (f = fopen("test01.raw", "wb"))) + return false; + + if(!write_little_endian_int16(f, x)) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo one-sample 16bps stream */ +static FLAC__bool generate_02(void) +{ + FILE *f; + FLAC__int16 xl = -32768, xr = 32767; + + if(0 == (f = fopen("test02.raw", "wb"))) + return false; + + if(!write_little_endian_int16(f, xl)) + goto foo; + if(!write_little_endian_int16(f, xr)) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono five-sample 16bps stream */ +static FLAC__bool generate_03(void) +{ + FILE *f; + FLAC__int16 x[] = { -25, 0, 25, 50, 100 }; + unsigned i; + + if(0 == (f = fopen("test03.raw", "wb"))) + return false; + + for(i = 0; i < 5; i++) + if(!write_little_endian_int16(f, x[i])) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo five-sample 16bps stream */ +static FLAC__bool generate_04(void) +{ + FILE *f; + FLAC__int16 x[] = { -25, 500, 0, 400, 25, 300, 50, 200, 100, 100 }; + unsigned i; + + if(0 == (f = fopen("test04.raw", "wb"))) + return false; + + for(i = 0; i < 10; i++) + if(!write_little_endian_int16(f, x[i])) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono full-scale deflection 8bps stream */ +static FLAC__bool generate_fsd8(const char *fn, const int pattern[], unsigned reps) +{ + FILE *f; + unsigned rep, p; + + FLAC__ASSERT(pattern != 0); + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(rep = 0; rep < reps; rep++) { + for(p = 0; pattern[p]; p++) { + signed char x = pattern[p] > 0? 127 : -128; + if(fwrite(&x, sizeof(x), 1, f) < 1) + goto foo; + } + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono full-scale deflection 16bps stream */ +static FLAC__bool generate_fsd16(const char *fn, const int pattern[], unsigned reps) +{ + FILE *f; + unsigned rep, p; + + FLAC__ASSERT(pattern != 0); + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(rep = 0; rep < reps; rep++) { + for(p = 0; pattern[p]; p++) { + FLAC__int16 x = pattern[p] > 0? 32767 : -32768; + if(!write_little_endian_int16(f, x)) + goto foo; + } + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo wasted-bits-per-sample 16bps stream */ +static FLAC__bool generate_wbps16(const char *fn, unsigned samples) +{ + FILE *f; + unsigned sample; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(sample = 0; sample < samples; sample++) { + FLAC__int16 l = (sample % 2000) << 2; + FLAC__int16 r = (sample % 1000) << 3; + if(!write_little_endian_int16(f, l)) + goto foo; + if(!write_little_endian_int16(f, r)) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono full-scale deflection 24bps stream */ +static FLAC__bool generate_fsd24(const char *fn, const int pattern[], unsigned reps) +{ + FILE *f; + unsigned rep, p; + + FLAC__ASSERT(pattern != 0); + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(rep = 0; rep < reps; rep++) { + for(p = 0; pattern[p]; p++) { + FLAC__int32 x = pattern[p] > 0? 8388607 : -8388608; + if(!write_little_endian_int24(f, x)) + goto foo; + } + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono sine-wave 8bps stream */ +static FLAC__bool generate_sine8_1(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2) +{ + const FLAC__int8 full_scale = 127; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int8 v = (FLAC__int8)(val + 0.5); + if(fwrite(&v, sizeof(v), 1, f) < 1) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo sine-wave 8bps stream */ +static FLAC__bool generate_sine8_2(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2, double fmult) +{ + const FLAC__int8 full_scale = 127; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int8 v = (FLAC__int8)(val + 0.5); + if(fwrite(&v, sizeof(v), 1, f) < 1) + goto foo; + val = -(a1*sin(theta1*fmult) + a2*sin(theta2*fmult))*(double)full_scale; + v = (FLAC__int8)(val + 0.5); + if(fwrite(&v, sizeof(v), 1, f) < 1) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono sine-wave 16bps stream */ +static FLAC__bool generate_sine16_1(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2) +{ + const FLAC__int16 full_scale = 32767; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int16 v = (FLAC__int16)(val + 0.5); + if(!write_little_endian_int16(f, v)) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo sine-wave 16bps stream */ +static FLAC__bool generate_sine16_2(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2, double fmult) +{ + const FLAC__int16 full_scale = 32767; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int16 v = (FLAC__int16)(val + 0.5); + if(!write_little_endian_int16(f, v)) + goto foo; + val = -(a1*sin(theta1*fmult) + a2*sin(theta2*fmult))*(double)full_scale; + v = (FLAC__int16)(val + 0.5); + if(!write_little_endian_int16(f, v)) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a mono sine-wave 24bps stream */ +static FLAC__bool generate_sine24_1(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2) +{ + const FLAC__int32 full_scale = 0x7fffff; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int32 v = (FLAC__int32)(val + 0.5); + if(!write_little_endian_int24(f, v)) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* a stereo sine-wave 24bps stream */ +static FLAC__bool generate_sine24_2(const char *fn, const double sample_rate, const unsigned samples, const double f1, const double a1, const double f2, const double a2, double fmult) +{ + const FLAC__int32 full_scale = 0x7fffff; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + FILE *f; + double theta1, theta2; + unsigned i; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int32 v = (FLAC__int32)(val + 0.5); + if(!write_little_endian_int24(f, v)) + goto foo; + val = -(a1*sin(theta1*fmult) + a2*sin(theta2*fmult))*(double)full_scale; + v = (FLAC__int32)(val + 0.5); + if(!write_little_endian_int24(f, v)) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_noise(const char *fn, unsigned bytes) +{ + FILE *f; + unsigned b; + + if(0 == (f = fopen(fn, "wb"))) + return false; + + for(b = 0; b < bytes; b++) { +#if !defined _MSC_VER && !defined __MINGW32__ + FLAC__byte x = (FLAC__byte)(((unsigned)random()) & 0xff); +#else + FLAC__byte x = (FLAC__byte)(((unsigned)rand()) & 0xff); +#endif + if(fwrite(&x, sizeof(x), 1, f) < 1) + goto foo; + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_raw(const char *filename, unsigned channels, unsigned bytes_per_sample, unsigned samples) +{ + const FLAC__int32 full_scale = (1 << (bytes_per_sample*8-1)) - 1; + const double f1 = 441.0, a1 = 0.61, f2 = 661.5, a2 = 0.37; + const double delta1 = 2.0 * M_PI / ( 44100.0 / f1); + const double delta2 = 2.0 * M_PI / ( 44100.0 / f2); + double theta1, theta2; + FILE *f; + unsigned i, j; + + if(0 == (f = fopen(filename, "wb"))) + return false; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + for(j = 0; j < channels; j++) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int32 v = (FLAC__int32)(val + 0.5) + ((GET_RANDOM_BYTE>>4)-8); + if(!write_little_endian(f, v, bytes_per_sample)) + goto foo; + } + } + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_aiff(const char *filename, unsigned sample_rate, unsigned channels, unsigned bps, unsigned samples) +{ + const unsigned bytes_per_sample = (bps+7)/8; + const unsigned true_size = channels * bytes_per_sample * samples; + const unsigned padded_size = (true_size + 1) & (~1u); + const unsigned shift = (bps%8)? 8 - (bps%8) : 0; + const FLAC__int32 full_scale = (1 << (bps-1)) - 1; + const double f1 = 441.0, a1 = 0.61, f2 = 661.5, a2 = 0.37; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + double theta1, theta2; + FILE *f; + unsigned i, j; + + if(0 == (f = fopen(filename, "wb"))) + return false; + if(fwrite("FORM", 1, 4, f) < 4) + goto foo; + if(!write_big_endian_uint32(f, padded_size + 46)) + goto foo; + if(fwrite("AIFFCOMM\000\000\000\022", 1, 12, f) < 12) + goto foo; + if(!write_big_endian_uint16(f, (FLAC__uint16)channels)) + goto foo; + if(!write_big_endian_uint32(f, samples)) + goto foo; + if(!write_big_endian_uint16(f, (FLAC__uint16)bps)) + goto foo; + if(!write_sane_extended(f, sample_rate)) + goto foo; + if(fwrite("SSND", 1, 4, f) < 4) + goto foo; + if(!write_big_endian_uint32(f, true_size + 8)) + goto foo; + if(fwrite("\000\000\000\000\000\000\000\000", 1, 8, f) < 8) + goto foo; + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + for(j = 0; j < channels; j++) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int32 v = ((FLAC__int32)(val + 0.5) + ((GET_RANDOM_BYTE>>4)-8)) << shift; + if(!write_big_endian(f, v, bytes_per_sample)) + goto foo; + } + } + for(i = true_size; i < padded_size; i++) + if(fputc(0, f) == EOF) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +/* flavor is: 0:WAVE, 1:RF64, 2:WAVE64 */ +static FLAC__bool generate_wav(const char *filename, unsigned sample_rate, unsigned channels, unsigned bps, unsigned samples, FLAC__bool strict, int flavor) +{ + const FLAC__bool waveformatextensible = strict && (channels > 2 || (bps%8)); + /* ^^^^^^^ + * (bps%8) allows 24 bps which is technically supposed to be WAVEFORMATEXTENSIBLE but we + * write 24bps as WAVEFORMATEX since it's unambiguous and matches how flac writes it + */ + + const unsigned bytes_per_sample = (bps+7)/8; + const unsigned shift = (bps%8)? 8 - (bps%8) : 0; + /* this rig is not going over 4G so we're ok with 32-bit sizes here */ + const FLAC__uint32 true_size = channels * bytes_per_sample * samples; + const FLAC__uint32 padded_size = flavor<2? (true_size + 1) & (~1u) : (true_size + 7) & (~7u); + const FLAC__int32 full_scale = (1 << (bps-1)) - 1; + const double f1 = 441.0, a1 = 0.61, f2 = 661.5, a2 = 0.37; + const double delta1 = 2.0 * M_PI / ( sample_rate / f1); + const double delta2 = 2.0 * M_PI / ( sample_rate / f2); + double theta1, theta2; + FILE *f; + unsigned i, j; + + if(0 == (f = fopen(filename, "wb"))) + return false; + /* RIFFxxxxWAVE or equivalent: */ + switch(flavor) { + case 0: + if(fwrite("RIFF", 1, 4, f) < 4) + goto foo; + /* +4 for WAVE */ + /* +8+{40,16} for fmt chunk */ + /* +8 for data chunk header */ + if(!write_little_endian_uint32(f, 4 + 8+(waveformatextensible?40:16) + 8 + padded_size)) + goto foo; + if(fwrite("WAVE", 1, 4, f) < 4) + goto foo; + break; + case 1: + if(fwrite("RF64", 1, 4, f) < 4) + goto foo; + if(!write_little_endian_uint32(f, 0xffffffff)) + goto foo; + if(fwrite("WAVE", 1, 4, f) < 4) + goto foo; + break; + case 2: + /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */ + if(fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 1, 16, f) < 16) + goto foo; + /* +(16+8) for RIFF GUID + size */ + /* +16 for WAVE GUID */ + /* +16+8+{40,16} for fmt chunk */ + /* +16+8 for data chunk header */ + if(!write_little_endian_uint64(f, (16+8) + 16 + 16+8+(waveformatextensible?40:16) + (16+8) + padded_size)) + goto foo; + /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) < 16) + goto foo; + break; + default: + goto foo; + } + if(flavor == 1) { /* rf64 */ + if(fwrite("ds64", 1, 4, f) < 4) + goto foo; + if(!write_little_endian_uint32(f, 28)) /* ds64 chunk size */ + goto foo; + if(!write_little_endian_uint64(f, 36 + padded_size + (waveformatextensible?60:36))) + goto foo; + if(!write_little_endian_uint64(f, true_size)) + goto foo; + if(!write_little_endian_uint64(f, samples)) + goto foo; + if(!write_little_endian_uint32(f, 0)) /* table size */ + goto foo; + } + /* fmt chunk */ + if(flavor < 2) { + if(fwrite("fmt ", 1, 4, f) < 4) + goto foo; + /* chunk size */ + if(!write_little_endian_uint32(f, waveformatextensible?40:16)) + goto foo; + } + else { /* wave64 */ + /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) < 16) + goto foo; + /* chunk size (+16+8 for GUID and size fields) */ + if(!write_little_endian_uint64(f, 16+8+(waveformatextensible?40:16))) + goto foo; + } + if(!write_little_endian_uint16(f, (FLAC__uint16)(waveformatextensible?65534:1))) + goto foo; + if(!write_little_endian_uint16(f, (FLAC__uint16)channels)) + goto foo; + if(!write_little_endian_uint32(f, sample_rate)) + goto foo; + if(!write_little_endian_uint32(f, sample_rate * channels * bytes_per_sample)) + goto foo; + if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * bytes_per_sample))) /* block align */ + goto foo; + if(!write_little_endian_uint16(f, (FLAC__uint16)(bps+shift))) + goto foo; + if(waveformatextensible) { + if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */ + goto foo; + if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */ + goto foo; + if(!write_little_endian_uint32(f, 0)) /* channelMask */ + goto foo; + /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */ + if(fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16) + goto foo; + } + /* data chunk */ + if(flavor < 2) { + if(fwrite("data", 1, 4, f) < 4) + goto foo; + if(!write_little_endian_uint32(f, flavor==1? 0xffffffff : true_size)) + goto foo; + } + else { /* wave64 */ + /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */ + if(fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16) + goto foo; + /* +16+8 for GUID and size fields */ + if(!write_little_endian_uint64(f, 16+8 + true_size)) + goto foo; + } + + for(i = 0, theta1 = theta2 = 0.0; i < samples; i++, theta1 += delta1, theta2 += delta2) { + for(j = 0; j < channels; j++) { + double val = (a1*sin(theta1) + a2*sin(theta2))*(double)full_scale; + FLAC__int32 v = ((FLAC__int32)(val + 0.5) + ((GET_RANDOM_BYTE>>4)-8)) << shift; + if(!write_little_endian(f, v, bytes_per_sample)) + goto foo; + } + } + for(i = true_size; i < padded_size; i++) + if(fputc(0, f) == EOF) + goto foo; + + fclose(f); + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_wackywavs(void) +{ + FILE *f; + FLAC__byte wav[] = { + 'R', 'I', 'F', 'F', 76, 0, 0, 0, + 'W', 'A', 'V', 'E', 'j', 'u', 'n', 'k', + 4, 0, 0, 0 , 'b', 'l', 'a', 'h', + 'p', 'a', 'd', ' ', 4, 0, 0, 0, + 'B', 'L', 'A', 'H', 'f', 'm', 't', ' ', + 16, 0, 0, 0, 1, 0, 1, 0, + 0x44,0xAC, 0, 0,0x88,0x58,0x01, 0, + 2, 0, 16, 0, 'd', 'a', 't', 'a', + 16, 0, 0, 0, 0, 0, 1, 0, + 4, 0, 9, 0, 16, 0, 25, 0, + 36, 0, 49, 0, 'p', 'a', 'd', ' ', + 4, 0, 0, 0, 'b', 'l', 'a', 'h' + }; + + if(0 == (f = fopen("wacky1.wav", "wb"))) + return false; + if(fwrite(wav, 1, 84, f) < 84) + goto foo; + fclose(f); + + wav[4] += 12; + if(0 == (f = fopen("wacky2.wav", "wb"))) + return false; + if(fwrite(wav, 1, 96, f) < 96) + goto foo; + fclose(f); + + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_wackywav64s(void) +{ + FILE *f; + FLAC__byte wav[] = { + 0x72,0x69,0x66,0x66,0x2E,0x91,0xCF,0x11, /* RIFF GUID */ + 0xD6,0xA5,0x28,0xDB,0x04,0xC1,0x00,0x00, + 152, 0, 0, 0, 0, 0, 0, 0, + 0x77,0x61,0x76,0x65,0xF3,0xAC,0xD3,0x11, /* WAVE GUID */ + 0xD1,0x8C,0x00,0xC0,0x4F,0x8E,0xDB,0x8A, + 0x6A,0x75,0x6E,0x6B,0xF3,0xAC,0xD3,0x11, /* junk GUID */ + 0xD1,0x8C,0x00,0xC0,0x4F,0x8E,0xDB,0x8A, + 32, 0, 0, 0 , 0, 0, 0, 0, + 'b', 'l', 'a', 'h', 'b', 'l', 'a', 'h', + 0x66,0x6D,0x74,0x20,0xF3,0xAC,0xD3,0x11, /* fmt GUID */ + 0xD1,0x8C,0x00,0xC0,0x4F,0x8E,0xDB,0x8A, + 40, 0, 0, 0 , 0, 0, 0, 0, + 1, 0, 1, 0,0x44,0xAC, 0, 0, + 0x88,0x58,0x01, 0, 2, 0, 16, 0, + 0x64,0x61,0x74,0x61,0xF3,0xAC,0xD3,0x11, /* data GUID */ + 0xD1,0x8C,0x00,0xC0,0x4F,0x8E,0xDB,0x8A, + 40, 0, 0, 0 , 0, 0, 0, 0, + 0, 0, 1, 0, 4, 0, 9, 0, + 16, 0, 25, 0, 36, 0, 49, 0, + 0x6A,0x75,0x6E,0x6B,0xF3,0xAC,0xD3,0x11, /* junk GUID */ + 0xD1,0x8C,0x00,0xC0,0x4F,0x8E,0xDB,0x8A, + 32, 0, 0, 0 , 0, 0, 0, 0, + 'b', 'l', 'a', 'h', 'b', 'l', 'a', 'h' + }; + + if(0 == (f = fopen("wacky1.w64", "wb"))) + return false; + if(fwrite(wav, 1, wav[16], f) < wav[16]) + goto foo; + fclose(f); + + wav[16] += 32; + if(0 == (f = fopen("wacky2.w64", "wb"))) + return false; + if(fwrite(wav, 1, wav[16], f) < wav[16]) + goto foo; + fclose(f); + + return true; +foo: + fclose(f); + return false; +} + +static FLAC__bool generate_wackyrf64s(void) +{ + FILE *f; + FLAC__byte wav[] = { + 'R', 'F', '6', '4', 255, 255, 255, 255, + 'W', 'A', 'V', 'E', 'd', 's', '6', '4', + 28, 0, 0, 0, 112, 0, 0, 0, + 0, 0, 0, 0, 16, 0, 0, 0, + 0, 0, 0, 0, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 'j', 'u', 'n', 'k', + 4, 0, 0, 0, 'b', 'l', 'a', 'h', + 'p', 'a', 'd', ' ', 4, 0, 0, 0, + 'B', 'L', 'A', 'H', 'f', 'm', 't', ' ', + 16, 0, 0, 0, 1, 0, 1, 0, + 0x44,0xAC, 0, 0,0x88,0x58,0x01, 0, + 2, 0, 16, 0, 'd', 'a', 't', 'a', + 255, 255, 255, 255, 0, 0, 1, 0, + 4, 0, 9, 0, 16, 0, 25, 0, + 36, 0, 49, 0, 'p', 'a', 'd', ' ', + 4, 0, 0, 0, 'b', 'l', 'a', 'h' + }; + + if(0 == (f = fopen("wacky1.rf64", "wb"))) + return false; + if(fwrite(wav, 1, 120, f) < 120) + goto foo; + fclose(f); + + wav[20] += 12; + if(0 == (f = fopen("wacky2.rf64", "wb"))) + return false; + if(fwrite(wav, 1, 132, f) < 132) + goto foo; + fclose(f); + + return true; +foo: + fclose(f); + return false; +} + +int main(int argc, char *argv[]) +{ + FLAC__uint32 test = 1; + unsigned channels; + + int pattern01[] = { 1, -1, 0 }; + int pattern02[] = { 1, 1, -1, 0 }; + int pattern03[] = { 1, -1, -1, 0 }; + int pattern04[] = { 1, -1, 1, -1, 0 }; + int pattern05[] = { 1, -1, -1, 1, 0 }; + int pattern06[] = { 1, -1, 1, 1, -1, 0 }; + int pattern07[] = { 1, -1, -1, 1, -1, 0 }; + + (void)argc; + (void)argv; + is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true; + +#if !defined _MSC_VER && !defined __MINGW32__ + { + struct timeval tv; + + if(gettimeofday(&tv, 0) < 0) { + fprintf(stderr, "WARNING: couldn't seed RNG with time\n"); + tv.tv_usec = 4321; + } + srandom(tv.tv_usec); + } +#else + srand((unsigned)time(0)); +#endif + + if(!generate_01()) return 1; + if(!generate_02()) return 1; + if(!generate_03()) return 1; + if(!generate_04()) return 1; + + if(!generate_fsd8("fsd8-01.raw", pattern01, 100)) return 1; + if(!generate_fsd8("fsd8-02.raw", pattern02, 100)) return 1; + if(!generate_fsd8("fsd8-03.raw", pattern03, 100)) return 1; + if(!generate_fsd8("fsd8-04.raw", pattern04, 100)) return 1; + if(!generate_fsd8("fsd8-05.raw", pattern05, 100)) return 1; + if(!generate_fsd8("fsd8-06.raw", pattern06, 100)) return 1; + if(!generate_fsd8("fsd8-07.raw", pattern07, 100)) return 1; + + if(!generate_fsd16("fsd16-01.raw", pattern01, 100)) return 1; + if(!generate_fsd16("fsd16-02.raw", pattern02, 100)) return 1; + if(!generate_fsd16("fsd16-03.raw", pattern03, 100)) return 1; + if(!generate_fsd16("fsd16-04.raw", pattern04, 100)) return 1; + if(!generate_fsd16("fsd16-05.raw", pattern05, 100)) return 1; + if(!generate_fsd16("fsd16-06.raw", pattern06, 100)) return 1; + if(!generate_fsd16("fsd16-07.raw", pattern07, 100)) return 1; + + if(!generate_fsd24("fsd24-01.raw", pattern01, 100)) return 1; + if(!generate_fsd24("fsd24-02.raw", pattern02, 100)) return 1; + if(!generate_fsd24("fsd24-03.raw", pattern03, 100)) return 1; + if(!generate_fsd24("fsd24-04.raw", pattern04, 100)) return 1; + if(!generate_fsd24("fsd24-05.raw", pattern05, 100)) return 1; + if(!generate_fsd24("fsd24-06.raw", pattern06, 100)) return 1; + if(!generate_fsd24("fsd24-07.raw", pattern07, 100)) return 1; + + if(!generate_wbps16("wbps16-01.raw", 1000)) return 1; + + if(!generate_sine8_1("sine8-00.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49)) return 1; + if(!generate_sine8_1("sine8-01.raw", 96000.0, 200000, 441.0, 0.61, 661.5, 0.37)) return 1; + if(!generate_sine8_1("sine8-02.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49)) return 1; + if(!generate_sine8_1("sine8-03.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49)) return 1; + if(!generate_sine8_1("sine8-04.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29)) return 1; + + if(!generate_sine8_2("sine8-10.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49, 1.0)) return 1; + if(!generate_sine8_2("sine8-11.raw", 48000.0, 200000, 441.0, 0.61, 661.5, 0.37, 1.0)) return 1; + if(!generate_sine8_2("sine8-12.raw", 96000.0, 200000, 441.0, 0.50, 882.0, 0.49, 1.0)) return 1; + if(!generate_sine8_2("sine8-13.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.0)) return 1; + if(!generate_sine8_2("sine8-14.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 1.0)) return 1; + if(!generate_sine8_2("sine8-15.raw", 44100.0, 200000, 441.0, 0.50, 441.0, 0.49, 0.5)) return 1; + if(!generate_sine8_2("sine8-16.raw", 44100.0, 200000, 441.0, 0.61, 661.5, 0.37, 2.0)) return 1; + if(!generate_sine8_2("sine8-17.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49, 0.7)) return 1; + if(!generate_sine8_2("sine8-18.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.3)) return 1; + if(!generate_sine8_2("sine8-19.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 0.1)) return 1; + + if(!generate_sine16_1("sine16-00.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49)) return 1; + if(!generate_sine16_1("sine16-01.raw", 96000.0, 200000, 441.0, 0.61, 661.5, 0.37)) return 1; + if(!generate_sine16_1("sine16-02.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49)) return 1; + if(!generate_sine16_1("sine16-03.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49)) return 1; + if(!generate_sine16_1("sine16-04.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29)) return 1; + + if(!generate_sine16_2("sine16-10.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49, 1.0)) return 1; + if(!generate_sine16_2("sine16-11.raw", 48000.0, 200000, 441.0, 0.61, 661.5, 0.37, 1.0)) return 1; + if(!generate_sine16_2("sine16-12.raw", 96000.0, 200000, 441.0, 0.50, 882.0, 0.49, 1.0)) return 1; + if(!generate_sine16_2("sine16-13.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.0)) return 1; + if(!generate_sine16_2("sine16-14.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 1.0)) return 1; + if(!generate_sine16_2("sine16-15.raw", 44100.0, 200000, 441.0, 0.50, 441.0, 0.49, 0.5)) return 1; + if(!generate_sine16_2("sine16-16.raw", 44100.0, 200000, 441.0, 0.61, 661.5, 0.37, 2.0)) return 1; + if(!generate_sine16_2("sine16-17.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49, 0.7)) return 1; + if(!generate_sine16_2("sine16-18.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.3)) return 1; + if(!generate_sine16_2("sine16-19.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 0.1)) return 1; + + if(!generate_sine24_1("sine24-00.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49)) return 1; + if(!generate_sine24_1("sine24-01.raw", 96000.0, 200000, 441.0, 0.61, 661.5, 0.37)) return 1; + if(!generate_sine24_1("sine24-02.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49)) return 1; + if(!generate_sine24_1("sine24-03.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49)) return 1; + if(!generate_sine24_1("sine24-04.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29)) return 1; + + if(!generate_sine24_2("sine24-10.raw", 48000.0, 200000, 441.0, 0.50, 441.0, 0.49, 1.0)) return 1; + if(!generate_sine24_2("sine24-11.raw", 48000.0, 200000, 441.0, 0.61, 661.5, 0.37, 1.0)) return 1; + if(!generate_sine24_2("sine24-12.raw", 96000.0, 200000, 441.0, 0.50, 882.0, 0.49, 1.0)) return 1; + if(!generate_sine24_2("sine24-13.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.0)) return 1; + if(!generate_sine24_2("sine24-14.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 1.0)) return 1; + if(!generate_sine24_2("sine24-15.raw", 44100.0, 200000, 441.0, 0.50, 441.0, 0.49, 0.5)) return 1; + if(!generate_sine24_2("sine24-16.raw", 44100.0, 200000, 441.0, 0.61, 661.5, 0.37, 2.0)) return 1; + if(!generate_sine24_2("sine24-17.raw", 44100.0, 200000, 441.0, 0.50, 882.0, 0.49, 0.7)) return 1; + if(!generate_sine24_2("sine24-18.raw", 44100.0, 200000, 441.0, 0.50, 4410.0, 0.49, 1.3)) return 1; + if(!generate_sine24_2("sine24-19.raw", 44100.0, 200000, 8820.0, 0.70, 4410.0, 0.29, 0.1)) return 1; + + /* WATCHOUT: the size of noise.raw is hardcoded into test/test_flac.sh */ + if(!generate_noise("noise.raw", 65536 * 8 * 3)) return 1; + if(!generate_noise("noise8m32.raw", 32)) return 1; + if(!generate_wackywavs()) return 1; + if(!generate_wackywav64s()) return 1; + if(!generate_wackyrf64s()) return 1; + for(channels = 1; channels <= 8; channels++) { + unsigned bits_per_sample; + for(bits_per_sample = 4; bits_per_sample <= 24; bits_per_sample++) { + static const unsigned nsamples[] = { 1, 111, 4777 } ; + unsigned samples; + for(samples = 0; samples < sizeof(nsamples)/sizeof(nsamples[0]); samples++) { + char fn[64]; + + sprintf(fn, "rt-%u-%u-%u.aiff", channels, bits_per_sample, nsamples[samples]); + if(!generate_aiff(fn, 44100, channels, bits_per_sample, nsamples[samples])) + return 1; + + sprintf(fn, "rt-%u-%u-%u.wav", channels, bits_per_sample, nsamples[samples]); + if(!generate_wav(fn, 44100, channels, bits_per_sample, nsamples[samples], /*strict=*/true, /*flavor=*/0)) + return 1; + + sprintf(fn, "rt-%u-%u-%u.rf64", channels, bits_per_sample, nsamples[samples]); + if(!generate_wav(fn, 44100, channels, bits_per_sample, nsamples[samples], /*strict=*/true, /*flavor=*/1)) + return 1; + + sprintf(fn, "rt-%u-%u-%u.w64", channels, bits_per_sample, nsamples[samples]); + if(!generate_wav(fn, 44100, channels, bits_per_sample, nsamples[samples], /*strict=*/true, /*flavor=*/2)) + return 1; + + if(bits_per_sample % 8 == 0) { + sprintf(fn, "rt-%u-%u-%u.raw", channels, bits_per_sample, nsamples[samples]); + if(!generate_raw(fn, channels, bits_per_sample/8, nsamples[samples])) + return 1; + } + } + } + } + + return 0; +} diff --git a/flac/src/test_streams/test_streams.dsp b/flac/src/test_streams/test_streams.dsp new file mode 100644 index 0000000..9490d20 --- /dev/null +++ b/flac/src/test_streams/test_streams.dsp @@ -0,0 +1,96 @@ +# Microsoft Developer Studio Project File - Name="test_streams" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=test_streams - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "test_streams.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "test_streams.mak" CFG="test_streams - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "test_streams - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "test_streams - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "test_streams - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "test_streams - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "test_streams - Win32 Release" +# Name "test_streams - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "c" +# Begin Source File + +SOURCE=.\main.c +# End Source File +# End Group +# End Target +# End Project diff --git a/flac/src/test_streams/test_streams.vcproj b/flac/src/test_streams/test_streams.vcproj new file mode 100644 index 0000000..8989a7e --- /dev/null +++ b/flac/src/test_streams/test_streams.vcproj @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/utils/flacdiff/Makefile.lite b/flac/src/utils/flacdiff/Makefile.lite new file mode 100644 index 0000000..033de2a --- /dev/null +++ b/flac/src/utils/flacdiff/Makefile.lite @@ -0,0 +1,42 @@ +# flacdiff - Displays where two FLAC streams differ +# Copyright (C) 2007,2008 Josh Coalson +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# +# GNU makefile +# + +topdir = ../../.. +libdir = $(topdir)/obj/$(BUILD)/lib + +PROGRAM_NAME = flacdiff + +INCLUDES = -I$(topdir)/include + +ifeq ($(OS),Darwin) +EXPLICIT_LIBS = $(libdir)/libFLAC++.a $(libdir)/libFLAC.a $(OGG_LIB_DIR)/libogg.a -lm +else +LIBS = -lFLAC++ -lFLAC -L$(OGG_LIB_DIR) -logg -lm +endif + +SRCS_CPP = \ + main.cpp + +include $(topdir)/build/exe.mk + +LINK = $(CCC) $(LINKAGE) + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/flac/src/utils/flacdiff/flacdiff.dsp b/flac/src/utils/flacdiff/flacdiff.dsp new file mode 100644 index 0000000..f7635db --- /dev/null +++ b/flac/src/utils/flacdiff/flacdiff.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="flacdiff" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=flacdiff - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "flacdiff.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "flacdiff.mak" CFG="flacdiff - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "flacdiff - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "flacdiff - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "flacdiff - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /I "..\..\..\include" /D "NDEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\obj\release\lib\libFLAC++_static.lib ..\..\..\obj\release\lib\libFLAC_static.lib ..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "flacdiff - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I "..\..\..\include" /D "_DEBUG" /D "DEBUG" /D "FLAC__NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\obj\debug\lib\libFLAC++_static.lib ..\..\..\obj\debug\lib\libFLAC_static.lib ..\..\..\obj\release\lib\ogg_static.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "flacdiff - Win32 Release" +# Name "flacdiff - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/src/utils/flacdiff/flacdiff.vcproj b/flac/src/utils/flacdiff/flacdiff.vcproj new file mode 100644 index 0000000..3ec65e1 --- /dev/null +++ b/flac/src/utils/flacdiff/flacdiff.vcproj @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/utils/flacdiff/main.cpp b/flac/src/utils/flacdiff/main.cpp new file mode 100644 index 0000000..bc90de2 --- /dev/null +++ b/flac/src/utils/flacdiff/main.cpp @@ -0,0 +1,227 @@ +/* flacdiff - Displays where two FLAC streams differ + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "FLAC++/decoder.h" +#if defined _MSC_VER || defined __MINGW32__ +#if _MSC_VER <= 1600 /* @@@ [2G limit] */ +#define fseeko fseek +#define ftello ftell +#endif +#endif + +#ifdef _MSC_VER +// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) +#pragma warning ( disable : 4800 ) +#endif + +class AutoFILE { +protected: + ::FILE *f_; +public: + inline AutoFILE(const char *path, const char *mode): f_(::fopen(path, mode)) { } + inline virtual ~AutoFILE() { if (f_) (void)::fclose(f_); } + + inline operator bool() const { return 0 != f_; } + inline operator const ::FILE *() const { return f_; } + inline operator ::FILE *() { return f_; } +private: + AutoFILE(); + AutoFILE(const AutoFILE &); + void operator=(const AutoFILE &); +}; + +class Decoder: public FLAC::Decoder::Stream { +public: + Decoder(AutoFILE &f, off_t tgt): tgtpos_((FLAC__uint64)tgt), curpos_(0), go_(true), err_(false), frame_(), f_(f) { memset(&frame_, 0, sizeof(::FLAC__Frame)); } + FLAC__uint64 tgtpos_, curpos_; + bool go_, err_; + ::FLAC__Frame frame_; +protected: + AutoFILE &f_; + // from FLAC::Decoder::Stream + virtual ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes) + { + *bytes = fread(buffer, 1, *bytes, f_); + if(ferror((FILE*)f_)) + return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; + else if(*bytes == 0 && feof((FILE*)f_)) + return ::FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; + else + return ::FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; + } + + virtual ::FLAC__StreamDecoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset) + { + off_t off = ftello(f_); + if(off < 0) + return ::FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + *absolute_byte_offset = off; + return ::FLAC__STREAM_DECODER_TELL_STATUS_OK; + } + + virtual bool eof_callback() + { + return (bool)feof((FILE*)f_); + } + + virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const /*buffer*/[]) + { + FLAC__uint64 pos; + if(!get_decode_position(&pos)) { + go_ = false; + err_ = true; + return ::FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; + } + if(pos > tgtpos_) { + go_ = false; + frame_ = *frame; + } + else + curpos_ = pos; + return ::FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; + } + + virtual void error_callback(::FLAC__StreamDecoderErrorStatus status) + { + fprintf(stderr, "get error %d:%s\n", status, ::FLAC__StreamDecoderErrorStatusString[status]); + go_ = false; + err_ = true; + } +}; + +static bool show_diff(AutoFILE &f1, AutoFILE &f2, off_t off) +{ + Decoder d1(f1, off), d2(f2, off); + if(!d1) { + fprintf(stderr, "ERROR: setting up decoder1, state=%s\n", d1.get_state().resolved_as_cstring(d1)); + return false; + } + if(!d2) { + fprintf(stderr, "ERROR: setting up decoder2, state=%s\n", d2.get_state().resolved_as_cstring(d2)); + return false; + } + ::FLAC__StreamDecoderInitStatus is; + if((is = d1.init()) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing decoder1, status=%s state=%s\n", FLAC__StreamDecoderInitStatusString[is], d1.get_state().resolved_as_cstring(d1)); + return false; + } + if((is = d2.init()) != FLAC__STREAM_DECODER_INIT_STATUS_OK) { + fprintf(stderr, "ERROR: initializing decoder2, status=%s state=%s\n", FLAC__StreamDecoderInitStatusString[is], d2.get_state().resolved_as_cstring(d2)); + return false; + } + if(!d1.process_until_end_of_metadata()) { + fprintf(stderr, "ERROR: skipping metadata in decoder1, state=%s\n", d1.get_state().resolved_as_cstring(d1)); + return false; + } + if(!d2.process_until_end_of_metadata()) { + fprintf(stderr, "ERROR: skipping metadata in decoder2, state=%s\n", d2.get_state().resolved_as_cstring(d2)); + return false; + } + while(d1.go_ && d2.go_) { + if(!d1.process_single()) { + fprintf(stderr, "ERROR: decoding frame in decoder1, state=%s\n", d1.get_state().resolved_as_cstring(d1)); + return false; + } + if(!d2.process_single()) { + fprintf(stderr, "ERROR: decoding frame in decoder2, state=%s\n", d2.get_state().resolved_as_cstring(d2)); + return false; + } + } + if(d1.err_) { + fprintf(stderr, "ERROR: got err_ in decoder1, state=%s\n", d1.get_state().resolved_as_cstring(d1)); + return false; + } + if(d2.err_) { + fprintf(stderr, "ERROR: got err_ in decoder2, state=%s\n", d2.get_state().resolved_as_cstring(d2)); + return false; + } + if(d1.go_ != d2.go_) { + fprintf(stderr, "ERROR: d1.go_(%s) != d2.go_(%s)\n", d1.go_?"true":"false", d2.go_?"true":"false"); + return false; + } + fprintf(stdout, "pos1 = %llu blocksize=%u sample#%llu frame#%llu\n", d1.curpos_, d1.frame_.header.blocksize, d1.frame_.header.number.sample_number, d1.frame_.header.number.sample_number / d1.frame_.header.blocksize); + fprintf(stdout, "pos2 = %llu blocksize=%u sample#%llu frame#%llu\n", d2.curpos_, d2.frame_.header.blocksize, d2.frame_.header.number.sample_number, d2.frame_.header.number.sample_number / d2.frame_.header.blocksize); + + return true; +} + +static off_t get_diff_offset(AutoFILE &f1, AutoFILE &f2) +{ + off_t off = 0; + while(1) { + if(feof((FILE*)f1) && feof((FILE*)f1)) { + fprintf(stderr, "ERROR: files are identical\n"); + return -1; + } + if(feof((FILE*)f1)) { + fprintf(stderr, "ERROR: file1 EOF\n"); + return -1; + } + if(feof((FILE*)f2)) { + fprintf(stderr, "ERROR: file2 EOF\n"); + return -1; + } + if(fgetc(f1) != fgetc(f2)) + return off; + off++; + } +} + +static bool run(const char *fn1, const char *fn2) +{ + off_t off; + AutoFILE f1(fn1, "rb"), f2(fn2, "rb"); + + if(!f1) { + fprintf(stderr, "ERROR: opening %s for reading\n", fn1); + return false; + } + if(!f2) { + fprintf(stderr, "ERROR: opening %s for reading\n", fn2); + return false; + } + + if((off = get_diff_offset(f1, f2)) < 0) + return false; + + fprintf(stdout, "got diff offset = %u\n", (unsigned)off); //@@@ 4G limit (what is % modifier for off_t?) + + return show_diff(f1, f2, off); +} + +int main(int argc, char *argv[]) +{ + const char *usage = "usage: flacdiff flacfile1 flacfile2\n"; + + if(argc > 1 && 0 == strcmp(argv[1], "-h")) { + printf(usage); + return 0; + } + else if(argc != 3) { + fprintf(stderr, usage); + return 255; + } + + return run(argv[1], argv[2])? 0 : 1; +} diff --git a/flac/src/utils/flactimer/flactimer.dsp b/flac/src/utils/flactimer/flactimer.dsp new file mode 100644 index 0000000..fee2d6c --- /dev/null +++ b/flac/src/utils/flactimer/flactimer.dsp @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="flactimer" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=flactimer - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "flactimer.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "flactimer.mak" CFG="flactimer - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "flactimer - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "flactimer - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "flactimer - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "..\..\..\obj\release\bin" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GR /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "flactimer - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "..\..\..\obj\debug\bin" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /D "_DEBUG" /D "DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "flactimer - Win32 Release" +# Name "flactimer - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\main.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Target +# End Project diff --git a/flac/src/utils/flactimer/flactimer.vcproj b/flac/src/utils/flactimer/flactimer.vcproj new file mode 100644 index 0000000..057cd96 --- /dev/null +++ b/flac/src/utils/flactimer/flactimer.vcproj @@ -0,0 +1,364 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flac/src/utils/flactimer/main.cpp b/flac/src/utils/flactimer/main.cpp new file mode 100644 index 0000000..84ce431 --- /dev/null +++ b/flac/src/utils/flactimer/main.cpp @@ -0,0 +1,171 @@ +/* flactimer - Runs a command and prints timing information + * Copyright (C) 2007,2008 Josh Coalson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include +#include +#include + +#define int64_t __int64 +#define uint64_t unsigned int64_t + +static inline uint64_t time2nsec(const FILETIME &t) +{ + uint64_t n = t.dwHighDateTime; + n <<= 32; + n |= (uint64_t)t.dwLowDateTime; + return n * 100; +} + +static void printtime(FILE *fout, uint64_t nsec, uint64_t total) +{ + unsigned pct = (unsigned)(100.0 * ((double)(int64_t)nsec / (double)(int64_t)total)); + uint64_t msec = nsec / 1000000; nsec -= msec * 1000000; + uint64_t sec = msec / 1000; msec -= sec * 1000; + uint64_t min = sec / 60; sec -= min * 60; + uint64_t hour = min / 60; min -= hour * 60; + fprintf(fout, " %5u.%03u = %02u:%02u:%02u.%03u = %3u%%\n", + (unsigned)((hour*60+min)*60+sec), + (unsigned)msec, + (unsigned)hour, + (unsigned)min, + (unsigned)sec, + (unsigned)msec, + pct + ); +} + +int main(int argc, char *argv[]) +{ + const char *usage = "usage: flactimer [-1 | -2 | -o outputfile] command\n"; + FILE *fout = stderr; + + if(argc == 1 || (argc > 1 && 0 == strcmp(argv[1], "-h"))) { + fprintf(stderr, usage); + return 0; + } + argv++; + argc--; + if(0 == strcmp(argv[0], "-1") || 0 == strcmp(argv[0], "/1")) { + fout = stdout; + argv++; + argc--; + } + else if(0 == strcmp(argv[0], "-2") || 0 == strcmp(argv[0], "/2")) { + fout = stdout; + argv++; + argc--; + } + else if(0 == strcmp(argv[0], "-o")) { + if(argc < 2) { + fprintf(stderr, usage); + return 1; + } + fout = fopen(argv[1], "w"); + if(!fout) { + fprintf(fout, "ERROR opening file %s for writing\n", argv[1]); + return 1; + } + argv += 2; + argc -= 2; + } + if(argc <= 0) { + fprintf(fout, "ERROR, no command!\n\n"); + fprintf(fout, usage); + fclose(fout); + return 1; + } + + // improvement: double-quote all args + int i, n = 0; + for(i = 0; i < argc; i++) { + if(i > 0) + n++; + n += strlen(argv[i]); + } + char *args = (char*)malloc(n+1); + if(!args) { + fprintf(fout, "ERROR, no memory\n"); + fclose(fout); + return 1; + } + args[0] = '\0'; + for(i = 0; i < argc; i++) { + if(i > 0) + strcat(args, " "); + strcat(args, argv[i]); + } + + //fprintf(stderr, "@@@ cmd=[%s] args=[%s]\n", argv[0], args); + + STARTUPINFO si; + GetStartupInfo(&si); + + DWORD wallclock_msec = GetTickCount(); + + PROCESS_INFORMATION pi; + BOOL ok = CreateProcess( + argv[0], // lpApplicationName + args, // lpCommandLine + NULL, // lpProcessAttributes + NULL, // lpThreadAttributes + FALSE, // bInheritHandles + 0, // dwCreationFlags + NULL, // lpEnvironment + NULL, // lpCurrentDirectory + &si, // lpStartupInfo (inherit from this proc?) + &pi // lpProcessInformation + ); + + if(!ok) { + fprintf(fout, "ERROR running command\n"); + free(args); //@@@ ok to free here or have to wait to wait till process is reaped? + fclose(fout); + return 1; + } + + //fprintf(stderr, "@@@ waiting...\n"); + WaitForSingleObject(pi.hProcess, INFINITE); + //fprintf(stderr, "@@@ done\n"); + + wallclock_msec = GetTickCount() - wallclock_msec; + + FILETIME creation_time; + FILETIME exit_time; + FILETIME kernel_time; + FILETIME user_time; + if(!GetProcessTimes(pi.hProcess, &creation_time, &exit_time, &kernel_time, &user_time)) { + fprintf(fout, "ERROR getting time info\n"); + free(args); //@@@ ok to free here or have to wait to wait till process is reaped? + fclose(fout); + return 1; + } + uint64_t kernel_nsec = time2nsec(kernel_time); + uint64_t user_nsec = time2nsec(user_time); + + fprintf(fout, "Kernel Time = "); printtime(fout, kernel_nsec, (uint64_t)wallclock_msec * 1000000); + fprintf(fout, "User Time = "); printtime(fout, user_nsec, (uint64_t)wallclock_msec * 1000000); + fprintf(fout, "Process Time = "); printtime(fout, kernel_nsec+user_nsec, (uint64_t)wallclock_msec * 1000000); + fprintf(fout, "Global Time = "); printtime(fout, (uint64_t)wallclock_msec * 1000000, (uint64_t)wallclock_msec * 1000000); + + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + + free(args); //@@@ always causes crash, maybe CreateProcess takes ownership? + fclose(fout); + return 0; +} diff --git a/flac/strip_non_asm_libtool_args.sh b/flac/strip_non_asm_libtool_args.sh new file mode 100644 index 0000000..a9d0a6e --- /dev/null +++ b/flac/strip_non_asm_libtool_args.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# libtool assumes that the compiler can handle the -fPIC flag. +# This isn't always true (for example, nasm can't handle it). +# Also, on some versions of OS X it tries to pass -fno-common +# to 'as' which causes problems. +command="" +while [ $1 ]; do + if [ "$1" != "-fPIC" ]; then + if [ "$1" != "-DPIC" ]; then + if [ "$1" != "-fno-common" ]; then + command="$command $1" + fi + fi + fi + shift +done +echo $command +exec $command diff --git a/flac/test/Makefile.am b/flac/test/Makefile.am new file mode 100644 index 0000000..d9c206b --- /dev/null +++ b/flac/test/Makefile.am @@ -0,0 +1,52 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +if FLaC__WITH_CPPLIBS +CPPLIBS_TESTS = test_libFLAC++.sh +endif + +TESTS_ENVIRONMENT = FLAC__TEST_LEVEL=@FLAC__TEST_LEVEL@ FLAC__TEST_WITH_VALRGIND=@FLAC__TEST_WITH_VALGRIND@ + +SUBDIRS = cuesheets flac-to-flac-metadata-test-files metaflac-test-files pictures + +TESTS = \ + ./test_libFLAC.sh \ + $(CPPLIBS_TESTS) \ + ./test_grabbag.sh \ + ./test_flac.sh \ + ./test_metaflac.sh \ + ./test_seeking.sh \ + ./test_streams.sh + +EXTRA_DIST = \ + Makefile.lite \ + cuesheet.ok \ + metaflac.flac.in \ + metaflac.flac.ok \ + picture.ok \ + test_libFLAC.sh \ + $(CPPLIBS_TESTS) \ + test_flac.sh \ + test_metaflac.sh \ + test_grabbag.sh \ + test_seeking.sh \ + test_streams.sh \ + test_bins.sh \ + write_iff.pl + +clean-local: + -rm -f *.raw *.flac *.oga *.ogg *.cmp *.aiff *.wav *.w64 *.rf64 *.diff *.log *.cue core diff --git a/flac/test/Makefile.lite b/flac/test/Makefile.lite new file mode 100644 index 0000000..d4d2831 --- /dev/null +++ b/flac/test/Makefile.lite @@ -0,0 +1,55 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +# +# GNU makefile +# + +topdir = .. + +DEFAULT_CONFIG = release + +CONFIG = $(DEFAULT_CONFIG) + +all: clean + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_libFLAC.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_libFLAC++.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_grabbag.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_flac.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_metaflac.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_seeking.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_streams.sh $(CONFIG) + $(FLAC__TEST_LEVEL) $(FLAC__TEST_WITH_VALGRIND) ./test_bins.sh $(CONFIG) + +debug : FLAC__TEST_LEVEL=FLAC__TEST_LEVEL=2 +valgrind: FLAC__TEST_LEVEL=FLAC__TEST_LEVEL=1 +release : FLAC__TEST_LEVEL=FLAC__TEST_LEVEL=2 + +debug : FLAC__TEST_WITH_VALGRIND=FLAC__TEST_WITH_VALGRIND=no +valgrind: FLAC__TEST_WITH_VALGRIND=FLAC__TEST_WITH_VALGRIND=yes +release : FLAC__TEST_WITH_VALGRIND=FLAC__TEST_WITH_VALGRIND=no + +debug : CONFIG = debug +valgrind: CONFIG = debug +release : CONFIG = release + +debug : all +valgrind: all +release : all + +clean: + rm -f *.raw *.flac *.oga *.ogg *.cmp *.aiff *.wav *.w64 *.rf64 *.diff *.log *.cue core flac-to-flac-metadata-test-files/out.* metaflac-test-files/out.* diff --git a/flac/test/cuesheet.ok b/flac/test/cuesheet.ok new file mode 100644 index 0000000..eea25f6 --- /dev/null +++ b/flac/test/cuesheet.ok @@ -0,0 +1,93 @@ +NEGATIVE cuesheets/bad.000.CATALOG_multiple.cue +pass1: parse error, line 2: "found multiple CATALOG commands" +NEGATIVE cuesheets/bad.001.CATALOG_missing_number.cue +pass1: parse error, line 1: "CATALOG is missing catalog number" +NEGATIVE cuesheets/bad.002.CATALOG_number_too_long.cue +pass1: parse error, line 1: "CATALOG number is too long" +NEGATIVE cuesheets/bad.003.CATALOG_not_13_digits.cue +pass1: parse error, line 1: "CD-DA CATALOG number must be 13 decimal digits" +NEGATIVE cuesheets/bad.030.FLAGS_multiple.cue +pass1: parse error, line 4: "found multiple FLAGS commands" +NEGATIVE cuesheets/bad.031.FLAGS_wrong_place_1.cue +pass1: parse error, line 1: "FLAGS command must come after TRACK but before INDEX" +NEGATIVE cuesheets/bad.032.FLAGS_wrong_place_2.cue +pass1: parse error, line 4: "FLAGS command must come after TRACK but before INDEX" +NEGATIVE cuesheets/bad.060.INDEX_wrong_place.cue +pass1: parse error, line 2: "found INDEX before any TRACK" +NEGATIVE cuesheets/bad.061.INDEX_missing_number.cue +pass1: parse error, line 4: "INDEX is missing index number" +NEGATIVE cuesheets/bad.062.INDEX_invalid_number_1.cue +pass1: parse error, line 4: "INDEX has invalid index number" +NEGATIVE cuesheets/bad.063.first_INDEX_not_0_or_1.cue +pass1: parse error, line 4: "first INDEX number of a TRACK must be 0 or 1" +NEGATIVE cuesheets/bad.064.INDEX_num_non_sequential.cue +pass1: parse error, line 5: "INDEX numbers must be sequential" +NEGATIVE cuesheets/bad.065.INDEX_num_out_of_range.cue +pass1: parse error, line 104: "CD-DA INDEX number must be between 0 and 99, inclusive" +NEGATIVE cuesheets/bad.066.INDEX_missing_offset.cue +pass1: parse error, line 4: "INDEX is missing an offset after the index number" +NEGATIVE cuesheets/bad.067.INDEX_illegal_offset.cue +pass1: parse error, line 4: "illegal INDEX offset (not of the form MM:SS:FF)" +NEGATIVE cuesheets/bad.068.INDEX_cdda_illegal_offset.cue +pass1: parse error, line 4: "illegal INDEX offset (not of the form MM:SS:FF)" +NEGATIVE cuesheets/bad.069.nonzero_first_INDEX.cue +pass1: parse error, line 4: "first INDEX of first TRACK must have an offset of 00:00:00" +NEGATIVE cuesheets/bad.070.INDEX_offset_not_ascending_1.cue +pass1: parse error, line 5: "CD-DA INDEX offsets must increase in time" +NEGATIVE cuesheets/bad.071.INDEX_offset_not_ascending_2.cue +pass1: parse error, line 6: "CD-DA INDEX offsets must increase in time" +NEGATIVE cuesheets/bad.110.ISRC_multiple.cue +pass1: parse error, line 4: "found multiple ISRC commands" +NEGATIVE cuesheets/bad.111.ISRC_wrong_place_1.cue +pass1: parse error, line 2: "ISRC command must come after TRACK but before INDEX" +NEGATIVE cuesheets/bad.112.ISRC_wrong_place_2.cue +pass1: parse error, line 4: "ISRC command must come after TRACK but before INDEX" +NEGATIVE cuesheets/bad.113.ISRC_missing_number.cue +pass1: parse error, line 3: "ISRC is missing ISRC number" +NEGATIVE cuesheets/bad.114.ISRC_invalid_number.cue +pass1: parse error, line 3: "invalid ISRC number" +NEGATIVE cuesheets/bad.130.TRACK_missing_INDEX_01_1.cue +pass1: parse error, line 2: "previous TRACK must specify at least one INDEX 01" +NEGATIVE cuesheets/bad.131.TRACK_missing_INDEX_01_2.cue +pass1: parse error, line 3: "previous TRACK must specify at least one INDEX 01" +NEGATIVE cuesheets/bad.132.TRACK_missing_INDEX_01_3.cue +pass1: parse error, line 3: "previous TRACK must specify at least one INDEX 01" +NEGATIVE cuesheets/bad.133.TRACK_missing_INDEX_01_4.cue +pass1: parse error, line 4: "previous TRACK must specify at least one INDEX 01" +NEGATIVE cuesheets/bad.134.TRACK_missing_number.cue +pass1: parse error, line 2: "TRACK is missing track number" +NEGATIVE cuesheets/bad.135.TRACK_invalid_number_1.cue +pass1: parse error, line 2: "TRACK has invalid track number" +NEGATIVE cuesheets/bad.136.TRACK_invalid_number_2.cue +pass1: parse error, line 2: "TRACK number must be greater than 0" +NEGATIVE cuesheets/bad.137.TRACK_cdda_out_of_range.cue +pass1: parse error, line 2: "CD-DA TRACK number must be between 1 and 99, inclusive" +NEGATIVE cuesheets/bad.138.TRACK_num_non_sequential.cue +pass1: parse error, line 6: "CD-DA TRACK numbers must be sequential" +NEGATIVE cuesheets/bad.139.TRACK_missing_type.cue +pass1: parse error, line 2: "TRACK is missing a track type after the track number" +NEGATIVE cuesheets/bad.140.no_TRACKs.cue +pass1: parse error, line 1: "there must be at least one TRACK command" +NEGATIVE cuesheets/bad.200.FLAC_leadin_missing_offset.cue +pass1: parse error, line 1: "FLAC__lead-in is missing offset" +NEGATIVE cuesheets/bad.201.FLAC_leadin_illegal_offset.cue +pass1: parse error, line 1: "illegal FLAC__lead-in offset" +NEGATIVE cuesheets/bad.202.FLAC_leadin_cdda_illegal_offset.cue +pass1: parse error, line 1: "illegal CD-DA FLAC__lead-in offset, must be even multiple of 588 samples" +NEGATIVE cuesheets/bad.230.FLAC_leadout_multiple.cue +pass1: parse error, line 3: "multiple FLAC__lead-out commands" +NEGATIVE cuesheets/bad.231.FLAC_leadout_missing_track.cue +pass1: parse error, line 1: "FLAC__lead-out is missing track number" +NEGATIVE cuesheets/bad.232.FLAC_leadout_illegal_track.cue +pass1: parse error, line 1: "illegal FLAC__lead-out track number" +NEGATIVE cuesheets/bad.233.FLAC_leadout_missing_offset.cue +pass1: parse error, line 1: "FLAC__lead-out is missing offset" +NEGATIVE cuesheets/bad.234.FLAC_leadout_illegal_offset.cue +pass1: parse error, line 1: "illegal FLAC__lead-out offset" +NEGATIVE cuesheets/bad.235.FLAC_leadout_offset_not_211680000.cue +pass1: parse error, line 1: "FLAC__lead-out offset does not match end-of-stream offset" +POSITIVE cuesheets/good.000.cue +POSITIVE cuesheets/good.001.cue +POSITIVE cuesheets/good.002.dos_format.cue +POSITIVE cuesheets/good.003.missing_final_newline.cue +POSITIVE cuesheets/good.004.dos_format.missing_final_newline.cue diff --git a/flac/test/cuesheets/Makefile.am b/flac/test/cuesheets/Makefile.am new file mode 100644 index 0000000..2fe8592 --- /dev/null +++ b/flac/test/cuesheets/Makefile.am @@ -0,0 +1,67 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + bad.000.CATALOG_multiple.cue \ + bad.001.CATALOG_missing_number.cue \ + bad.002.CATALOG_number_too_long.cue \ + bad.003.CATALOG_not_13_digits.cue \ + bad.030.FLAGS_multiple.cue \ + bad.031.FLAGS_wrong_place_1.cue \ + bad.032.FLAGS_wrong_place_2.cue \ + bad.060.INDEX_wrong_place.cue \ + bad.061.INDEX_missing_number.cue \ + bad.062.INDEX_invalid_number_1.cue \ + bad.063.first_INDEX_not_0_or_1.cue \ + bad.064.INDEX_num_non_sequential.cue \ + bad.065.INDEX_num_out_of_range.cue \ + bad.066.INDEX_missing_offset.cue \ + bad.067.INDEX_illegal_offset.cue \ + bad.068.INDEX_cdda_illegal_offset.cue \ + bad.069.nonzero_first_INDEX.cue \ + bad.070.INDEX_offset_not_ascending_1.cue \ + bad.071.INDEX_offset_not_ascending_2.cue \ + bad.110.ISRC_multiple.cue \ + bad.111.ISRC_wrong_place_1.cue \ + bad.112.ISRC_wrong_place_2.cue \ + bad.113.ISRC_missing_number.cue \ + bad.114.ISRC_invalid_number.cue \ + bad.130.TRACK_missing_INDEX_01_1.cue \ + bad.131.TRACK_missing_INDEX_01_2.cue \ + bad.132.TRACK_missing_INDEX_01_3.cue \ + bad.133.TRACK_missing_INDEX_01_4.cue \ + bad.134.TRACK_missing_number.cue \ + bad.135.TRACK_invalid_number_1.cue \ + bad.136.TRACK_invalid_number_2.cue \ + bad.137.TRACK_cdda_out_of_range.cue \ + bad.138.TRACK_num_non_sequential.cue \ + bad.139.TRACK_missing_type.cue \ + bad.140.no_TRACKs.cue \ + bad.200.FLAC_leadin_missing_offset.cue \ + bad.201.FLAC_leadin_illegal_offset.cue \ + bad.202.FLAC_leadin_cdda_illegal_offset.cue \ + bad.230.FLAC_leadout_multiple.cue \ + bad.231.FLAC_leadout_missing_track.cue \ + bad.232.FLAC_leadout_illegal_track.cue \ + bad.233.FLAC_leadout_missing_offset.cue \ + bad.234.FLAC_leadout_illegal_offset.cue \ + bad.235.FLAC_leadout_offset_not_211680000.cue \ + good.000.cue \ + good.001.cue \ + good.002.dos_format.cue \ + good.003.missing_final_newline.cue \ + good.004.dos_format.missing_final_newline.cue diff --git a/flac/test/cuesheets/bad.000.CATALOG_multiple.cue b/flac/test/cuesheets/bad.000.CATALOG_multiple.cue new file mode 100644 index 0000000..3e5a5e7 --- /dev/null +++ b/flac/test/cuesheets/bad.000.CATALOG_multiple.cue @@ -0,0 +1,5 @@ +CATALOG 1234567890123 +CATALOG 0234567890123 +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.001.CATALOG_missing_number.cue b/flac/test/cuesheets/bad.001.CATALOG_missing_number.cue new file mode 100644 index 0000000..c14095a --- /dev/null +++ b/flac/test/cuesheets/bad.001.CATALOG_missing_number.cue @@ -0,0 +1,4 @@ +CATALOG +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.002.CATALOG_number_too_long.cue b/flac/test/cuesheets/bad.002.CATALOG_number_too_long.cue new file mode 100644 index 0000000..72af84b --- /dev/null +++ b/flac/test/cuesheets/bad.002.CATALOG_number_too_long.cue @@ -0,0 +1,4 @@ +CATALOG 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.003.CATALOG_not_13_digits.cue b/flac/test/cuesheets/bad.003.CATALOG_not_13_digits.cue new file mode 100644 index 0000000..8f80cb0 --- /dev/null +++ b/flac/test/cuesheets/bad.003.CATALOG_not_13_digits.cue @@ -0,0 +1,4 @@ +CATALOG 123456789012z +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.030.FLAGS_multiple.cue b/flac/test/cuesheets/bad.030.FLAGS_multiple.cue new file mode 100644 index 0000000..a0620a5 --- /dev/null +++ b/flac/test/cuesheets/bad.030.FLAGS_multiple.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + FLAGS 4CH + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.031.FLAGS_wrong_place_1.cue b/flac/test/cuesheets/bad.031.FLAGS_wrong_place_1.cue new file mode 100644 index 0000000..ceb304f --- /dev/null +++ b/flac/test/cuesheets/bad.031.FLAGS_wrong_place_1.cue @@ -0,0 +1,4 @@ +FLAGS PRE +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.032.FLAGS_wrong_place_2.cue b/flac/test/cuesheets/bad.032.FLAGS_wrong_place_2.cue new file mode 100644 index 0000000..ae5b7a3 --- /dev/null +++ b/flac/test/cuesheets/bad.032.FLAGS_wrong_place_2.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 + FLAGS PRE diff --git a/flac/test/cuesheets/bad.060.INDEX_wrong_place.cue b/flac/test/cuesheets/bad.060.INDEX_wrong_place.cue new file mode 100644 index 0000000..6a339a6 --- /dev/null +++ b/flac/test/cuesheets/bad.060.INDEX_wrong_place.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE +INDEX 00 00:00:00 + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.061.INDEX_missing_number.cue b/flac/test/cuesheets/bad.061.INDEX_missing_number.cue new file mode 100644 index 0000000..e090459 --- /dev/null +++ b/flac/test/cuesheets/bad.061.INDEX_missing_number.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX diff --git a/flac/test/cuesheets/bad.062.INDEX_invalid_number_1.cue b/flac/test/cuesheets/bad.062.INDEX_invalid_number_1.cue new file mode 100644 index 0000000..63bda2b --- /dev/null +++ b/flac/test/cuesheets/bad.062.INDEX_invalid_number_1.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX thhpt! diff --git a/flac/test/cuesheets/bad.063.first_INDEX_not_0_or_1.cue b/flac/test/cuesheets/bad.063.first_INDEX_not_0_or_1.cue new file mode 100644 index 0000000..35abb77 --- /dev/null +++ b/flac/test/cuesheets/bad.063.first_INDEX_not_0_or_1.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 02 00:00:00 diff --git a/flac/test/cuesheets/bad.064.INDEX_num_non_sequential.cue b/flac/test/cuesheets/bad.064.INDEX_num_non_sequential.cue new file mode 100644 index 0000000..9fd5c34 --- /dev/null +++ b/flac/test/cuesheets/bad.064.INDEX_num_non_sequential.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 00:00:00 + INDEX 00 00:00:00 diff --git a/flac/test/cuesheets/bad.065.INDEX_num_out_of_range.cue b/flac/test/cuesheets/bad.065.INDEX_num_out_of_range.cue new file mode 100644 index 0000000..426e7be --- /dev/null +++ b/flac/test/cuesheets/bad.065.INDEX_num_out_of_range.cue @@ -0,0 +1,104 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 00 00:00:00 + INDEX 01 02:10:15 + INDEX 02 02:20:15 + INDEX 03 02:30:15 + INDEX 04 03:30:15 + INDEX 05 03:31:15 + INDEX 06 03:32:06 + INDEX 07 03:32:07 + INDEX 08 03:32:08 + INDEX 09 03:32:09 + INDEX 10 03:32:10 + INDEX 11 03:32:11 + INDEX 12 03:32:12 + INDEX 13 03:32:13 + INDEX 14 03:32:14 + INDEX 15 03:32:15 + INDEX 16 03:32:16 + INDEX 17 03:32:17 + INDEX 18 03:32:18 + INDEX 19 03:32:19 + INDEX 20 03:32:20 + INDEX 21 03:32:21 + INDEX 22 03:32:22 + INDEX 23 03:32:23 + INDEX 24 03:32:24 + INDEX 25 03:32:25 + INDEX 26 03:32:26 + INDEX 27 03:32:27 + INDEX 28 03:32:28 + INDEX 29 03:32:29 + INDEX 30 03:32:30 + INDEX 31 03:32:31 + INDEX 32 03:32:32 + INDEX 33 03:32:33 + INDEX 34 03:32:34 + INDEX 35 03:32:35 + INDEX 36 03:32:36 + INDEX 37 03:32:37 + INDEX 38 03:32:38 + INDEX 39 03:32:39 + INDEX 40 03:32:40 + INDEX 41 03:32:41 + INDEX 42 03:32:42 + INDEX 43 03:32:43 + INDEX 44 03:32:44 + INDEX 45 03:32:45 + INDEX 46 03:32:46 + INDEX 47 03:32:47 + INDEX 48 03:32:48 + INDEX 49 03:32:49 + INDEX 50 03:32:50 + INDEX 51 03:32:51 + INDEX 52 03:32:52 + INDEX 53 03:32:53 + INDEX 54 03:32:54 + INDEX 55 03:32:55 + INDEX 56 03:32:56 + INDEX 57 03:32:57 + INDEX 58 03:32:58 + INDEX 59 03:32:59 + INDEX 60 03:32:60 + INDEX 61 03:32:61 + INDEX 62 03:32:62 + INDEX 63 03:32:63 + INDEX 64 03:32:64 + INDEX 65 03:32:65 + INDEX 66 03:32:66 + INDEX 67 03:32:67 + INDEX 68 03:32:68 + INDEX 69 03:32:69 + INDEX 70 03:40:50 + INDEX 71 03:40:51 + INDEX 72 03:40:52 + INDEX 73 03:40:53 + INDEX 74 03:40:54 + INDEX 75 03:40:55 + INDEX 76 03:40:56 + INDEX 77 03:40:57 + INDEX 78 03:40:58 + INDEX 79 03:40:59 + INDEX 80 03:41:50 + INDEX 81 03:41:51 + INDEX 82 03:41:52 + INDEX 83 03:41:53 + INDEX 84 03:41:54 + INDEX 85 03:41:55 + INDEX 86 03:41:56 + INDEX 87 03:41:57 + INDEX 88 03:41:58 + INDEX 89 03:41:59 + INDEX 90 03:42:50 + INDEX 91 03:42:51 + INDEX 92 03:42:52 + INDEX 93 03:42:53 + INDEX 94 03:42:54 + INDEX 95 03:42:55 + INDEX 96 03:42:56 + INDEX 97 03:42:57 + INDEX 98 03:42:58 + INDEX 99 03:42:59 + INDEX 100 04:00:00 diff --git a/flac/test/cuesheets/bad.066.INDEX_missing_offset.cue b/flac/test/cuesheets/bad.066.INDEX_missing_offset.cue new file mode 100644 index 0000000..9838c95 --- /dev/null +++ b/flac/test/cuesheets/bad.066.INDEX_missing_offset.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 diff --git a/flac/test/cuesheets/bad.067.INDEX_illegal_offset.cue b/flac/test/cuesheets/bad.067.INDEX_illegal_offset.cue new file mode 100644 index 0000000..51cb99a --- /dev/null +++ b/flac/test/cuesheets/bad.067.INDEX_illegal_offset.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 00:00.00 diff --git a/flac/test/cuesheets/bad.068.INDEX_cdda_illegal_offset.cue b/flac/test/cuesheets/bad.068.INDEX_cdda_illegal_offset.cue new file mode 100644 index 0000000..7f94d37 --- /dev/null +++ b/flac/test/cuesheets/bad.068.INDEX_cdda_illegal_offset.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 588 diff --git a/flac/test/cuesheets/bad.069.nonzero_first_INDEX.cue b/flac/test/cuesheets/bad.069.nonzero_first_INDEX.cue new file mode 100644 index 0000000..7aaca52 --- /dev/null +++ b/flac/test/cuesheets/bad.069.nonzero_first_INDEX.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 00:02:00 diff --git a/flac/test/cuesheets/bad.070.INDEX_offset_not_ascending_1.cue b/flac/test/cuesheets/bad.070.INDEX_offset_not_ascending_1.cue new file mode 100644 index 0000000..5d9e740 --- /dev/null +++ b/flac/test/cuesheets/bad.070.INDEX_offset_not_ascending_1.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 + INDEX 02 00:02:00 + INDEX 03 00:01:74 diff --git a/flac/test/cuesheets/bad.071.INDEX_offset_not_ascending_2.cue b/flac/test/cuesheets/bad.071.INDEX_offset_not_ascending_2.cue new file mode 100644 index 0000000..9ccdcff --- /dev/null +++ b/flac/test/cuesheets/bad.071.INDEX_offset_not_ascending_2.cue @@ -0,0 +1,6 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 + INDEX 02 00:02:00 + TRACK 02 AUDIO + INDEX 01 00:01:74 diff --git a/flac/test/cuesheets/bad.110.ISRC_multiple.cue b/flac/test/cuesheets/bad.110.ISRC_multiple.cue new file mode 100644 index 0000000..2115934 --- /dev/null +++ b/flac/test/cuesheets/bad.110.ISRC_multiple.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + ISRC ABCDE1234567 + ISRC ABCD01234567 + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.111.ISRC_wrong_place_1.cue b/flac/test/cuesheets/bad.111.ISRC_wrong_place_1.cue new file mode 100644 index 0000000..c7781f4 --- /dev/null +++ b/flac/test/cuesheets/bad.111.ISRC_wrong_place_1.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE +ISRC ABCD01234567 + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.112.ISRC_wrong_place_2.cue b/flac/test/cuesheets/bad.112.ISRC_wrong_place_2.cue new file mode 100644 index 0000000..922d89f --- /dev/null +++ b/flac/test/cuesheets/bad.112.ISRC_wrong_place_2.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 + ISRC ABCD01234567 diff --git a/flac/test/cuesheets/bad.113.ISRC_missing_number.cue b/flac/test/cuesheets/bad.113.ISRC_missing_number.cue new file mode 100644 index 0000000..6404d6d --- /dev/null +++ b/flac/test/cuesheets/bad.113.ISRC_missing_number.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + ISRC + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.114.ISRC_invalid_number.cue b/flac/test/cuesheets/bad.114.ISRC_invalid_number.cue new file mode 100644 index 0000000..406e7f3 --- /dev/null +++ b/flac/test/cuesheets/bad.114.ISRC_invalid_number.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + ISRC ABCD0123456Z + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/bad.130.TRACK_missing_INDEX_01_1.cue b/flac/test/cuesheets/bad.130.TRACK_missing_INDEX_01_1.cue new file mode 100644 index 0000000..88f9b2f --- /dev/null +++ b/flac/test/cuesheets/bad.130.TRACK_missing_INDEX_01_1.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO diff --git a/flac/test/cuesheets/bad.131.TRACK_missing_INDEX_01_2.cue b/flac/test/cuesheets/bad.131.TRACK_missing_INDEX_01_2.cue new file mode 100644 index 0000000..ad1481d --- /dev/null +++ b/flac/test/cuesheets/bad.131.TRACK_missing_INDEX_01_2.cue @@ -0,0 +1,3 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 00 00:00:00 diff --git a/flac/test/cuesheets/bad.132.TRACK_missing_INDEX_01_3.cue b/flac/test/cuesheets/bad.132.TRACK_missing_INDEX_01_3.cue new file mode 100644 index 0000000..1d17759 --- /dev/null +++ b/flac/test/cuesheets/bad.132.TRACK_missing_INDEX_01_3.cue @@ -0,0 +1,4 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + TRACK 02 AUDIO + INDEX 01 00:02:00 diff --git a/flac/test/cuesheets/bad.133.TRACK_missing_INDEX_01_4.cue b/flac/test/cuesheets/bad.133.TRACK_missing_INDEX_01_4.cue new file mode 100644 index 0000000..bbeec0b --- /dev/null +++ b/flac/test/cuesheets/bad.133.TRACK_missing_INDEX_01_4.cue @@ -0,0 +1,5 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 00 00:00:00 + TRACK 02 AUDIO + INDEX 01 00:02:00 diff --git a/flac/test/cuesheets/bad.134.TRACK_missing_number.cue b/flac/test/cuesheets/bad.134.TRACK_missing_number.cue new file mode 100644 index 0000000..d2bb7d9 --- /dev/null +++ b/flac/test/cuesheets/bad.134.TRACK_missing_number.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK diff --git a/flac/test/cuesheets/bad.135.TRACK_invalid_number_1.cue b/flac/test/cuesheets/bad.135.TRACK_invalid_number_1.cue new file mode 100644 index 0000000..a4609a6 --- /dev/null +++ b/flac/test/cuesheets/bad.135.TRACK_invalid_number_1.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK thhpt! AUDIO diff --git a/flac/test/cuesheets/bad.136.TRACK_invalid_number_2.cue b/flac/test/cuesheets/bad.136.TRACK_invalid_number_2.cue new file mode 100644 index 0000000..6fa3d96 --- /dev/null +++ b/flac/test/cuesheets/bad.136.TRACK_invalid_number_2.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK 0 AUDIO diff --git a/flac/test/cuesheets/bad.137.TRACK_cdda_out_of_range.cue b/flac/test/cuesheets/bad.137.TRACK_cdda_out_of_range.cue new file mode 100644 index 0000000..57a7a21 --- /dev/null +++ b/flac/test/cuesheets/bad.137.TRACK_cdda_out_of_range.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK 100 AUDIO diff --git a/flac/test/cuesheets/bad.138.TRACK_num_non_sequential.cue b/flac/test/cuesheets/bad.138.TRACK_num_non_sequential.cue new file mode 100644 index 0000000..638ecf0 --- /dev/null +++ b/flac/test/cuesheets/bad.138.TRACK_num_non_sequential.cue @@ -0,0 +1,6 @@ +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 0:0:0 + TRACK 02 AUDIO + INDEX 01 2:0:0 + TRACK 01 AUDIO diff --git a/flac/test/cuesheets/bad.139.TRACK_missing_type.cue b/flac/test/cuesheets/bad.139.TRACK_missing_type.cue new file mode 100644 index 0000000..1ba64d5 --- /dev/null +++ b/flac/test/cuesheets/bad.139.TRACK_missing_type.cue @@ -0,0 +1,2 @@ +FILE "z.wav" WAVE + TRACK 01 diff --git a/flac/test/cuesheets/bad.140.no_TRACKs.cue b/flac/test/cuesheets/bad.140.no_TRACKs.cue new file mode 100644 index 0000000..6bee619 --- /dev/null +++ b/flac/test/cuesheets/bad.140.no_TRACKs.cue @@ -0,0 +1 @@ +FILE "z.wav" WAVE diff --git a/flac/test/cuesheets/bad.200.FLAC_leadin_missing_offset.cue b/flac/test/cuesheets/bad.200.FLAC_leadin_missing_offset.cue new file mode 100644 index 0000000..47b7846 --- /dev/null +++ b/flac/test/cuesheets/bad.200.FLAC_leadin_missing_offset.cue @@ -0,0 +1 @@ +REM FLAC__lead-in diff --git a/flac/test/cuesheets/bad.201.FLAC_leadin_illegal_offset.cue b/flac/test/cuesheets/bad.201.FLAC_leadin_illegal_offset.cue new file mode 100644 index 0000000..1593fdd --- /dev/null +++ b/flac/test/cuesheets/bad.201.FLAC_leadin_illegal_offset.cue @@ -0,0 +1 @@ +REM FLAC__lead-in thhpt! diff --git a/flac/test/cuesheets/bad.202.FLAC_leadin_cdda_illegal_offset.cue b/flac/test/cuesheets/bad.202.FLAC_leadin_cdda_illegal_offset.cue new file mode 100644 index 0000000..0a52ee9 --- /dev/null +++ b/flac/test/cuesheets/bad.202.FLAC_leadin_cdda_illegal_offset.cue @@ -0,0 +1 @@ +REM FLAC__lead-in 123 diff --git a/flac/test/cuesheets/bad.230.FLAC_leadout_multiple.cue b/flac/test/cuesheets/bad.230.FLAC_leadout_multiple.cue new file mode 100644 index 0000000..b87cbcf --- /dev/null +++ b/flac/test/cuesheets/bad.230.FLAC_leadout_multiple.cue @@ -0,0 +1,3 @@ +REM FLAC__lead-in 88200 +REM FLAC__lead-out 170 211680000 +REM FLAC__lead-out 170 211680588 diff --git a/flac/test/cuesheets/bad.231.FLAC_leadout_missing_track.cue b/flac/test/cuesheets/bad.231.FLAC_leadout_missing_track.cue new file mode 100644 index 0000000..ad2b785 --- /dev/null +++ b/flac/test/cuesheets/bad.231.FLAC_leadout_missing_track.cue @@ -0,0 +1 @@ +REM FLAC__lead-out diff --git a/flac/test/cuesheets/bad.232.FLAC_leadout_illegal_track.cue b/flac/test/cuesheets/bad.232.FLAC_leadout_illegal_track.cue new file mode 100644 index 0000000..04db524 --- /dev/null +++ b/flac/test/cuesheets/bad.232.FLAC_leadout_illegal_track.cue @@ -0,0 +1 @@ +REM FLAC__lead-out thhpt! diff --git a/flac/test/cuesheets/bad.233.FLAC_leadout_missing_offset.cue b/flac/test/cuesheets/bad.233.FLAC_leadout_missing_offset.cue new file mode 100644 index 0000000..653cf39 --- /dev/null +++ b/flac/test/cuesheets/bad.233.FLAC_leadout_missing_offset.cue @@ -0,0 +1 @@ +REM FLAC__lead-out 170 diff --git a/flac/test/cuesheets/bad.234.FLAC_leadout_illegal_offset.cue b/flac/test/cuesheets/bad.234.FLAC_leadout_illegal_offset.cue new file mode 100644 index 0000000..26d5145 --- /dev/null +++ b/flac/test/cuesheets/bad.234.FLAC_leadout_illegal_offset.cue @@ -0,0 +1 @@ +REM FLAC__lead-out 170 thhpt! diff --git a/flac/test/cuesheets/bad.235.FLAC_leadout_offset_not_211680000.cue b/flac/test/cuesheets/bad.235.FLAC_leadout_offset_not_211680000.cue new file mode 100644 index 0000000..4105cf8 --- /dev/null +++ b/flac/test/cuesheets/bad.235.FLAC_leadout_offset_not_211680000.cue @@ -0,0 +1 @@ +REM FLAC__lead-out 170 211680588 diff --git a/flac/test/cuesheets/good.000.cue b/flac/test/cuesheets/good.000.cue new file mode 100644 index 0000000..a60e03b --- /dev/null +++ b/flac/test/cuesheets/good.000.cue @@ -0,0 +1,4 @@ +CATALOG "1234567890123" +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/good.001.cue b/flac/test/cuesheets/good.001.cue new file mode 100644 index 0000000..894b3c8 --- /dev/null +++ b/flac/test/cuesheets/good.001.cue @@ -0,0 +1,184 @@ +REM FLAC__lead-in 88200 +REM FLAC__lead-out 170 211680000 +CATALOG 1234567890123 +FILE "z.wav" WAVE + TRACK 01 AUDIO + FLAGS PRE + INDEX 01 00:00:00 + TRACK 02 AUDIO + FLAGS PRE + ISRC ABCDE7654321 + INDEX 00 02:09:12 + INDEX 01 02:10:15 + INDEX 02 02:20:15 + INDEX 03 02:30:15 + INDEX 04 03:30:15 + INDEX 05 03:31:15 + INDEX 06 03:32:06 + INDEX 07 03:32:07 + INDEX 08 03:32:08 + INDEX 09 03:32:09 + INDEX 10 03:32:10 + INDEX 11 03:32:11 + INDEX 12 03:32:12 + INDEX 13 03:32:13 + INDEX 14 03:32:14 + INDEX 15 03:32:15 + INDEX 16 03:32:16 + INDEX 17 03:32:17 + INDEX 18 03:32:18 + INDEX 19 03:32:19 + INDEX 20 03:32:20 + INDEX 21 03:32:21 + INDEX 22 03:32:22 + INDEX 23 03:32:23 + INDEX 24 03:32:24 + INDEX 25 03:32:25 + INDEX 26 03:32:26 + INDEX 27 03:32:27 + INDEX 28 03:32:28 + INDEX 29 03:32:29 + INDEX 30 03:32:30 + INDEX 31 03:32:31 + INDEX 32 03:32:32 + INDEX 33 03:32:33 + INDEX 34 03:32:34 + INDEX 35 03:32:35 + INDEX 36 03:32:36 + INDEX 37 03:32:37 + INDEX 38 03:32:38 + INDEX 39 03:32:39 + INDEX 40 03:32:40 + INDEX 41 03:32:41 + INDEX 42 03:32:42 + INDEX 43 03:32:43 + INDEX 44 03:32:44 + INDEX 45 03:32:45 + INDEX 46 03:32:46 + INDEX 47 03:32:47 + INDEX 48 03:32:48 + INDEX 49 03:32:49 + INDEX 50 03:32:50 + INDEX 51 03:32:51 + INDEX 52 03:32:52 + INDEX 53 03:32:53 + INDEX 54 03:32:54 + INDEX 55 03:32:55 + INDEX 56 03:32:56 + INDEX 57 03:32:57 + INDEX 58 03:32:58 + INDEX 59 03:32:59 + INDEX 60 03:32:60 + INDEX 61 03:32:61 + INDEX 62 03:32:62 + INDEX 63 03:32:63 + INDEX 64 03:32:64 + INDEX 65 03:32:65 + INDEX 66 03:32:66 + INDEX 67 03:32:67 + INDEX 68 03:32:68 + INDEX 69 03:32:69 + INDEX 70 03:40:50 + INDEX 71 03:40:51 + INDEX 72 03:40:52 + INDEX 73 03:40:53 + INDEX 74 03:40:54 + INDEX 75 03:40:55 + INDEX 76 03:40:56 + INDEX 77 03:40:57 + INDEX 78 03:40:58 + INDEX 79 03:40:59 + INDEX 80 03:41:50 + INDEX 81 03:41:51 + INDEX 82 03:41:52 + INDEX 83 03:41:53 + INDEX 84 03:41:54 + INDEX 85 03:41:55 + INDEX 86 03:41:56 + INDEX 87 03:41:57 + INDEX 88 03:41:58 + INDEX 89 03:41:59 + INDEX 90 03:42:50 + INDEX 91 03:42:51 + INDEX 92 03:42:52 + INDEX 93 03:42:53 + INDEX 94 03:42:54 + INDEX 95 03:42:55 + INDEX 96 03:42:56 + INDEX 97 03:42:57 + INDEX 98 03:42:58 + INDEX 99 03:42:59 + TRACK 03 AUDIO + ISRC AB-CD7-65-43210 + INDEX 00 04:50:12 + INDEX 01 04:51:72 + TRACK 04 AUDIO + INDEX 00 06:36:10 + INDEX 01 06:38:47 + TRACK 05 AUDIO + INDEX 00 08:34:45 + INDEX 01 08:36:15 + TRACK 06 AUDIO + INDEX 00 13:20:22 + INDEX 01 13:22:12 + TRACK 07 AUDIO + INDEX 00 16:08:20 + INDEX 01 16:11:17 + TRACK 08 AUDIO + INDEX 01 17:48:37 + TRACK 09 AUDIO + INDEX 00 19:38:17 + INDEX 01 19:39:30 + TRACK 10 AUDIO + INDEX 00 22:07:07 + INDEX 01 22:08:20 + TRACK 11 AUDIO + INDEX 01 24:16:45 + TRACK 12 AUDIO + INDEX 01 26:13:67 + TRACK 13 AUDIO + INDEX 01 28:03:27 + TRACK 14 AUDIO + INDEX 00 30:22:42 + INDEX 01 30:24:45 + TRACK 15 AUDIO + INDEX 00 34:06:22 + INDEX 01 34:07:62 + TRACK 16 AUDIO + INDEX 00 35:54:30 + INDEX 01 35:56:60 + TRACK 17 AUDIO + INDEX 00 38:49:10 + INDEX 01 38:51:22 + TRACK 18 AUDIO + INDEX 00 41:14:15 + INDEX 01 41:17:15 + TRACK 19 AUDIO + INDEX 00 44:27:15 + INDEX 01 44:28:45 + TRACK 20 AUDIO + INDEX 00 48:07:17 + INDEX 01 48:09:72 + TRACK 21 AUDIO + INDEX 00 50:48:05 + INDEX 01 50:49:27 + TRACK 22 AUDIO + INDEX 00 53:29:72 + INDEX 01 53:31:20 + TRACK 23 AUDIO + INDEX 00 57:57:60 + INDEX 01 58:00:40 + TRACK 24 AUDIO + INDEX 00 61:52:65 + INDEX 01 61:55:37 + TRACK 25 AUDIO + INDEX 00 65:07:50 + INDEX 01 65:10:52 + TRACK 26 AUDIO + INDEX 00 68:30:05 + INDEX 01 68:32:45 + TRACK 27 AUDIO + INDEX 01 71:45:17 + TRACK 28 AUDIO + INDEX 00 74:49:07 + INDEX 01 74:51:47 diff --git a/flac/test/cuesheets/good.002.dos_format.cue b/flac/test/cuesheets/good.002.dos_format.cue new file mode 100644 index 0000000..ee0359d --- /dev/null +++ b/flac/test/cuesheets/good.002.dos_format.cue @@ -0,0 +1,4 @@ +CATALOG "1234567890123" +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 diff --git a/flac/test/cuesheets/good.003.missing_final_newline.cue b/flac/test/cuesheets/good.003.missing_final_newline.cue new file mode 100644 index 0000000..1f6d0e5 --- /dev/null +++ b/flac/test/cuesheets/good.003.missing_final_newline.cue @@ -0,0 +1,4 @@ +CATALOG "1234567890123" +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 \ No newline at end of file diff --git a/flac/test/cuesheets/good.004.dos_format.missing_final_newline.cue b/flac/test/cuesheets/good.004.dos_format.missing_final_newline.cue new file mode 100644 index 0000000..7115cf5 --- /dev/null +++ b/flac/test/cuesheets/good.004.dos_format.missing_final_newline.cue @@ -0,0 +1,4 @@ +CATALOG "1234567890123" +FILE "z.wav" WAVE + TRACK 01 AUDIO + INDEX 01 00:00:00 \ No newline at end of file diff --git a/flac/test/flac-to-flac-metadata-test-files/Makefile.am b/flac/test/flac-to-flac-metadata-test-files/Makefile.am new file mode 100644 index 0000000..7901667 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/Makefile.am @@ -0,0 +1,45 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + case00a-expect.meta \ + case01a-expect.meta \ + case01b-expect.meta \ + case01c-expect.meta \ + case01d-expect.meta \ + case01e-expect.meta \ + case02a-expect.meta \ + case02b-expect.meta \ + case02c-expect.meta \ + case03a-expect.meta \ + case03b-expect.meta \ + case03c-expect.meta \ + case04a-expect.meta \ + case04b-expect.meta \ + case04c-expect.meta \ + case04d-expect.meta \ + case04e-expect.meta \ + input-SCPAP.flac \ + input-SCVA.flac \ + input-SCVAUP.flac \ + input-SCVPAP.flac \ + input-SVAUP.flac \ + input-VA.flac \ + input0.cue + +clean-local: + -rm -f out.* diff --git a/flac/test/flac-to-flac-metadata-test-files/case00a-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case00a-expect.meta new file mode 100644 index 0000000..bae7ce9 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case00a-expect.meta @@ -0,0 +1,84 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 126 (UNKNOWN) + is last: false + length: 0 + data contents: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 3201 diff --git a/flac/test/flac-to-flac-metadata-test-files/case01a-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case01a-expect.meta new file mode 100644 index 0000000..f0f38a9 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case01a-expect.meta @@ -0,0 +1,79 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 3205 diff --git a/flac/test/flac-to-flac-metadata-test-files/case01b-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case01b-expect.meta new file mode 100644 index 0000000..f7a5f00 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case01b-expect.meta @@ -0,0 +1,75 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/case01c-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case01c-expect.meta new file mode 100644 index 0000000..d7f115a --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case01c-expect.meta @@ -0,0 +1,79 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 1234 diff --git a/flac/test/flac-to-flac-metadata-test-files/case01d-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case01d-expect.meta new file mode 100644 index 0000000..d7f115a --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case01d-expect.meta @@ -0,0 +1,79 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 1234 diff --git a/flac/test/flac-to-flac-metadata-test-files/case01e-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case01e-expect.meta new file mode 100644 index 0000000..fcb5128 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case01e-expect.meta @@ -0,0 +1,79 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 8192 diff --git a/flac/test/flac-to-flac-metadata-test-files/case02a-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case02a-expect.meta new file mode 100644 index 0000000..f64cac7 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case02a-expect.meta @@ -0,0 +1,73 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #2 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 3205 diff --git a/flac/test/flac-to-flac-metadata-test-files/case02b-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case02b-expect.meta new file mode 100644 index 0000000..8cee53f --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case02b-expect.meta @@ -0,0 +1,74 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 52 + comments: 1 + comment[0]: artist=0 +METADATA block #2 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 3205 diff --git a/flac/test/flac-to-flac-metadata-test-files/case02c-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case02c-expect.meta new file mode 100644 index 0000000..170f28a --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case02c-expect.meta @@ -0,0 +1,79 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 52 + comments: 1 + comment[0]: artist=0 +METADATA block #2 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 126 (UNKNOWN) + is last: false + length: 0 + data contents: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 3201 diff --git a/flac/test/flac-to-flac-metadata-test-files/case03a-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case03a-expect.meta new file mode 100644 index 0000000..5c8f443 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case03a-expect.meta @@ -0,0 +1,84 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 9294969890929 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 588 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 2352 + number: 2 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #2 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 126 (UNKNOWN) + is last: false + length: 0 + data contents: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 3201 diff --git a/flac/test/flac-to-flac-metadata-test-files/case03b-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case03b-expect.meta new file mode 100644 index 0000000..5c8f443 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case03b-expect.meta @@ -0,0 +1,84 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 9294969890929 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 588 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 2352 + number: 2 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #2 + type: 3 (SEEKTABLE) + is last: false + length: 180 + seek points: 10 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER + point 5: PLACEHOLDER + point 6: PLACEHOLDER + point 7: PLACEHOLDER + point 8: PLACEHOLDER + point 9: PLACEHOLDER +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #5 + type: 126 (UNKNOWN) + is last: false + length: 0 + data contents: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 3201 diff --git a/flac/test/flac-to-flac-metadata-test-files/case03c-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case03c-expect.meta new file mode 100644 index 0000000..c3f1d5d --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case03c-expect.meta @@ -0,0 +1,41 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5879 + MD5 signature: 2ea0e6a767b66bf0668523fd77672ce1 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #3 + type: 2 (APPLICATION) + is last: false + length: 4 + application ID: 66616b65 + data contents: +METADATA block #4 + type: 126 (UNKNOWN) + is last: false + length: 0 + data contents: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 3201 diff --git a/flac/test/flac-to-flac-metadata-test-files/case04a-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case04a-expect.meta new file mode 100644 index 0000000..217418e --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case04a-expect.meta @@ -0,0 +1,26 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #2 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/case04b-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case04b-expect.meta new file mode 100644 index 0000000..6bb53a8 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case04b-expect.meta @@ -0,0 +1,36 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 90 + seek points: 5 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #3 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/case04c-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case04c-expect.meta new file mode 100644 index 0000000..bc913ad --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case04c-expect.meta @@ -0,0 +1,32 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #3 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/case04d-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case04d-expect.meta new file mode 100644 index 0000000..663d1d4 --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case04d-expect.meta @@ -0,0 +1,60 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #3 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/case04e-expect.meta b/flac/test/flac-to-flac-metadata-test-files/case04e-expect.meta new file mode 100644 index 0000000..6b7e52c --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/case04e-expect.meta @@ -0,0 +1,70 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 44100 Hz + channels: 2 + bits-per-sample: 16 + total samples: 5880 + MD5 signature: 74ffd4737eb5488d512be4af58943362 +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 90 + seek points: 5 + point 0: sample_number=0 + point 1: sample_number=4096 + point 2: PLACEHOLDER + point 3: PLACEHOLDER + point 4: PLACEHOLDER +METADATA block #2 + type: 5 (CUESHEET) + is last: false + length: 540 + media catalog number: 1234567890123 + lead-in: 88200 + is CD: true + number of tracks: 3 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 2 + index[0] + offset: 0 + number: 1 + index[1] + offset: 588 + number: 2 + track[1] + offset: 2940 + number: 2 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[2] + offset: 5880 + number: 170 (LEAD-OUT) +METADATA block #3 + type: 4 (VORBIS_COMMENT) + is last: false + length: 203 + comments: 6 + comment[0]: REPLAYGAIN_TRACK_PEAK=0.99996948 + comment[1]: REPLAYGAIN_TRACK_GAIN=-7.89 dB + comment[2]: REPLAYGAIN_ALBUM_PEAK=0.99996948 + comment[3]: REPLAYGAIN_ALBUM_GAIN=-7.89 dB + comment[4]: artist=1 + comment[5]: title=2 +METADATA block #4 + type: 2 (APPLICATION) + is last: true + length: 4 + application ID: 66616b65 + data contents: diff --git a/flac/test/flac-to-flac-metadata-test-files/input-SCPAP.flac b/flac/test/flac-to-flac-metadata-test-files/input-SCPAP.flac new file mode 100644 index 0000000..b7c480e Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-SCPAP.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input-SCVA.flac b/flac/test/flac-to-flac-metadata-test-files/input-SCVA.flac new file mode 100644 index 0000000..7554817 Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-SCVA.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input-SCVAUP.flac b/flac/test/flac-to-flac-metadata-test-files/input-SCVAUP.flac new file mode 100644 index 0000000..0aade53 Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-SCVAUP.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input-SCVPAP.flac b/flac/test/flac-to-flac-metadata-test-files/input-SCVPAP.flac new file mode 100644 index 0000000..406c565 Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-SCVPAP.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input-SVAUP.flac b/flac/test/flac-to-flac-metadata-test-files/input-SVAUP.flac new file mode 100644 index 0000000..5031ec7 Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-SVAUP.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input-VA.flac b/flac/test/flac-to-flac-metadata-test-files/input-VA.flac new file mode 100644 index 0000000..7a273b0 Binary files /dev/null and b/flac/test/flac-to-flac-metadata-test-files/input-VA.flac differ diff --git a/flac/test/flac-to-flac-metadata-test-files/input0.cue b/flac/test/flac-to-flac-metadata-test-files/input0.cue new file mode 100644 index 0000000..627c87f --- /dev/null +++ b/flac/test/flac-to-flac-metadata-test-files/input0.cue @@ -0,0 +1,7 @@ +CATALOG 9294969890929 +FILE "blah" FLAC + TRACK 01 AUDIO + INDEX 01 00:00:00 + TRACK 02 AUDIO + INDEX 01 00:00:01 + INDEX 02 00:00:05 diff --git a/flac/test/metaflac-test-files/Makefile.am b/flac/test/metaflac-test-files/Makefile.am new file mode 100644 index 0000000..07b2b86 --- /dev/null +++ b/flac/test/metaflac-test-files/Makefile.am @@ -0,0 +1,84 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + case00-expect.meta \ + case01-expect.meta \ + case02-expect.meta \ + case03-expect.meta \ + case04-expect.meta \ + case05-expect.meta \ + case06-expect.meta \ + case07-expect.meta \ + case08-expect.meta \ + case09-expect.meta \ + case10-expect.meta \ + case11-expect.meta \ + case12-expect.meta \ + case13-expect.meta \ + case14-expect.meta \ + case15-expect.meta \ + case16-expect.meta \ + case17-expect.meta \ + case18-expect.meta \ + case19-expect.meta \ + case20-expect.meta \ + case21-expect.meta \ + case22-expect.meta \ + case23-expect.meta \ + case24-expect.meta \ + case25-expect.meta \ + case26-expect.meta \ + case27-expect.meta \ + case28-expect.meta \ + case29-expect.meta \ + case30-expect.meta \ + case31-expect.meta \ + case32-expect.meta \ + case33-expect.meta \ + case34-expect.meta \ + case35-expect.meta \ + case36-expect.meta \ + case37-expect.meta \ + case38-expect.meta \ + case39-expect.meta \ + case40-expect.meta \ + case41-expect.meta \ + case42-expect.meta \ + case43-expect.meta \ + case44-expect.meta \ + case45-expect.meta \ + case46-expect.meta \ + case47-expect.meta \ + case48-expect.meta \ + case49-expect.meta \ + case50-expect.meta \ + case51-expect.meta \ + case52-expect.meta \ + case53-expect.meta \ + case54-expect.meta \ + case55-expect.meta \ + case56-expect.meta \ + case57-expect.meta \ + case58-expect.meta \ + case59-expect.meta \ + case60-expect.meta \ + case61-expect.meta \ + case62-expect.meta + +clean-local: + -rm -f out.* diff --git a/flac/test/metaflac-test-files/case00-expect.meta b/flac/test/metaflac-test-files/case00-expect.meta new file mode 100644 index 0000000..5c14d03 --- /dev/null +++ b/flac/test/metaflac-test-files/case00-expect.meta @@ -0,0 +1,24 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 8192 diff --git a/flac/test/metaflac-test-files/case01-expect.meta b/flac/test/metaflac-test-files/case01-expect.meta new file mode 100644 index 0000000..e4d4aee --- /dev/null +++ b/flac/test/metaflac-test-files/case01-expect.meta @@ -0,0 +1,9 @@ +a042237c5493fdb9656b94a83608d11a +1152 +1152 +10 +10 +8000 +1 +8 +80000 diff --git a/flac/test/metaflac-test-files/case02-expect.meta b/flac/test/metaflac-test-files/case02-expect.meta new file mode 100644 index 0000000..392bc74 --- /dev/null +++ b/flac/test/metaflac-test-files/case02-expect.meta @@ -0,0 +1,28 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #3 + type: 1 (PADDING) + is last: false + length: 8192 +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 12345 diff --git a/flac/test/metaflac-test-files/case03-expect.meta b/flac/test/metaflac-test-files/case03-expect.meta new file mode 100644 index 0000000..8f391eb --- /dev/null +++ b/flac/test/metaflac-test-files/case03-expect.meta @@ -0,0 +1,25 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 93 + comments: 1 + comment[0]: ARTIST=The_artist_formerly_known_as_the_artist... +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20488 diff --git a/flac/test/metaflac-test-files/case04-expect.meta b/flac/test/metaflac-test-files/case04-expect.meta new file mode 100644 index 0000000..dc79553 --- /dev/null +++ b/flac/test/metaflac-test-files/case04-expect.meta @@ -0,0 +1,26 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 2 + comment[0]: ARTIST=The_artist_formerly_known_as_the_artist... + comment[1]: ARTIST=Chuck_Woolery +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20464 diff --git a/flac/test/metaflac-test-files/case05-expect.meta b/flac/test/metaflac-test-files/case05-expect.meta new file mode 100644 index 0000000..72bdd50 --- /dev/null +++ b/flac/test/metaflac-test-files/case05-expect.meta @@ -0,0 +1,27 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 132 + comments: 3 + comment[0]: ARTIST=The_artist_formerly_known_as_the_artist... + comment[1]: ARTIST=Chuck_Woolery + comment[2]: ARTIST=Vern +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20449 diff --git a/flac/test/metaflac-test-files/case06-expect.meta b/flac/test/metaflac-test-files/case06-expect.meta new file mode 100644 index 0000000..d5d8a0e --- /dev/null +++ b/flac/test/metaflac-test-files/case06-expect.meta @@ -0,0 +1,28 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 166 + comments: 4 + comment[0]: ARTIST=The_artist_formerly_known_as_the_artist... + comment[1]: ARTIST=Chuck_Woolery + comment[2]: ARTIST=Vern + comment[3]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20415 diff --git a/flac/test/metaflac-test-files/case07-expect.meta b/flac/test/metaflac-test-files/case07-expect.meta new file mode 100644 index 0000000..7fc8b63 --- /dev/null +++ b/flac/test/metaflac-test-files/case07-expect.meta @@ -0,0 +1,4 @@ +reference libFLAC 1.2.1 20070917 +ARTIST=The_artist_formerly_known_as_the_artist... +ARTIST=Chuck_Woolery +ARTIST=Vern diff --git a/flac/test/metaflac-test-files/case08-expect.meta b/flac/test/metaflac-test-files/case08-expect.meta new file mode 100644 index 0000000..6703152 --- /dev/null +++ b/flac/test/metaflac-test-files/case08-expect.meta @@ -0,0 +1,27 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 113 + comments: 3 + comment[0]: ARTIST=Chuck_Woolery + comment[1]: ARTIST=Vern + comment[2]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20468 diff --git a/flac/test/metaflac-test-files/case09-expect.meta b/flac/test/metaflac-test-files/case09-expect.meta new file mode 100644 index 0000000..4e25e75 --- /dev/null +++ b/flac/test/metaflac-test-files/case09-expect.meta @@ -0,0 +1,25 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20507 diff --git a/flac/test/metaflac-test-files/case10-expect.meta b/flac/test/metaflac-test-files/case10-expect.meta new file mode 100644 index 0000000..100233f --- /dev/null +++ b/flac/test/metaflac-test-files/case10-expect.meta @@ -0,0 +1,6 @@ +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it diff --git a/flac/test/metaflac-test-files/case11-expect.meta b/flac/test/metaflac-test-files/case11-expect.meta new file mode 100644 index 0000000..3c1ea54 --- /dev/null +++ b/flac/test/metaflac-test-files/case11-expect.meta @@ -0,0 +1,9 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a diff --git a/flac/test/metaflac-test-files/case12-expect.meta b/flac/test/metaflac-test-files/case12-expect.meta new file mode 100644 index 0000000..e5ef60e --- /dev/null +++ b/flac/test/metaflac-test-files/case12-expect.meta @@ -0,0 +1,12 @@ +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it diff --git a/flac/test/metaflac-test-files/case13-expect.meta b/flac/test/metaflac-test-files/case13-expect.meta new file mode 100644 index 0000000..ce394c7 --- /dev/null +++ b/flac/test/metaflac-test-files/case13-expect.meta @@ -0,0 +1,10 @@ +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20507 diff --git a/flac/test/metaflac-test-files/case14-expect.meta b/flac/test/metaflac-test-files/case14-expect.meta new file mode 100644 index 0000000..05a2a9a --- /dev/null +++ b/flac/test/metaflac-test-files/case14-expect.meta @@ -0,0 +1,13 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20507 diff --git a/flac/test/metaflac-test-files/case15-expect.meta b/flac/test/metaflac-test-files/case15-expect.meta new file mode 100644 index 0000000..1b24c46 --- /dev/null +++ b/flac/test/metaflac-test-files/case15-expect.meta @@ -0,0 +1,16 @@ +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 20507 diff --git a/flac/test/metaflac-test-files/case16-expect.meta b/flac/test/metaflac-test-files/case16-expect.meta new file mode 100644 index 0000000..a85cc5b --- /dev/null +++ b/flac/test/metaflac-test-files/case16-expect.meta @@ -0,0 +1,33 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: false + length: 20507 +METADATA block #4 + type: 1 (PADDING) + is last: false + length: 4321 +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 4321 diff --git a/flac/test/metaflac-test-files/case17-expect.meta b/flac/test/metaflac-test-files/case17-expect.meta new file mode 100644 index 0000000..1c9d043 --- /dev/null +++ b/flac/test/metaflac-test-files/case17-expect.meta @@ -0,0 +1,25 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 29157 diff --git a/flac/test/metaflac-test-files/case18-expect.meta b/flac/test/metaflac-test-files/case18-expect.meta new file mode 100644 index 0000000..38355c6 --- /dev/null +++ b/flac/test/metaflac-test-files/case18-expect.meta @@ -0,0 +1,29 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: false + length: 29157 +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 0 diff --git a/flac/test/metaflac-test-files/case19-expect.meta b/flac/test/metaflac-test-files/case19-expect.meta new file mode 100644 index 0000000..9983f31 --- /dev/null +++ b/flac/test/metaflac-test-files/case19-expect.meta @@ -0,0 +1,25 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 29161 diff --git a/flac/test/metaflac-test-files/case20-expect.meta b/flac/test/metaflac-test-files/case20-expect.meta new file mode 100644 index 0000000..8e26532 --- /dev/null +++ b/flac/test/metaflac-test-files/case20-expect.meta @@ -0,0 +1,29 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 74 + comments: 1 + comment[0]: TITLE=He_who_smelt_it_dealt_it +METADATA block #3 + type: 1 (PADDING) + is last: false + length: 29161 +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 0 diff --git a/flac/test/metaflac-test-files/case21-expect.meta b/flac/test/metaflac-test-files/case21-expect.meta new file mode 100644 index 0000000..ed9422f --- /dev/null +++ b/flac/test/metaflac-test-files/case21-expect.meta @@ -0,0 +1,24 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 29199 diff --git a/flac/test/metaflac-test-files/case22-expect.meta b/flac/test/metaflac-test-files/case22-expect.meta new file mode 100644 index 0000000..e575a92 --- /dev/null +++ b/flac/test/metaflac-test-files/case22-expect.meta @@ -0,0 +1,18 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 29199 diff --git a/flac/test/metaflac-test-files/case23-expect.meta b/flac/test/metaflac-test-files/case23-expect.meta new file mode 100644 index 0000000..e575a92 --- /dev/null +++ b/flac/test/metaflac-test-files/case23-expect.meta @@ -0,0 +1,18 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 29199 diff --git a/flac/test/metaflac-test-files/case24-expect.meta b/flac/test/metaflac-test-files/case24-expect.meta new file mode 100644 index 0000000..e575a92 --- /dev/null +++ b/flac/test/metaflac-test-files/case24-expect.meta @@ -0,0 +1,18 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 29199 diff --git a/flac/test/metaflac-test-files/case25-expect.meta b/flac/test/metaflac-test-files/case25-expect.meta new file mode 100644 index 0000000..3973e52 --- /dev/null +++ b/flac/test/metaflac-test-files/case25-expect.meta @@ -0,0 +1,14 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: true + length: 40 + comments: 0 diff --git a/flac/test/metaflac-test-files/case26-expect.meta b/flac/test/metaflac-test-files/case26-expect.meta new file mode 100644 index 0000000..cadd501 --- /dev/null +++ b/flac/test/metaflac-test-files/case26-expect.meta @@ -0,0 +1,22 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 40 + comments: 0 +METADATA block #2 + type: 1 (PADDING) + is last: false + length: 0 +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 0 diff --git a/flac/test/metaflac-test-files/case27-expect.meta b/flac/test/metaflac-test-files/case27-expect.meta new file mode 100644 index 0000000..b5d2fd3 --- /dev/null +++ b/flac/test/metaflac-test-files/case27-expect.meta @@ -0,0 +1,13 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 1 (PADDING) + is last: true + length: 48 diff --git a/flac/test/metaflac-test-files/case28-expect.meta b/flac/test/metaflac-test-files/case28-expect.meta new file mode 100644 index 0000000..b5d2fd3 --- /dev/null +++ b/flac/test/metaflac-test-files/case28-expect.meta @@ -0,0 +1,13 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 1 (PADDING) + is last: true + length: 48 diff --git a/flac/test/metaflac-test-files/case29-expect.meta b/flac/test/metaflac-test-files/case29-expect.meta new file mode 100644 index 0000000..6eba886 --- /dev/null +++ b/flac/test/metaflac-test-files/case29-expect.meta @@ -0,0 +1,9 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: true + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a diff --git a/flac/test/metaflac-test-files/case30-expect.meta b/flac/test/metaflac-test-files/case30-expect.meta new file mode 100644 index 0000000..6eba886 --- /dev/null +++ b/flac/test/metaflac-test-files/case30-expect.meta @@ -0,0 +1,9 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: true + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a diff --git a/flac/test/metaflac-test-files/case31-expect.meta b/flac/test/metaflac-test-files/case31-expect.meta new file mode 100644 index 0000000..e73f95d --- /dev/null +++ b/flac/test/metaflac-test-files/case31-expect.meta @@ -0,0 +1,15 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: true + length: 66 + comments: 1 + comment[0]: f=0123456789abcdefghij diff --git a/flac/test/metaflac-test-files/case32-expect.meta b/flac/test/metaflac-test-files/case32-expect.meta new file mode 100644 index 0000000..3e96d54 --- /dev/null +++ b/flac/test/metaflac-test-files/case32-expect.meta @@ -0,0 +1,15 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: true + length: 65 + comments: 1 + comment[0]: f=0123456789abcdefghi diff --git a/flac/test/metaflac-test-files/case33-expect.meta b/flac/test/metaflac-test-files/case33-expect.meta new file mode 100644 index 0000000..701a4b3 --- /dev/null +++ b/flac/test/metaflac-test-files/case33-expect.meta @@ -0,0 +1,19 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 61 + comments: 1 + comment[0]: f=0123456789abcde +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 0 diff --git a/flac/test/metaflac-test-files/case34-expect.meta b/flac/test/metaflac-test-files/case34-expect.meta new file mode 100644 index 0000000..d024e3c --- /dev/null +++ b/flac/test/metaflac-test-files/case34-expect.meta @@ -0,0 +1,19 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 47 + comments: 1 + comment[0]: f=0 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 14 diff --git a/flac/test/metaflac-test-files/case35-expect.meta b/flac/test/metaflac-test-files/case35-expect.meta new file mode 100644 index 0000000..3c384a3 --- /dev/null +++ b/flac/test/metaflac-test-files/case35-expect.meta @@ -0,0 +1,19 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 56 + comments: 1 + comment[0]: f=0123456789 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case36-expect.meta b/flac/test/metaflac-test-files/case36-expect.meta new file mode 100644 index 0000000..3e96d54 --- /dev/null +++ b/flac/test/metaflac-test-files/case36-expect.meta @@ -0,0 +1,15 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: true + length: 65 + comments: 1 + comment[0]: f=0123456789abcdefghi diff --git a/flac/test/metaflac-test-files/case37-expect.meta b/flac/test/metaflac-test-files/case37-expect.meta new file mode 100644 index 0000000..3c384a3 --- /dev/null +++ b/flac/test/metaflac-test-files/case37-expect.meta @@ -0,0 +1,19 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 56 + comments: 1 + comment[0]: f=0123456789 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case38-expect.meta b/flac/test/metaflac-test-files/case38-expect.meta new file mode 100644 index 0000000..5fdeaf0 --- /dev/null +++ b/flac/test/metaflac-test-files/case38-expect.meta @@ -0,0 +1,19 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 66 + comments: 1 + comment[0]: f=0123456789abcdefghij +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case39-expect.meta b/flac/test/metaflac-test-files/case39-expect.meta new file mode 100644 index 0000000..e09ab85 --- /dev/null +++ b/flac/test/metaflac-test-files/case39-expect.meta @@ -0,0 +1,20 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 82 + comments: 2 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case40-expect.meta b/flac/test/metaflac-test-files/case40-expect.meta new file mode 100644 index 0000000..538f7b1 --- /dev/null +++ b/flac/test/metaflac-test-files/case40-expect.meta @@ -0,0 +1,22 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case41-expect.meta b/flac/test/metaflac-test-files/case41-expect.meta new file mode 100644 index 0000000..ed13427 --- /dev/null +++ b/flac/test/metaflac-test-files/case41-expect.meta @@ -0,0 +1,27 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 300 + comments: 9 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits + comment[4]: REPLAYGAIN_REFERENCE_LOUDNESS=89.0 dB + comment[5]: REPLAYGAIN_TRACK_GAIN=+64.82 dB + comment[6]: REPLAYGAIN_TRACK_PEAK=0.00000000 + comment[7]: REPLAYGAIN_ALBUM_GAIN=+64.82 dB + comment[8]: REPLAYGAIN_ALBUM_PEAK=0.00000000 +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 5 diff --git a/flac/test/metaflac-test-files/case42-expect.meta b/flac/test/metaflac-test-files/case42-expect.meta new file mode 100644 index 0000000..ae7d5b1 --- /dev/null +++ b/flac/test/metaflac-test-files/case42-expect.meta @@ -0,0 +1,22 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #2 + type: 1 (PADDING) + is last: true + length: 188 diff --git a/flac/test/metaflac-test-files/case43-expect.meta b/flac/test/metaflac-test-files/case43-expect.meta new file mode 100644 index 0000000..d29726c --- /dev/null +++ b/flac/test/metaflac-test-files/case43-expect.meta @@ -0,0 +1,49 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 188 diff --git a/flac/test/metaflac-test-files/case44-expect.meta b/flac/test/metaflac-test-files/case44-expect.meta new file mode 100644 index 0000000..1342f1d --- /dev/null +++ b/flac/test/metaflac-test-files/case44-expect.meta @@ -0,0 +1,28 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 1 (PADDING) + is last: true + length: 672 diff --git a/flac/test/metaflac-test-files/case45-expect.meta b/flac/test/metaflac-test-files/case45-expect.meta new file mode 100644 index 0000000..d29726c --- /dev/null +++ b/flac/test/metaflac-test-files/case45-expect.meta @@ -0,0 +1,49 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 188 diff --git a/flac/test/metaflac-test-files/case46-expect.meta b/flac/test/metaflac-test-files/case46-expect.meta new file mode 100644 index 0000000..c6f29f3 --- /dev/null +++ b/flac/test/metaflac-test-files/case46-expect.meta @@ -0,0 +1,62 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case47-expect.meta b/flac/test/metaflac-test-files/case47-expect.meta new file mode 100644 index 0000000..8b5d488 --- /dev/null +++ b/flac/test/metaflac-test-files/case47-expect.meta @@ -0,0 +1,75 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case48-expect.meta b/flac/test/metaflac-test-files/case48-expect.meta new file mode 100644 index 0000000..8f2bff0 --- /dev/null +++ b/flac/test/metaflac-test-files/case48-expect.meta @@ -0,0 +1,88 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case49-expect.meta b/flac/test/metaflac-test-files/case49-expect.meta new file mode 100644 index 0000000..b4a5ecf --- /dev/null +++ b/flac/test/metaflac-test-files/case49-expect.meta @@ -0,0 +1,101 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case50-expect.meta b/flac/test/metaflac-test-files/case50-expect.meta new file mode 100644 index 0000000..e80428c --- /dev/null +++ b/flac/test/metaflac-test-files/case50-expect.meta @@ -0,0 +1,114 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case51-expect.meta b/flac/test/metaflac-test-files/case51-expect.meta new file mode 100644 index 0000000..0cc7dd3 --- /dev/null +++ b/flac/test/metaflac-test-files/case51-expect.meta @@ -0,0 +1,127 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case52-expect.meta b/flac/test/metaflac-test-files/case52-expect.meta new file mode 100644 index 0000000..e393929 --- /dev/null +++ b/flac/test/metaflac-test-files/case52-expect.meta @@ -0,0 +1,140 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case53-expect.meta b/flac/test/metaflac-test-files/case53-expect.meta new file mode 100644 index 0000000..2b74e8a --- /dev/null +++ b/flac/test/metaflac-test-files/case53-expect.meta @@ -0,0 +1,153 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case54-expect.meta b/flac/test/metaflac-test-files/case54-expect.meta new file mode 100644 index 0000000..60c5ff0 --- /dev/null +++ b/flac/test/metaflac-test-files/case54-expect.meta @@ -0,0 +1,166 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case55-expect.meta b/flac/test/metaflac-test-files/case55-expect.meta new file mode 100644 index 0000000..f73f3ad --- /dev/null +++ b/flac/test/metaflac-test-files/case55-expect.meta @@ -0,0 +1,179 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 6 (PICTURE) + is last: false + length: 1846 + type: 5 (Leaflet page) + MIME type: image/png + description: 4.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1800 + data: +METADATA block #14 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case56-expect.meta b/flac/test/metaflac-test-files/case56-expect.meta new file mode 100644 index 0000000..25a2525 --- /dev/null +++ b/flac/test/metaflac-test-files/case56-expect.meta @@ -0,0 +1,192 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 6 (PICTURE) + is last: false + length: 1846 + type: 5 (Leaflet page) + MIME type: image/png + description: 4.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1800 + data: +METADATA block #14 + type: 6 (PICTURE) + is last: false + length: 1862 + type: 5 (Leaflet page) + MIME type: image/png + description: 5.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1816 + data: +METADATA block #15 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case57-expect.meta b/flac/test/metaflac-test-files/case57-expect.meta new file mode 100644 index 0000000..441762e --- /dev/null +++ b/flac/test/metaflac-test-files/case57-expect.meta @@ -0,0 +1,205 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 6 (PICTURE) + is last: false + length: 1846 + type: 5 (Leaflet page) + MIME type: image/png + description: 4.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1800 + data: +METADATA block #14 + type: 6 (PICTURE) + is last: false + length: 1862 + type: 5 (Leaflet page) + MIME type: image/png + description: 5.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1816 + data: +METADATA block #15 + type: 6 (PICTURE) + is last: false + length: 589 + type: 5 (Leaflet page) + MIME type: image/png + description: 6.png + width: 31 + height: 47 + depth: 24 + colors: 23 + data length: 543 + data: +METADATA block #16 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case58-expect.meta b/flac/test/metaflac-test-files/case58-expect.meta new file mode 100644 index 0000000..9b8bb50 --- /dev/null +++ b/flac/test/metaflac-test-files/case58-expect.meta @@ -0,0 +1,218 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 6 (PICTURE) + is last: false + length: 1846 + type: 5 (Leaflet page) + MIME type: image/png + description: 4.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1800 + data: +METADATA block #14 + type: 6 (PICTURE) + is last: false + length: 1862 + type: 5 (Leaflet page) + MIME type: image/png + description: 5.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1816 + data: +METADATA block #15 + type: 6 (PICTURE) + is last: false + length: 589 + type: 5 (Leaflet page) + MIME type: image/png + description: 6.png + width: 31 + height: 47 + depth: 24 + colors: 23 + data length: 543 + data: +METADATA block #16 + type: 6 (PICTURE) + is last: false + length: 605 + type: 5 (Leaflet page) + MIME type: image/png + description: 7.png + width: 31 + height: 47 + depth: 24 + colors: 23 + data length: 559 + data: +METADATA block #17 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case59-expect.meta b/flac/test/metaflac-test-files/case59-expect.meta new file mode 100644 index 0000000..e8a169c --- /dev/null +++ b/flac/test/metaflac-test-files/case59-expect.meta @@ -0,0 +1,231 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 141 + type: 3 (Cover (front)) + MIME type: image/gif + description: 0.gif + width: 24 + height: 24 + depth: 24 + colors: 2 + data length: 95 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 917 + type: 3 (Cover (front)) + MIME type: image/gif + description: 1.gif + width: 12 + height: 8 + depth: 24 + colors: 256 + data length: 871 + data: +METADATA block #6 + type: 6 (PICTURE) + is last: false + length: 578 + type: 3 (Cover (front)) + MIME type: image/gif + description: 2.gif + width: 16 + height: 14 + depth: 24 + colors: 128 + data length: 532 + data: +METADATA block #7 + type: 6 (PICTURE) + is last: false + length: 377 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 0.jpg + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 330 + data: +METADATA block #8 + type: 6 (PICTURE) + is last: false + length: 614 + type: 4 (Cover (back)) + MIME type: image/jpeg + description: 4.jpg + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 567 + data: +METADATA block #9 + type: 6 (PICTURE) + is last: false + length: 492 + type: 5 (Leaflet page) + MIME type: image/png + description: 0.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #10 + type: 6 (PICTURE) + is last: false + length: 508 + type: 5 (Leaflet page) + MIME type: image/png + description: 1.png + width: 30 + height: 20 + depth: 8 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #11 + type: 6 (PICTURE) + is last: false + length: 338 + type: 5 (Leaflet page) + MIME type: image/png + description: 2.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 292 + data: +METADATA block #12 + type: 6 (PICTURE) + is last: false + length: 354 + type: 5 (Leaflet page) + MIME type: image/png + description: 3.png + width: 30 + height: 20 + depth: 24 + colors: 7 + data length: 308 + data: +METADATA block #13 + type: 6 (PICTURE) + is last: false + length: 1846 + type: 5 (Leaflet page) + MIME type: image/png + description: 4.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1800 + data: +METADATA block #14 + type: 6 (PICTURE) + is last: false + length: 1862 + type: 5 (Leaflet page) + MIME type: image/png + description: 5.png + width: 31 + height: 47 + depth: 24 + colors: 0 (unindexed) + data length: 1816 + data: +METADATA block #15 + type: 6 (PICTURE) + is last: false + length: 589 + type: 5 (Leaflet page) + MIME type: image/png + description: 6.png + width: 31 + height: 47 + depth: 24 + colors: 23 + data length: 543 + data: +METADATA block #16 + type: 6 (PICTURE) + is last: false + length: 605 + type: 5 (Leaflet page) + MIME type: image/png + description: 7.png + width: 31 + height: 47 + depth: 24 + colors: 23 + data length: 559 + data: +METADATA block #17 + type: 6 (PICTURE) + is last: false + length: 290 + type: 5 (Leaflet page) + MIME type: image/png + description: 8.png + width: 32 + height: 32 + depth: 32 + colors: 0 (unindexed) + data length: 244 + data: +METADATA block #18 + type: 1 (PADDING) + is last: true + length: 43 diff --git a/flac/test/metaflac-test-files/case60-expect.meta b/flac/test/metaflac-test-files/case60-expect.meta new file mode 100644 index 0000000..3020bd0 --- /dev/null +++ b/flac/test/metaflac-test-files/case60-expect.meta @@ -0,0 +1,49 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 1 (PADDING) + is last: true + length: 9610 diff --git a/flac/test/metaflac-test-files/case61-expect.meta b/flac/test/metaflac-test-files/case61-expect.meta new file mode 100644 index 0000000..afac47f --- /dev/null +++ b/flac/test/metaflac-test-files/case61-expect.meta @@ -0,0 +1,62 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 500 + type: 1 (32x32 pixels 'file icon' (PNG only)) + MIME type: image/png + description: standard_icon + width: 32 + height: 32 + depth: 24 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #5 + type: 1 (PADDING) + is last: true + length: 9106 diff --git a/flac/test/metaflac-test-files/case62-expect.meta b/flac/test/metaflac-test-files/case62-expect.meta new file mode 100644 index 0000000..3249388 --- /dev/null +++ b/flac/test/metaflac-test-files/case62-expect.meta @@ -0,0 +1,75 @@ +METADATA block #0 + type: 0 (STREAMINFO) + is last: false + length: 34 + sample_rate: 8000 Hz + channels: 1 + bits-per-sample: 8 + total samples: 80000 + MD5 signature: a042237c5493fdb9656b94a83608d11a +METADATA block #1 + type: 3 (SEEKTABLE) + is last: false + length: 18 + seek points: 1 + point 0: sample_number=0 +METADATA block #2 + type: 4 (VORBIS_COMMENT) + is last: false + length: 117 + comments: 4 + comment[0]: f=0123456789abcdefghij + comment[1]: TITLE=Tittle + comment[2]: artist=Fartist + comment[3]: artist=artits +METADATA block #3 + type: 5 (CUESHEET) + is last: false + length: 480 + media catalog number: 1234567890123 + lead-in: 0 + is CD: false + number of tracks: 2 + track[0] + offset: 0 + number: 1 + ISRC: + type: AUDIO + pre-emphasis: false + number of index points: 1 + index[0] + offset: 0 + number: 1 + track[1] + offset: 80000 + number: 255 (LEAD-OUT) +METADATA block #4 + type: 6 (PICTURE) + is last: false + length: 500 + type: 1 (32x32 pixels 'file icon' (PNG only)) + MIME type: image/png + description: standard_icon + width: 32 + height: 32 + depth: 24 + colors: 0 (unindexed) + data length: 446 + data: +METADATA block #5 + type: 6 (PICTURE) + is last: false + length: 507 + type: 2 (Other file icon) + MIME type: image/png + description: icon + width: 64 + height: 64 + depth: 24 + colors: 0 (unindexed) + data length: 462 + data: +METADATA block #6 + type: 1 (PADDING) + is last: true + length: 8595 diff --git a/flac/test/metaflac.flac.in b/flac/test/metaflac.flac.in new file mode 100644 index 0000000..72c8ad4 Binary files /dev/null and b/flac/test/metaflac.flac.in differ diff --git a/flac/test/metaflac.flac.ok b/flac/test/metaflac.flac.ok new file mode 100644 index 0000000..8ecd6a0 Binary files /dev/null and b/flac/test/metaflac.flac.ok differ diff --git a/flac/test/picture.ok b/flac/test/picture.ok new file mode 100644 index 0000000..c95bd3a --- /dev/null +++ b/flac/test/picture.ok @@ -0,0 +1,42 @@ + ++++ grabbag unit test: picture + +testing grabbag__picture_parse_specification("")... OK (failed as expected, error: error opening picture file) +testing grabbag__picture_parse_specification("||||")... OK (failed as expected: error opening picture file) +testing grabbag__picture_parse_specification("|image/gif|||")... OK (failed as expected: error opening picture file) +testing grabbag__picture_parse_specification("|image/gif|desc|320|0.gif")... OK (failed as expected: invalid picture specification: can't parse resolution/color part) +testing grabbag__picture_parse_specification("|image/gif|desc|320x240|0.gif")... OK (failed as expected: invalid picture specification: can't parse resolution/color part) +testing grabbag__picture_parse_specification("|image/gif|desc|320x240x9|")... OK (failed as expected: error opening picture file) +testing grabbag__picture_parse_specification("|image/gif|desc|320x240x9/2345|0.gif")... OK (failed as expected: invalid picture specification: can't parse resolution/color part) +testing grabbag__picture_parse_specification("1|-->|desc|32x24x9|0.gif")... OK (failed as expected: type 1 icon must be a 32x32 pixel PNG) +testing grabbag__picture_parse_specification("|-->|desc||http://blah.blah.blah/z.gif")... OK (failed as expected: unable to extract resolution and color info from URL, user must set explicitly) +testing grabbag__picture_parse_specification("|-->|desc|320x240x9|http://blah.blah.blah/z.gif")... OK +testing grabbag__picture_parse_specification("pictures/0.gif")... OK +testing grabbag__picture_parse_specification("pictures/1.gif")... OK +testing grabbag__picture_parse_specification("pictures/2.gif")... OK +testing grabbag__picture_parse_specification("pictures/0.jpg")... OK +testing grabbag__picture_parse_specification("pictures/4.jpg")... OK +testing grabbag__picture_parse_specification("pictures/0.png")... OK +testing grabbag__picture_parse_specification("pictures/1.png")... OK +testing grabbag__picture_parse_specification("pictures/2.png")... OK +testing grabbag__picture_parse_specification("pictures/3.png")... OK +testing grabbag__picture_parse_specification("pictures/4.png")... OK +testing grabbag__picture_parse_specification("pictures/5.png")... OK +testing grabbag__picture_parse_specification("pictures/6.png")... OK +testing grabbag__picture_parse_specification("pictures/7.png")... OK +testing grabbag__picture_parse_specification("pictures/8.png")... OK +testing grabbag__picture_parse_specification("3|image/gif|||pictures/0.gif")... OK +testing grabbag__picture_parse_specification("4|image/gif|||pictures/1.gif")... OK +testing grabbag__picture_parse_specification("0|image/gif|||pictures/2.gif")... OK +testing grabbag__picture_parse_specification("3|image/jpeg|||pictures/0.jpg")... OK +testing grabbag__picture_parse_specification("3|image/jpeg|||pictures/4.jpg")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/0.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/1.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/2.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/3.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/4.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/5.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/6.png")... OK +testing grabbag__picture_parse_specification("3|image/png|||pictures/7.png")... OK +testing grabbag__picture_parse_specification("999|image/png|||pictures/8.png")... OK +testing grabbag__picture_parse_specification("3|image/gif||320x240x3/2|pictures/0.gif")... OK diff --git a/flac/test/pictures/0.gif b/flac/test/pictures/0.gif new file mode 100644 index 0000000..c9f3d71 Binary files /dev/null and b/flac/test/pictures/0.gif differ diff --git a/flac/test/pictures/0.jpg b/flac/test/pictures/0.jpg new file mode 100644 index 0000000..54b9a7c Binary files /dev/null and b/flac/test/pictures/0.jpg differ diff --git a/flac/test/pictures/0.png b/flac/test/pictures/0.png new file mode 100644 index 0000000..6ff450c Binary files /dev/null and b/flac/test/pictures/0.png differ diff --git a/flac/test/pictures/1.gif b/flac/test/pictures/1.gif new file mode 100644 index 0000000..c40eeae Binary files /dev/null and b/flac/test/pictures/1.gif differ diff --git a/flac/test/pictures/1.png b/flac/test/pictures/1.png new file mode 100644 index 0000000..c643acf Binary files /dev/null and b/flac/test/pictures/1.png differ diff --git a/flac/test/pictures/2.gif b/flac/test/pictures/2.gif new file mode 100644 index 0000000..632098b Binary files /dev/null and b/flac/test/pictures/2.gif differ diff --git a/flac/test/pictures/2.png b/flac/test/pictures/2.png new file mode 100644 index 0000000..c2ee03f Binary files /dev/null and b/flac/test/pictures/2.png differ diff --git a/flac/test/pictures/3.png b/flac/test/pictures/3.png new file mode 100644 index 0000000..b497223 Binary files /dev/null and b/flac/test/pictures/3.png differ diff --git a/flac/test/pictures/4.jpg b/flac/test/pictures/4.jpg new file mode 100644 index 0000000..da78796 Binary files /dev/null and b/flac/test/pictures/4.jpg differ diff --git a/flac/test/pictures/4.png b/flac/test/pictures/4.png new file mode 100644 index 0000000..1e97931 Binary files /dev/null and b/flac/test/pictures/4.png differ diff --git a/flac/test/pictures/5.png b/flac/test/pictures/5.png new file mode 100644 index 0000000..fcaf8b0 Binary files /dev/null and b/flac/test/pictures/5.png differ diff --git a/flac/test/pictures/6.png b/flac/test/pictures/6.png new file mode 100644 index 0000000..93994f4 Binary files /dev/null and b/flac/test/pictures/6.png differ diff --git a/flac/test/pictures/7.png b/flac/test/pictures/7.png new file mode 100644 index 0000000..e50448c Binary files /dev/null and b/flac/test/pictures/7.png differ diff --git a/flac/test/pictures/8.png b/flac/test/pictures/8.png new file mode 100644 index 0000000..27948b8 Binary files /dev/null and b/flac/test/pictures/8.png differ diff --git a/flac/test/pictures/Makefile.am b/flac/test/pictures/Makefile.am new file mode 100644 index 0000000..834e337 --- /dev/null +++ b/flac/test/pictures/Makefile.am @@ -0,0 +1,32 @@ +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +EXTRA_DIST = \ + 0.gif \ + 0.jpg \ + 0.png \ + 1.gif \ + 1.png \ + 2.gif \ + 2.png \ + 3.png \ + 4.jpg \ + 4.png \ + 5.png \ + 6.png \ + 7.png \ + 8.png diff --git a/flac/test/test_bins.sh b/flac/test/test_bins.sh new file mode 100644 index 0000000..8c5a35c --- /dev/null +++ b/flac/test/test_bins.sh @@ -0,0 +1,114 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/getopt/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/replaygain_synthesis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/utf8/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/flac:$PATH +PATH=../obj/$BUILD/bin:$PATH +BINS_PATH=../../test_files/bins + +if [ x"$FLAC__TEST_LEVEL" = x ] ; then + FLAC__TEST_LEVEL=1 +fi + +flac --help 1>/dev/null 2>/dev/null || die "ERROR can't find flac executable" + +run_flac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 flac $*" >>test_bins.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 flac $* 4>>test_bins.valgrind.log + else + flac $* + fi +} + +test -d ${BINS_PATH} || exit 77 + +test_file () +{ + name=$1 + channels=$2 + bps=$3 + encode_options="$4" + + echo -n "$name.bin (--channels=$channels --bps=$bps $encode_options): encode..." + cmd="run_flac --verify --silent --force --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=$bps --channels=$channels $encode_options --no-padding $name.bin" + echo "### ENCODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 2>>./streams.log || die "ERROR during encode of $name" + + echo -n "decode..." + cmd="run_flac --silent --force --endian=big --sign=signed --decode --force-raw-format $name.flac"; + echo "### DECODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 2>>./streams.log || die "ERROR during decode of $name" + + ls -1l $name.bin >> ./streams.log + ls -1l $name.flac >> ./streams.log + ls -1l $name.raw >> ./streams.log + + echo -n "compare..." + cmp $name.bin $name.raw || die "ERROR during compare of $name" + + echo OK +} + +echo "Testing bins..." +for f in b00 b01 b02 b03 b04 ; do + binfile=$BINS_PATH/$f + if [ -f $binfile.bin ] ; then + for disable in '' '--disable-verbatim-subframes --disable-constant-subframes' '--disable-verbatim-subframes --disable-constant-subframes --disable-fixed-subframes' ; do + for channels in 1 2 4 8 ; do + for bps in 8 16 24 ; do + for opt in 0 1 2 4 5 6 8 ; do + for extras in '' '-p' '-e' ; do + for blocksize in '' '--lax -b 32' '--lax -b 32768' '--lax -b 65535' ; do + test_file $binfile $channels $bps "-$opt $extras $blocksize $disable" + done + done + done + if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + test_file $binfile $channels $bps "--lax -b 16384 -m -r 8 -l 32 -e -p $disable" + fi + done + done + done + else + echo "$binfile not found, skipping." + fi +done diff --git a/flac/test/test_flac.sh b/flac/test/test_flac.sh new file mode 100644 index 0000000..e1410a4 --- /dev/null +++ b/flac/test/test_flac.sh @@ -0,0 +1,1243 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +dddie="die ERROR: creating files with dd" + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +# change to 'false' to show flac output (useful for debugging) +if true ; then + SILENT='--silent' + TOTALLY_SILENT='--totally-silent' +else + SILENT='' + TOTALLY_SILENT='' +fi + +LD_LIBRARY_PATH=`pwd`/../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/getopt/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/replaygain_synthesis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/utf8/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=`pwd`/../src/flac:$PATH +PATH=`pwd`/../src/metaflac:$PATH +PATH=`pwd`/../src/test_streams:$PATH +PATH=`pwd`/../obj/$BUILD/bin:$PATH + +flac --help 1>/dev/null 2>/dev/null || die "ERROR can't find flac executable" + +run_flac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 flac $*" >>test_flac.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 flac $* 4>>test_flac.valgrind.log + else + flac $* + fi +} + +run_metaflac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 metaflac $*" >>test_flac.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 metaflac $* 4>>test_flac.valgrind.log + else + metaflac $* + fi +} + +md5cmp () +{ + #n=`( [ -f "$1" ] && [ -f "$2" ] && metaflac --show-md5sum --no-filename "$1" "$2" 2>/dev/null || die "ERROR: comparing FLAC files $1 and $2 by MD5 sum" ) | uniq | wc -l` + n=`( [ -f "$1" ] && [ -f "$2" ] && metaflac --show-md5sum --no-filename "$1" "$2" 2>/dev/null || exit 1 ) | uniq | wc -l` + [ "$n" != "" ] && [ $n = 1 ] +} + +if [ `env | grep -ic '^comspec='` != 0 ] ; then + is_win=yes +else + is_win=no +fi + +echo "Checking for --ogg support in flac..." +if flac --ogg $SILENT --force-raw-format --endian=little --sign=signed --channels=1 --bps=8 --sample-rate=44100 -c $0 1>/dev/null 2>&1 ; then + has_ogg=yes; + echo "flac --ogg works" +else + has_ogg=no; + echo "flac --ogg doesn't work" +fi + +echo "Generating streams..." +if [ ! -f wacky1.wav ] ; then + test_streams || die "ERROR during test_streams" +fi + +############################################################################ +# test that flac doesn't automatically overwrite files unless -f is used +############################################################################ + +echo "Try encoding to a file that exists; should fail" +cp wacky1.wav exist.wav +touch exist.flac +if run_flac $TOTALLY_SILENT -0 exist.wav ; then + die "ERROR: it should have failed but didn't" +else + echo "OK, it failed as it should" +fi + +echo "Try encoding with -f to a file that exists; should succeed" +if run_flac $TOTALLY_SILENT -0 --force exist.wav ; then + echo "OK, it succeeded as it should" +else + die "ERROR: it should have succeeded but didn't" +fi + +echo "Try decoding to a file that exists; should fail" +if run_flac $TOTALLY_SILENT -d exist.flac ; then + die "ERROR: it should have failed but didn't" +else + echo "OK, it failed as it should" +fi + +echo "Try decoding with -f to a file that exists; should succeed" +if run_flac $TOTALLY_SILENT -d -f exist.flac ; then + echo "OK, it succeeded as it should" +else + die "ERROR: it should have succeeded but didn't" +fi + +rm -f exist.wav exist.flac + +############################################################################ +# test fractional block sizes +############################################################################ + +test_fractional () +{ + blocksize=$1 + samples=$2 + dd if=noise.raw ibs=4 count=$samples of=pbs.raw 2>/dev/null || $dddie + echo -n "fractional block size test (blocksize=$blocksize samples=$samples) encode... " + run_flac $SILENT --force --verify --force-raw-format --endian=little --sign=signed --sample-rate=44100 --bps=16 --channels=2 --blocksize=$blocksize --no-padding --lax -o pbs.flac pbs.raw || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --force-raw-format --endian=little --sign=signed -o pbs.cmp pbs.flac || die "ERROR" + echo -n "compare... " + cmp pbs.raw pbs.cmp || die "ERROR: file mismatch" + echo "OK" + rm -f pbs.raw pbs.flac pbs.cmp +} + +# The special significance of 2048 is it's the # of samples that flac calls +# FLAC__stream_encoder_process() on. +# +# We're trying to make sure the 1-sample overread logic in the stream encoder +# (used for last-block checking) works; these values probe around common +# multiples of the flac sample chunk size (2048) and the blocksize. +for samples in 31 32 33 34 35 2046 2047 2048 2049 2050 ; do + test_fractional 33 $samples +done +for samples in 254 255 256 257 258 510 511 512 513 514 1022 1023 1024 1025 1026 2046 2047 2048 2049 2050 4094 4095 4096 4097 4098 ; do + test_fractional 256 $samples +done +for samples in 1022 1023 1024 1025 1026 2046 2047 2048 2049 2050 4094 4095 4096 4097 4098 ; do + test_fractional 2048 $samples +done +for samples in 1022 1023 1024 1025 1026 2046 2047 2048 2049 2050 4094 4095 4096 4097 4098 4606 4607 4608 4609 4610 8190 8191 8192 8193 8194 16382 16383 16384 16385 16386 ; do + test_fractional 4608 $samples +done + +############################################################################ +# basic 'round-trip' tests of various kinds of streams +############################################################################ + +rt_test_raw () +{ + f="$1" + extra="$2" + channels=`echo $f | awk -F- '{print $2}'` + bps=`echo $f | awk -F- '{print $3}'` + echo -n "round-trip test ($f) encode... " + run_flac $SILENT --force --verify --force-raw-format --endian=little --sign=signed --sample-rate=44100 --bps=$bps --channels=$channels --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --force-raw-format --endian=little --sign=signed -o rt.raw $extra rt.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.raw || die "ERROR: file mismatch" + echo "OK" + rm -f rt.flac rt.raw +} + +rt_test_wav () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.wav $extra rt.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.wav || die "ERROR: file mismatch" + echo "OK" + rm -f rt.flac rt.wav +} + +rt_test_w64 () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.w64 $extra rt.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.w64 || die "ERROR: file mismatch" + echo "OK" + rm -f rt.flac rt.w64 +} + +rt_test_rf64 () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.rf64 $extra rt.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.rf64 || die "ERROR: file mismatch" + echo "OK" + rm -f rt.flac rt.rf64 +} + +rt_test_aiff () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.aiff $extra rt.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.aiff || die "ERROR: file mismatch" + echo "OK" + rm -f rt.flac rt.aiff +} + +# assumes input file is WAVE; does not check the metadata-preserving features of flac-to-flac; that is checked later +rt_test_flac () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f->flac->flac->wav) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.flac $extra $f || die "ERROR" + echo -n "re-encode... " + run_flac $SILENT --force --verify --lax -o rt2.flac rt.flac || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.wav $extra rt2.flac || die "ERROR" + echo -n "compare... " + cmp $f rt.wav || die "ERROR: file mismatch" + echo "OK" + rm -f rt.wav rt.flac rt2.flac +} + +# assumes input file is WAVE; does not check the metadata-preserving features of flac-to-flac; that is checked later +rt_test_ogg_flac () +{ + f="$1" + extra="$2" + echo -n "round-trip test ($f->oggflac->oggflac->wav) encode... " + run_flac $SILENT --force --verify --channel-map=none --no-padding --lax -o rt.oga --ogg $extra $f || die "ERROR" + echo -n "re-encode... " + run_flac $SILENT --force --verify --lax -o rt2.oga --ogg rt.oga || die "ERROR" + echo -n "decode... " + run_flac $SILENT --force --decode --channel-map=none -o rt.wav $extra rt2.oga || die "ERROR" + echo -n "compare... " + cmp $f rt.wav || die "ERROR: file mismatch" + echo "OK" + rm -f rt.wav rt.oga rt2.oga +} + +for f in rt-*.raw ; do + rt_test_raw $f +done +for f in rt-*.wav ; do + rt_test_wav $f +done +for f in rt-*.w64 ; do + rt_test_w64 $f +done +for f in rt-*.rf64 ; do + rt_test_rf64 $f +done +for f in rt-*.aiff ; do + rt_test_aiff $f +done +for f in rt-*.wav ; do + rt_test_flac $f +done +if [ $has_ogg = yes ] ; then + for f in rt-*.wav ; do + rt_test_ogg_flac $f + done +fi + +############################################################################ +# test --skip and --until +############################################################################ + +# +# first make some chopped-up raw files +# +echo "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMN" > master.raw +dd if=master.raw ibs=1 count=50 of=50c.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=10 count=40 of=50c.skip10.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=11 count=39 of=50c.skip11.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=20 count=30 of=50c.skip20.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=30 count=20 of=50c.skip30.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=40 count=10 of=50c.skip40.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 count=10 of=50c.until10.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 count=20 of=50c.until20.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 count=30 of=50c.until30.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 count=39 of=50c.until39.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 count=40 of=50c.until40.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=10 count=20 of=50c.skip10.until30.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=10 count=29 of=50c.skip10.until39.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=10 count=30 of=50c.skip10.until40.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=20 count=10 of=50c.skip20.until30.raw 2>/dev/null || $dddie +dd if=master.raw ibs=1 skip=20 count=20 of=50c.skip20.until40.raw 2>/dev/null || $dddie + +wav_eopt="$SILENT --force --verify --no-padding --lax" +wav_dopt="$SILENT --force --decode" + +raw_eopt="$wav_eopt --force-raw-format --endian=big --sign=signed --sample-rate=10 --bps=8 --channels=1" +raw_dopt="$wav_dopt --force-raw-format --endian=big --sign=signed" + +# +# convert them to WAVE/AIFF/Ogg FLAC files +# +convert_to_wav () +{ + run_flac "$2" $1.raw || die "ERROR converting $1.raw to WAVE" + run_flac "$3" $1.flac || die "ERROR converting $1.raw to WAVE" +} +convert_to_wav 50c "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip10 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip11 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip20 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip30 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip40 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.until10 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.until20 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.until30 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.until39 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.until40 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip10.until30 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip10.until39 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip10.until40 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip20.until30 "$raw_eopt" "$wav_dopt" +convert_to_wav 50c.skip20.until40 "$raw_eopt" "$wav_dopt" + +convert_to_aiff () +{ + run_flac "$2" $1.raw || die "ERROR converting $1.raw to AIFF" + run_flac "$3" $1.flac -o $1.aiff || die "ERROR converting $1.raw to AIFF" +} +convert_to_aiff 50c "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip10 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip11 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip20 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip30 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip40 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.until10 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.until20 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.until30 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.until39 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.until40 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip10.until30 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip10.until39 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip10.until40 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip20.until30 "$raw_eopt" "$wav_dopt" +convert_to_aiff 50c.skip20.until40 "$raw_eopt" "$wav_dopt" + +convert_to_ogg () +{ + run_flac "$wav_eopt" --ogg $1.wav || die "ERROR converting $1.raw to Ogg FLAC" +} +if [ $has_ogg = yes ] ; then + convert_to_ogg 50c + convert_to_ogg 50c.skip10 + convert_to_ogg 50c.skip11 + convert_to_ogg 50c.skip20 + convert_to_ogg 50c.skip30 + convert_to_ogg 50c.skip40 + convert_to_ogg 50c.until10 + convert_to_ogg 50c.until20 + convert_to_ogg 50c.until30 + convert_to_ogg 50c.until39 + convert_to_ogg 50c.until40 + convert_to_ogg 50c.skip10.until30 + convert_to_ogg 50c.skip10.until39 + convert_to_ogg 50c.skip10.until40 + convert_to_ogg 50c.skip20.until30 + convert_to_ogg 50c.skip20.until40 +fi + +test_skip_until () +{ + in_fmt=$1 + out_fmt=$2 + + [ "$in_fmt" = wav ] || [ "$in_fmt" = aiff ] || [ "$in_fmt" = raw ] || [ "$in_fmt" = flac ] || [ "$in_fmt" = ogg ] || die "ERROR: internal error, bad 'in' format '$in_fmt'" + + [ "$out_fmt" = flac ] || [ "$out_fmt" = ogg ] || die "ERROR: internal error, bad 'out' format '$out_fmt'" + + if [ $in_fmt = raw ] ; then + eopt="$raw_eopt" + dopt="$raw_dopt" + else + eopt="$wav_eopt" + dopt="$wav_dopt" + fi + + if ( [ $in_fmt = flac ] || [ $in_fmt = ogg ] ) && ( [ $out_fmt = flac ] || [ $out_fmt = ogg ] ) ; then + CMP=md5cmp + else + CMP=cmp + fi + + if [ $out_fmt = ogg ] ; then + eopt="--ogg $eopt" + fi + + # + # test --skip when encoding + # + + desc="($in_fmt<->$out_fmt)" + + echo -n "testing --skip=# (encode) $desc... " + run_flac $eopt --skip=10 -o z50c.skip10.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.$in_fmt z50c.skip10.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.skip10.$in_fmt || die "ERROR: file mismatch for --skip=10 (encode) $desc" + rm -f z50c.skip10.$out_fmt z50c.skip10.$in_fmt + echo OK + + echo -n "testing --skip=mm:ss (encode) $desc... " + run_flac $eopt --skip=0:01 -o z50c.skip0_01.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip0_01.$in_fmt z50c.skip0_01.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.skip0_01.$in_fmt || die "ERROR: file mismatch for --skip=0:01 (encode) $desc" + rm -f z50c.skip0_01.$out_fmt z50c.skip0_01.$in_fmt + echo OK + + echo -n "testing --skip=mm:ss.sss (encode) $desc... " + run_flac $eopt --skip=0:01.1001 -o z50c.skip0_01.1001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip0_01.1001.$in_fmt z50c.skip0_01.1001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip11.$in_fmt z50c.skip0_01.1001.$in_fmt || die "ERROR: file mismatch for --skip=0:01.1001 (encode) $desc" + rm -f z50c.skip0_01.1001.$out_fmt z50c.skip0_01.1001.$in_fmt + echo OK + + # + # test --skip when decoding + # + + if [ $in_fmt != $out_fmt ] ; then run_flac $eopt -o z50c.$out_fmt 50c.$in_fmt ; else cp -f 50c.$in_fmt z50c.$out_fmt ; fi || die "ERROR generating FLAC file $desc" + + echo -n "testing --skip=# (decode) $desc... " + run_flac $dopt --skip=10 -o z50c.skip10.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.skip10.$in_fmt || die "ERROR: file mismatch for --skip=10 (decode) $desc" + rm -f z50c.skip10.$in_fmt + echo OK + + echo -n "testing --skip=mm:ss (decode) $desc... " + run_flac $dopt --skip=0:01 -o z50c.skip0_01.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.skip0_01.$in_fmt || die "ERROR: file mismatch for --skip=0:01 (decode) $desc" + rm -f z50c.skip0_01.$in_fmt + echo OK + + echo -n "testing --skip=mm:ss.sss (decode) $desc... " + run_flac $dopt --skip=0:01.1001 -o z50c.skip0_01.1001.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip11.$in_fmt z50c.skip0_01.1001.$in_fmt || die "ERROR: file mismatch for --skip=0:01.1001 (decode) $desc" + rm -f z50c.skip0_01.1001.$in_fmt + echo OK + + rm -f z50c.$out_fmt + + # + # test --until when encoding + # + + echo -n "testing --until=# (encode) $desc... " + run_flac $eopt --until=40 -o z50c.until40.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until40.$in_fmt z50c.until40.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until40.$in_fmt || die "ERROR: file mismatch for --until=40 (encode) $desc" + rm -f z50c.until40.$out_fmt z50c.until40.$in_fmt + echo OK + + echo -n "testing --until=mm:ss (encode) $desc... " + run_flac $eopt --until=0:04 -o z50c.until0_04.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until0_04.$in_fmt z50c.until0_04.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until0_04.$in_fmt || die "ERROR: file mismatch for --until=0:04 (encode) $desc" + rm -f z50c.until0_04.$out_fmt z50c.until0_04.$in_fmt + echo OK + + echo -n "testing --until=mm:ss.sss (encode) $desc... " + run_flac $eopt --until=0:03.9001 -o z50c.until0_03.9001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until0_03.9001.$in_fmt z50c.until0_03.9001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until39.$in_fmt z50c.until0_03.9001.$in_fmt || die "ERROR: file mismatch for --until=0:03.9001 (encode) $desc" + rm -f z50c.until0_03.9001.$out_fmt z50c.until0_03.9001.$in_fmt + echo OK + + echo -n "testing --until=-# (encode) $desc... " + run_flac $eopt --until=-10 -o z50c.until-10.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until-10.$in_fmt z50c.until-10.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until-10.$in_fmt || die "ERROR: file mismatch for --until=-10 (encode) $desc" + rm -f z50c.until-10.$out_fmt z50c.until-10.$in_fmt + echo OK + + echo -n "testing --until=-mm:ss (encode) $desc... " + run_flac $eopt --until=-0:01 -o z50c.until-0_01.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until-0_01.$in_fmt z50c.until-0_01.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until-0_01.$in_fmt || die "ERROR: file mismatch for --until=-0:01 (encode) $desc" + rm -f z50c.until-0_01.$out_fmt z50c.until-0_01.$in_fmt + echo OK + + echo -n "testing --until=-mm:ss.sss (encode) $desc... " + run_flac $eopt --until=-0:01.1001 -o z50c.until-0_01.1001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.until-0_01.1001.$in_fmt z50c.until-0_01.1001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until39.$in_fmt z50c.until-0_01.1001.$in_fmt || die "ERROR: file mismatch for --until=-0:01.1001 (encode) $desc" + rm -f z50c.until-0_01.1001.$out_fmt z50c.until-0_01.1001.$in_fmt + echo OK + + # + # test --until when decoding + # + + if [ $in_fmt != $out_fmt ] ; then run_flac $eopt -o z50c.$out_fmt 50c.$in_fmt ; else cp -f 50c.$in_fmt z50c.$out_fmt ; fi || die "ERROR generating FLAC file $desc" + + echo -n "testing --until=# (decode) $desc... " + run_flac $dopt --until=40 -o z50c.until40.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until40.$in_fmt || die "ERROR: file mismatch for --until=40 (decode) $desc" + rm -f z50c.until40.$in_fmt + echo OK + + echo -n "testing --until=mm:ss (decode) $desc... " + run_flac $dopt --until=0:04 -o z50c.until0_04.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until0_04.$in_fmt || die "ERROR: file mismatch for --until=0:04 (decode) $desc" + rm -f z50c.until0_04.$in_fmt + echo OK + + echo -n "testing --until=mm:ss.sss (decode) $desc... " + run_flac $dopt --until=0:03.9001 -o z50c.until0_03.9001.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until39.$in_fmt z50c.until0_03.9001.$in_fmt || die "ERROR: file mismatch for --until=0:03.9001 (decode) $desc" + rm -f z50c.until0_03.9001.$in_fmt + echo OK + + echo -n "testing --until=-# (decode) $desc... " + run_flac $dopt --until=-10 -o z50c.until-10.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until-10.$in_fmt || die "ERROR: file mismatch for --until=-10 (decode) $desc" + rm -f z50c.until-10.$in_fmt + echo OK + + echo -n "testing --until=-mm:ss (decode) $desc... " + run_flac $dopt --until=-0:01 -o z50c.until-0_01.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.until-0_01.$in_fmt || die "ERROR: file mismatch for --until=-0:01 (decode) $desc" + rm -f z50c.until-0_01.$in_fmt + echo OK + + echo -n "testing --until=-mm:ss.sss (decode) $desc... " + run_flac $dopt --until=-0:01.1001 -o z50c.until-0_01.1001.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until39.$in_fmt z50c.until-0_01.1001.$in_fmt || die "ERROR: file mismatch for --until=-0:01.1001 (decode) $desc" + rm -f z50c.until-0_01.1001.$in_fmt + echo OK + + rm -f z50c.$out_fmt + + # + # test --skip and --until when encoding + # + + echo -n "testing --skip=10 --until=# (encode) $desc... " + run_flac $eopt --skip=10 --until=40 -o z50c.skip10.until40.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until40.$in_fmt z50c.skip10.until40.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until40.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=40 (encode) $desc" + rm -f z50c.skip10.until40.$out_fmt z50c.skip10.until40.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=mm:ss (encode) $desc... " + run_flac $eopt --skip=10 --until=0:04 -o z50c.skip10.until0_04.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until0_04.$in_fmt z50c.skip10.until0_04.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until0_04.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=0:04 (encode) $desc" + rm -f z50c.skip10.until0_04.$out_fmt z50c.skip10.until0_04.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=mm:ss.sss (encode) $desc... " + run_flac $eopt --skip=10 --until=0:03.9001 -o z50c.skip10.until0_03.9001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until0_03.9001.$in_fmt z50c.skip10.until0_03.9001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until39.$in_fmt z50c.skip10.until0_03.9001.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=0:03.9001 (encode) $desc" + rm -f z50c.skip10.until0_03.9001.$out_fmt z50c.skip10.until0_03.9001.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=+# (encode) $desc... " + run_flac $eopt --skip=10 --until=+30 -o z50c.skip10.until+30.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until+30.$in_fmt z50c.skip10.until+30.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until+30.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=+30 (encode) $desc" + rm -f z50c.skip10.until+30.$out_fmt z50c.skip10.until+30.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=+mm:ss (encode) $desc... " + run_flac $eopt --skip=10 --until=+0:03 -o z50c.skip10.until+0_03.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until+0_03.$in_fmt z50c.skip10.until+0_03.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until+0_03.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=+0:03 (encode) $desc" + rm -f z50c.skip10.until+0_03.$out_fmt z50c.skip10.until+0_03.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=+mm:ss.sss (encode) $desc... " + run_flac $eopt --skip=10 --until=+0:02.9001 -o z50c.skip10.until+0_02.9001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until+0_02.9001.$in_fmt z50c.skip10.until+0_02.9001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until39.$in_fmt z50c.skip10.until+0_02.9001.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=+0:02.9001 (encode) $desc" + rm -f z50c.skip10.until+0_02.9001.$out_fmt z50c.skip10.until+0_02.9001.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-# (encode) $desc... " + run_flac $eopt --skip=10 --until=-10 -o z50c.skip10.until-10.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until-10.$in_fmt z50c.skip10.until-10.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until-10.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-10 (encode) $desc" + rm -f z50c.skip10.until-10.$out_fmt z50c.skip10.until-10.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-mm:ss (encode) $desc... " + run_flac $eopt --skip=10 --until=-0:01 -o z50c.skip10.until-0_01.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until-0_01.$in_fmt z50c.skip10.until-0_01.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until-0_01.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-0:01 (encode) $desc" + rm -f z50c.skip10.until-0_01.$out_fmt z50c.skip10.until-0_01.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-mm:ss.sss (encode) $desc... " + run_flac $eopt --skip=10 --until=-0:01.1001 -o z50c.skip10.until-0_01.1001.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + [ $in_fmt = $out_fmt ] || run_flac $dopt -o z50c.skip10.until-0_01.1001.$in_fmt z50c.skip10.until-0_01.1001.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until39.$in_fmt z50c.skip10.until-0_01.1001.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-0:01.1001 (encode) $desc" + rm -f z50c.skip10.until-0_01.1001.$out_fmt z50c.skip10.until-0_01.1001.$in_fmt + echo OK + + # + # test --skip and --until when decoding + # + + if [ $in_fmt != $out_fmt ] ; then run_flac $eopt -o z50c.$out_fmt 50c.$in_fmt ; else cp -f 50c.$in_fmt z50c.$out_fmt ; fi || die "ERROR generating FLAC file $desc" + + + echo -n "testing --skip=10 --until=# (decode) $desc... " + run_flac $dopt --skip=10 --until=40 -o z50c.skip10.until40.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until40.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=40 (decode) $desc" + rm -f z50c.skip10.until40.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=mm:ss (decode) $desc... " + run_flac $dopt --skip=10 --until=0:04 -o z50c.skip10.until0_04.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until0_04.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=0:04 (decode) $desc" + rm -f z50c.skip10.until0_04.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=mm:ss.sss (decode) $desc... " + run_flac $dopt --skip=10 --until=0:03.9001 -o z50c.skip10.until0_03.9001.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until39.$in_fmt z50c.skip10.until0_03.9001.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=0:03.9001 (decode) $desc" + rm -f z50c.skip10.until0_03.9001.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-# (decode) $desc... " + run_flac $dopt --skip=10 --until=-10 -o z50c.skip10.until-10.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until-10.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-10 (decode) $desc" + rm -f z50c.skip10.until-10.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-mm:ss (decode) $desc... " + run_flac $dopt --skip=10 --until=-0:01 -o z50c.skip10.until-0_01.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.skip10.until-0_01.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-0:01 (decode) $desc" + rm -f z50c.skip10.until-0_01.$in_fmt + echo OK + + echo -n "testing --skip=10 --until=-mm:ss.sss (decode) $desc... " + run_flac $dopt --skip=10 --until=-0:01.1001 -o z50c.skip10.until-0_01.1001.$in_fmt z50c.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until39.$in_fmt z50c.skip10.until-0_01.1001.$in_fmt || die "ERROR: file mismatch for --skip=10 --until=-0:01.1001 (decode) $desc" + rm -f z50c.skip10.until-0_01.1001.$in_fmt + echo OK + + rm -f z50c.$out_fmt +} + +test_skip_until raw flac +test_skip_until wav flac +test_skip_until aiff flac +test_skip_until flac flac +#@@@if [ $has_ogg = yes ] ; then +#@@@ #@@@ doesn't work yet because md5cmp doesn't work because metaflac doesn't work on ogg flac yet +#@@@ test_skip_until ogg flac +#@@@fi + +if [ $has_ogg = yes ] ; then + test_skip_until raw ogg + test_skip_until wav ogg + test_skip_until aiff ogg + #@@@ doesn't work yet because md5cmp doesn't work because metaflac doesn't work on ogg flac yet + #@@@test_skip_until flac ogg + #@@@test_skip_until ogg ogg +fi + +echo "testing seek extremes:" + +run_flac --verify --force $SILENT --no-padding --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=16 --channels=2 --blocksize=576 noise.raw || die "ERROR generating FLAC file" + +if [ $is_win = no ] ; then + total_noise_cdda_samples=`run_metaflac --show-total-samples noise.flac` + [ $? = 0 ] || die "ERROR getting total sample count from noise.flac" +else + # some flavors of cygwin don't seem to treat the \x0d as a word + # separator, so we hard code it. we'll just have to fix it later + # if we change the way noise.flac is made. + total_noise_cdda_samples=393216 +fi + +echo -n "testing --skip=0... " +run_flac $wav_dopt --skip=0 -o z.wav noise.flac || die "ERROR decoding FLAC file noise.flac" +echo OK + +for delta in 2 1 ; do + n=`expr $total_noise_cdda_samples - $delta` + echo -n "testing --skip=$n... " + run_flac $wav_dopt --skip=$n -o z.wav noise.flac || die "ERROR decoding FLAC file noise.flac" + echo OK +done + +rm noise.flac z.wav + + +############################################################################ +# test --input-size +############################################################################ + +#@@@ cat will not work on old cygwin, need to fix +if [ $is_win = no ] ; then + echo -n "testing --input-size=50 --skip=10... " + cat 50c.raw | run_flac $raw_eopt --input-size=50 --skip=10 -o z50c.skip10.flac - || die "ERROR generating FLAC file" + run_flac $raw_dopt -o z50c.skip10.raw z50c.skip10.flac || die "ERROR decoding FLAC file" + cmp 50c.skip10.raw z50c.skip10.raw || die "ERROR: file mismatch for --input-size=50 --skip=10" + rm -f z50c.skip10.raw z50c.skip10.flac + echo OK +fi + + +############################################################################ +# test --cue +############################################################################ + +# +# create the cue sheet +# +cuesheet=cuetest.cue +cat > $cuesheet << EOF +CATALOG 1234567890123 +FILE "blah" WAVE + TRACK 01 AUDIO + INDEX 01 0 + INDEX 02 10 + INDEX 03 20 + TRACK 02 AUDIO + INDEX 01 30 + TRACK 04 AUDIO + INDEX 01 40 +EOF + +test_cue () +{ + in_fmt=$1 + out_fmt=$2 + + [ "$in_fmt" = wav ] || [ "$in_fmt" = aiff ] || [ "$in_fmt" = raw ] || [ "$in_fmt" = flac ] || [ "$in_fmt" = ogg ] || die "ERROR: internal error, bad 'in' format '$in_fmt'" + + [ "$out_fmt" = flac ] || [ "$out_fmt" = ogg ] || die "ERROR: internal error, bad 'out' format '$out_fmt'" + + if [ $in_fmt = raw ] ; then + eopt="$raw_eopt" + dopt="$raw_dopt" + else + eopt="$wav_eopt" + dopt="$wav_dopt" + fi + + if ( [ $in_fmt = flac ] || [ $in_fmt = ogg ] ) && ( [ $out_fmt = flac ] || [ $out_fmt = ogg ] ) ; then + CMP=md5cmp + else + CMP=cmp + fi + + if [ $out_fmt = ogg ] ; then + eopt="--ogg $eopt" + fi + + desc="($in_fmt<->$out_fmt)" + + # + # for this we need just need just one FLAC file; --cue only works while decoding + # + run_flac $eopt --cuesheet=$cuesheet -o z50c.cue.$out_fmt 50c.$in_fmt || die "ERROR generating FLAC file $desc" + + # To make it easy to translate from cue point to sample numbers, the + # file has a sample rate of 10 Hz and a cuesheet like so: + # + # TRACK 01, INDEX 01 : 0:00.00 -> sample 0 + # TRACK 01, INDEX 02 : 0:01.00 -> sample 10 + # TRACK 01, INDEX 03 : 0:02.00 -> sample 20 + # TRACK 02, INDEX 01 : 0:03.00 -> sample 30 + # TRACK 04, INDEX 01 : 0:04.00 -> sample 40 + # + echo -n "testing --cue=- $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=- z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=- $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.0 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.0 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.0 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.0- $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.0- z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.0- $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.1 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.1 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.1 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.1- $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.1- z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.1- $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.2 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.2 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.2 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.2- $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.2- z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.2- $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.4 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.4 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip20.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.4 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.4- $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.4- z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip20.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.4- $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=-5.0 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=-5.0 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=-5.0 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=-4.1 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=-4.1 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=-4.1 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=-3.1 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=-3.1 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until40.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=-3.1 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=-1.4 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=-1.4 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.until30.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=-1.4 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.0-5.0 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.0-5.0 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.0-5.0 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.1-5.0 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.1-5.0 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.1-5.0 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.2-4.1 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.2-4.1 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip10.until40.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.2-4.1 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + echo -n "testing --cue=1.4-2.0 $desc... " + run_flac $dopt -o z50c.cued.$in_fmt --cue=1.4-2.0 z50c.cue.$out_fmt || die "ERROR decoding FLAC file $desc" + $CMP 50c.skip20.until30.$in_fmt z50c.cued.$in_fmt || die "ERROR: file mismatch for --cue=1.4-2.0 $desc" + rm -f z50c.cued.$in_fmt + echo OK + + rm -f z50c.cue.$out_fmt +} + +test_cue raw flac +test_cue wav flac +test_cue aiff flac +test_cue flac flac +#@@@if [ $has_ogg = yes ] ; then +#@@@ #@@@ doesn't work yet because md5cmp doesn't work because metaflac doesn't work on ogg flac yet +#@@@ test_cue ogg flac +#@@@fi + +if [ $has_ogg = yes ] ; then + test_cue raw ogg + test_cue wav ogg + test_cue aiff ogg + #@@@ doesn't work yet because md5cmp doesn't work because metaflac doesn't work on ogg flac yet + #@@@test_cue flac ogg + #@@@test_cue ogg ogg +fi + +############################################################################ +# test 'fixup' code that happens when a FLAC file with total_samples == 0 +# in the STREAMINFO block is converted to WAVE or AIFF, requiring the +# decoder go back and fix up the chunk headers +############################################################################ + +echo -n "WAVE fixup test... " + +echo -n "prepare... " +convert_to_wav noise "$raw_eopt" "$wav_dopt" || die "ERROR creating reference WAVE" + +echo -n "encode... " +# the pipe from 'cat' to 'flac' does not work on cygwin because of the EOF/ +# binary-mode stdin problem, so we use an undocumented option to metaflac to +# set the total sample count to 0 +if [ $is_win = yes ] ; then + run_flac $raw_eopt noise.raw -o fixup.flac || die "ERROR generating FLAC file" + run_metaflac --set-total-samples=0 fixup.flac 2> /dev/null +else + cat noise.raw | run_flac $raw_eopt - -c > fixup.flac || die "ERROR generating FLAC file" +fi + +echo -n "decode... " +run_flac $wav_dopt fixup.flac -o fixup.wav || die "ERROR decoding FLAC file" + +echo -n "compare... " +cmp noise.wav fixup.wav || die "ERROR: file mismatch" + +echo OK +rm -f noise.wav fixup.wav fixup.flac + +echo -n "AIFF fixup test... " + +echo -n "prepare... " +convert_to_aiff noise "$raw_eopt" "$wav_dopt" || die "ERROR creating reference AIFF" + +echo -n "encode... " +# the pipe from 'cat' to 'flac' does not work on cygwin because of the EOF/ +# binary-mode stdin problem, so we use an undocumented option to metaflac to +# set the total sample count to 0 +if [ $is_win = yes ] ; then + run_flac $raw_eopt noise.raw -o fixup.flac || die "ERROR generating FLAC file" + run_metaflac --set-total-samples=0 fixup.flac 2> /dev/null +else + cat noise.raw | run_flac $raw_eopt - -c > fixup.flac || die "ERROR generating FLAC file" +fi + +echo -n "decode... " +run_flac $wav_dopt fixup.flac -o fixup.aiff || die "ERROR decoding FLAC file" + +echo -n "compare... " +cmp noise.aiff fixup.aiff || die "ERROR: file mismatch" + +echo OK +rm -f noise.aiff fixup.aiff fixup.flac + + +############################################################################ +# multi-file tests +############################################################################ + +echo "Generating multiple input files from noise..." +multifile_format_decode="--endian=big --sign=signed" +multifile_format_encode="$multifile_format_decode --sample-rate=44100 --bps=16 --channels=2 --no-padding" +short_noise_cdda_samples=`expr $total_noise_cdda_samples / 8` +run_flac --verify --force $SILENT --force-raw-format $multifile_format_encode --until=$short_noise_cdda_samples -o shortnoise.flac noise.raw || die "ERROR generating FLAC file" +run_flac --decode --force $SILENT shortnoise.flac -o shortnoise.raw --force-raw-format $multifile_format_decode || die "ERROR generating RAW file" +run_flac --decode --force $SILENT shortnoise.flac || die "ERROR generating WAVE file" +run_flac --decode --force $SILENT shortnoise.flac -o shortnoise.aiff || die "ERROR generating AIFF file" +cp shortnoise.flac file0.flac +cp shortnoise.flac file1.flac +cp shortnoise.flac file2.flac +rm -f shortnoise.flac +cp shortnoise.wav file0.wav +cp shortnoise.wav file1.wav +cp shortnoise.wav file2.wav +rm -f shortnoise.wav +cp shortnoise.aiff file0.aiff +cp shortnoise.aiff file1.aiff +cp shortnoise.aiff file2.aiff +rm -f shortnoise.aiff +cp shortnoise.raw file0.raw +cp shortnoise.raw file1.raw +cp shortnoise.raw file2.raw +rm -f shortnoise.raw +# create authoritative sector-aligned files for comparison +file0_samples=`expr \( $short_noise_cdda_samples / 588 \) \* 588` +file0_remainder=`expr $short_noise_cdda_samples - $file0_samples` +file1_samples=`expr \( \( $file0_remainder + $short_noise_cdda_samples \) / 588 \) \* 588` +file1_remainder=`expr $file0_remainder + $short_noise_cdda_samples - $file1_samples` +file1_samples=`expr $file1_samples - $file0_remainder` +file2_samples=`expr \( \( $file1_remainder + $short_noise_cdda_samples \) / 588 \) \* 588` +file2_remainder=`expr $file1_remainder + $short_noise_cdda_samples - $file2_samples` +file2_samples=`expr $file2_samples - $file1_remainder` +if [ $file2_remainder != '0' ] ; then + file2_samples=`expr $file2_samples + $file2_remainder` + file2_remainder=`expr 588 - $file2_remainder` +fi + +dd if=file0.raw ibs=4 count=$file0_samples of=file0s.raw 2>/dev/null || $dddie +dd if=file0.raw ibs=4 count=$file0_remainder of=file1s.raw skip=$file0_samples 2>/dev/null || $dddie +dd if=file1.raw ibs=4 count=$file1_samples of=z.raw 2>/dev/null || $dddie +cat z.raw >> file1s.raw || die "ERROR: cat-ing sector-aligned files" +dd if=file1.raw ibs=4 count=$file1_remainder of=file2s.raw skip=$file1_samples 2>/dev/null || $dddie +dd if=file2.raw ibs=4 count=$file2_samples of=z.raw 2>/dev/null || $dddie +cat z.raw >> file2s.raw || die "ERROR: cat-ing sector-aligned files" +dd if=/dev/zero ibs=4 count=$file2_remainder of=z.raw 2>/dev/null || $dddie +cat z.raw >> file2s.raw || die "ERROR: cat-ing sector-aligned files" +rm -f z.raw + +convert_to_wav file0s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned WAVE" +convert_to_wav file1s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned WAVE" +convert_to_wav file2s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned WAVE" + +convert_to_aiff file0s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned AIFF" +convert_to_aiff file1s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned AIFF" +convert_to_aiff file2s "$multifile_format_encode --force" "$SILENT --force --decode" || die "ERROR creating authoritative sector-aligned AIFF" + +test_multifile () +{ + input_type=$1 + streamtype=$2 + sector_align=$3 + encode_options="$4" + + extra_encode_options="" + extra_decode_options="" + if [ $input_type = "raw" ] ; then + extra_encode_options="--force-raw-format $multifile_format_encode" + extra_decode_options="--force-raw-format $multifile_format_decode" + else + if [ $input_type = "aiff" ] ; then + extra_decode_options="--force-aiff-format" + fi + fi + + if [ $streamtype = ogg ] ; then + suffix=oga + encode_options="$encode_options --ogg" + else + suffix=flac + fi + + if [ $sector_align = sector_align ] ; then + encode_options="$encode_options --sector-align" + fi + + if [ $input_type = flac ] || [ $input_type = ogg ] ; then + CMP=md5cmp + else + CMP=cmp + fi + + for n in 0 1 2 ; do + cp file$n.$input_type file${n}x.$input_type + done + run_flac --force $encode_options $extra_encode_options file0x.$input_type file1x.$input_type file2x.$input_type || die "ERROR" + run_flac --force --decode $extra_decode_options file0x.$suffix file1x.$suffix file2x.$suffix || die "ERROR" + if [ $sector_align != sector_align ] ; then + for n in 0 1 2 ; do + $CMP file$n.$input_type file${n}x.$input_type || die "ERROR: file mismatch on file #$n" + done + else + for n in 0 1 2 ; do + $CMP file${n}s.$input_type file${n}x.$input_type || die "ERROR: file mismatch on file #$n" + done + fi + for n in 0 1 2 ; do + rm -f file${n}x.$suffix file${n}x.$input_type + done +} + +input_types="raw wav aiff flac" +#@@@ doesn't work yet because md5cmp doesn't work because metaflac doesn't work on ogg flac yet +#@@@if [ $has_ogg = yes ] ; then +#@@@ input_types="$input_types ogg" +#@@@fi +for input_type in $input_types ; do + echo "Testing multiple $input_type files without verify..." + test_multifile $input_type flac no_sector_align "" + + echo "Testing multiple $input_type files with verify..." + test_multifile $input_type flac no_sector_align "--verify" + + if [ $input_type != flac ] && [ $input_type != ogg ] ; then # --sector-align not supported for FLAC input + echo "Testing multiple $input_type files with --sector-align, without verify..." + test_multifile $input_type flac sector_align "" + + echo "Testing multiple $input_type files with --sector-align, with verify..." + test_multifile $input_type flac sector_align "--verify" + fi + + if [ $has_ogg = yes ] ; then + echo "Testing multiple $input_type files with --ogg, without verify..." + test_multifile $input_type ogg no_sector_align "" + + echo "Testing multiple $input_type files with --ogg, with verify..." + test_multifile $input_type ogg no_sector_align "--verify" + + if [ $input_type != flac ] ; then # --sector-align not supported for FLAC input + echo "Testing multiple $input_type files with --ogg and --sector-align, without verify..." + test_multifile $input_type ogg sector_align "" + + echo "Testing multiple $input_type files with --ogg and --sector-align, with verify..." + test_multifile $input_type ogg sector_align "--verify" + fi + + echo "Testing multiple $input_type files with --ogg and --serial-number, with verify..." + test_multifile $input_type ogg no_sector_align "--serial-number=321 --verify" + fi +done + + +############################################################################ +# test --keep-foreign-metadata +############################################################################ + +echo "Testing --keep-foreign-metadata..." + +rt_test_wav wacky1.wav '--keep-foreign-metadata' +rt_test_wav wacky2.wav '--keep-foreign-metadata' +rt_test_w64 wacky1.w64 '--keep-foreign-metadata' +rt_test_w64 wacky2.w64 '--keep-foreign-metadata' +rt_test_rf64 wacky1.rf64 '--keep-foreign-metadata' +rt_test_rf64 wacky2.rf64 '--keep-foreign-metadata' + + +############################################################################ +# test the metadata-handling properties of flac-to-flac encoding +############################################################################ + +echo "Testing the metadata-handling properties of flac-to-flac encoding..." + +testdir="flac-to-flac-metadata-test-files" +filter () +{ + # minor danger, changing vendor strings might change the length of the + # VORBIS_COMMENT block, but if we add "^ length: " to the patterns, + # we lose info about PADDING size that we need + grep -Ev '^ vendor string: |^ m..imum .....size: ' | sed -e 's/, stream_offset.*//' +} +flac2flac () +{ + file="$1" + case="$2" + args="$3" + expect="$case-expect.meta" + echo -n "$case... " + run_flac $SILENT -f -o out.flac $args $file || die "ERROR encoding FLAC file" + run_metaflac --list out.flac | filter > out.meta || die "ERROR listing metadata of output FLAC file" + diff -q -w $expect out.meta 2>/dev/null || die "ERROR: metadata does not match expected $expect" + echo OK +} + +#filter=', stream_offset.*|^ vendor string: |^ length: |^ m..imum .....size: ' +cd $testdir || die "ERROR changing to directory $testdir" + +# case 00a: no alterations on a file with all metadata types, keep all metadata, in same order +flac2flac input-SCVAUP.flac case00a "" +# case 01a: on file with multiple PADDING blocks, they should be aggregated into one at the end +flac2flac input-SCVPAP.flac case01a "" +# case 01b: on file with multiple PADDING blocks and --no-padding specified, they should all be deleted +flac2flac input-SCVPAP.flac case01b "--no-padding" +# case 01c: on file with multiple PADDING blocks and -P specified, they should all be overwritten with -P value +flac2flac input-SCVPAP.flac case01c "-P 1234" +# case 01d: on file with no PADDING blocks, use -P setting +flac2flac input-SCVA.flac case01d "-P 1234" +# case 01e: on file with no PADDING blocks and no -P given, use default padding +flac2flac input-SCVA.flac case01e "" +# case 02a: on file with no VORBIS_COMMENT block, add new VORBIS_COMMENT +flac2flac input-SCPAP.flac case02a "" +# case 02b: on file with no VORBIS_COMMENT block and --tag, add new VORBIS_COMMENT with tags +flac2flac input-SCPAP.flac case02b "--tag=artist=0" +# case 02c: on file with VORBIS_COMMENT block and --tag, replace existing VORBIS_COMMENT with new tags +flac2flac input-SCVAUP.flac case02c "$TOTALLY_SILENT --tag=artist=0" +# case 03a: on file with no CUESHEET block and --cuesheet specified, add it +flac2flac input-SVAUP.flac case03a "--cuesheet=input0.cue" +# case 03b: on file with CUESHEET block and --cuesheet specified, overwrite existing CUESHEET +flac2flac input-SCVAUP.flac case03b "$TOTALLY_SILENT --cuesheet=input0.cue" +# case 03c: on file with CUESHEET block and size-changing option specified, drop existing CUESHEET +flac2flac input-SCVAUP.flac case03c "$TOTALLY_SILENT --skip=1" +# case 04a: on file with no SEEKTABLE block and --no-seektable specified, no SEEKTABLE +flac2flac input-VA.flac case04a "--no-padding --no-seektable" +# case 04b: on file with no SEEKTABLE block and -S specified, new SEEKTABLE +flac2flac input-VA.flac case04b "--no-padding -S 5x" +# case 04c: on file with no SEEKTABLE block and no seektable options specified, new SEEKTABLE with default points +flac2flac input-VA.flac case04c "--no-padding" +# case 04d: on file with SEEKTABLE block and --no-seektable specified, drop existing SEEKTABLE +flac2flac input-SCVA.flac case04d "--no-padding --no-seektable" +# case 04e: on file with SEEKTABLE block and -S specified, overwrite existing SEEKTABLE +flac2flac input-SCVA.flac case04e "$TOTALLY_SILENT --no-padding -S 5x" +# case 04f: on file with SEEKTABLE block and size-changing option specified, drop existing SEEKTABLE, new SEEKTABLE with default points +#(already covered by case03c) + +rm -f out.flac out.meta + +#@@@ when metaflac handles ogg flac, duplicate flac2flac tests here + +cd .. diff --git a/flac/test/test_grabbag.sh b/flac/test/test_grabbag.sh new file mode 100644 index 0000000..e6b5d66 --- /dev/null +++ b/flac/test/test_grabbag.sh @@ -0,0 +1,148 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/test_grabbag/cuesheet:$PATH +PATH=../src/test_grabbag/picture:$PATH +PATH=../obj/$BUILD/bin:$PATH + +test_cuesheet -h 1>/dev/null 2>/dev/null || die "ERROR can't find test_cuesheet executable" +test_picture -h 1>/dev/null 2>/dev/null || die "ERROR can't find test_picture executable" + +run_test_cuesheet () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 test_cuesheet $*" >>test_grabbag.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 test_cuesheet $* 4>>test_grabbag.valgrind.log + else + test_cuesheet $* + fi +} + +run_test_picture () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 test_picture $*" >>test_grabbag.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 test_picture $* 4>>test_grabbag.valgrind.log + else + test_picture $* + fi +} + +if [ `env | grep -ic '^comspec='` != 0 ] ; then + is_win=yes +else + is_win=no +fi + +######################################################################## +# +# test_picture +# +######################################################################## + +log=picture.log +picture_dir=pictures + +echo "Running test_picture..." + +rm -f $log + +run_test_picture $picture_dir >> $log 2>&1 + +if [ $is_win = yes ] ; then + diff -w picture.ok $log > picture.diff || die "Error: .log file does not match .ok file, see picture.diff" +else + diff picture.ok $log > picture.diff || die "Error: .log file does not match .ok file, see picture.diff" +fi + +echo "PASSED (results are in $log)" + +######################################################################## +# +# test_cuesheet +# +######################################################################## + +log=cuesheet.log +bad_cuesheets=cuesheets/bad.*.cue +good_cuesheets=cuesheets/good.*.cue +good_leadout=`expr 80 \* 60 \* 44100` +bad_leadout=`expr $good_leadout + 1` + +echo "Running test_cuesheet..." + +rm -f $log + +# +# negative tests +# +for cuesheet in $bad_cuesheets ; do + echo "NEGATIVE $cuesheet" >> $log 2>&1 + run_test_cuesheet $cuesheet $good_leadout cdda >> $log 2>&1 + exit_code=$? + if [ "$exit_code" = 255 ] ; then + die "Error: test script is broken" + fi + cuesheet_pass1=${cuesheet}.1 + cuesheet_pass2=${cuesheet}.2 + rm -f $cuesheet_pass1 $cuesheet_pass2 +done + +# +# positve tests +# +for cuesheet in $good_cuesheets ; do + echo "POSITIVE $cuesheet" >> $log 2>&1 + run_test_cuesheet $cuesheet $good_leadout cdda >> $log 2>&1 + exit_code=$? + if [ "$exit_code" = 255 ] ; then + die "Error: test script is broken" + elif [ "$exit_code" != 0 ] ; then + die "Error: good cuesheet is broken" + fi + cuesheet_pass1=${cuesheet}.1 + cuesheet_pass2=${cuesheet}.2 + diff $cuesheet_pass1 $cuesheet_pass2 >> $log 2>&1 || die "Error: pass1 and pass2 output differ" + rm -f $cuesheet_pass1 $cuesheet_pass2 +done + +if [ $is_win = yes ] ; then + diff -w cuesheet.ok $log > cuesheet.diff || die "Error: .log file does not match .ok file, see cuesheet.diff" +else + diff cuesheet.ok $log > cuesheet.diff || die "Error: .log file does not match .ok file, see cuesheet.diff" +fi + +echo "PASSED (results are in $log)" diff --git a/flac/test/test_libFLAC++.sh b/flac/test/test_libFLAC++.sh new file mode 100644 index 0000000..0333e1a --- /dev/null +++ b/flac/test/test_libFLAC++.sh @@ -0,0 +1,50 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/libFLAC++/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/test_libFLAC++:$PATH +PATH=../obj/$BUILD/bin:$PATH + +run_test_libFLACpp () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 test_libFLAC++ $* 4>>test_libFLAC++.valgrind.log + else + test_libFLAC++ $* + fi +} + +run_test_libFLACpp || die "ERROR during test_libFLAC++" diff --git a/flac/test/test_libFLAC.sh b/flac/test/test_libFLAC.sh new file mode 100644 index 0000000..8702bf7 --- /dev/null +++ b/flac/test/test_libFLAC.sh @@ -0,0 +1,49 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/test_libFLAC:$PATH +PATH=../obj/$BUILD/bin:$PATH + +run_test_libFLAC () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 test_libFLAC $* 4>>test_libFLAC.valgrind.log + else + test_libFLAC $* + fi +} + +run_test_libFLAC || die "ERROR during test_libFLAC" diff --git a/flac/test/test_metaflac.sh b/flac/test/test_metaflac.sh new file mode 100644 index 0000000..b92f817 --- /dev/null +++ b/flac/test/test_metaflac.sh @@ -0,0 +1,397 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +# change to 'false' to show all flac/metaflac output (useful for debugging) +if true ; then + SILENT='--silent' + TOTALLY_SILENT='--totally-silent' +else + SILENT='' + TOTALLY_SILENT='' +fi + +LD_LIBRARY_PATH=`pwd`/../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/grabbag/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/getopt/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/replaygain_analysis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/replaygain_synthesis/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../src/share/utf8/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=`pwd`/../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=`pwd`/../src/flac:$PATH +PATH=`pwd`/../src/metaflac:$PATH +PATH=`pwd`/../obj/$BUILD/bin:$PATH + +if echo a | (grep -E '(a|b)') >/dev/null 2>&1 + then EGREP='grep -E' + else EGREP='egrep' +fi + +testdir="metaflac-test-files" +flacfile="metaflac.flac" + +flac --help 1>/dev/null 2>/dev/null || die "ERROR can't find flac executable" +metaflac --help 1>/dev/null 2>/dev/null || die "ERROR can't find metaflac executable" + +run_flac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 flac $*" >>test_metaflac.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 flac $* 4>>test_metaflac.valgrind.log + else + flac $* + fi +} + +run_metaflac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 metaflac $*" >>test_metaflac.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 metaflac $* 4>>test_metaflac.valgrind.log + else + metaflac $* + fi +} + +run_metaflac_silent () +{ + if [ -z "$SILENT" ] ; then + run_metaflac $* + else + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 metaflac $*" >>test_metaflac.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 metaflac $* 2>/dev/null 4>>test_metaflac.valgrind.log + else + metaflac $* 2>/dev/null + fi + fi +} + +check_flac () +{ + run_flac --silent --test $flacfile || die "ERROR in $flacfile" 1>&2 +} + +echo "Generating stream..." +bytes=80000 +if dd if=/dev/zero ibs=1 count=$bytes | flac --force --verify -0 --input-size=$bytes --output-name=$flacfile --force-raw-format --endian=big --sign=signed --channels=1 --bps=8 --sample-rate=8000 - ; then + chmod +w $flacfile +else + die "ERROR during generation" +fi + +check_flac + +echo + +filter () +{ + # minor danger, changing vendor strings will change the length of the + # VORBIS_COMMENT block, but if we add "^ length: " to the patterns, + # we lose info about PADDING size that we need + # grep pattern 1: remove vendor string + # grep pattern 2: remove minimum/maximum frame and block size from STREAMINFO + # grep pattern 3: remove hexdump data from PICTURE metadata blocks + # sed pattern 1: remove stream offset values from SEEKTABLE points + $EGREP -v '^ vendor string: |^ m..imum .....size: |^ 0000[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]: ' | sed -e 's/, stream_offset.*//' +} +metaflac_test () +{ + case="$1" + desc="$2" + args="$3" + expect="$testdir/$case-expect.meta" + echo -n "test $case: $desc... " + run_metaflac $args $flacfile | filter > $testdir/out.meta || die "ERROR running metaflac" + diff -w $expect $testdir/out.meta > /dev/null 2>&1 || die "ERROR: metadata does not match expected $expect" + echo OK +} + +metaflac_test case00 "--list" "--list" + +metaflac_test case01 "STREAMINFO --show-* shortcuts" " + --show-md5sum + --show-min-blocksize + --show-max-blocksize + --show-min-framesize + --show-max-framesize + --show-sample-rate + --show-channels + --show-bps + --show-total-samples" + +run_metaflac --preserve-modtime --add-padding=12345 $flacfile +check_flac +metaflac_test case02 "--add-padding" "--list" + +# some flavors of /bin/sh (e.g. Darwin's) won't even handle quoted spaces, so we underscore: +run_metaflac --set-tag="ARTIST=The_artist_formerly_known_as_the_artist..." $flacfile +check_flac +metaflac_test case03 "--set-tag=ARTIST" "--list" + +run_metaflac --set-tag="ARTIST=Chuck_Woolery" $flacfile +check_flac +metaflac_test case04 "--set-tag=ARTIST" "--list" + +run_metaflac --set-tag="ARTIST=Vern" $flacfile +check_flac +metaflac_test case05 "--set-tag=ARTIST" "--list" + +run_metaflac --set-tag="TITLE=He_who_smelt_it_dealt_it" $flacfile +check_flac +metaflac_test case06 "--set-tag=TITLE" "--list" + +metaflac_test case07 "--show-vendor-tag --show-tag=ARTIST" "--show-vendor-tag --show-tag=ARTIST" + +run_metaflac --remove-first-tag=ARTIST $flacfile +check_flac +metaflac_test case08 "--remove-first-tag=ARTIST" "--list" + +run_metaflac --remove-tag=ARTIST $flacfile +check_flac +metaflac_test case09 "--remove-tag=ARTIST" "--list" + +metaflac_test case10 "--list --block-type=VORBIS_COMMENT" "--list --block-type=VORBIS_COMMENT" +metaflac_test case11 "--list --block-number=0" "--list --block-number=0" +metaflac_test case12 "--list --block-number=1,2,999" "--list --block-number=1,2,999" +metaflac_test case13 "--list --block-type=VORBIS_COMMENT,PADDING" "--list --block-type=VORBIS_COMMENT,PADDING" +metaflac_test case14 "--list --except-block-type=SEEKTABLE,VORBIS_COMMENT" "--list --except-block-type=SEEKTABLE,VORBIS_COMMENT" +metaflac_test case15 "--list --except-block-type=STREAMINFO" "--list --except-block-type=STREAMINFO" + +run_metaflac --add-padding=4321 $flacfile $flacfile +check_flac +metaflac_test case16 "--add-padding=4321 * 2" "--list" + +run_metaflac --merge-padding $flacfile +check_flac +metaflac_test case17 "--merge-padding" "--list" + +run_metaflac --add-padding=0 $flacfile +check_flac +metaflac_test case18 "--add-padding=0" "--list" + +run_metaflac --sort-padding $flacfile +check_flac +metaflac_test case19 "--sort-padding" "--list" + +run_metaflac --add-padding=0 $flacfile +check_flac +metaflac_test case20 "--add-padding=0" "--list" + +run_metaflac --remove-all-tags $flacfile +check_flac +metaflac_test case21 "--remove-all-tags" "--list" + +run_metaflac --remove --block-number=1,99 --dont-use-padding $flacfile +check_flac +metaflac_test case22 "--remove --block-number=1,99 --dont-use-padding" "--list" + +run_metaflac --remove --block-number=99 --dont-use-padding $flacfile +check_flac +metaflac_test case23 "--remove --block-number=99 --dont-use-padding" "--list" + +run_metaflac --remove --block-type=PADDING $flacfile +check_flac +metaflac_test case24 "--remove --block-type=PADDING" "--list" + +run_metaflac --remove --block-type=PADDING --dont-use-padding $flacfile +check_flac +metaflac_test case25 "--remove --block-type=PADDING --dont-use-padding" "--list" + +run_metaflac --add-padding=0 $flacfile $flacfile +check_flac +metaflac_test case26 "--add-padding=0 * 2" "--list" + +run_metaflac --remove --except-block-type=PADDING $flacfile +check_flac +metaflac_test case27 "--remove --except-block-type=PADDING" "--list" + +run_metaflac --remove-all $flacfile +check_flac +metaflac_test case28 "--remove-all" "--list" + +run_metaflac --remove-all --dont-use-padding $flacfile +check_flac +metaflac_test case29 "--remove-all --dont-use-padding" "--list" + +run_metaflac --remove-all --dont-use-padding $flacfile +check_flac +metaflac_test case30 "--remove-all --dont-use-padding" "--list" + +run_metaflac --set-tag="f=0123456789abcdefghij" $flacfile +check_flac +metaflac_test case31 "--set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789abcdefghi" $flacfile +check_flac +metaflac_test case32 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789abcde" $flacfile +check_flac +metaflac_test case33 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0" $flacfile +check_flac +metaflac_test case34 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789" $flacfile +check_flac +metaflac_test case35 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789abcdefghi" $flacfile +check_flac +metaflac_test case36 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789" $flacfile +check_flac +metaflac_test case37 "--remove-all-tags --set-tag=..." "--list" + +run_metaflac --remove-all-tags --set-tag="f=0123456789abcdefghij" $flacfile +check_flac +metaflac_test case38 "--remove-all-tags --set-tag=..." "--list" + +echo "TITLE=Tittle" | run_metaflac --import-tags-from=- $flacfile +check_flac +metaflac_test case39 "--import-tags-from=-" "--list" + +cat > vc.txt << EOF +artist=Fartist +artist=artits +EOF +run_metaflac --import-tags-from=vc.txt $flacfile +check_flac +metaflac_test case40 "--import-tags-from=[FILE]" "--list" + +rm vc.txt + +run_metaflac --add-replay-gain $flacfile +check_flac +metaflac_test case41 "--add-replay-gain" "--list" + +run_metaflac --remove-replay-gain $flacfile +check_flac +metaflac_test case42 "--remove-replay-gain" "--list" + +# CUESHEET blocks +cs_in=cuesheets/good.000.cue +cs_out=metaflac.cue +cs_out2=metaflac2.cue +run_metaflac --import-cuesheet-from="$cs_in" $flacfile +check_flac +metaflac_test case43 "--import-cuesheet-from" "--list" +run_metaflac --export-cuesheet-to=$cs_out $flacfile +run_metaflac --remove --block-type=CUESHEET $flacfile +check_flac +metaflac_test case44 "--remove --block-type=CUESHEET" "--list" +run_metaflac --import-cuesheet-from=$cs_out $flacfile +check_flac +metaflac_test case45 "--import-cuesheet-from" "--list" +run_metaflac --export-cuesheet-to=$cs_out2 $flacfile +echo "comparing cuesheets:" +diff $cs_out $cs_out2 || die "ERROR, cuesheets should be identical" +echo identical + +rm -f $cs_out $cs_out2 + +# PICTURE blocks +ncase=46 +for f in \ + 0.gif \ + 1.gif \ + 2.gif \ +; do + run_metaflac --import-picture-from="|image/gif|$f||pictures/$f" $flacfile + check_flac + metaflac_test "case$ncase" "--import-picture-from" "--list" + ncase=`expr $ncase + 1` +done +for f in \ + 0.jpg \ + 4.jpg \ +; do + run_metaflac --import-picture-from="4|image/jpeg|$f||pictures/$f" $flacfile + check_flac + metaflac_test "case$ncase" "--import-picture-from" "--list" + ncase=`expr $ncase + 1` +done +for f in \ + 0.png \ + 1.png \ + 2.png \ + 3.png \ + 4.png \ + 5.png \ + 6.png \ + 7.png \ + 8.png \ +; do + run_metaflac --import-picture-from="5|image/png|$f||pictures/$f" $flacfile + check_flac + metaflac_test "case$ncase" "--import-picture-from" "--list" + ncase=`expr $ncase + 1` +done +[ $ncase = 60 ] || die "expected case# to be 60" + +fn=export-picture-check +echo -n "Testing --export-picture-to... " +run_metaflac --export-picture-to=$fn $flacfile +check_flac +cmp $fn pictures/0.gif || die "ERROR, exported picture file and original differ" +echo OK +rm -f $fn +echo -n "Testing --block-number --export-picture-to... " +run_metaflac --block-number=9 --export-picture-to=$fn $flacfile +check_flac +cmp $fn pictures/0.png || die "ERROR, exported picture file and original differ" +echo OK +rm -f $fn + +run_metaflac --remove --block-type=PICTURE $flacfile +check_flac +metaflac_test case60 "--remove --block-type=PICTURE" "--list" +run_metaflac --import-picture-from="1|image/png|standard_icon|32x32x24|pictures/0.png" $flacfile +check_flac +metaflac_test case61 "--import-picture-from" "--list" +run_metaflac --import-picture-from="2|image/png|icon|64x64x24|pictures/1.png" $flacfile +check_flac +metaflac_test case62 "--import-picture-from" "--list" + +# UNKNOWN blocks +echo -n "Testing FLAC file with unknown metadata... " +cp -p metaflac.flac.in $flacfile +# remove the VORBIS_COMMENT block so vendor string changes don't interfere with the comparison: +run_metaflac --remove --block-type=VORBIS_COMMENT --dont-use-padding $flacfile +cmp $flacfile metaflac.flac.ok || die "ERROR, $flacfile and metaflac.flac.ok differ" +echo OK + +rm -f $testdir/out.flac $testdir/out.meta + +exit 0 diff --git a/flac/test/test_seeking.sh b/flac/test/test_seeking.sh new file mode 100644 index 0000000..69c5117 --- /dev/null +++ b/flac/test/test_seeking.sh @@ -0,0 +1,155 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../src/libFLAC/.libs:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/flac:$PATH +PATH=../src/metaflac:$PATH +PATH=../src/test_seeking:$PATH +PATH=../src/test_streams:$PATH +PATH=../obj/$BUILD/bin:$PATH + +if [ x"$FLAC__TEST_LEVEL" = x ] ; then + FLAC__TEST_LEVEL=1 +fi + +flac --help 1>/dev/null 2>/dev/null || die "ERROR can't find flac executable" +metaflac --help 1>/dev/null 2>/dev/null || die "ERROR can't find metaflac executable" + +run_flac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 flac $*" >>test_seeking.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 flac $* 4>>test_seeking.valgrind.log + else + flac $* + fi +} + +run_metaflac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 metaflac $*" >>test_seeking.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 metaflac $* 4>>test_seeking.valgrind.log + else + metaflac $* + fi +} + +run_test_seeking () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 test_seeking $*" >>test_seeking.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 test_seeking $* 4>>test_seeking.valgrind.log + else + test_seeking $* + fi +} + +echo "Checking for --ogg support in flac..." +if flac --ogg --silent --force-raw-format --endian=little --sign=signed --channels=1 --bps=8 --sample-rate=44100 -c $0 1>/dev/null 2>&1 ; then + has_ogg=yes; + echo "flac --ogg works" +else + has_ogg=no; + echo "flac --ogg doesn't work" +fi + + +echo "Generating streams..." +if [ ! -f noise.raw ] ; then + test_streams || die "ERROR during test_streams" +fi + +echo "generating FLAC files for seeking:" +run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=8 --channels=1 --blocksize=576 -S- --output-name=tiny.flac noise8m32.raw || die "ERROR generating FLAC file" +run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=16 --channels=2 --blocksize=576 -S- --output-name=small.flac noise.raw || die "ERROR generating FLAC file" +run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=8 --channels=1 --blocksize=576 -S10x --output-name=tiny-s.flac noise8m32.raw || die "ERROR generating FLAC file" +run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=16 --channels=2 --blocksize=576 -S10x --output-name=small-s.flac noise.raw || die "ERROR generating FLAC file" + +tiny_samples=`metaflac --show-total-samples tiny.flac` +small_samples=`metaflac --show-total-samples small.flac` + +tiny_seek_count=100 +if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + small_seek_count=10000 +else + small_seek_count=100000 +fi + +for suffix in '' '-s' ; do + echo "testing tiny$suffix.flac:" + if run_test_seeking tiny$suffix.flac $tiny_seek_count $tiny_samples noise8m32.raw ; then : ; else + die "ERROR: during test_seeking" + fi + + echo "testing small$suffix.flac:" + if run_test_seeking small$suffix.flac $small_seek_count $small_samples noise.raw ; then : ; else + die "ERROR: during test_seeking" + fi + + echo "removing sample count from tiny$suffix.flac and small$suffix.flac:" + if run_metaflac --no-filename --set-total-samples=0 tiny$suffix.flac small$suffix.flac ; then : ; else + die "ERROR: during metaflac" + fi + + echo "testing tiny$suffix.flac with total_samples=0:" + if run_test_seeking tiny$suffix.flac $tiny_seek_count $tiny_samples noise8m32.raw ; then : ; else + die "ERROR: during test_seeking" + fi + + echo "testing small$suffix.flac with total_samples=0:" + if run_test_seeking small$suffix.flac $small_seek_count $small_samples noise.raw ; then : ; else + die "ERROR: during test_seeking" + fi +done + +if [ $has_ogg = "yes" ] ; then + + echo "generating Ogg FLAC files for seeking:" + run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=8 --channels=1 --blocksize=576 --output-name=tiny.oga --ogg noise8m32.raw || die "ERROR generating Ogg FLAC file" + run_flac --verify --force --silent --force-raw-format --endian=big --sign=signed --sample-rate=44100 --bps=16 --channels=2 --blocksize=576 --output-name=small.oga --ogg noise.raw || die "ERROR generating Ogg FLAC file" + # seek tables are not used in Ogg FLAC + + echo "testing tiny.oga:" + if run_test_seeking tiny.oga $tiny_seek_count $tiny_samples noise8m32.raw ; then : ; else + die "ERROR: during test_seeking" + fi + + echo "testing small.oga:" + if run_test_seeking small.oga $small_seek_count $small_samples noise.raw ; then : ; else + die "ERROR: during test_seeking" + fi + +fi + +rm -f tiny.flac tiny.oga small.flac small.oga tiny-s.flac small-s.flac diff --git a/flac/test/test_streams.sh b/flac/test/test_streams.sh new file mode 100644 index 0000000..9b923cf --- /dev/null +++ b/flac/test/test_streams.sh @@ -0,0 +1,268 @@ +#!/bin/sh + +# FLAC - Free Lossless Audio Codec +# Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008 Josh Coalson +# +# This file is part the FLAC project. FLAC is comprised of several +# components distributed under difference licenses. The codec libraries +# are distributed under Xiph.Org's BSD-like license (see the file +# COPYING.Xiph in this distribution). All other programs, libraries, and +# plugins are distributed under the GPL (see COPYING.GPL). The documentation +# is distributed under the Gnu FDL (see COPYING.FDL). Each file in the +# FLAC distribution contains at the top the terms under which it may be +# distributed. +# +# Since this particular file is relevant to all components of FLAC, +# it may be distributed under the Xiph.Org license, which is the least +# restrictive of those mentioned above. See the file COPYING.Xiph in this +# distribution. + +die () +{ + echo $* 1>&2 + exit 1 +} + +if [ x = x"$1" ] ; then + BUILD=debug +else + BUILD="$1" +fi + +LD_LIBRARY_PATH=../obj/$BUILD/lib:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH +PATH=../src/flac:$PATH +PATH=../src/test_streams:$PATH +PATH=../obj/$BUILD/bin:$PATH + +if [ x"$FLAC__TEST_LEVEL" = x ] ; then + FLAC__TEST_LEVEL=1 +fi + +flac --help 1>/dev/null 2>/dev/null || die "ERROR can't find flac executable" + +run_flac () +{ + if [ x"$FLAC__TEST_WITH_VALGRIND" = xyes ] ; then + echo "valgrind --leak-check=yes --show-reachable=yes --num-callers=100 flac $*" >>test_streams.valgrind.log + valgrind --leak-check=yes --show-reachable=yes --num-callers=100 --log-fd=4 flac $* 4>>test_streams.valgrind.log + else + flac $* + fi +} + +echo "Generating streams..." +if [ ! -f wacky1.wav ] ; then + test_streams || die "ERROR during test_streams" +fi + +# +# single-file test routines +# + +test_file () +{ + name=$1 + channels=$2 + bps=$3 + encode_options="$4" + + echo -n "$name (--channels=$channels --bps=$bps $encode_options): encode..." + cmd="run_flac --verify --silent --force --force-raw-format --endian=little --sign=signed --sample-rate=44100 --bps=$bps --channels=$channels $encode_options --no-padding $name.raw" + echo "### ENCODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 2>>./streams.log || die "ERROR during encode of $name" + + echo -n "decode..." + cmd="run_flac --silent --force --endian=little --sign=signed --decode --force-raw-format --output-name=$name.cmp $name.flac" + echo "### DECODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 2>>./streams.log || die "ERROR during decode of $name" + + ls -1l $name.raw >> ./streams.log + ls -1l $name.flac >> ./streams.log + ls -1l $name.cmp >> ./streams.log + + echo -n "compare..." + cmp $name.raw $name.cmp || die "ERROR during compare of $name" + + echo OK +} + +test_file_piped () +{ + name=$1 + channels=$2 + bps=$3 + encode_options="$4" + + if [ `env | grep -ic '^comspec='` != 0 ] ; then + is_win=yes + else + is_win=no + fi + + echo -n "$name: encode via pipes..." + if [ $is_win = yes ] ; then + cmd="run_flac --verify --silent --force --force-raw-format --endian=little --sign=signed --sample-rate=44100 --bps=$bps --channels=$channels $encode_options --no-padding --stdout $name.raw" + echo "### ENCODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 1>$name.flac 2>>./streams.log || die "ERROR during encode of $name" + else + cmd="run_flac --verify --silent --force --force-raw-format --endian=little --sign=signed --sample-rate=44100 --bps=$bps --channels=$channels $encode_options --no-padding --stdout -" + echo "### ENCODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + cat $name.raw | $cmd 1>$name.flac 2>>./streams.log || die "ERROR during encode of $name" + fi + echo -n "decode via pipes..." + if [ $is_win = yes ] ; then + cmd="run_flac --silent --force --endian=little --sign=signed --decode --force-raw-format --stdout $name.flac" + echo "### DECODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + $cmd 1>$name.cmp 2>>./streams.log || die "ERROR during decode of $name" + else + cmd="run_flac --silent --force --endian=little --sign=signed --decode --force-raw-format --stdout -" + echo "### DECODE $name #######################################################" >> ./streams.log + echo "### cmd=$cmd" >> ./streams.log + cat $name.flac | $cmd 1>$name.cmp 2>>./streams.log || die "ERROR during decode of $name" + fi + ls -1l $name.raw >> ./streams.log + ls -1l $name.flac >> ./streams.log + ls -1l $name.cmp >> ./streams.log + + echo -n "compare..." + cmp $name.raw $name.cmp || die "ERROR during compare of $name" + + echo OK +} + +if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + max_lpc_order=32 +else + max_lpc_order=16 +fi + +echo "Testing noise through pipes..." +test_file_piped noise 1 8 "-0" + +echo "Testing small files..." +test_file test01 1 16 "-0 -l $max_lpc_order --lax -m -e -p" +test_file test02 2 16 "-0 -l $max_lpc_order --lax -m -e -p" +test_file test03 1 16 "-0 -l $max_lpc_order --lax -m -e -p" +test_file test04 2 16 "-0 -l $max_lpc_order --lax -m -e -p" + +for bps in 8 16 24 ; do + echo "Testing $bps-bit full-scale deflection streams..." + for b in 01 02 03 04 05 06 07 ; do + test_file fsd$bps-$b 1 $bps "-0 -l $max_lpc_order --lax -m -e -p" + done +done + +echo "Testing 16-bit wasted-bits-per-sample streams..." +for b in 01 ; do + test_file wbps16-$b 1 16 "-0 -l $max_lpc_order --lax -m -e -p" +done + +for bps in 8 16 24 ; do + echo "Testing $bps-bit sine wave streams..." + for b in 00 ; do + test_file sine${bps}-$b 1 $bps "-0 -l $max_lpc_order --lax -m -e --sample-rate=48000" + done + for b in 01 ; do + test_file sine${bps}-$b 1 $bps "-0 -l $max_lpc_order --lax -m -e --sample-rate=96000" + done + for b in 02 03 04 ; do + test_file sine${bps}-$b 1 $bps "-0 -l $max_lpc_order --lax -m -e" + done + for b in 10 11 ; do + test_file sine${bps}-$b 2 $bps "-0 -l $max_lpc_order --lax -m -e --sample-rate=48000" + done + for b in 12 ; do + test_file sine${bps}-$b 2 $bps "-0 -l $max_lpc_order --lax -m -e --sample-rate=96000" + done + for b in 13 14 15 16 17 18 19 ; do + test_file sine${bps}-$b 2 $bps "-0 -l $max_lpc_order --lax -m -e" + done +done + +echo "Testing blocksize variations..." +for disable in '' '--disable-verbatim-subframes --disable-constant-subframes' '--disable-verbatim-subframes --disable-constant-subframes --disable-fixed-subframes' ; do + for blocksize in 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ; do + for lpc_order in 0 1 2 3 4 5 7 8 9 15 16 17 31 32 ; do + if [ $lpc_order = 0 ] || [ $lpc_order -le $blocksize ] ; then + test_file noise8m32 1 8 "-8 -p -e -l $lpc_order --lax --blocksize=$blocksize $disable" + fi + done + done +done + +echo "Testing some frame header variations..." +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax -b $max_lpc_order" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax -b 65535" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=9" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=90" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=90000" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=9" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=90" +test_file sine16-01 1 16 "-0 -l $max_lpc_order -m -e -p --lax --sample-rate=90000" + +echo "Testing option variations..." +for f in 00 01 02 03 04 ; do + for disable in '' '--disable-verbatim-subframes --disable-constant-subframes' '--disable-verbatim-subframes --disable-constant-subframes --disable-fixed-subframes' ; do + if [ -z "$disable" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + for opt in 0 1 2 4 5 6 8 ; do + for extras in '' '-p' '-e' ; do + if [ -z "$extras" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + test_file sine16-$f 1 16 "-$opt $extras $disable" + fi + done + done + if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + test_file sine16-$f 1 16 "-b 16384 -m -r 8 -l $max_lpc_order --lax -e -p $disable" + fi + fi + done +done + +for f in 10 11 12 13 14 15 16 17 18 19 ; do + for disable in '' '--disable-verbatim-subframes --disable-constant-subframes' '--disable-verbatim-subframes --disable-constant-subframes --disable-fixed-subframes' ; do + if [ -z "$disable" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + for opt in 0 1 2 4 5 6 8 ; do + for extras in '' '-p' '-e' ; do + if [ -z "$extras" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + test_file sine16-$f 2 16 "-$opt $extras $disable" + fi + done + done + if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + test_file sine16-$f 2 16 "-b 16384 -m -r 8 -l $max_lpc_order --lax -e -p $disable" + fi + fi + done +done + +echo "Testing noise..." +for disable in '' '--disable-verbatim-subframes --disable-constant-subframes' '--disable-verbatim-subframes --disable-constant-subframes --disable-fixed-subframes' ; do + if [ -z "$disable" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + for channels in 1 2 4 8 ; do + if [ $channels -le 2 ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + for bps in 8 16 24 ; do + for opt in 0 1 2 3 4 5 6 7 8 ; do + for extras in '' '-p' '-e' ; do + if [ -z "$extras" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + for blocksize in '' '--lax -b 32' '--lax -b 32768' '--lax -b 65535' ; do + if [ -z "$blocksize" ] || [ "$FLAC__TEST_LEVEL" -gt 0 ] ; then + test_file noise $channels $bps "-$opt $extras $blocksize $disable" + fi + done + fi + done + done + if [ "$FLAC__TEST_LEVEL" -gt 1 ] ; then + test_file noise $channels $bps "-b 16384 -m -r 8 -l $max_lpc_order --lax -e -p $disable" + fi + done + fi + done + fi +done diff --git a/flac/test/write_iff.pl b/flac/test/write_iff.pl new file mode 100644 index 0000000..88c61e4 --- /dev/null +++ b/flac/test/write_iff.pl @@ -0,0 +1,211 @@ +#!/usr/bin/perl -w + +use strict; + +require Math::BigInt; + +my $usage = " +$0 <#samples> + + is one of aiff,wave,wave64,rf64 + is 8,16,24,32 + is 1-8 + is any 32-bit value + <#samples> is 0-2^64-1 + is one of zero,rand + +"; + +die $usage unless @ARGV == 6; + +my %formats = ( 'aiff'=>1, 'wave'=>1, 'wave64'=>1, 'rf64'=>1 ); +my %sampletypes = ( 'zero'=>1, 'rand'=>1 ); +my @channelmask = ( 0, 1, 3, 7, 0x33, 0x607, 0x60f, 0, 0 ); #@@@@@@ need proper masks for 7,8 + +my ($format, $bps, $channels, $samplerate, $samples, $sampletype) = @ARGV; +my $bigsamples = new Math::BigInt $samples; + +die $usage unless defined $formats{$format}; +die $usage unless $bps == 8 || $bps == 16 || $bps == 24 || $bps == 32; +die $usage unless $channels >= 1 && $channels <= 8; +die $usage unless $samplerate >= 0 && $samplerate <= 4294967295; +die $usage unless defined $sampletypes{$sampletype}; + +# convert bits-per-sample to bytes-per-sample +$bps /= 8; + +my $datasize = $samples * $bps * $channels; +my $bigdatasize = $bigsamples * $bps * $channels; + +my $padding = int($bigdatasize & 1); # for aiff/wave/rf64 chunk alignment +my $padding8 = 8 - int($bigdatasize & 7); $padding8 = 0 if $padding8 == 8; # for wave64 alignment +# wave-ish file needs to be WAVEFORMATEXTENSIBLE? +my $wavx = ($format eq 'wave' || $format eq 'wave64' || $format eq 'rf64') && ($channels > 2); + +# write header + +if ($format eq 'aiff') { + die "sample data too big for format\n" if 46 + $datasize + $padding > 4294967295; + # header + print "FORM"; + print pack('N', 46 + $datasize + $padding); + print "AIFF"; + # COMM chunk + print "COMM"; + print pack('N', 18); # chunk size = 18 + print pack('n', $channels); + print pack('N', $samples); + print pack('n', $bps * 8); + print pack_sane_extended($samplerate); + # SSND header + print "SSND"; + print pack('N', $datasize + 8); # chunk size + print pack('N', 0); # ssnd_offset_size + print pack('N', 0); # blocksize +} +elsif ($format eq 'wave' || $format eq 'wave64' || $format eq 'rf64') { + die "sample data too big for format\n" if $format eq 'wave' && ($wavx?60:36) + $datasize + $padding > 4294967295; + # header + if ($format eq 'wave') { + print "RIFF"; + # +4 for WAVE + # +8+{40,16} for fmt chunk + # +8 for data chunk header + print pack('V', 4 + 8+($wavx?40:16) + 8 + $datasize + $padding); + print "WAVE"; + } + elsif ($format eq 'wave64') { + # RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 + print "\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00"; + # +(16+8) for RIFF GUID + size + # +16 for WAVE GUID + # +16+8+{40,16} for fmt chunk + # +16+8 for data chunk header + my $bigriffsize = $bigdatasize + (16+8) + 16 + 16+8+($wavx?40:16) + (16+8) + $padding8; + print pack_64('V', $bigriffsize); + # WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A + print "\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A"; + } + else { + print "RF64"; + print pack('V', 0xffffffff); + print "WAVE"; + # ds64 chunk + print "ds64"; + print pack('V', 28); # chunk size + # +4 for WAVE + # +(8+28) for ds64 chunk + # +8+{40,16} for fmt chunk + # +8 for data chunk header + my $bigriffsize = $bigdatasize + 4 + (8+28) + 8+($wavx?40:16) + 8 + $padding; + print pack_64('V', $bigriffsize); + print pack_64('V', $bigdatasize); + print pack_64('V', $bigsamples); + print pack('V', 0); # table size + } + # fmt chunk + if ($format ne 'wave64') { + print "fmt "; + print pack('V', $wavx?40:16); # chunk size + } + else { # wave64 + # fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A + print "\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A"; + print pack('V', 16+8+($wavx?40:16)); # chunk size (+16+8 for GUID and size fields) + print pack('V', 0); # ...is 8 bytes for wave64 + } + print pack('v', $wavx?65534:1); # compression code + print pack('v', $channels); + print pack('V', $samplerate); + print pack('V', $samplerate * $channels * $bps); + print pack('v', $channels * $bps); # block align = channels*((bps+7)/8) + print pack('v', $bps * 8); # bits per sample = ((bps+7)/8)*8 + if ($wavx) { + print pack('v', 22); # cbSize + print pack('v', $bps * 8); # validBitsPerSample + print pack('V', $channelmask[$channels]); + # GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} + print "\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71"; + } + # data header + if ($format ne 'wave64') { + print "data"; + print pack('V', $format eq 'wave'? $datasize : 0xffffffff); + } + else { # wave64 + # data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A + print "\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A"; + print pack_64('V', $bigdatasize+16+8); # +16+8 for GUID and size fields + } +} +else { + die; +} + +# write sample data + +if ($sampletype eq 'zero') { + my $chunk = 4096; + my $buf = pack("x[".($channels*$bps*$chunk)."]"); + for (my $s = $samples; $s > 0; $s -= $chunk) { + if ($s < $chunk) { + print substr($buf, 0, $channels*$bps*$s); + } + else { + print $buf; + } + } +} +elsif ($sampletype eq 'rand') { + for (my $s = 0; $s < $samples; $s++) { + for (my $c = 0; $c < $channels; $c++) { + for (my $b = 0; $b < $bps; $b++) { + print pack('C', int(rand(256))); + } + } + } +} +else { + die; +} + +# write padding +if ($format eq 'wave64') { + print pack("x[$padding8]") if $padding8; +} +else { + print "\x00" if $padding; +} + +exit 0; + +sub pack_sane_extended +{ + my $val = shift; + die unless $val > 0; + my $shift; + for ($shift = 0; ($val>>(31-$shift)) == 0; ++$shift) { + } + $val <<= $shift; + my $exponent = 63 - ($shift + 32); + return pack('nNN', $exponent + 16383, $val, 0); +} + +sub pack_64 +{ + my $c = shift; # 'N' for big-endian, 'V' for little-endian, ala pack() + my $v1 = shift; # value, must be Math::BigInt + my $v2 = $v1->copy(); + if ($c eq 'V') { + $v1->band(0xffffffff); + $v2->brsft(32); + } + elsif ($c eq 'N') { + $v2->band(0xffffffff); + $v1->brsft(32); + } + else { + die; + } + return pack("$c$c", 0+$v1->bstr(), 0+$v2->bstr()); +} diff --git a/wavpack-4.4.1/include/wavpack.h b/wavpack-4.4.1/include/wavpack.h new file mode 100644 index 0000000..8ba9d91 --- /dev/null +++ b/wavpack-4.4.1/include/wavpack.h @@ -0,0 +1,300 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wavpack.h + +#ifndef WAVPACK_H +#define WAVPACK_H + +// This header file contains all the definitions required to use the +// functions in "wputils.c" to read and write WavPack files and streams. + +#include + +#if defined(_WIN32) && !defined(__MINGW32__) +#include +typedef unsigned __int64 uint64_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int8 uint8_t; +typedef __int64 int64_t; +typedef __int32 int32_t; +typedef __int16 int16_t; +typedef __int8 int8_t; +typedef float float32_t; +#else +#include +#endif + +typedef unsigned char uchar; + +#if !defined(__GNUC__) || defined(WIN32) +typedef unsigned short ushort; +typedef unsigned int uint; +#endif + +// RIFF / wav header formats (these occur at the beginning of both wav files +// and pre-4.0 WavPack files that are not in the "raw" mode). Generally, an +// application using the library to read or write WavPack files will not be +// concerned with any of these. + +typedef struct { + char ckID [4]; + uint32_t ckSize; + char formType [4]; +} RiffChunkHeader; + +typedef struct { + char ckID [4]; + uint32_t ckSize; +} ChunkHeader; + +#define ChunkHeaderFormat "4L" + +typedef struct { + ushort FormatTag, NumChannels; + uint32_t SampleRate, BytesPerSecond; + ushort BlockAlign, BitsPerSample; + ushort cbSize, ValidBitsPerSample; + int32_t ChannelMask; + ushort SubFormat; + char GUID [14]; +} WaveHeader; + +#define WaveHeaderFormat "SSLLSSSSLS" + +// This is the ONLY structure that occurs in WavPack files (as of version +// 4.0), and is the preamble to every block in both the .wv and .wvc +// files (in little-endian format). Normally, this structure has no use +// to an application using the library to read or write WavPack files, +// but if an application needs to manually parse WavPack files then this +// would be used (with appropriate endian correction). + +typedef struct { + char ckID [4]; + uint32_t ckSize; + short version; + uchar track_no, index_no; + uint32_t total_samples, block_index, block_samples, flags, crc; +} WavpackHeader; + +#define WavpackHeaderFormat "4LS2LLLLL" + +// or-values for WavpackHeader.flags +#define BYTES_STORED 3 // 1-4 bytes/sample +#define MONO_FLAG 4 // not stereo +#define HYBRID_FLAG 8 // hybrid mode +#define JOINT_STEREO 0x10 // joint stereo +#define CROSS_DECORR 0x20 // no-delay cross decorrelation +#define HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define FLOAT_DATA 0x80 // ieee 32-bit floating point data + +#define INT32_DATA 0x100 // special extended int handling +#define HYBRID_BITRATE 0x200 // bitrate noise (hybrid mode only) +#define HYBRID_BALANCE 0x400 // balance noise (hybrid stereo mode only) + +#define INITIAL_BLOCK 0x800 // initial block of multichannel segment +#define FINAL_BLOCK 0x1000 // final block of multichannel segment + +#define SHIFT_LSB 13 +#define SHIFT_MASK (0x1fL << SHIFT_LSB) + +#define MAG_LSB 18 +#define MAG_MASK (0x1fL << MAG_LSB) + +#define SRATE_LSB 23 +#define SRATE_MASK (0xfL << SRATE_LSB) + +#define FALSE_STEREO 0x40000000 // block is stereo, but data is mono + +#define IGNORED_FLAGS 0x18000000 // reserved, but ignore if encountered +#define NEW_SHAPING 0x20000000 // use IIR filter for negative shaping +#define UNKNOWN_FLAGS 0x80000000 // also reserved, but refuse decode if + // encountered + +#define MONO_DATA (MONO_FLAG | FALSE_STEREO) + +#define MIN_STREAM_VERS 0x402 // lowest stream version we'll decode +#define MAX_STREAM_VERS 0x410 // highest stream version we'll decode or encode +#define CUR_STREAM_VERS 0x405 // stream version we are writing now + +// These are the mask bit definitions for the metadata chunk id byte (see format.txt) + +#define ID_UNIQUE 0x3f +#define ID_OPTIONAL_DATA 0x20 +#define ID_ODD_SIZE 0x40 +#define ID_LARGE 0x80 + +#define ID_DUMMY 0x0 +#define ID_ENCODER_INFO 0x1 +#define ID_DECORR_TERMS 0x2 +#define ID_DECORR_WEIGHTS 0x3 +#define ID_DECORR_SAMPLES 0x4 +#define ID_ENTROPY_VARS 0x5 +#define ID_HYBRID_PROFILE 0x6 +#define ID_SHAPING_WEIGHTS 0x7 +#define ID_FLOAT_INFO 0x8 +#define ID_INT32_INFO 0x9 +#define ID_WV_BITSTREAM 0xa +#define ID_WVC_BITSTREAM 0xb +#define ID_WVX_BITSTREAM 0xc +#define ID_CHANNEL_INFO 0xd + +#define ID_RIFF_HEADER (ID_OPTIONAL_DATA | 0x1) +#define ID_RIFF_TRAILER (ID_OPTIONAL_DATA | 0x2) +#define ID_REPLAY_GAIN (ID_OPTIONAL_DATA | 0x3) // never used (APEv2) +#define ID_CUESHEET (ID_OPTIONAL_DATA | 0x4) // never used (APEv2) +#define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) +#define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) +#define ID_SAMPLE_RATE (ID_OPTIONAL_DATA | 0x7) + +///////////////////////// WavPack Configuration /////////////////////////////// + +// This external structure is used during encode to provide configuration to +// the encoding engine and during decoding to provide fle information back to +// the higher level functions. Not all fields are used in both modes. + +typedef struct { + float bitrate, shaping_weight; + int bits_per_sample, bytes_per_sample; + int qmode, flags, xmode, num_channels, float_norm_exp; + int32_t block_samples, extra_flags, sample_rate, channel_mask; + uchar md5_checksum [16], md5_read; + int num_tag_strings; + char **tag_strings; +} WavpackConfig; + +#define CONFIG_HYBRID_FLAG 8 // hybrid mode +#define CONFIG_JOINT_STEREO 0x10 // joint stereo +#define CONFIG_HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define CONFIG_FAST_FLAG 0x200 // fast mode +#define CONFIG_HIGH_FLAG 0x800 // high quality mode +#define CONFIG_VERY_HIGH_FLAG 0x1000 // very high +#define CONFIG_BITRATE_KBPS 0x2000 // bitrate is kbps, not bits / sample +#define CONFIG_SHAPE_OVERRIDE 0x8000 // shaping mode specified +#define CONFIG_JOINT_OVERRIDE 0x10000 // joint-stereo mode specified +#define CONFIG_CREATE_EXE 0x40000 // create executable +#define CONFIG_CREATE_WVC 0x80000 // create correction file +#define CONFIG_OPTIMIZE_WVC 0x100000 // maximize bybrid compression +#define CONFIG_CALC_NOISE 0x800000 // calc noise in hybrid mode +#define CONFIG_EXTRA_MODE 0x2000000 // extra processing mode +#define CONFIG_SKIP_WVX 0x4000000 // no wvx stream w/ floats & big ints +#define CONFIG_MD5_CHECKSUM 0x8000000 // store MD5 signature +#define CONFIG_OPTIMIZE_MONO 0x80000000 // optimize for mono streams posing as stereo + +////////////// Callbacks used for reading & writing WavPack streams ////////// + +typedef struct { + int32_t (*read_bytes)(void *id, void *data, int32_t bcount); + uint32_t (*get_pos)(void *id); + int (*set_pos_abs)(void *id, uint32_t pos); + int (*set_pos_rel)(void *id, int32_t delta, int mode); + int (*push_back_byte)(void *id, int c); + uint32_t (*get_length)(void *id); + int (*can_seek)(void *id); + + // this callback is for writing edited tags only + int32_t (*write_bytes)(void *id, void *data, int32_t bcount); +} WavpackStreamReader; + +typedef int (*WavpackBlockOutput)(void *id, void *data, int32_t bcount); + +//////////////////////////// function prototypes ///////////////////////////// + +// Note: See wputils.c sourcecode for descriptions for using these functions. + +typedef void WavpackContext; + +#ifdef __cplusplus +extern "C" { +#endif + +WavpackContext *WavpackOpenFileInputEx (WavpackStreamReader *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset); +WavpackContext *WavpackOpenFileInput (const wchar_t *infilename, char *error, int flags, int norm_offset); + +#define OPEN_WVC 0x1 // open/read "correction" file +#define OPEN_TAGS 0x2 // read ID3v1 / APEv2 tags (seekable file) +#define OPEN_WRAPPER 0x4 // make audio wrapper available (i.e. RIFF) +#define OPEN_2CH_MAX 0x8 // open multichannel as stereo (no downmix) +#define OPEN_NORMALIZE 0x10 // normalize floating point data to +/- 1.0 +#define OPEN_STREAMING 0x20 // "streaming" mode blindly unpacks blocks + // w/o regard to header file position info +#define OPEN_EDIT_TAGS 0x40 // allow editing of tags + +int WavpackGetMode (WavpackContext *wpc); + +#define MODE_WVC 0x1 +#define MODE_LOSSLESS 0x2 +#define MODE_HYBRID 0x4 +#define MODE_FLOAT 0x8 +#define MODE_VALID_TAG 0x10 +#define MODE_HIGH 0x20 +#define MODE_FAST 0x40 +#define MODE_EXTRA 0x80 +#define MODE_APETAG 0x100 +#define MODE_SFX 0x200 +#define MODE_VERY_HIGH 0x400 +#define MODE_MD5 0x800 + +char *WavpackGetErrorMessage (WavpackContext *wpc); +int WavpackGetVersion (WavpackContext *wpc); +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples); +uint32_t WavpackGetNumSamples (WavpackContext *wpc); +uint32_t WavpackGetSampleIndex (WavpackContext *wpc); +int WavpackGetNumErrors (WavpackContext *wpc); +int WavpackLossyBlocks (WavpackContext *wpc); +int WavpackSeekSample (WavpackContext *wpc, uint32_t sample); +WavpackContext *WavpackCloseFile (WavpackContext *wpc); +uint32_t WavpackGetSampleRate (WavpackContext *wpc); +int WavpackGetBitsPerSample (WavpackContext *wpc); +int WavpackGetBytesPerSample (WavpackContext *wpc); +int WavpackGetNumChannels (WavpackContext *wpc); +int WavpackGetChannelMask (WavpackContext *wpc); +int WavpackGetReducedChannels (WavpackContext *wpc); +int WavpackGetFloatNormExp (WavpackContext *wpc); +int WavpackGetMD5Sum (WavpackContext *wpc, uchar data [16]); +uint32_t WavpackGetWrapperBytes (WavpackContext *wpc); +uchar *WavpackGetWrapperData (WavpackContext *wpc); +void WavpackFreeWrapper (WavpackContext *wpc); +void WavpackSeekTrailingWrapper (WavpackContext *wpc); +double WavpackGetProgress (WavpackContext *wpc); +uint32_t WavpackGetFileSize (WavpackContext *wpc); +double WavpackGetRatio (WavpackContext *wpc); +double WavpackGetAverageBitrate (WavpackContext *wpc, int count_wvc); +double WavpackGetInstantBitrate (WavpackContext *wpc); +int WavpackGetNumTagItems (WavpackContext *wpc); +int WavpackGetTagItem (WavpackContext *wpc, const char *item, char *value, int size); +int WavpackGetTagItemIndexed (WavpackContext *wpc, int index, char *item, int size); +int WavpackAppendTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize); +int WavpackDeleteTagItem (WavpackContext *wpc, const char *item); +int WavpackWriteTag (WavpackContext *wpc); + +WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id); +int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples); +int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount); +int WavpackStoreMD5Sum (WavpackContext *wpc, uchar data [16]); +int WavpackPackInit (WavpackContext *wpc); +int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count); +int WavpackFlushSamples (WavpackContext *wpc); +void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block); +void *WavpackGetWrapperLocation (void *first_block, uint32_t *size); +double WavpackGetEncodedNoise (WavpackContext *wpc, double *peak); + +void WavpackFloatNormalize (int32_t *values, int32_t num_values, int delta_exp); + +void WavpackLittleEndianToNative (void *data, char *format); +void WavpackNativeToLittleEndian (void *data, char *format); + +uint32_t WavpackGetLibraryVersion (); +const char *WavpackGetLibraryVersionString (); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/wavpack-4.4.1/src/wavpack_local.h b/wavpack-4.4.1/src/wavpack_local.h new file mode 100644 index 0000000..5e73024 --- /dev/null +++ b/wavpack-4.4.1/src/wavpack_local.h @@ -0,0 +1,748 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wavpack_local.h + +#ifndef WAVPACK_LOCAL_H +#define WAVPACK_LOCAL_H + +#if defined(WIN32) +#define FASTCALL __fastcall +#else +#define FASTCALL +#endif + +#if defined(WIN32) || \ + (defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN)) +#define BITSTREAM_SHORTS // use "shorts" for reading/writing bitstreams + // (only works on little-endian machines) +#endif + +#include + +// This header file contains all the definitions required by WavPack. + +#if defined(_WIN32) && !defined(__MINGW32__) +#include +typedef unsigned __int64 uint64_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int8 uint8_t; +typedef __int64 int64_t; +typedef __int32 int32_t; +typedef __int16 int16_t; +typedef __int8 int8_t; +typedef float float32_t; +#else +#include +#endif + +typedef unsigned char uchar; + +#if !defined(__GNUC__) || defined(WIN32) +typedef unsigned short ushort; +typedef unsigned int uint; +#endif + +// Because the C99 specification states that "The order of allocation of +// bit-fields within a unit (high-order to low-order or low-order to +// high-order) is implementation-defined" (6.7.2.1), I decided to change +// the representation of floating-point values from a structure of +// bit-fields to a 32-bit integer with access macros. Note that the WavPack +// library doesn't use any floating-point math to implement compression of +// floating-point data (although a little floating-point math is used in +// high-level functions unrelated to the codec). + +typedef int32_t f32; + +#define get_mantissa(f) ((f) & 0x7fffff) +#define get_exponent(f) (((f) >> 23) & 0xff) +#define get_sign(f) (((f) >> 31) & 0x1) + +#define set_mantissa(f,v) (f) ^= (((f) ^ (v)) & 0x7fffff) +#define set_exponent(f,v) (f) ^= (((f) ^ ((v) << 23)) & 0x7f800000) +#define set_sign(f,v) (f) ^= (((f) ^ ((v) << 31)) & 0x80000000) + +#include + +#define FALSE 0 +#define TRUE 1 + +// ID3v1 and APEv2 TAG formats (may occur at the end of WavPack files) + +typedef struct { + char tag_id [3], title [30], artist [30], album [30]; + char year [4], comment [30], genre; +} ID3_Tag; + +typedef struct { + char ID [8]; + int32_t version, length, item_count, flags; + char res [8]; +} APE_Tag_Hdr; + +#define APE_Tag_Hdr_Format "8LLLL" + +typedef struct { + int32_t tag_file_pos; + ID3_Tag id3_tag; + APE_Tag_Hdr ape_tag_hdr; + char *ape_tag_data; +} M_Tag; + +// RIFF / wav header formats (these occur at the beginning of both wav files +// and pre-4.0 WavPack files that are not in the "raw" mode) + +typedef struct { + char ckID [4]; + uint32_t ckSize; + char formType [4]; +} RiffChunkHeader; + +typedef struct { + char ckID [4]; + uint32_t ckSize; +} ChunkHeader; + +#define ChunkHeaderFormat "4L" + +typedef struct { + ushort FormatTag, NumChannels; + uint32_t SampleRate, BytesPerSecond; + ushort BlockAlign, BitsPerSample; + ushort cbSize, ValidBitsPerSample; + int32_t ChannelMask; + ushort SubFormat; + char GUID [14]; +} WaveHeader; + +#define WaveHeaderFormat "SSLLSSSSLS" + +////////////////////////////// WavPack Header ///////////////////////////////// + +// Note that this is the ONLY structure that is written to (or read from) +// WavPack 4.0 files, and is the preamble to every block in both the .wv +// and .wvc files. + +typedef struct { + char ckID [4]; + uint32_t ckSize; + short version; + uchar track_no, index_no; + uint32_t total_samples, block_index, block_samples, flags, crc; +} WavpackHeader; + +#define WavpackHeaderFormat "4LS2LLLLL" + +// or-values for "flags" + +#define BYTES_STORED 3 // 1-4 bytes/sample +#define MONO_FLAG 4 // not stereo +#define HYBRID_FLAG 8 // hybrid mode +#define JOINT_STEREO 0x10 // joint stereo +#define CROSS_DECORR 0x20 // no-delay cross decorrelation +#define HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define FLOAT_DATA 0x80 // ieee 32-bit floating point data + +#define INT32_DATA 0x100 // special extended int handling +#define HYBRID_BITRATE 0x200 // bitrate noise (hybrid mode only) +#define HYBRID_BALANCE 0x400 // balance noise (hybrid stereo mode only) + +#define INITIAL_BLOCK 0x800 // initial block of multichannel segment +#define FINAL_BLOCK 0x1000 // final block of multichannel segment + +#define SHIFT_LSB 13 +#define SHIFT_MASK (0x1fL << SHIFT_LSB) + +#define MAG_LSB 18 +#define MAG_MASK (0x1fL << MAG_LSB) + +#define SRATE_LSB 23 +#define SRATE_MASK (0xfL << SRATE_LSB) + +#define FALSE_STEREO 0x40000000 // block is stereo, but data is mono + +#define IGNORED_FLAGS 0x18000000 // reserved, but ignore if encountered +#define NEW_SHAPING 0x20000000 // use IIR filter for negative shaping +#define UNKNOWN_FLAGS 0x80000000 // also reserved, but refuse decode if + // encountered + +#define MONO_DATA (MONO_FLAG | FALSE_STEREO) + +#define MIN_STREAM_VERS 0x402 // lowest stream version we'll decode +#define MAX_STREAM_VERS 0x410 // highest stream version we'll decode or encode +#define CUR_STREAM_VERS 0x406 // stream version we are [normally] writing now + + +//////////////////////////// WavPack Metadata ///////////////////////////////// + +// This is an internal representation of metadata. + +typedef struct { + int32_t byte_length; + void *data; + uchar id; +} WavpackMetadata; + +#define ID_UNIQUE 0x3f +#define ID_OPTIONAL_DATA 0x20 +#define ID_ODD_SIZE 0x40 +#define ID_LARGE 0x80 + +#define ID_DUMMY 0x0 +#define ID_ENCODER_INFO 0x1 +#define ID_DECORR_TERMS 0x2 +#define ID_DECORR_WEIGHTS 0x3 +#define ID_DECORR_SAMPLES 0x4 +#define ID_ENTROPY_VARS 0x5 +#define ID_HYBRID_PROFILE 0x6 +#define ID_SHAPING_WEIGHTS 0x7 +#define ID_FLOAT_INFO 0x8 +#define ID_INT32_INFO 0x9 +#define ID_WV_BITSTREAM 0xa +#define ID_WVC_BITSTREAM 0xb +#define ID_WVX_BITSTREAM 0xc +#define ID_CHANNEL_INFO 0xd + +#define ID_RIFF_HEADER (ID_OPTIONAL_DATA | 0x1) +#define ID_RIFF_TRAILER (ID_OPTIONAL_DATA | 0x2) +#define ID_REPLAY_GAIN (ID_OPTIONAL_DATA | 0x3) +#define ID_CUESHEET (ID_OPTIONAL_DATA | 0x4) +#define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) +#define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) +#define ID_SAMPLE_RATE (ID_OPTIONAL_DATA | 0x7) + +///////////////////////// WavPack Configuration /////////////////////////////// + +// This internal structure is used during encode to provide configuration to +// the encoding engine and during decoding to provide fle information back to +// the higher level functions. Not all fields are used in both modes. + +typedef struct { + float bitrate, shaping_weight; + int bits_per_sample, bytes_per_sample; + int qmode, flags, xmode, num_channels, float_norm_exp; + int32_t block_samples, extra_flags, sample_rate, channel_mask; + uchar md5_checksum [16], md5_read; + int num_tag_strings; + char **tag_strings; +} WavpackConfig; + +#define CONFIG_BYTES_STORED 3 // 1-4 bytes/sample +#define CONFIG_MONO_FLAG 4 // not stereo +#define CONFIG_HYBRID_FLAG 8 // hybrid mode +#define CONFIG_JOINT_STEREO 0x10 // joint stereo +#define CONFIG_CROSS_DECORR 0x20 // no-delay cross decorrelation +#define CONFIG_HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) +#define CONFIG_FLOAT_DATA 0x80 // ieee 32-bit floating point data + +#define CONFIG_FAST_FLAG 0x200 // fast mode +#define CONFIG_HIGH_FLAG 0x800 // high quality mode +#define CONFIG_VERY_HIGH_FLAG 0x1000 // very high +#define CONFIG_BITRATE_KBPS 0x2000 // bitrate is kbps, not bits / sample +#define CONFIG_AUTO_SHAPING 0x4000 // automatic noise shaping +#define CONFIG_SHAPE_OVERRIDE 0x8000 // shaping mode specified +#define CONFIG_JOINT_OVERRIDE 0x10000 // joint-stereo mode specified +#define CONFIG_CREATE_EXE 0x40000 // create executable +#define CONFIG_CREATE_WVC 0x80000 // create correction file +#define CONFIG_OPTIMIZE_WVC 0x100000 // maximize bybrid compression +#define CONFIG_CALC_NOISE 0x800000 // calc noise in hybrid mode +#define CONFIG_LOSSY_MODE 0x1000000 // obsolete (for information) +#define CONFIG_EXTRA_MODE 0x2000000 // extra processing mode +#define CONFIG_SKIP_WVX 0x4000000 // no wvx stream w/ floats & big ints +#define CONFIG_MD5_CHECKSUM 0x8000000 // compute & store MD5 signature +#define CONFIG_OPTIMIZE_MONO 0x80000000 // optimize for mono streams posing as stereo + +/* + * These config flags are no longer used (or were never used) although there + * may be WavPack files that have some of these bits set in the config + * metadata structure, so be careful reusing them for something else. + * +#define CONFIG_ADOBE_MODE 0x100 // "adobe" mode for 32-bit floats +#define CONFIG_VERY_FAST_FLAG 0x400 // double fast +#define CONFIG_COPY_TIME 0x20000 // copy file-time from source +#define CONFIG_QUALITY_MODE 0x200000 // psychoacoustic quality mode +#define CONFIG_RAW_FLAG 0x400000 // raw mode (not implemented yet) +#define CONFIG_QUIET_MODE 0x10000000 // don't report progress % +#define CONFIG_IGNORE_LENGTH 0x20000000 // ignore length in wav header +#define CONFIG_NEW_RIFF_HEADER 0x40000000 // generate new RIFF wav header + * + */ + +#define EXTRA_SCAN_ONLY 1 +#define EXTRA_STEREO_MODES 2 +#define EXTRA_TRY_DELTAS 8 +#define EXTRA_ADJUST_DELTAS 16 +#define EXTRA_SORT_FIRST 32 +#define EXTRA_BRANCHES 0x1c0 +#define EXTRA_SKIP_8TO16 512 +#define EXTRA_TERMS 0x3c00 +#define EXTRA_DUMP_TERMS 16384 +#define EXTRA_SORT_LAST 32768 + +//////////////////////////////// WavPack Stream /////////////////////////////// + +// This internal structure contains everything required to handle a WavPack +// "stream", which is defined as a stereo or mono stream of audio samples. For +// multichannel audio several of these would be required. Each stream contains +// pointers to hold a complete allocated block of WavPack data, although it's +// possible to decode WavPack blocks without buffering an entire block. + +typedef struct bs { +#ifdef BITSTREAM_SHORTS + unsigned short *buf, *end, *ptr; +#else + unsigned char *buf, *end, *ptr; +#endif + void (*wrap)(struct bs *bs); + int error, bc; + uint32_t sr; +} Bitstream; + +#define MAX_WRAPPER_BYTES 16777216 +#define MAX_STREAMS 8 +#define MAX_NTERMS 16 +#define MAX_TERM 8 + +struct decorr_pass { + int term, delta, weight_A, weight_B; + int32_t samples_A [MAX_TERM], samples_B [MAX_TERM]; + int32_t aweight_A, aweight_B; + int32_t sum_A, sum_B; +}; + +typedef struct { + char joint_stereo, delta, terms [MAX_NTERMS+1]; +} WavpackDecorrSpec; + +struct entropy_data { + uint32_t median [3], slow_level, error_limit; +}; + +struct words_data { + uint32_t bitrate_delta [2], bitrate_acc [2]; + uint32_t pend_data, holding_one, zeros_acc; + int holding_zero, pend_count; + struct entropy_data c [2]; +}; + +typedef struct { + WavpackHeader wphdr; + struct words_data w; + + uchar *blockbuff, *blockend; + uchar *block2buff, *block2end; + int32_t *sample_buffer; + + int bits, num_terms, mute_error, joint_stereo, false_stereo, shift; + int num_decorrs, num_passes, best_decorr, mask_decorr; + uint32_t sample_index, crc, crc_x, crc_wvx; + Bitstream wvbits, wvcbits, wvxbits; + int init_done, wvc_skip; + float delta_decay; + + uchar int32_sent_bits, int32_zeros, int32_ones, int32_dups; + uchar float_flags, float_shift, float_max_exp, float_norm_exp; + + struct { + int32_t shaping_acc [2], shaping_delta [2], error [2]; + double noise_sum, noise_ave, noise_max; + } dc; + + struct decorr_pass decorr_passes [MAX_NTERMS]; + WavpackDecorrSpec *decorr_specs; +} WavpackStream; + +// flags for float_flags: + +#define FLOAT_SHIFT_ONES 1 // bits left-shifted into float = '1' +#define FLOAT_SHIFT_SAME 2 // bits left-shifted into float are the same +#define FLOAT_SHIFT_SENT 4 // bits shifted into float are sent literally +#define FLOAT_ZEROS_SENT 8 // "zeros" are not all real zeros +#define FLOAT_NEG_ZEROS 0x10 // contains negative zeros +#define FLOAT_EXCEPTIONS 0x20 // contains exceptions (inf, nan, etc.) + +/////////////////////////////// WavPack Context /////////////////////////////// + +// This internal structure holds everything required to encode or decode WavPack +// files. It is recommended that direct access to this structure be minimized +// and the provided utilities used instead. + +typedef struct { + int32_t (*read_bytes)(void *id, void *data, int32_t bcount); + uint32_t (*get_pos)(void *id); + int (*set_pos_abs)(void *id, uint32_t pos); + int (*set_pos_rel)(void *id, int32_t delta, int mode); + int (*push_back_byte)(void *id, int c); + uint32_t (*get_length)(void *id); + int (*can_seek)(void *id); + + // this callback is for writing edited tags only + int32_t (*write_bytes)(void *id, void *data, int32_t bcount); +} WavpackStreamReader; + +typedef int (*WavpackBlockOutput)(void *id, void *data, int32_t bcount); + +typedef struct { + WavpackConfig config; + + WavpackMetadata *metadata; + uint32_t metabytes; + int metacount; + + uchar *wrapper_data; + uint32_t wrapper_bytes; + + WavpackBlockOutput blockout; + void *wv_out, *wvc_out; + + WavpackStreamReader *reader; + void *wv_in, *wvc_in; + + uint32_t filelen, file2len, filepos, file2pos, total_samples, crc_errors, first_flags; + int wvc_flag, open_flags, norm_offset, reduced_channels, lossy_blocks, close_files; + uint32_t block_samples, max_samples, acc_samples, initial_index; + int riff_header_added, riff_header_created; + M_Tag m_tag; + + int current_stream, num_streams, stream_version; + WavpackStream *streams [MAX_STREAMS]; + void *stream3; + + char error_message [80]; +} WavpackContext; + +//////////////////////// function prototypes and macros ////////////////////// + +#define CLEAR(destin) memset (&destin, 0, sizeof (destin)); + +// these macros implement the weight application and update operations +// that are at the heart of the decorrelation loops + +#define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10) + +#define apply_weight_f(weight, sample) (((((sample & 0xffff) * weight) >> 9) + \ + (((sample & ~0xffff) >> 9) * weight) + 1) >> 1) + +#if 1 // PERFCOND +#define apply_weight(weight, sample) (sample != (short) sample ? \ + apply_weight_f (weight, sample) : apply_weight_i (weight, sample)) +#else +#define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10)) +#endif + +#if 1 // PERFCOND +#define update_weight(weight, delta, source, result) \ + if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); } +#elif 1 +#define update_weight(weight, delta, source, result) \ + if (source && result) weight += (((source ^ result) >> 30) | 1) * delta; +#else +#define update_weight(weight, delta, source, result) \ + if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta); +#endif + +#define update_weight_d2(weight, delta, source, result) \ + if (source && result) weight -= (((source ^ result) >> 29) & 4) - 2; + +#define update_weight_clip(weight, delta, source, result) \ + if (source && result) { \ + const int32_t s = (source ^ result) >> 31; \ + if ((weight = (weight ^ s) + (delta - s)) > 1024) weight = 1024; \ + weight = (weight ^ s) - s; \ + } + +#define update_weight_clip_d2(weight, delta, source, result) \ + if (source && result) { \ + const int32_t s = (source ^ result) >> 31; \ + if ((weight = (weight ^ s) + (2 - s)) > 1024) weight = 1024; \ + weight = (weight ^ s) - s; \ + } + +// bits.c + +void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end); +void bs_open_write (Bitstream *bs, void *buffer_start, void *buffer_end); +uint32_t bs_close_read (Bitstream *bs); +uint32_t bs_close_write (Bitstream *bs); + +int DoReadFile (FILE *hFile, void *lpBuffer, uint32_t nNumberOfBytesToRead, uint32_t *lpNumberOfBytesRead); +int DoWriteFile (FILE *hFile, void *lpBuffer, uint32_t nNumberOfBytesToWrite, uint32_t *lpNumberOfBytesWritten); +uint32_t DoGetFileSize (FILE *hFile), DoGetFilePosition (FILE *hFile); +int DoSetFilePositionRelative (FILE *hFile, int32_t pos, int mode); +int DoSetFilePositionAbsolute (FILE *hFile, uint32_t pos); +int DoUngetc (int c, FILE *hFile), DoDeleteFile (char *filename); +int DoCloseHandle (FILE *hFile), DoTruncateFile (FILE *hFile); + +#define bs_is_open(bs) ((bs)->ptr != NULL) + +#define getbit(bs) ( \ + (((bs)->bc) ? \ + ((bs)->bc--, (bs)->sr & 1) : \ + (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = sizeof (*((bs)->ptr)) * 8 - 1, ((bs)->sr = *((bs)->ptr)) & 1) \ + ) ? \ + ((bs)->sr >>= 1, 1) : \ + ((bs)->sr >>= 1, 0) \ +) + +#define getbits(value, nbits, bs) { \ + while ((nbits) > (bs)->bc) { \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + (bs)->sr |= (int32_t)*((bs)->ptr) << (bs)->bc; \ + (bs)->bc += sizeof (*((bs)->ptr)) * 8; \ + } \ + *(value) = (bs)->sr; \ + if ((bs)->bc > 32) { \ + (bs)->bc -= (nbits); \ + (bs)->sr = *((bs)->ptr) >> (sizeof (*((bs)->ptr)) * 8 - (bs)->bc); \ + } \ + else { \ + (bs)->bc -= (nbits); \ + (bs)->sr >>= (nbits); \ + } \ +} + +#define putbit(bit, bs) { if (bit) (bs)->sr |= (1 << (bs)->bc); \ + if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \ + *((bs)->ptr) = (bs)->sr; \ + (bs)->sr = (bs)->bc = 0; \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + }} + +#define putbit_0(bs) { \ + if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \ + *((bs)->ptr) = (bs)->sr; \ + (bs)->sr = (bs)->bc = 0; \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + }} + +#define putbit_1(bs) { (bs)->sr |= (1 << (bs)->bc); \ + if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \ + *((bs)->ptr) = (bs)->sr; \ + (bs)->sr = (bs)->bc = 0; \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + }} + +#define putbits(value, nbits, bs) { \ + (bs)->sr |= (int32_t)(value) << (bs)->bc; \ + if (((bs)->bc += (nbits)) >= sizeof (*((bs)->ptr)) * 8) \ + do { \ + *((bs)->ptr) = (bs)->sr; \ + (bs)->sr >>= sizeof (*((bs)->ptr)) * 8; \ + if (((bs)->bc -= sizeof (*((bs)->ptr)) * 8) > 32 - sizeof (*((bs)->ptr)) * 8) \ + (bs)->sr |= ((value) >> ((nbits) - (bs)->bc)); \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + } while ((bs)->bc >= sizeof (*((bs)->ptr)) * 8); \ +} + +void little_endian_to_native (void *data, char *format); +void native_to_little_endian (void *data, char *format); + +// pack.c + +void pack_init (WavpackContext *wpc); +int pack_block (WavpackContext *wpc, int32_t *buffer); +double WavpackGetEncodedNoise (WavpackContext *wpc, double *peak); + +// unpack.c + +int unpack_init (WavpackContext *wpc); +int init_wv_bitstream (WavpackStream *wps, WavpackMetadata *wpmd); +int init_wvc_bitstream (WavpackStream *wps, WavpackMetadata *wpmd); +int init_wvx_bitstream (WavpackStream *wps, WavpackMetadata *wpmd); +int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd); +int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd); +int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd); +int read_shaping_info (WavpackStream *wps, WavpackMetadata *wpmd); +int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); +int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd); +int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd); +int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd); +int read_sample_rate (WavpackContext *wpc, WavpackMetadata *wpmd); +int read_wrapper_data (WavpackContext *wpc, WavpackMetadata *wpmd); +int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count); +int check_crc_error (WavpackContext *wpc); + +// unpack3.c + +WavpackContext *open_file3 (WavpackContext *wpc, char *error); +int32_t unpack_samples3 (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count); +int seek_sample3 (WavpackContext *wpc, uint32_t desired_index); +uint32_t get_sample_index3 (WavpackContext *wpc); +void free_stream3 (WavpackContext *wpc); +int get_version3 (WavpackContext *wpc); + +// metadata.c stuff + +int read_metadata_buff (WavpackMetadata *wpmd, uchar *blockbuff, uchar **buffptr); +int write_metadata_block (WavpackContext *wpc); +int copy_metadata (WavpackMetadata *wpmd, uchar *buffer_start, uchar *buffer_end); +int add_to_metadata (WavpackContext *wpc, void *data, uint32_t bcount, uchar id); +int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd); +void free_metadata (WavpackMetadata *wpmd); + +// words.c stuff + +void init_words (WavpackStream *wps); +void word_set_bitrate (WavpackStream *wps); +void write_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd); +void write_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd); +int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd); +int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd); +int32_t FASTCALL send_word (WavpackStream *wps, int32_t value, int chan); +void send_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples); +int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction); +int32_t get_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples); +void flush_word (WavpackStream *wps); +int32_t nosend_word (WavpackStream *wps, int32_t value, int chan); +void scan_word (WavpackStream *wps, int32_t *samples, uint32_t num_samples, int dir); + +int log2s (int32_t value); +int32_t exp2s (int log); +uint32_t log2buffer (int32_t *samples, uint32_t num_samples, int limit); + +signed char store_weight (int weight); +int restore_weight (signed char weight); + +#define WORD_EOF ((int32_t)(1L << 31)) + +// float.c + +void write_float_info (WavpackStream *wps, WavpackMetadata *wpmd); +int scan_float_data (WavpackStream *wps, f32 *values, int32_t num_values); +void send_float_data (WavpackStream *wps, f32 *values, int32_t num_values); +int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); +void float_values (WavpackStream *wps, int32_t *values, int32_t num_values); +void WavpackFloatNormalize (int32_t *values, int32_t num_values, int delta_exp); + +// extra?.c + +// void analyze_stereo (WavpackContext *wpc, int32_t *samples); +// void analyze_mono (WavpackContext *wpc, int32_t *samples); +void execute_stereo (WavpackContext *wpc, int32_t *samples, int no_history, int do_samples); +void execute_mono (WavpackContext *wpc, int32_t *samples, int no_history, int do_samples); + +// wputils.c + +WavpackContext *WavpackOpenFileInputEx (WavpackStreamReader *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset); +WavpackContext *WavpackOpenFileInput (const wchar_t *infilename, char *error, int flags, int norm_offset); + +#define OPEN_WVC 0x1 // open/read "correction" file +#define OPEN_TAGS 0x2 // read ID3v1 / APEv2 tags (seekable file) +#define OPEN_WRAPPER 0x4 // make audio wrapper available (i.e. RIFF) +#define OPEN_2CH_MAX 0x8 // open multichannel as stereo (no downmix) +#define OPEN_NORMALIZE 0x10 // normalize floating point data to +/- 1.0 +#define OPEN_STREAMING 0x20 // "streaming" mode blindly unpacks blocks + // w/o regard to header file position info +#define OPEN_EDIT_TAGS 0x40 // allow editing of tags + +int WavpackGetMode (WavpackContext *wpc); + +#define MODE_WVC 0x1 +#define MODE_LOSSLESS 0x2 +#define MODE_HYBRID 0x4 +#define MODE_FLOAT 0x8 +#define MODE_VALID_TAG 0x10 +#define MODE_HIGH 0x20 +#define MODE_FAST 0x40 +#define MODE_EXTRA 0x80 +#define MODE_APETAG 0x100 +#define MODE_SFX 0x200 +#define MODE_VERY_HIGH 0x400 +#define MODE_MD5 0x800 + +int WavpackGetVersion (WavpackContext *wpc); +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples); +uint32_t WavpackGetNumSamples (WavpackContext *wpc); +uint32_t WavpackGetSampleIndex (WavpackContext *wpc); +int WavpackGetNumErrors (WavpackContext *wpc); +int WavpackLossyBlocks (WavpackContext *wpc); +int WavpackSeekSample (WavpackContext *wpc, uint32_t sample); +WavpackContext *WavpackCloseFile (WavpackContext *wpc); +uint32_t WavpackGetSampleRate (WavpackContext *wpc); +int WavpackGetBitsPerSample (WavpackContext *wpc); +int WavpackGetBytesPerSample (WavpackContext *wpc); +int WavpackGetNumChannels (WavpackContext *wpc); +int WavpackGetChannelMask (WavpackContext *wpc); +int WavpackGetReducedChannels (WavpackContext *wpc); +int WavpackGetMD5Sum (WavpackContext *wpc, uchar data [16]); +uint32_t WavpackGetWrapperBytes (WavpackContext *wpc); +uchar *WavpackGetWrapperData (WavpackContext *wpc); +void WavpackFreeWrapper (WavpackContext *wpc); +void WavpackSeekTrailingWrapper (WavpackContext *wpc); +double WavpackGetProgress (WavpackContext *wpc); +uint32_t WavpackGetFileSize (WavpackContext *wpc); +double WavpackGetRatio (WavpackContext *wpc); +double WavpackGetAverageBitrate (WavpackContext *wpc, int count_wvc); +double WavpackGetInstantBitrate (WavpackContext *wpc); +int WavpackGetNumTagItems (WavpackContext *wpc); +int WavpackGetTagItem (WavpackContext *wpc, const char *item, char *value, int size); +int WavpackGetTagItemIndexed (WavpackContext *wpc, int index, char *item, int size); +int WavpackAppendTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize); +int WavpackDeleteTagItem (WavpackContext *wpc, const char *item); +int WavpackWriteTag (WavpackContext *wpc); + +WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id); +int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples); +int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount); +int WavpackStoreMD5Sum (WavpackContext *wpc, uchar data [16]); +int WavpackPackInit (WavpackContext *wpc); +int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count); +int WavpackFlushSamples (WavpackContext *wpc); +void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block); +void *WavpackGetWrapperLocation (void *first_block, uint32_t *size); + +void WavpackLittleEndianToNative (void *data, char *format); +void WavpackNativeToLittleEndian (void *data, char *format); + +///////////////////////////// SIMD helper macros ///////////////////////////// + +#ifdef OPT_MMX + +#if defined (__GNUC__) && !defined (__INTEL_COMPILER) +//directly map to gcc's native builtins for faster code + +#if __GNUC__ < 4 +typedef int __di __attribute__ ((__mode__ (__DI__))); +typedef int __m64 __attribute__ ((__mode__ (__V2SI__))); +typedef int __v4hi __attribute__ ((__mode__ (__V4HI__))); +#define _m_paddsw(m1, m2) (__m64) __builtin_ia32_paddsw ((__v4hi) m1, (__v4hi) m2) +#define _m_pand(m1, m2) (__m64) __builtin_ia32_pand ((__di) m1, (__di) m2) +#define _m_pandn(m1, m2) (__m64) __builtin_ia32_pandn ((__di) m1, (__di) m2) +#define _m_pmaddwd(m1, m2) __builtin_ia32_pmaddwd ((__v4hi) m1, (__v4hi) m2) +#define _m_por(m1, m2) (__m64) __builtin_ia32_por ((__di) m1, (__di) m2) +#define _m_pxor(m1, m2) (__m64) __builtin_ia32_pxor ((__di) m1, (__di) m2) +#else +typedef int __m64 __attribute__ ((__vector_size__ (8))); +#define _m_paddsw(m1, m2) __builtin_ia32_paddsw (m1, m2) +#define _m_pand(m1, m2) __builtin_ia32_pand (m1, m2) +#define _m_pandn(m1, m2) __builtin_ia32_pandn (m1, m2) +#define _m_pmaddwd(m1, m2) __builtin_ia32_pmaddwd (m1, m2) +#define _m_por(m1, m2) __builtin_ia32_por (m1, m2) +#define _m_pxor(m1, m2) __builtin_ia32_pxor (m1, m2) +#endif + +#define _m_paddd(m1, m2) __builtin_ia32_paddd (m1, m2) +#define _m_pcmpeqd(m1, m2) __builtin_ia32_pcmpeqd (m1, m2) +#define _m_pslldi(m1, m2) __builtin_ia32_pslld (m1, m2) +#define _m_psradi(m1, m2) __builtin_ia32_psrad (m1, m2) +#define _m_psrldi(m1, m2) __builtin_ia32_psrld (m1, m2) +#define _m_psubd(m1, m2) __builtin_ia32_psubd (m1, m2) +#define _m_punpckhdq(m1, m2) __builtin_ia32_punpckhdq (m1, m2) +#define _m_punpckldq(m1, m2) __builtin_ia32_punpckldq (m1, m2) +#define _mm_empty() __builtin_ia32_emms () +#define _mm_set_pi32(m1, m2) { m2, m1 } +#define _mm_set1_pi32(m) { m, m } + +#else +#include +#endif + +#endif //OPT_MMX + +#endif diff --git a/wavpack-4.4.1/src/wputils.c b/wavpack-4.4.1/src/wputils.c new file mode 100644 index 0000000..31c82d0 --- /dev/null +++ b/wavpack-4.4.1/src/wputils.c @@ -0,0 +1,2881 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wputils.c + +// This module provides a high-level interface to reading and writing WavPack +// files. WavPack input files can be opened as standard "C" streams using a +// provided filename. However, an alternate entry uses stream-reading +// callbacks to make using another file I/O method easy. Note that in this +// case the user application is responsible for finding and opening the .wvc +// file if the use of them is desired. + +// For writing WavPack files there are no I/O routines used; a callback for +// writing completed blocks is provided. + +#include +#include +#include +#include +#include + +#ifdef WIN32 +#include +#endif + +#if defined(WIN32) && !defined(__MINGW32__) +#include "wavpack_version.h" +#endif + +#include "wavpack_local.h" + +#ifdef WIN32 +#define stricmp(x,y) _stricmp(x,y) +#define fileno _fileno +#else +#define stricmp(x,y) strcasecmp(x,y) +#endif + +#ifdef DEBUG_ALLOC +#define malloc malloc_db +#define realloc realloc_db +#define free free_db +void *malloc_db (uint32_t size); +void *realloc_db (void *ptr, uint32_t size); +void free_db (void *ptr); +int32_t dump_alloc (void); +#endif + +static void free_streams (WavpackContext *wpc); + +///////////////////////////// local table storage //////////////////////////// + +const uint32_t sample_rates [] = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, + 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 }; + +///////////////////////////// executable code //////////////////////////////// + +#ifndef NO_TAGS +static int load_tag (WavpackContext *wpc); +static int valid_tag (M_Tag *m_tag); +static void free_tag (M_Tag *m_tag); +#endif + +#if !defined(NO_UNPACK) || defined(INFO_ONLY) + +static uint32_t read_next_header (WavpackStreamReader *reader, void *id, WavpackHeader *wphdr); +static uint32_t seek_final_index (WavpackStreamReader *reader, void *id); +static int read_wvc_block (WavpackContext *wpc); + +// This code provides an interface between the reader callback mechanism that +// WavPack uses internally and the standard fstream C library. + +#ifndef NO_USE_FSTREAMS + +static int32_t read_bytes (void *id, void *data, int32_t bcount) +{ + return (int32_t) fread (data, 1, bcount, (FILE*) id); +} + +static uint32_t get_pos (void *id) +{ + return ftell ((FILE*) id); +} + +static int set_pos_abs (void *id, uint32_t pos) +{ + return fseek (id, pos, SEEK_SET); +} + +static int set_pos_rel (void *id, int32_t delta, int mode) +{ + return fseek (id, delta, mode); +} + +static int push_back_byte (void *id, int c) +{ + return ungetc (c, id); +} + +static uint32_t get_length (void *id) +{ + FILE *file = id; + struct stat statbuf; + + if (!file || fstat (fileno (file), &statbuf) || !(statbuf.st_mode & S_IFREG)) + return 0; + + return statbuf.st_size; +} + +static int can_seek (void *id) +{ + FILE *file = id; + struct stat statbuf; + + return file && !fstat (fileno (file), &statbuf) && (statbuf.st_mode & S_IFREG); +} + +static int32_t write_bytes (void *id, void *data, int32_t bcount) +{ + return (int32_t) fwrite (data, 1, bcount, (FILE*) id); +} + +static WavpackStreamReader freader = { + read_bytes, get_pos, set_pos_abs, set_pos_rel, push_back_byte, get_length, can_seek, + write_bytes +}; + +// This function attempts to open the specified WavPack file for reading. If +// this fails for any reason then an appropriate message is copied to "error" +// (which must accept 80 characters) and NULL is returned, otherwise a +// pointer to a WavpackContext structure is returned (which is used to call +// all other functions in this module). A filename beginning with "-" is +// assumed to be stdin. The "flags" argument has the following bit mask +// values to specify details of the open operation: + +// OPEN_WVC: attempt to open/read "correction" file +// OPEN_TAGS: attempt to read ID3v1 / APEv2 tags (requires seekable file) +// OPEN_WRAPPER: make audio wrapper available (i.e. RIFF) to caller +// OPEN_2CH_MAX: open only first stream of multichannel file (usually L/R) +// OPEN_NORMALIZE: normalize floating point data to +/- 1.0 (w/ offset exp) +// OPEN_STREAMING: blindly unpacks blocks w/o regard to header file position +// OPEN_EDIT_TAGS: allow editing of tags (file must be writable) + +// Version 4.2 of the WavPack library adds the OPEN_STREAMING flag. This is +// essentially a "raw" mode where the library will simply decode any blocks +// fed it through the reader callback, regardless of where those blocks came +// from in a stream. The only requirement is that complete WavPack blocks are +// fed to the decoder (and this may require multiple blocks in multichannel +// mode) and that complete blocks are decoded (even if all samples are not +// actually required). All the blocks must contain the same number of channels +// and bit resolution, and the correction data must be either present or not. +// All other parameters may change from block to block (like lossy/lossless). +// Obviously, in this mode any seeking must be performed by the application +// (and again, decoding must start at the beginning of the block containing +// the seek sample). + +WavpackContext *WavpackOpenFileInput (const wchar_t *infilename, char *error, int flags, int norm_offset) +{ + const wchar_t *file_mode = (flags & OPEN_EDIT_TAGS) ? L"r+b" : L"rb"; + FILE *wv_id, *wvc_id; + WavpackContext *wpc; + + if (*infilename == L'-') { + wv_id = stdin; +#if defined(WIN32) + _setmode (fileno (stdin), O_BINARY); +#endif + } + else if ((wv_id = _wfopen (infilename, file_mode)) == NULL) { + strcpy (error, (flags & OPEN_EDIT_TAGS) ? "can't open file for editing" : "can't open file"); + return NULL; + } + + if (wv_id != stdin && (flags & OPEN_WVC)) { + wchar_t *in2filename = malloc ((wcslen (infilename) + 10) * sizeof(wchar_t)); + + wcscpy (in2filename, infilename); + wcscat (in2filename, L"c"); + wvc_id = _wfopen (in2filename, L"rb"); + free (in2filename); + } + else + wvc_id = NULL; + + wpc = WavpackOpenFileInputEx (&freader, wv_id, wvc_id, error, flags, norm_offset); + + if (!wpc) { + if (wv_id) + fclose (wv_id); + + if (wvc_id) + fclose (wvc_id); + } + else + wpc->close_files = TRUE; + + return wpc; +} + +#endif + +// This function is identical to WavpackOpenFileInput() except that instead +// of providing a filename to open, the caller provides a pointer to a set of +// reader callbacks and instances of up to two streams. The first of these +// streams is required and contains the regular WavPack data stream; the second +// contains the "correction" file if desired. Unlike the standard open +// function which handles the correction file transparently, in this case it +// is the responsibility of the caller to be aware of correction files. + +WavpackContext *WavpackOpenFileInputEx (WavpackStreamReader *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset) +{ + WavpackContext *wpc = malloc (sizeof (WavpackContext)); + WavpackStream *wps; + int num_blocks = 0; + uchar first_byte; + uint32_t bcount; + + if (!wpc) { + strcpy (error, "can't allocate memory"); + return NULL; + } + + CLEAR (*wpc); + wpc->wv_in = wv_id; + wpc->wvc_in = wvc_id; + wpc->reader = reader; + wpc->total_samples = (uint32_t) -1; + wpc->norm_offset = norm_offset; + wpc->open_flags = flags; + + wpc->filelen = wpc->reader->get_length (wpc->wv_in); + +#ifndef NO_TAGS + if ((flags & (OPEN_TAGS | OPEN_EDIT_TAGS)) && wpc->reader->can_seek (wpc->wv_in)) { + load_tag (wpc); + wpc->reader->set_pos_abs (wpc->wv_in, 0); + } +#endif + +#ifndef VER4_ONLY + if (wpc->reader->read_bytes (wpc->wv_in, &first_byte, 1) != 1) { + strcpy (error, "can't read all of WavPack file!"); + return WavpackCloseFile (wpc); + } + + wpc->reader->push_back_byte (wpc->wv_in, first_byte); + + if (first_byte == 'R') + return open_file3 (wpc, error); +#endif + + wpc->streams [0] = wps = malloc (sizeof (WavpackStream)); + wpc->num_streams = 1; + CLEAR (*wps); + + while (!wps->wphdr.block_samples) { + + wpc->filepos = wpc->reader->get_pos (wpc->wv_in); + bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr); + + if (bcount == (uint32_t) -1 || + (!wps->wphdr.block_samples && num_blocks++ > 16)) { + strcpy (error, "not compatible with this version of WavPack file!"); + return WavpackCloseFile (wpc); + } + + wpc->filepos += bcount; + wps->blockbuff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->blockbuff, &wps->wphdr, 32); + + if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != wps->wphdr.ckSize - 24) { + strcpy (error, "can't read all of WavPack file!"); + return WavpackCloseFile (wpc); + } + + wps->init_done = FALSE; + + if (wps->wphdr.block_samples && !(flags & OPEN_STREAMING)) { + if (wps->wphdr.block_index || wps->wphdr.total_samples == (uint32_t) -1) { + wpc->initial_index = wps->wphdr.block_index; + wps->wphdr.block_index = 0; + + if (wpc->reader->can_seek (wpc->wv_in)) { + uint32_t pos_save = wpc->reader->get_pos (wpc->wv_in); + uint32_t final_index = seek_final_index (wpc->reader, wpc->wv_in); + + if (final_index != (uint32_t) -1) + wpc->total_samples = final_index - wpc->initial_index; + + wpc->reader->set_pos_abs (wpc->wv_in, pos_save); + } + } + else + wpc->total_samples = wps->wphdr.total_samples; + } + + if (wpc->wvc_in && wps->wphdr.block_samples && (wps->wphdr.flags & HYBRID_FLAG)) { + wpc->file2len = wpc->reader->get_length (wpc->wvc_in); + wpc->wvc_flag = TRUE; + } + + if (wpc->wvc_flag && !read_wvc_block (wpc)) { + strcpy (error, "not compatible with this version of correction file!"); + return WavpackCloseFile (wpc); + } + + if (!wps->init_done && !unpack_init (wpc)) { + strcpy (error, wpc->error_message [0] ? wpc->error_message : + "not compatible with this version of WavPack file!"); + + return WavpackCloseFile (wpc); + } + + wps->init_done = TRUE; + } + + wpc->config.flags &= ~0xff; + wpc->config.flags |= wps->wphdr.flags & 0xff; + wpc->config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1; + wpc->config.float_norm_exp = wps->float_norm_exp; + + wpc->config.bits_per_sample = (wpc->config.bytes_per_sample * 8) - + ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB); + + if (!wpc->config.sample_rate) { + if (!wps || !wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK) + wpc->config.sample_rate = 44100; + else + wpc->config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB]; + } + + if (!wpc->config.num_channels) { + wpc->config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; + wpc->config.channel_mask = 0x5 - wpc->config.num_channels; + } + + if ((flags & OPEN_2CH_MAX) && !(wps->wphdr.flags & FINAL_BLOCK)) + wpc->reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; + + return wpc; +} + +// This function obtains general information about an open input file and +// returns a mask with the following bit values: + +// MODE_WVC: a .wvc file has been found and will be used for lossless +// MODE_LOSSLESS: file is lossless (either pure or hybrid) +// MODE_HYBRID: file is hybrid mode (either lossy or lossless) +// MODE_FLOAT: audio data is 32-bit ieee floating point +// MODE_VALID_TAG: file conatins a valid ID3v1 or APEv2 tag +// MODE_HIGH: file was created in "high" mode (information only) +// MODE_FAST: file was created in "fast" mode (information only) +// MODE_EXTRA: file was created using "extra" mode (information only) +// MODE_APETAG: file contains a valid APEv2 tag +// MODE_SFX: file was created as a "self-extracting" executable +// MODE_VERY_HIGH: file was created in the "very high" mode (or in +// the "high" mode prior to 4.4) +// MODE_MD5: file contains an MD5 checksum + +int WavpackGetMode (WavpackContext *wpc) +{ + int mode = 0; + + if (wpc) { + if (wpc->config.flags & CONFIG_HYBRID_FLAG) + mode |= MODE_HYBRID; + else if (!(wpc->config.flags & CONFIG_LOSSY_MODE)) + mode |= MODE_LOSSLESS; + + if (wpc->wvc_flag) + mode |= (MODE_LOSSLESS | MODE_WVC); + + if (wpc->lossy_blocks) + mode &= ~MODE_LOSSLESS; + + if (wpc->config.flags & CONFIG_FLOAT_DATA) + mode |= MODE_FLOAT; + + if (wpc->config.flags & CONFIG_HIGH_FLAG) { + mode |= MODE_HIGH; + + if ((wpc->config.flags & CONFIG_VERY_HIGH_FLAG) || + (wpc->streams [0] && wpc->streams [0]->wphdr.version < 0x405)) + mode |= MODE_VERY_HIGH; + } + + if (wpc->config.flags & CONFIG_FAST_FLAG) + mode |= MODE_FAST; + + if (wpc->config.flags & CONFIG_EXTRA_MODE) + mode |= MODE_EXTRA; + + if (wpc->config.flags & CONFIG_CREATE_EXE) + mode |= MODE_SFX; + + if (wpc->config.flags & CONFIG_MD5_CHECKSUM) + mode |= MODE_MD5; + +#ifndef NO_TAGS + if (valid_tag (&wpc->m_tag)) { + mode |= MODE_VALID_TAG; + + if (valid_tag (&wpc->m_tag) == 'A') + mode |= MODE_APETAG; + } +#endif + } + + return mode; +} + +// This function returns the major version number of the WavPack program +// (or library) that created the open file. Currently, this can be 1 to 4. +// Minor versions are not recorded in WavPack files. + +int WavpackGetVersion (WavpackContext *wpc) +{ + if (wpc) { +#ifndef VER4_ONLY + if (wpc->stream3) + return get_version3 (wpc); +#endif + return 4; + } + + return 0; +} + +#endif + +// This function returns a pointer to a string describing the last error +// generated by WavPack. + +char *WavpackGetErrorMessage (WavpackContext *wpc) +{ + return wpc->error_message; +} + +#ifndef NO_UNPACK + +// Unpack the specified number of samples from the current file position. +// Note that "samples" here refers to "complete" samples, which would be +// 2 longs for stereo files or even more for multichannel files, so the +// required memory at "buffer" is 4 * samples * num_channels bytes. The +// audio data is returned right-justified in 32-bit longs in the endian +// mode native to the executing processor. So, if the original data was +// 16-bit, then the values returned would be +/-32k. Floating point data +// can also be returned if the source was floating point data (and this +// can be optionally normalized to +/-1.0 by using the appropriate flag +// in the call to WavpackOpenFileInput ()). The actual number of samples +// unpacked is returned, which should be equal to the number requested unless +// the end of fle is encountered or an error occurs. After all samples have +// been unpacked then 0 will be returned. + +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples) +{ + WavpackStream *wps = wpc->streams [wpc->current_stream = 0]; + uint32_t bcount, samples_unpacked = 0, samples_to_unpack; + int num_channels = wpc->config.num_channels; + int file_done = FALSE; + +#ifndef VER4_ONLY + if (wpc->stream3) + return unpack_samples3 (wpc, buffer, samples); +#endif + + while (samples) { + if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || + wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) { + + if (wpc->wrapper_bytes >= MAX_WRAPPER_BYTES) + break; + + free_streams (wpc); + wpc->filepos = wpc->reader->get_pos (wpc->wv_in); + bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr); + + if (bcount == (uint32_t) -1) + break; + + if (wpc->open_flags & OPEN_STREAMING) + wps->wphdr.block_index = wps->sample_index = 0; + else + wps->wphdr.block_index -= wpc->initial_index; + + wpc->filepos += bcount; + wps->blockbuff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->blockbuff, &wps->wphdr, 32); + + if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != + wps->wphdr.ckSize - 24) { + strcpy (wpc->error_message, "can't read all of last block!"); + wps->wphdr.block_samples = 0; + wps->wphdr.ckSize = 24; + break; + } + + wps->init_done = FALSE; + + if (wps->wphdr.block_samples && wps->sample_index != wps->wphdr.block_index) + wpc->crc_errors++; + + if (wps->wphdr.block_samples && wpc->wvc_flag) + read_wvc_block (wpc); + + if (!wps->wphdr.block_samples) { + if (!wps->init_done && !unpack_init (wpc)) + wpc->crc_errors++; + + wps->init_done = TRUE; + } + } + + if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || + wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) + continue; + + if (wps->sample_index < wps->wphdr.block_index) { + samples_to_unpack = wps->wphdr.block_index - wps->sample_index; + + if (samples_to_unpack > 262144) { + strcpy (wpc->error_message, "discontinuity found, aborting file!"); + wps->wphdr.block_samples = 0; + wps->wphdr.ckSize = 24; + break; + } + + if (samples_to_unpack > samples) + samples_to_unpack = samples; + + wps->sample_index += samples_to_unpack; + samples_unpacked += samples_to_unpack; + samples -= samples_to_unpack; + + if (wpc->reduced_channels) + samples_to_unpack *= wpc->reduced_channels; + else + samples_to_unpack *= num_channels; + + while (samples_to_unpack--) + *buffer++ = 0; + + continue; + } + + samples_to_unpack = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index; + + if (samples_to_unpack > samples) + samples_to_unpack = samples; + + if (!wps->init_done && !unpack_init (wpc)) + wpc->crc_errors++; + + wps->init_done = TRUE; + + if (!wpc->reduced_channels && !(wps->wphdr.flags & FINAL_BLOCK)) { + int32_t *temp_buffer = malloc (samples_to_unpack * 8), *src, *dst; + int offset = 0; + uint32_t samcnt; + + while (1) { + if (wpc->current_stream == wpc->num_streams) { + wps = wpc->streams [wpc->num_streams++] = malloc (sizeof (WavpackStream)); + CLEAR (*wps); + bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr); + + if (bcount == (uint32_t) -1) { + wpc->streams [0]->wphdr.block_samples = 0; + wpc->streams [0]->wphdr.ckSize = 24; + file_done = TRUE; + break; + } + + if (wpc->open_flags & OPEN_STREAMING) + wps->wphdr.block_index = wps->sample_index = 0; + else + wps->wphdr.block_index -= wpc->initial_index; + + wps->blockbuff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->blockbuff, &wps->wphdr, 32); + + if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != + wps->wphdr.ckSize - 24) { + wpc->streams [0]->wphdr.block_samples = 0; + wpc->streams [0]->wphdr.ckSize = 24; + file_done = TRUE; + break; + } + + wps->init_done = FALSE; + + if (wpc->wvc_flag) + read_wvc_block (wpc); + + if (!wps->init_done && !unpack_init (wpc)) + wpc->crc_errors++; + + wps->init_done = TRUE; + } + else + wps = wpc->streams [wpc->current_stream]; + + unpack_samples (wpc, src = temp_buffer, samples_to_unpack); + samcnt = samples_to_unpack; + dst = buffer + offset; + + if (wps->wphdr.flags & MONO_FLAG) { + while (samcnt--) { + dst [0] = *src++; + dst += num_channels; + } + + offset++; + } + else { + while (samcnt--) { + dst [0] = *src++; + dst [1] = *src++; + dst += num_channels; + } + + offset += 2; + } + + if ((wps->wphdr.flags & FINAL_BLOCK) || wpc->num_streams == MAX_STREAMS) + break; + else + wpc->current_stream++; + } + + wps = wpc->streams [wpc->current_stream = 0]; + free (temp_buffer); + } + else + unpack_samples (wpc, buffer, samples_to_unpack); + + if (!(wps->wphdr.flags & FINAL_BLOCK) && wpc->num_streams == MAX_STREAMS) { + strcpy (wpc->error_message, "too many channels!"); + break; + } + + if (file_done) { + strcpy (wpc->error_message, "can't read all of last block!"); + break; + } + + if (wpc->reduced_channels) + buffer += samples_to_unpack * wpc->reduced_channels; + else + buffer += samples_to_unpack * num_channels; + + samples_unpacked += samples_to_unpack; + samples -= samples_to_unpack; + + if (wps->sample_index == wps->wphdr.block_index + wps->wphdr.block_samples) { + if (check_crc_error (wpc) && wps->blockbuff) { + + if (wpc->reader->can_seek (wpc->wv_in)) { + int32_t rseek = ((WavpackHeader *) wps->blockbuff)->ckSize / 3; + wpc->reader->set_pos_rel (wpc->wv_in, (rseek > 16384) ? -16384 : -rseek, SEEK_CUR); + } + + if (wpc->wvc_flag && wps->block2buff && wpc->reader->can_seek (wpc->wvc_in)) { + int32_t rseek = ((WavpackHeader *) wps->block2buff)->ckSize / 3; + wpc->reader->set_pos_rel (wpc->wvc_in, (rseek > 16384) ? -16384 : -rseek, SEEK_CUR); + } + + wpc->crc_errors++; + } + } + + if (wpc->total_samples != (uint32_t) -1 && wps->sample_index == wpc->total_samples) + break; + } + + return samples_unpacked; +} + +#ifndef NO_SEEKING + +static uint32_t find_sample (WavpackContext *wpc, void *infile, uint32_t header_pos, uint32_t sample); + +// Seek to the specifed sample index, returning TRUE on success. Note that +// files generated with version 4.0 or newer will seek almost immediately. +// Older files can take quite long if required to seek through unplayed +// portions of the file, but will create a seek map so that reverse seeks +// (or forward seeks to already scanned areas) will be very fast. After a +// FALSE return the file should not be accessed again (other than to close +// it); this is a fatal error. + +int WavpackSeekSample (WavpackContext *wpc, uint32_t sample) +{ + WavpackStream *wps = wpc->streams [wpc->current_stream = 0]; + uint32_t bcount, samples_to_skip; + int32_t *buffer; + + if (wpc->total_samples == (uint32_t) -1 || sample >= wpc->total_samples || + !wpc->reader->can_seek (wpc->wv_in) || (wpc->open_flags & OPEN_STREAMING) || + (wpc->wvc_flag && !wpc->reader->can_seek (wpc->wvc_in))) + return FALSE; + +#ifndef VER4_ONLY + if (wpc->stream3) + return seek_sample3 (wpc, sample); +#endif + + if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || sample < wps->wphdr.block_index || + sample >= wps->wphdr.block_index + wps->wphdr.block_samples) { + + free_streams (wpc); + wpc->filepos = find_sample (wpc, wpc->wv_in, wpc->filepos, sample); + + if (wpc->filepos == (uint32_t) -1) + return FALSE; + + if (wpc->wvc_flag) { + wpc->file2pos = find_sample (wpc, wpc->wvc_in, 0, sample); + + if (wpc->file2pos == (uint32_t) -1) + return FALSE; + } + } + + if (!wps->blockbuff) { + wpc->reader->set_pos_abs (wpc->wv_in, wpc->filepos); + wpc->reader->read_bytes (wpc->wv_in, &wps->wphdr, sizeof (WavpackHeader)); + little_endian_to_native (&wps->wphdr, WavpackHeaderFormat); + wps->wphdr.block_index -= wpc->initial_index; + wps->blockbuff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->blockbuff, &wps->wphdr, sizeof (WavpackHeader)); + + if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + sizeof (WavpackHeader), wps->wphdr.ckSize - 24) != + wps->wphdr.ckSize - 24) { + free_streams (wpc); + return FALSE; + } + + wps->init_done = FALSE; + + if (wpc->wvc_flag) { + wpc->reader->set_pos_abs (wpc->wvc_in, wpc->file2pos); + wpc->reader->read_bytes (wpc->wvc_in, &wps->wphdr, sizeof (WavpackHeader)); + little_endian_to_native (&wps->wphdr, WavpackHeaderFormat); + wps->wphdr.block_index -= wpc->initial_index; + wps->block2buff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->block2buff, &wps->wphdr, sizeof (WavpackHeader)); + + if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + sizeof (WavpackHeader), wps->wphdr.ckSize - 24) != + wps->wphdr.ckSize - 24) { + free_streams (wpc); + return FALSE; + } + } + + if (!wps->init_done && !unpack_init (wpc)) { + free_streams (wpc); + return FALSE; + } + + wps->init_done = TRUE; + } + + while (!wpc->reduced_channels && !(wps->wphdr.flags & FINAL_BLOCK)) { + if (++wpc->current_stream == wpc->num_streams) { + + if (wpc->num_streams == MAX_STREAMS) { + free_streams (wpc); + return FALSE; + } + + wps = wpc->streams [wpc->num_streams++] = malloc (sizeof (WavpackStream)); + CLEAR (*wps); + bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr); + + if (bcount == (uint32_t) -1) { + free_streams (wpc); + return FALSE; + } + + wps->blockbuff = malloc (wps->wphdr.ckSize + 8); + memcpy (wps->blockbuff, &wps->wphdr, 32); + + if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != + wps->wphdr.ckSize - 24) { + free_streams (wpc); + return FALSE; + } + + wps->init_done = FALSE; + + if (wpc->wvc_flag && !read_wvc_block (wpc)) { + free_streams (wpc); + return FALSE; + } + + if (!wps->init_done && !unpack_init (wpc)) { + free_streams (wpc); + return FALSE; + } + + wps->init_done = TRUE; + } + else + wps = wpc->streams [wpc->current_stream]; + } + + if (sample < wps->sample_index) { + for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) + if (!unpack_init (wpc)) + return FALSE; + else + wpc->streams [wpc->current_stream]->init_done = TRUE; + } + + samples_to_skip = sample - wps->sample_index; + + if (samples_to_skip > 131072) { + free_streams (wpc); + return FALSE; + } + + if (samples_to_skip) { + buffer = malloc (samples_to_skip * 8); + + for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) + unpack_samples (wpc, buffer, samples_to_skip); + + free (buffer); + } + + wpc->current_stream = 0; + return TRUE; +} + +#endif + +#ifndef NO_TAGS + +// Count and return the total number of tag items in the specified file. + +int WavpackGetNumTagItems (WavpackContext *wpc) +{ + int i = 0; + + while (WavpackGetTagItemIndexed (wpc, i, NULL, 0)) + ++i; + + return i; +} + +// Attempt to get the specified item from the specified file's ID3v1 or APEv2 +// tag. The "size" parameter specifies the amount of space available at "value", +// if the desired item will not fit in this space then ellipses (...) will +// be appended and the string terminated. Only text data are supported. The +// actual length of the string is returned (or 0 if no matching value found). +// Note that with APEv2 tags the length might not be the same as the number of +// characters because UTF-8 encoding is used. Also, APEv2 tags can have multiple +// (NULL separated) strings for a single value (this is why the length is +// returned). If this function is called with a NULL "value" pointer (or a +// zero "length") then only the actual length of the value data is returned +// (not counting the terminating NULL). This can be used to determine the +// actual memory to be allocated beforehand. + +static int get_ape_tag_item (M_Tag *m_tag, const char *item, char *value, int size); +static int get_id3_tag_item (M_Tag *m_tag, const char *item, char *value, int size); + +int WavpackGetTagItem (WavpackContext *wpc, const char *item, char *value, int size) +{ + M_Tag *m_tag = &wpc->m_tag; + + if (value && size) + *value = 0; + + if (m_tag->ape_tag_hdr.ID [0] == 'A') + return get_ape_tag_item (m_tag, item, value, size); + else if (m_tag->id3_tag.tag_id [0] == 'T') + return get_id3_tag_item (m_tag, item, value, size); + else + return 0; +} + +static int get_ape_tag_item (M_Tag *m_tag, const char *item, char *value, int size) +{ + char *p = m_tag->ape_tag_data; + char *q = p + m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr); + int i; + + for (i = 0; i < m_tag->ape_tag_hdr.item_count; ++i) { + int vsize, flags, isize; + + vsize = * (int32_t *) p; p += 4; + flags = * (int32_t *) p; p += 4; + isize = (int) strlen (p); + + little_endian_to_native (&vsize, "L"); + little_endian_to_native (&flags, "L"); + + if (p + isize + vsize + 1 > q) + break; + + if (isize && vsize && !stricmp (item, p) && !(flags & 6)) { + + if (!value || !size) + return vsize; + + if (vsize < size) { + memcpy (value, p + isize + 1, vsize); + value [vsize] = 0; + return vsize; + } + else if (size >= 4) { + memcpy (value, p + isize + 1, size - 1); + value [size - 4] = value [size - 3] = value [size - 2] = '.'; + value [size - 1] = 0; + return size - 1; + } + else + return 0; + } + else + p += isize + vsize + 1; + } + + return 0; +} + +static void tagcpy (char *dest, char *src, int tag_size); + +static int get_id3_tag_item (M_Tag *m_tag, const char *item, char *value, int size) +{ + char lvalue [64]; + int len; + + lvalue [0] = 0; + + if (!stricmp (item, "title")) + tagcpy (lvalue, m_tag->id3_tag.title, sizeof (m_tag->id3_tag.title)); + else if (!stricmp (item, "artist")) + tagcpy (lvalue, m_tag->id3_tag.artist, sizeof (m_tag->id3_tag.artist)); + else if (!stricmp (item, "album")) + tagcpy (lvalue, m_tag->id3_tag.album, sizeof (m_tag->id3_tag.album)); + else if (!stricmp (item, "year")) + tagcpy (lvalue, m_tag->id3_tag.year, sizeof (m_tag->id3_tag.year)); + else if (!stricmp (item, "comment")) + tagcpy (lvalue, m_tag->id3_tag.comment, sizeof (m_tag->id3_tag.comment)); + else if (!stricmp (item, "track") && m_tag->id3_tag.comment [29] && !m_tag->id3_tag.comment [28]) + sprintf (lvalue, "%d", m_tag->id3_tag.comment [29]); + else + return 0; + + len = (int) strlen (lvalue); + + if (!value || !size) + return len; + + if (len < size) { + strcpy (value, lvalue); + return len; + } + else if (size >= 4) { + strncpy (value, lvalue, size - 1); + value [size - 4] = value [size - 3] = value [size - 2] = '.'; + value [size - 1] = 0; + return size - 1; + } + else + return 0; +} + +// This function looks up the tag item name by index and is used when the +// application wants to access all the items in the file's ID3v1 or APEv2 tag. +// Note that this function accesses only the item's name; WavpackGetTagItem() +// still must be called to get the actual value. The "size" parameter specifies +// the amount of space available at "item", if the desired item will not fit in +// this space then ellipses (...) will be appended and the string terminated. +// The actual length of the string is returned (or 0 if no item exists for +// index). If this function is called with a NULL "value" pointer (or a +// zero "length") then only the actual length of the item name is returned +// (not counting the terminating NULL). This can be used to determine the +// actual memory to be allocated beforehand. + +static int get_ape_tag_item_indexed (M_Tag *m_tag, int index, char *item, int size); +static int get_id3_tag_item_indexed (M_Tag *m_tag, int index, char *item, int size); + +int WavpackGetTagItemIndexed (WavpackContext *wpc, int index, char *item, int size) +{ + M_Tag *m_tag = &wpc->m_tag; + + if (item && size) + *item = 0; + + if (m_tag->ape_tag_hdr.ID [0] == 'A') + return get_ape_tag_item_indexed (m_tag, index, item, size); + else if (m_tag->id3_tag.tag_id [0] == 'T') + return get_id3_tag_item_indexed (m_tag, index, item, size); + else + return 0; +} + +static int get_ape_tag_item_indexed (M_Tag *m_tag, int index, char *item, int size) +{ + char *p = m_tag->ape_tag_data; + char *q = p + m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr); + int i; + + for (i = 0; i < m_tag->ape_tag_hdr.item_count && index >= 0; ++i) { + int vsize, flags, isize; + + vsize = * (int32_t *) p; p += 4; + flags = * (int32_t *) p; p += 4; + isize = (int) strlen (p); + + little_endian_to_native (&vsize, "L"); + little_endian_to_native (&flags, "L"); + + if (p + isize + vsize + 1 > q) + break; + + if (isize && vsize && !(flags & 6) && !index--) { + + if (!item || !size) + return isize; + + if (isize < size) { + memcpy (item, p, isize); + item [isize] = 0; + return isize; + } + else if (size >= 4) { + memcpy (item, p, size - 1); + item [size - 4] = item [size - 3] = item [size - 2] = '.'; + item [size - 1] = 0; + return size - 1; + } + else + return 0; + } + else + p += isize + vsize + 1; + } + + return 0; +} + +static int tagdata (char *src, int tag_size); + +static int get_id3_tag_item_indexed (M_Tag *m_tag, int index, char *item, int size) +{ + char lvalue [16]; + int len; + + lvalue [0] = 0; + + if (tagdata (m_tag->id3_tag.title, sizeof (m_tag->id3_tag.title)) && !index--) + strcpy (lvalue, "Title"); + else if (tagdata (m_tag->id3_tag.artist, sizeof (m_tag->id3_tag.artist)) && !index--) + strcpy (lvalue, "Artist"); + else if (tagdata (m_tag->id3_tag.album, sizeof (m_tag->id3_tag.album)) && !index--) + strcpy (lvalue, "Album"); + else if (tagdata (m_tag->id3_tag.year, sizeof (m_tag->id3_tag.year)) && !index--) + strcpy (lvalue, "Year"); + else if (tagdata (m_tag->id3_tag.comment, sizeof (m_tag->id3_tag.comment)) && !index--) + strcpy (lvalue, "Comment"); + else if (m_tag->id3_tag.comment [29] && !m_tag->id3_tag.comment [28] && !index--) + strcpy (lvalue, "Track"); + else + return 0; + + len = (int) strlen (lvalue); + + if (!item || !size) + return len; + + if (len < size) { + strcpy (item, lvalue); + return len; + } + else if (size >= 4) { + strncpy (item, lvalue, size - 1); + item [size - 4] = item [size - 3] = item [size - 2] = '.'; + item [size - 1] = 0; + return size - 1; + } + else + return 0; +} + +#endif + +#endif + +#ifndef NO_PACK + +// Open context for writing WavPack files. The returned context pointer is used +// in all following calls to the library. The "blockout" function will be used +// to store the actual completed WavPack blocks and will be called with the id +// pointers containing user defined data (one for the wv file and one for the +// wvc file). A return value of NULL indicates that memory could not be +// allocated for the context. + +WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id) +{ + WavpackContext *wpc = malloc (sizeof (WavpackContext)); + + if (!wpc) + return NULL; + + CLEAR (*wpc); + wpc->blockout = blockout; + wpc->wv_out = wv_id; + wpc->wvc_out = wvc_id; + return wpc; +} + +// Set configuration for writing WavPack files. This must be done before +// sending any actual samples, however it is okay to send wrapper or other +// metadata before calling this. The "config" structure contains the following +// required information: + +// config->bytes_per_sample see WavpackGetBytesPerSample() for info +// config->bits_per_sample see WavpackGetBitsPerSample() for info +// config->channel_mask Microsoft standard (mono = 4, stereo = 3) +// config->num_channels self evident +// config->sample_rate self evident + +// In addition, the following fields and flags may be set: + +// config->flags: +// -------------- +// o CONFIG_HYBRID_FLAG select hybrid mode (must set bitrate) +// o CONFIG_JOINT_STEREO select joint stereo (must set override also) +// o CONFIG_JOINT_OVERRIDE override default joint stereo selection +// o CONFIG_HYBRID_SHAPE select hybrid noise shaping (set override & +// shaping_weight != 0.0) +// o CONFIG_SHAPE_OVERRIDE override default hybrid noise shaping +// (set CONFIG_HYBRID_SHAPE and shaping_weight) +// o CONFIG_FAST_FLAG "fast" compression mode +// o CONFIG_HIGH_FLAG "high" compression mode +// o CONFIG_BITRATE_KBPS hybrid bitrate is kbps, not bits / sample +// o CONFIG_CREATE_WVC create correction file +// o CONFIG_OPTIMIZE_WVC maximize bybrid compression (-cc option) +// o CONFIG_CALC_NOISE calc noise in hybrid mode +// o CONFIG_EXTRA_MODE extra processing mode (slow!) +// o CONFIG_SKIP_WVX no wvx stream for floats & large ints +// o CONFIG_MD5_CHECKSUM specify if you plan to store MD5 signature +// o CONFIG_CREATE_EXE specify if you plan to prepend sfx module +// o CONFIG_OPTIMIZE_MONO detect and optimize for mono files posing as +// stereo (uses a more recent stream format that +// is not compatible with decoders < 4.3) + +// config->bitrate hybrid bitrate in either bits/sample or kbps +// config->shaping_weight hybrid noise shaping coefficient override +// config->block_samples force samples per WavPack block (0 = use deflt) +// config->float_norm_exp select floating-point data (127 for +/-1.0) +// config->xmode extra mode processing value override + +// If the number of samples to be written is known then it should be passed +// here. If the duration is not known then pass -1. In the case that the size +// is not known (or the writing is terminated early) then it is suggested that +// the application retrieve the first block written and let the library update +// the total samples indication. A function is provided to do this update and +// it should be done to the "correction" file also. If this cannot be done +// (because a pipe is being used, for instance) then a valid WavPack will still +// be created, but when applications want to access that file they will have +// to seek all the way to the end to determine the actual duration. Also, if +// a RIFF header has been included then it should be updated as well or the +// WavPack file will not be directly unpackable to a valid wav file (although +// it will still be usable by itself). A return of FALSE indicates an error. + +int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples) +{ + uint32_t flags = (config->bytes_per_sample - 1), bps = 0, shift = 0; + uint32_t chan_mask = config->channel_mask; + int num_chans = config->num_channels; + int i; + + wpc->total_samples = total_samples; + wpc->config.sample_rate = config->sample_rate; + wpc->config.num_channels = config->num_channels; + wpc->config.channel_mask = config->channel_mask; + wpc->config.bits_per_sample = config->bits_per_sample; + wpc->config.bytes_per_sample = config->bytes_per_sample; + wpc->config.block_samples = config->block_samples; + wpc->config.flags = config->flags; + + if (config->flags & CONFIG_VERY_HIGH_FLAG) + config->flags |= CONFIG_HIGH_FLAG; + + if (config->float_norm_exp) { + wpc->config.float_norm_exp = config->float_norm_exp; + wpc->config.flags |= CONFIG_FLOAT_DATA; + flags |= FLOAT_DATA; + } + else + shift = (config->bytes_per_sample * 8) - config->bits_per_sample; + + for (i = 0; i < 15; ++i) + if (wpc->config.sample_rate == sample_rates [i]) + break; + + flags |= i << SRATE_LSB; + flags |= shift << SHIFT_LSB; + + if (config->flags & CONFIG_HYBRID_FLAG) { + flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE; + + if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) { + wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING; + flags |= HYBRID_SHAPE | NEW_SHAPING; + } + else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) { + wpc->config.shaping_weight = config->shaping_weight; + flags |= HYBRID_SHAPE | NEW_SHAPING; + } + + if (wpc->config.flags & CONFIG_OPTIMIZE_WVC) + flags |= CROSS_DECORR; + + if (config->flags & CONFIG_BITRATE_KBPS) { + bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5); + + if (bps > (64 << 8)) + bps = 64 << 8; + } + else + bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5); + } + else + flags |= CROSS_DECORR; + + if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO)) + flags |= JOINT_STEREO; + + if (config->flags & CONFIG_CREATE_WVC) + wpc->wvc_flag = TRUE; + + wpc->stream_version = (config->flags & CONFIG_OPTIMIZE_MONO) ? MAX_STREAM_VERS : CUR_STREAM_VERS; + + for (wpc->current_stream = 0; num_chans; wpc->current_stream++) { + WavpackStream *wps = malloc (sizeof (WavpackStream)); + uint32_t stereo_mask, mono_mask; + int pos, chans = 0; + + wpc->streams [wpc->current_stream] = wps; + CLEAR (*wps); + + for (pos = 1; pos <= 18; ++pos) { + stereo_mask = 3 << (pos - 1); + mono_mask = 1 << (pos - 1); + + if ((chan_mask & stereo_mask) == stereo_mask && (mono_mask & 0x251)) { + chan_mask &= ~stereo_mask; + chans = 2; + break; + } + else if (chan_mask & mono_mask) { + chan_mask &= ~mono_mask; + chans = 1; + break; + } + } + + if (!chans) + chans = num_chans > 1 ? 2 : 1; + + num_chans -= chans; + + if (num_chans && wpc->current_stream == MAX_STREAMS - 1) + break; + + memcpy (wps->wphdr.ckID, "wvpk", 4); + wps->wphdr.ckSize = sizeof (WavpackHeader) - 8; + wps->wphdr.total_samples = wpc->total_samples; + wps->wphdr.version = wpc->stream_version; + wps->wphdr.flags = flags; + wps->bits = bps; + + if (!wpc->current_stream) + wps->wphdr.flags |= INITIAL_BLOCK; + + if (!num_chans) + wps->wphdr.flags |= FINAL_BLOCK; + + if (chans == 1) { + wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE); + wps->wphdr.flags |= MONO_FLAG; + } + } + + wpc->num_streams = wpc->current_stream; + wpc->current_stream = 0; + + if (num_chans) { + strcpy (wpc->error_message, "too many channels!"); + return FALSE; + } + + if (config->flags & CONFIG_EXTRA_MODE) + wpc->config.xmode = config->xmode ? config->xmode : 1; + + return TRUE; +} + +// Prepare to actually pack samples by determining the size of the WavPack +// blocks and allocating sample buffers and initializing each stream. Call +// after WavpackSetConfiguration() and before WavpackPackSamples(). A return +// of FALSE indicates an error. + +int WavpackPackInit (WavpackContext *wpc) +{ + if (wpc->metabytes > 4096) + write_metadata_block (wpc); + + if (wpc->config.block_samples) + wpc->block_samples = wpc->config.block_samples; + else { + if (wpc->config.flags & CONFIG_HIGH_FLAG) + wpc->block_samples = wpc->config.sample_rate; + else if (!(wpc->config.sample_rate % 2)) + wpc->block_samples = wpc->config.sample_rate / 2; + else + wpc->block_samples = wpc->config.sample_rate; + + while (wpc->block_samples * wpc->config.num_channels > 150000) + wpc->block_samples /= 2; + + while (wpc->block_samples * wpc->config.num_channels < 40000) + wpc->block_samples *= 2; + } + + wpc->max_samples = wpc->block_samples + (wpc->block_samples >> 1); + + for (wpc->current_stream = 0; wpc->streams [wpc->current_stream]; wpc->current_stream++) { + WavpackStream *wps = wpc->streams [wpc->current_stream]; + + wps->sample_buffer = malloc (wpc->max_samples * (wps->wphdr.flags & MONO_FLAG ? 4 : 8)); + pack_init (wpc); + } + + return TRUE; +} + +// Pack the specified samples. Samples must be stored in longs in the native +// endian format of the executing processor. The number of samples specified +// indicates composite samples (sometimes called "frames"). So, the actual +// number of data points would be this "sample_count" times the number of +// channels. Note that samples are accumulated here until enough exist to +// create a complete WavPack block (or several blocks for multichannel audio). +// If an application wants to break a block at a specific sample, then it must +// simply call WavpackFlushSamples() to force an early termination. Completed +// WavPack blocks are send to the function provided in the initial call to +// WavpackOpenFileOutput(). A return of FALSE indicates an error. + +static int pack_streams (WavpackContext *wpc, uint32_t block_samples); +static int create_riff_header (WavpackContext *wpc); + +int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count) +{ + int nch = wpc->config.num_channels; + + while (sample_count) { + int32_t *source_pointer = sample_buffer; + uint samples_to_copy; + + if (!wpc->riff_header_added && !wpc->riff_header_created && !create_riff_header (wpc)) + return FALSE; + + if (wpc->acc_samples + sample_count > wpc->max_samples) + samples_to_copy = wpc->max_samples - wpc->acc_samples; + else + samples_to_copy = sample_count; + + for (wpc->current_stream = 0; wpc->streams [wpc->current_stream]; wpc->current_stream++) { + WavpackStream *wps = wpc->streams [wpc->current_stream]; + int32_t *dptr, *sptr, cnt; + + dptr = wps->sample_buffer + wpc->acc_samples * (wps->wphdr.flags & MONO_FLAG ? 1 : 2); + sptr = source_pointer; + cnt = samples_to_copy; + + if (wps->wphdr.flags & MONO_FLAG) { + while (cnt--) { + *dptr++ = *sptr; + sptr += nch; + } + + source_pointer++; + } + else { + while (cnt--) { + *dptr++ = sptr [0]; + *dptr++ = sptr [1]; + sptr += nch; + } + + source_pointer += 2; + } + } + + sample_buffer += samples_to_copy * nch; + sample_count -= samples_to_copy; + + if ((wpc->acc_samples += samples_to_copy) == wpc->max_samples && + !pack_streams (wpc, wpc->block_samples)) + return FALSE; + } + + return TRUE; +} + +// Flush all accumulated samples into WavPack blocks. This is normally called +// after all samples have been sent to WavpackPackSamples(), but can also be +// called to terminate a WavPack block at a specific sample (in other words it +// is possible to continue after this operation). This is also called to +// dump non-audio blocks like those holding metadata for various purposes. +// A return of FALSE indicates an error. + +int WavpackFlushSamples (WavpackContext *wpc) +{ + while (wpc->acc_samples) { + uint32_t block_samples; + + if (wpc->acc_samples > wpc->block_samples) + block_samples = wpc->acc_samples / 2; + else + block_samples = wpc->acc_samples; + + if (!pack_streams (wpc, block_samples)) + return FALSE; + } + + if (wpc->metacount) + write_metadata_block (wpc); + + return TRUE; +} + +// Note: The following function is no longer required because a proper wav +// header is now automatically generated for the application. However, if the +// application wants to generate its own header or wants to include additional +// chunks, then this function can still be used in which case the automatic +// wav header generation is suppressed. + +// Add wrapper (currently RIFF only) to WavPack blocks. This should be called +// before sending any audio samples for the RIFF header or after all samples +// have been sent for any RIFF trailer. WavpackFlushSamples() should be called +// between sending the last samples and calling this for trailer data to make +// sure that headers and trailers don't get mixed up in very short files. If +// the exact contents of the RIFF header are not known because, for example, +// the file duration is uncertain or trailing chunks are possible, simply write +// a "dummy" header of the correct length. When all data has been written it +// will be possible to read the first block written and update the header +// directly. An example of this can be found in the Audition filter. A +// return of FALSE indicates an error. + +int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount) +{ + uint32_t index = WavpackGetSampleIndex (wpc); + uchar meta_id; + + if (!index || index == (uint32_t) -1) { + wpc->riff_header_added = TRUE; + meta_id = ID_RIFF_HEADER; + } + else + meta_id = ID_RIFF_TRAILER; + + return add_to_metadata (wpc, data, bcount, meta_id); +} + +// Store computed MD5 sum in WavPack metadata. Note that the user must compute +// the 16 byte sum; it is not done here. A return of FALSE indicates an error. + +int WavpackStoreMD5Sum (WavpackContext *wpc, uchar data [16]) +{ + return add_to_metadata (wpc, data, 16, ID_MD5_CHECKSUM); +} + +static int create_riff_header (WavpackContext *wpc) +{ + RiffChunkHeader riffhdr; + ChunkHeader datahdr, fmthdr; + WaveHeader wavhdr; + + uint32_t total_samples = wpc->total_samples, total_data_bytes; + int32_t channel_mask = wpc->config.channel_mask; + int32_t sample_rate = wpc->config.sample_rate; + int bytes_per_sample = wpc->config.bytes_per_sample; + int bits_per_sample = wpc->config.bits_per_sample; + int format = (wpc->config.float_norm_exp) ? 3 : 1; + int num_channels = wpc->config.num_channels; + int wavhdrsize = 16; + + wpc->riff_header_created = TRUE; + + if (format == 3 && wpc->config.float_norm_exp != 127) { + strcpy (wpc->error_message, "can't create valid RIFF wav header for non-normalized floating data!"); + return FALSE; + } + + if (total_samples == (uint32_t) -1) + total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); + + total_data_bytes = total_samples * bytes_per_sample * num_channels; + + CLEAR (wavhdr); + + wavhdr.FormatTag = format; + wavhdr.NumChannels = num_channels; + wavhdr.SampleRate = sample_rate; + wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; + wavhdr.BlockAlign = bytes_per_sample * num_channels; + wavhdr.BitsPerSample = bits_per_sample; + + if (num_channels > 2 || channel_mask != 0x5 - num_channels) { + wavhdrsize = sizeof (wavhdr); + wavhdr.cbSize = 22; + wavhdr.ValidBitsPerSample = bits_per_sample; + wavhdr.SubFormat = format; + wavhdr.ChannelMask = channel_mask; + wavhdr.FormatTag = 0xfffe; + wavhdr.BitsPerSample = bytes_per_sample * 8; + wavhdr.GUID [4] = 0x10; + wavhdr.GUID [6] = 0x80; + wavhdr.GUID [9] = 0xaa; + wavhdr.GUID [11] = 0x38; + wavhdr.GUID [12] = 0x9b; + wavhdr.GUID [13] = 0x71; + } + + strncpy (riffhdr.ckID, "RIFF", sizeof (riffhdr.ckID)); + strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); + riffhdr.ckSize = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + total_data_bytes; + strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); + fmthdr.ckSize = wavhdrsize; + + strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); + datahdr.ckSize = total_data_bytes; + + // write the RIFF chunks up to just before the data starts + + native_to_little_endian (&riffhdr, ChunkHeaderFormat); + native_to_little_endian (&fmthdr, ChunkHeaderFormat); + native_to_little_endian (&wavhdr, WaveHeaderFormat); + native_to_little_endian (&datahdr, ChunkHeaderFormat); + + return add_to_metadata (wpc, &riffhdr, sizeof (riffhdr), ID_RIFF_HEADER) && + add_to_metadata (wpc, &fmthdr, sizeof (fmthdr), ID_RIFF_HEADER) && + add_to_metadata (wpc, &wavhdr, wavhdrsize, ID_RIFF_HEADER) && + add_to_metadata (wpc, &datahdr, sizeof (datahdr), ID_RIFF_HEADER); +} + +static int pack_streams (WavpackContext *wpc, uint32_t block_samples) +{ + uint32_t max_blocksize, bcount; + uchar *outbuff, *outend, *out2buff, *out2end; + int result = TRUE; + + if ((wpc->config.flags & CONFIG_FLOAT_DATA) && !(wpc->config.flags & CONFIG_SKIP_WVX)) + max_blocksize = block_samples * 16 + 4096; + else + max_blocksize = block_samples * 10 + 4096; + + out2buff = (wpc->wvc_flag) ? malloc (max_blocksize) : NULL; + out2end = out2buff + max_blocksize; + outbuff = malloc (max_blocksize); + outend = outbuff + max_blocksize; + + for (wpc->current_stream = 0; wpc->streams [wpc->current_stream]; wpc->current_stream++) { + WavpackStream *wps = wpc->streams [wpc->current_stream]; + uint32_t flags = wps->wphdr.flags; + + flags &= ~MAG_MASK; + flags += (1 << MAG_LSB) * ((flags & BYTES_STORED) * 8 + 7); + + wps->wphdr.block_index = wps->sample_index; + wps->wphdr.block_samples = block_samples; + wps->wphdr.flags = flags; + wps->block2buff = out2buff; + wps->block2end = out2end; + wps->blockbuff = outbuff; + wps->blockend = outend; + + result = pack_block (wpc, wps->sample_buffer); + wps->blockbuff = wps->block2buff = NULL; + + if (!result) { + strcpy (wpc->error_message, "output buffer overflowed!"); + break; + } + + bcount = ((WavpackHeader *) outbuff)->ckSize + 8; + native_to_little_endian ((WavpackHeader *) outbuff, WavpackHeaderFormat); + result = wpc->blockout (wpc->wv_out, outbuff, bcount); + + if (!result) { + strcpy (wpc->error_message, "can't write WavPack data, disk probably full!"); + break; + } + + wpc->filelen += bcount; + + if (out2buff) { + bcount = ((WavpackHeader *) out2buff)->ckSize + 8; + native_to_little_endian ((WavpackHeader *) out2buff, WavpackHeaderFormat); + result = wpc->blockout (wpc->wvc_out, out2buff, bcount); + + if (!result) { + strcpy (wpc->error_message, "can't write WavPack data, disk probably full!"); + break; + } + + wpc->file2len += bcount; + } + + if (wpc->acc_samples != block_samples) + memcpy (wps->sample_buffer, wps->sample_buffer + block_samples * (flags & MONO_FLAG ? 1 : 2), + (wpc->acc_samples - block_samples) * sizeof (int32_t) * (flags & MONO_FLAG ? 1 : 2)); + } + + wpc->current_stream = 0; + wpc->acc_samples -= block_samples; + free (outbuff); + + if (out2buff) + free (out2buff); + + return result; +} + +// Given the pointer to the first block written (to either a .wv or .wvc file), +// update the block with the actual number of samples written. If the wav +// header was generated by the library, then it is updated also. This should +// be done if WavpackSetConfiguration() was called with an incorrect number +// of samples (or -1). It is the responsibility of the application to read and +// rewrite the block. An example of this can be found in the Audition filter. + +void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block) +{ + uint32_t wrapper_size; + + little_endian_to_native (first_block, WavpackHeaderFormat); + ((WavpackHeader *) first_block)->total_samples = WavpackGetSampleIndex (wpc); + + if (wpc->riff_header_created) { + if (WavpackGetWrapperLocation (first_block, &wrapper_size)) { + RiffChunkHeader *riffhdr = WavpackGetWrapperLocation (first_block, NULL); + ChunkHeader *datahdr = (ChunkHeader *)((char *) riffhdr + wrapper_size - sizeof (ChunkHeader)); + uint32_t data_size = WavpackGetSampleIndex (wpc) * WavpackGetNumChannels (wpc) * WavpackGetBytesPerSample (wpc); + + if (!strncmp (riffhdr->ckID, "RIFF", 4)) { + little_endian_to_native (riffhdr, ChunkHeaderFormat); + riffhdr->ckSize = wrapper_size + data_size - 8; + native_to_little_endian (riffhdr, ChunkHeaderFormat); + } + + if (!strncmp (datahdr->ckID, "data", 4)) { + little_endian_to_native (datahdr, ChunkHeaderFormat); + datahdr->ckSize = data_size; + native_to_little_endian (datahdr, ChunkHeaderFormat); + } + } + } + + native_to_little_endian (first_block, WavpackHeaderFormat); +} + +// Note: The following function is no longer required because the wav header +// automatically generated for the application will also be updated by +// WavpackUpdateNumSamples (). However, if the application wants to generate +// its own header or wants to include additional chunks, then this function +// still must be used to update the application generated header. + +// Given the pointer to the first block written to a WavPack file, this +// function returns the location of the stored RIFF header that was originally +// written with WavpackAddWrapper(). This would normally be used to update +// the wav header to indicate that a different number of samples was actually +// written or if additional RIFF chunks are written at the end of the file. +// The "size" parameter can be set to non-NULL to obtain the exact size of the +// RIFF header, and the function will return FALSE if the header is not found +// in the block's metadata (or it is not a valid WavPack block). It is the +// responsibility of the application to read and rewrite the block. An example +// of this can be found in the Audition filter. + +static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size); + +void *WavpackGetWrapperLocation (void *first_block, uint32_t *size) +{ + void *loc; + + little_endian_to_native (first_block, WavpackHeaderFormat); + loc = find_metadata (first_block, ID_RIFF_HEADER, size); + native_to_little_endian (first_block, WavpackHeaderFormat); + + return loc; +} + +static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size) +{ + WavpackHeader *wphdr = wavpack_block; + uchar *dp, meta_id, c1, c2; + int32_t bcount, meta_bc; + + if (strncmp (wphdr->ckID, "wvpk", 4)) + return NULL; + + bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; + dp = (uchar *)(wphdr + 1); + + while (bcount >= 2) { + meta_id = *dp++; + c1 = *dp++; + + meta_bc = c1 << 1; + bcount -= 2; + + if (meta_id & ID_LARGE) { + if (bcount < 2) + break; + + c1 = *dp++; + c2 = *dp++; + meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); + bcount -= 2; + } + + if ((meta_id & ID_UNIQUE) == desired_id) { + if ((bcount - meta_bc) >= 0) { + if (size) + *size = meta_bc - ((meta_id & ID_ODD_SIZE) ? 1 : 0); + + return dp; + } + else + return NULL; + } + + bcount -= meta_bc; + dp += meta_bc; + } + + return FALSE; +} + +#endif + +#ifndef NO_TAGS + +// Limited functionality to append APEv2 tags to WavPack files when they are +// created has been added for version 4.2. This function is used to append the +// specified field to the tag being created. If no tag has been started, then +// an empty one will be allocated first. When finished, use WavpackWriteTag() +// to write the completed tag to the file. Note that ID3 tags are not +// supported and that no editing of existing tags is allowed (there are several +// fine libraries available for this). A size parameter is included so that +// values containing multiple (NULL separated) strings can be written. + +int WavpackAppendTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize) +{ + M_Tag *m_tag = &wpc->m_tag; + int isize = (int) strlen (item); + + while (WavpackDeleteTagItem (wpc, item)); + + if (!m_tag->ape_tag_hdr.ID [0]) { + strncpy (m_tag->ape_tag_hdr.ID, "APETAGEX", sizeof (m_tag->ape_tag_hdr.ID)); + m_tag->ape_tag_hdr.version = 2000; + m_tag->ape_tag_hdr.length = sizeof (m_tag->ape_tag_hdr); + m_tag->ape_tag_hdr.item_count = 0; + m_tag->ape_tag_hdr.flags = 0x80000000; + } + + if (m_tag->ape_tag_hdr.ID [0] == 'A') { + int new_item_len = vsize + isize + 9, flags = 0; + char *p; + + m_tag->ape_tag_hdr.item_count++; + m_tag->ape_tag_hdr.length += new_item_len; + p = m_tag->ape_tag_data = realloc (m_tag->ape_tag_data, m_tag->ape_tag_hdr.length); + p += m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr) - new_item_len; + native_to_little_endian (&vsize, "L"); + native_to_little_endian (&flags, "L"); + * (int32_t *) p = vsize; p += 4; + * (int32_t *) p = flags; p += 4; + little_endian_to_native (&vsize, "L"); + little_endian_to_native (&flags, "L"); + strcpy (p, item); + p += isize + 1; + memcpy (p, value, vsize); + + return TRUE; + } + else + return FALSE; +} + +int WavpackDeleteTagItem (WavpackContext *wpc, const char *item) +{ + M_Tag *m_tag = &wpc->m_tag; + + if (m_tag->ape_tag_hdr.ID [0] == 'A') { + char *p = m_tag->ape_tag_data; + char *q = p + m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr); + int i; + + for (i = 0; i < m_tag->ape_tag_hdr.item_count; ++i) { + int vsize, flags, isize; + + vsize = * (int32_t *) p; p += 4; + flags = * (int32_t *) p; p += 4; + isize = (int) strlen (p); + + little_endian_to_native (&vsize, "L"); + little_endian_to_native (&flags, "L"); + + if (p + isize + vsize + 1 > q) + break; + + if (isize && vsize && !stricmp (item, p)) { + char *d = p - 8; + + p += isize + vsize + 1; + + while (p < q) + *d++ = *p++; + + m_tag->ape_tag_hdr.length = (int32_t)(d - m_tag->ape_tag_data) + sizeof (APE_Tag_Hdr); + m_tag->ape_tag_hdr.item_count--; + return 1; + } + else + p += isize + vsize + 1; + } + } + + return 0; +} + +// Once a APEv2 tag has been created with WavpackAppendTag(), this function is +// used to write the completed tag to the end of the WavPack file. Note that +// this function uses the same "blockout" function that is used to write +// regular WavPack blocks, although that's where the similarity ends. + +static int write_tag_blockout (WavpackContext *wpc); +static int write_tag_reader (WavpackContext *wpc); + +int WavpackWriteTag (WavpackContext *wpc) +{ + if (wpc->blockout) + return write_tag_blockout (wpc); + else + return write_tag_reader (wpc); +} + +static int write_tag_blockout (WavpackContext *wpc) +{ + M_Tag *m_tag = &wpc->m_tag; + int result = TRUE; + + if (m_tag->ape_tag_hdr.ID [0] == 'A' && m_tag->ape_tag_hdr.item_count) { + m_tag->ape_tag_hdr.flags |= 0x20000000; + native_to_little_endian (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + result = wpc->blockout (wpc->wv_out, &m_tag->ape_tag_hdr, sizeof (m_tag->ape_tag_hdr)); + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + + if (m_tag->ape_tag_hdr.length > sizeof (m_tag->ape_tag_hdr)) + result = wpc->blockout (wpc->wv_out, m_tag->ape_tag_data, m_tag->ape_tag_hdr.length - sizeof (m_tag->ape_tag_hdr)); + + m_tag->ape_tag_hdr.flags &= ~0x20000000; + native_to_little_endian (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + result = wpc->blockout (wpc->wv_out, &m_tag->ape_tag_hdr, sizeof (m_tag->ape_tag_hdr)); + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + } + + if (!result) + strcpy (wpc->error_message, "can't write WavPack data, disk probably full!"); + + return result; +} + +static int write_tag_reader (WavpackContext *wpc) +{ + M_Tag *m_tag = &wpc->m_tag; + int32_t tag_size = 0; + int result = TRUE; + + if (m_tag->ape_tag_hdr.ID [0] == 'A' && m_tag->ape_tag_hdr.item_count && + m_tag->ape_tag_hdr.length > sizeof (m_tag->ape_tag_hdr)) + tag_size = m_tag->ape_tag_hdr.length + sizeof (m_tag->ape_tag_hdr); + + result = (wpc->open_flags & OPEN_EDIT_TAGS) && wpc->reader->can_seek (wpc->wv_in) && + !wpc->reader->set_pos_rel (wpc->wv_in, m_tag->tag_file_pos, SEEK_END); + + if (result && tag_size < -m_tag->tag_file_pos) { + int nullcnt = -m_tag->tag_file_pos - tag_size; + char zero [1] = { 0 }; + + while (nullcnt--) + wpc->reader->write_bytes (wpc->wv_in, &zero, 1); + } + + if (result && tag_size) { + m_tag->ape_tag_hdr.flags |= 0x20000000; + native_to_little_endian (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + result = (wpc->reader->write_bytes (wpc->wv_in, &m_tag->ape_tag_hdr, sizeof (m_tag->ape_tag_hdr)) == sizeof (m_tag->ape_tag_hdr)); + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + result = (wpc->reader->write_bytes (wpc->wv_in, m_tag->ape_tag_data, m_tag->ape_tag_hdr.length - sizeof (m_tag->ape_tag_hdr)) == sizeof (m_tag->ape_tag_hdr)); + m_tag->ape_tag_hdr.flags &= ~0x20000000; + native_to_little_endian (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + result = (wpc->reader->write_bytes (wpc->wv_in, &m_tag->ape_tag_hdr, sizeof (m_tag->ape_tag_hdr)) == sizeof (m_tag->ape_tag_hdr)); + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + } + + if (!result) + strcpy (wpc->error_message, "can't write WavPack data, disk probably full!"); + + return result; +} + +#endif + +// Get total number of samples contained in the WavPack file, or -1 if unknown + +uint32_t WavpackGetNumSamples (WavpackContext *wpc) +{ + return wpc ? wpc->total_samples : (uint32_t) -1; +} + +// Get the current sample index position, or -1 if unknown + +uint32_t WavpackGetSampleIndex (WavpackContext *wpc) +{ + if (wpc) { +#if !defined(VER4_ONLY) && !defined(NO_UNPACK) + if (wpc->stream3) + return get_sample_index3 (wpc); + else if (wpc->streams [0]) + return wpc->streams [0]->sample_index; +#else + if (wpc->streams [0]) + return wpc->streams [0]->sample_index; +#endif + } + + return (uint32_t) -1; +} + +// Get the number of errors encountered so far + +int WavpackGetNumErrors (WavpackContext *wpc) +{ + return wpc ? wpc->crc_errors : 0; +} + +// return TRUE if any uncorrected lossy blocks were actually written or read + +int WavpackLossyBlocks (WavpackContext *wpc) +{ + return wpc ? wpc->lossy_blocks : 0; +} + +// Calculate the progress through the file as a double from 0.0 (for begin) +// to 1.0 (for done). A return value of -1.0 indicates that the progress is +// unknown. + +double WavpackGetProgress (WavpackContext *wpc) +{ + if (wpc && wpc->total_samples != (uint32_t) -1 && wpc->total_samples != 0) + return (double) WavpackGetSampleIndex (wpc) / wpc->total_samples; + else + return -1.0; +} + +// Return the total size of the WavPack file(s) in bytes. + +uint32_t WavpackGetFileSize (WavpackContext *wpc) +{ + return wpc ? wpc->filelen + wpc->file2len : 0; +} + +// Calculate the ratio of the specified WavPack file size to the size of the +// original audio data as a double greater than 0.0 and (usually) smaller than +// 1.0. A value greater than 1.0 represents "negative" compression and a +// return value of 0.0 indicates that the ratio cannot be determined. + +double WavpackGetRatio (WavpackContext *wpc) +{ + if (wpc && wpc->total_samples != (uint32_t) -1 && wpc->filelen) { + double output_size = (double) wpc->total_samples * wpc->config.num_channels * + wpc->config.bytes_per_sample; + double input_size = (double) wpc->filelen + wpc->file2len; + + if (output_size >= 1.0 && input_size >= 1.0) + return input_size / output_size; + } + + return 0.0; +} + +// Calculate the average bitrate of the WavPack file in bits per second. A +// return of 0.0 indicates that the bitrate cannot be determined. An option is +// provided to use (or not use) any attendant .wvc file. + +double WavpackGetAverageBitrate (WavpackContext *wpc, int count_wvc) +{ + if (wpc && wpc->total_samples != (uint32_t) -1 && wpc->filelen) { + double output_time = (double) wpc->total_samples / wpc->config.sample_rate; + double input_size = (double) wpc->filelen + (count_wvc ? wpc->file2len : 0); + + if (output_time >= 1.0 && input_size >= 1.0) + return input_size * 8.0 / output_time; + } + + return 0.0; +} + +#ifndef NO_UNPACK + +// Calculate the bitrate of the current WavPack file block in bits per second. +// This can be used for an "instant" bit display and gets updated from about +// 1 to 4 times per second. A return of 0.0 indicates that the bitrate cannot +// be determined. + +double WavpackGetInstantBitrate (WavpackContext *wpc) +{ + if (wpc->stream3) + return WavpackGetAverageBitrate (wpc, TRUE); + + if (wpc && wpc->streams [0] && wpc->streams [0]->wphdr.block_samples) { + double output_time = (double) wpc->streams [0]->wphdr.block_samples / wpc->config.sample_rate; + double input_size = 0; + int si; + + for (si = 0; si < wpc->num_streams; ++si) { + if (wpc->streams [si]->blockbuff) + input_size += ((WavpackHeader *) wpc->streams [si]->blockbuff)->ckSize; + + if (wpc->streams [si]->block2buff) + input_size += ((WavpackHeader *) wpc->streams [si]->block2buff)->ckSize; + } + + if (output_time > 0.0 && input_size >= 1.0) + return input_size * 8.0 / output_time; + } + + return 0.0; +} + +#endif + +// Close the specified WavPack file and release all resources used by it. +// Returns NULL. + +WavpackContext *WavpackCloseFile (WavpackContext *wpc) +{ + free_streams (wpc); + + if (wpc->streams [0]) + free (wpc->streams [0]); + +#if !defined(VER4_ONLY) && !defined(NO_UNPACK) + if (wpc->stream3) + free_stream3 (wpc); +#endif + +#if !defined(NO_UNPACK) || defined(INFO_ONLY) + if (wpc->close_files) { +#ifndef NO_USE_FSTREAMS + if (wpc->wv_in != NULL) + fclose (wpc->wv_in); + + if (wpc->wvc_in != NULL) + fclose (wpc->wvc_in); +#endif + } + + WavpackFreeWrapper (wpc); +#endif + +#ifndef NO_TAGS + free_tag (&wpc->m_tag); +#endif + + free (wpc); + + return NULL; +} + +// Returns the sample rate of the specified WavPack file + +uint32_t WavpackGetSampleRate (WavpackContext *wpc) +{ + return wpc ? wpc->config.sample_rate : 44100; +} + +// Returns the number of channels of the specified WavPack file. Note that +// this is the actual number of channels contained in the file even if the +// OPEN_2CH_MAX flag was specified when the file was opened. + +int WavpackGetNumChannels (WavpackContext *wpc) +{ + return wpc ? wpc->config.num_channels : 2; +} + +// Returns the standard Microsoft channel mask for the specified WavPack +// file. A value of zero indicates that there is no speaker assignment +// information. + +int WavpackGetChannelMask (WavpackContext *wpc) +{ + return wpc ? wpc->config.channel_mask : 0; +} + +// Return the normalization value for floating point data (valid only +// if floating point data is present). A value of 127 indicates that +// the floating point range is +/- 1.0. Higher values indicate a +// larger floating point range. + +int WavpackGetFloatNormExp (WavpackContext *wpc) +{ + return wpc->config.float_norm_exp; +} + +// Returns the actual number of valid bits per sample contained in the +// original file, which may or may not be a multiple of 8. Floating data +// always has 32 bits, integers may be from 1 to 32 bits each. When this +// value is not a multiple of 8, then the "extra" bits are located in the +// LSBs of the results. That is, values are right justified when unpacked +// into ints, but are left justified in the number of bytes used by the +// original data. + +int WavpackGetBitsPerSample (WavpackContext *wpc) +{ + return wpc ? wpc->config.bits_per_sample : 16; +} + +// Returns the number of bytes used for each sample (1 to 4) in the original +// file. This is required information for the user of this module because the +// audio data is returned in the LOWER bytes of the long buffer and must be +// left-shifted 8, 16, or 24 bits if normalized longs are required. + +int WavpackGetBytesPerSample (WavpackContext *wpc) +{ + return wpc ? wpc->config.bytes_per_sample : 2; +} + +#if !defined(NO_UNPACK) || defined(INFO_ONLY) + +// If the OPEN_2CH_MAX flag is specified when opening the file, this function +// will return the actual number of channels decoded from the file (which may +// or may not be less than the actual number of channels, but will always be +// 1 or 2). Normally, this will be the front left and right channels of a +// multichannel file. + +int WavpackGetReducedChannels (WavpackContext *wpc) +{ + if (wpc) + return wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels; + else + return 2; +} + +// These routines are used to access (and free) header and trailer data that +// was retrieved from the Wavpack file. The header will be available before +// the samples are decoded and the trailer will be available after all samples +// have been read. + +uint32_t WavpackGetWrapperBytes (WavpackContext *wpc) +{ + return wpc ? wpc->wrapper_bytes : 0; +} + +uchar *WavpackGetWrapperData (WavpackContext *wpc) +{ + return wpc ? wpc->wrapper_data : NULL; +} + +void WavpackFreeWrapper (WavpackContext *wpc) +{ + if (wpc && wpc->wrapper_data) { + free (wpc->wrapper_data); + wpc->wrapper_data = NULL; + wpc->wrapper_bytes = 0; + } +} + +// Normally the trailing wrapper will not be available when a WavPack file is first +// opened for reading because it is stored in the final block of the file. This +// function forces a seek to the end of the file to pick up any trailing wrapper +// stored there (then use WavPackGetWrapper**() to obtain). This can obviously only +// be used for seekable files (not pipes) and is not available for pre-4.0 WavPack +// files. + +static void seek_riff_trailer (WavpackContext *wpc); + +void WavpackSeekTrailingWrapper (WavpackContext *wpc) +{ + if ((wpc->open_flags & OPEN_WRAPPER) && + wpc->reader->can_seek (wpc->wv_in) && !wpc->stream3) { + uint32_t pos_save = wpc->reader->get_pos (wpc->wv_in); + + seek_riff_trailer (wpc); + wpc->reader->set_pos_abs (wpc->wv_in, pos_save); + } +} + +// Get any MD5 checksum stored in the metadata (should be called after reading +// last sample or an extra seek will occur). A return value of FALSE indicates +// that no MD5 checksum was stored. + +static int seek_md5 (WavpackStreamReader *reader, void *id, uchar data [16]); + +int WavpackGetMD5Sum (WavpackContext *wpc, uchar data [16]) +{ + if (wpc->config.flags & CONFIG_MD5_CHECKSUM) { + if (wpc->config.md5_read) { + memcpy (data, wpc->config.md5_checksum, 16); + return TRUE; + } + else if (wpc->reader->can_seek (wpc->wv_in)) { + uint32_t pos_save = wpc->reader->get_pos (wpc->wv_in); + + wpc->config.md5_read = seek_md5 (wpc->reader, wpc->wv_in, wpc->config.md5_checksum); + wpc->reader->set_pos_abs (wpc->wv_in, pos_save); + + if (wpc->config.md5_read) { + memcpy (data, wpc->config.md5_checksum, 16); + return TRUE; + } + else + return FALSE; + } + } + + return FALSE; +} + +#endif + +// Free all memory allocated for raw WavPack blocks (for all allocated streams) +// and free all additonal streams. This does not free the default stream ([0]) +// which is always kept around. + +static void free_streams (WavpackContext *wpc) +{ + int si = wpc->num_streams; + + while (si--) { + if (wpc->streams [si]->blockbuff) { + free (wpc->streams [si]->blockbuff); + wpc->streams [si]->blockbuff = NULL; + } + + if (wpc->streams [si]->block2buff) { + free (wpc->streams [si]->block2buff); + wpc->streams [si]->block2buff = NULL; + } + + if (wpc->streams [si]->sample_buffer) { + free (wpc->streams [si]->sample_buffer); + wpc->streams [si]->sample_buffer = NULL; + } + + if (si) { + wpc->num_streams--; + free (wpc->streams [si]); + wpc->streams [si] = NULL; + } + } + + wpc->current_stream = 0; +} + +#ifndef NO_TAGS + +// Return TRUE is a valid ID3v1 or APEv2 tag has been loaded. + +static int valid_tag (M_Tag *m_tag) +{ + if (m_tag->ape_tag_hdr.ID [0] == 'A') + return 'A'; + else if (m_tag->id3_tag.tag_id [0] == 'T') + return 'T'; + else + return 0; +} + +// Free the data for any APEv2 tag that was allocated. + +static void free_tag (M_Tag *m_tag) +{ + if (m_tag->ape_tag_data) { + free (m_tag->ape_tag_data); + m_tag->ape_tag_data = 0; + } +} + +#endif + +#if !defined(NO_UNPACK) || defined(INFO_ONLY) + +// Read from current file position until a valid 32-byte WavPack 4.0 header is +// found and read into the specified pointer. The number of bytes skipped is +// returned. If no WavPack header is found within 1 meg, then a -1 is returned +// to indicate the error. No additional bytes are read past the header and it +// is returned in the processor's native endian mode. Seeking is not required. + +static uint32_t read_next_header (WavpackStreamReader *reader, void *id, WavpackHeader *wphdr) +{ + char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp; + uint32_t bytes_skipped = 0; + int bleft; + + while (1) { + if (sp < ep) { + bleft = (int)(ep - sp); + memcpy (buffer, sp, bleft); + } + else + bleft = 0; + + if (reader->read_bytes (id, buffer + bleft, sizeof (*wphdr) - bleft) != sizeof (*wphdr) - bleft) + return -1; + + sp = buffer; + + if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' && + !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 && + sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) { + memcpy (wphdr, buffer, sizeof (*wphdr)); + little_endian_to_native (wphdr, WavpackHeaderFormat); + return bytes_skipped; + } + + while (sp < ep && *sp != 'w') + sp++; + + if ((bytes_skipped += (uint32_t)(sp - buffer)) > 1024 * 1024) + return -1; + } +} + +// This function is used to seek to end of a file to determine its actual +// length in samples by reading the last header block containing data. +// Currently, all WavPack files contain the sample length in the first block +// containing samples, however this might not always be the case. Obviously, +// this function requires a seekable file or stream and leaves the file +// pointer undefined. A return value of -1 indicates the length could not +// be determined. + +static uint32_t seek_final_index (WavpackStreamReader *reader, void *id) +{ + uint32_t result = (uint32_t) -1, bcount; + WavpackHeader wphdr; + uchar *tempbuff; + + if (reader->get_length (id) > 1200000L) + reader->set_pos_rel (id, -1048576L, SEEK_END); + else + reader->set_pos_abs (id, 0); + + while (1) { + bcount = read_next_header (reader, id, &wphdr); + + if (bcount == (uint32_t) -1) + return result; + + tempbuff = malloc (wphdr.ckSize + 8); + memcpy (tempbuff, &wphdr, 32); + + if (reader->read_bytes (id, tempbuff + 32, wphdr.ckSize - 24) != wphdr.ckSize - 24) { + free (tempbuff); + return result; + } + + free (tempbuff); + + if (wphdr.block_samples && (wphdr.flags & FINAL_BLOCK)) + result = wphdr.block_index + wphdr.block_samples; + } +} + +static int seek_md5 (WavpackStreamReader *reader, void *id, uchar data [16]) +{ + uchar meta_id, c1, c2; + uint32_t bcount, meta_bc; + WavpackHeader wphdr; + + if (reader->get_length (id) > 1200000L) + reader->set_pos_rel (id, -1048576L, SEEK_END); + + while (1) { + bcount = read_next_header (reader, id, &wphdr); + + if (bcount == (uint32_t) -1) + return FALSE; + + bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8; + + while (bcount >= 2) { + if (reader->read_bytes (id, &meta_id, 1) != 1 || + reader->read_bytes (id, &c1, 1) != 1) + return FALSE; + + meta_bc = c1 << 1; + bcount -= 2; + + if (meta_id & ID_LARGE) { + if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 || + reader->read_bytes (id, &c2, 1) != 1) + return FALSE; + + meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); + bcount -= 2; + } + + if (meta_id == ID_MD5_CHECKSUM) + return (meta_bc == 16 && bcount >= 16 && + reader->read_bytes (id, data, 16) == 16); + + reader->set_pos_rel (id, meta_bc, SEEK_CUR); + bcount -= meta_bc; + } + } +} + +static void seek_riff_trailer (WavpackContext *wpc) +{ + WavpackStreamReader *reader = wpc->reader; + void *id = wpc->wv_in; + uchar meta_id, c1, c2; + uint32_t bcount, meta_bc; + WavpackHeader wphdr; + + if (reader->get_length (id) > 1200000L) + reader->set_pos_rel (id, -1048576L, SEEK_END); + + while (1) { + bcount = read_next_header (reader, id, &wphdr); + + if (bcount == (uint32_t) -1) + return; + + bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8; + + while (bcount >= 2) { + if (reader->read_bytes (id, &meta_id, 1) != 1 || + reader->read_bytes (id, &c1, 1) != 1) + return; + + meta_bc = c1 << 1; + bcount -= 2; + + if (meta_id & ID_LARGE) { + if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 || + reader->read_bytes (id, &c2, 1) != 1) + return; + + meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); + bcount -= 2; + } + + if ((meta_id & ID_UNIQUE) == ID_RIFF_TRAILER) { + wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + meta_bc); + + if (reader->read_bytes (id, wpc->wrapper_data + wpc->wrapper_bytes, meta_bc) == meta_bc) + wpc->wrapper_bytes += meta_bc; + else + return; + } + else + reader->set_pos_rel (id, meta_bc, SEEK_CUR); + + bcount -= meta_bc; + } + } +} + +// Compare the regular wv file block header to a potential matching wvc +// file block header and return action code based on analysis: +// +// 0 = use wvc block (assuming rest of block is readable) +// 1 = bad match; try to read next wvc block +// -1 = bad match; ignore wvc file for this block and backup fp (if +// possible) and try to use this block next time + +static int match_wvc_header (WavpackHeader *wv_hdr, WavpackHeader *wvc_hdr) +{ + if (wv_hdr->block_index == wvc_hdr->block_index && + wv_hdr->block_samples == wvc_hdr->block_samples) { + int wvi = 0, wvci = 0; + + if (wv_hdr->flags == wvc_hdr->flags) + return 0; + + if (wv_hdr->flags & INITIAL_BLOCK) + wvi -= 1; + + if (wv_hdr->flags & FINAL_BLOCK) + wvi += 1; + + if (wvc_hdr->flags & INITIAL_BLOCK) + wvci -= 1; + + if (wvc_hdr->flags & FINAL_BLOCK) + wvci += 1; + + return (wvci - wvi < 0) ? 1 : -1; + } + + if ((int32_t)(wvc_hdr->block_index - wv_hdr->block_index) < 0) + return 1; + else + return -1; +} + +// Read the wvc block that matches the regular wv block that has been +// read for the current stream. If an exact match is not found then +// we either keep reading or back up and (possibly) use the block +// later. The skip_wvc flag is set if not matching wvc block is found +// so that we can still decode using only the lossy version (although +// we flag this as an error). A return of FALSE indicates a serious +// error (not just that we missed one wvc block). + +static int read_wvc_block (WavpackContext *wpc) +{ + WavpackStream *wps = wpc->streams [wpc->current_stream]; + uint32_t bcount, file2pos; + WavpackHeader wphdr; + int compare_result; + + while (1) { + file2pos = wpc->reader->get_pos (wpc->wvc_in); + bcount = read_next_header (wpc->reader, wpc->wvc_in, &wphdr); + + if (bcount == (uint32_t) -1) { + wps->wvc_skip = TRUE; + wpc->crc_errors++; + return FALSE; + } + + if (wpc->open_flags & OPEN_STREAMING) + wphdr.block_index = wps->sample_index = 0; + else + wphdr.block_index -= wpc->initial_index; + + if (wphdr.flags & INITIAL_BLOCK) + wpc->file2pos = file2pos + bcount; + + compare_result = match_wvc_header (&wps->wphdr, &wphdr); + + if (!compare_result) { + wps->block2buff = malloc (wphdr.ckSize + 8); + memcpy (wps->block2buff, &wphdr, 32); + + if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + 32, wphdr.ckSize - 24) != + wphdr.ckSize - 24 || (wphdr.flags & UNKNOWN_FLAGS)) { + free (wps->block2buff); + wps->block2buff = 0; + wps->wvc_skip = TRUE; + wpc->crc_errors++; + return FALSE; + } + + wps->wvc_skip = FALSE; + memcpy (&wps->wphdr, &wphdr, 32); + return TRUE; + } + else if (compare_result == -1) { + wps->wvc_skip = TRUE; + wpc->reader->set_pos_rel (wpc->wvc_in, -32, SEEK_CUR); + wpc->crc_errors++; + return TRUE; + } + } +} + +#ifndef NO_SEEKING + +// Find a valid WavPack header, searching either from the current file position +// (or from the specified position if not -1) and store it (endian corrected) +// at the specified pointer. The return value is the exact file position of the +// header, although we may have actually read past it. Because this function +// is used for seeking to a specific audio sample, it only considers blocks +// that contain audio samples for the initial stream to be valid. + +#define BUFSIZE 4096 + +static uint32_t find_header (WavpackStreamReader *reader, void *id, uint32_t filepos, WavpackHeader *wphdr) +{ + char *buffer = malloc (BUFSIZE), *sp = buffer, *ep = buffer; + + if (filepos != (uint32_t) -1 && reader->set_pos_abs (id, filepos)) { + free (buffer); + return -1; + } + + while (1) { + int bleft; + + if (sp < ep) { + bleft = (int)(ep - sp); + memcpy (buffer, sp, bleft); + ep -= (sp - buffer); + sp = buffer; + } + else { + if (sp > ep) + if (reader->set_pos_rel (id, (int32_t)(sp - ep), SEEK_CUR)) { + free (buffer); + return -1; + } + + sp = ep = buffer; + bleft = 0; + } + + ep += reader->read_bytes (id, ep, BUFSIZE - bleft); + + if (ep - sp < 32) { + free (buffer); + return -1; + } + + while (sp + 32 <= ep) + if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' && + !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 && + sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) { + memcpy (wphdr, sp - 4, sizeof (*wphdr)); + little_endian_to_native (wphdr, WavpackHeaderFormat); + + if (wphdr->block_samples && (wphdr->flags & INITIAL_BLOCK)) { + free (buffer); + return reader->get_pos (id) - (ep - sp + 4); + } + + if (wphdr->ckSize > 1024) + sp += wphdr->ckSize - 1024; + } + } +} + +// Find the WavPack block that contains the specified sample. If "header_pos" +// is zero, then no information is assumed except the total number of samples +// in the file and its size in bytes. If "header_pos" is non-zero then we +// assume that it is the file position of the valid header image contained in +// the first stream and we can limit our search to either the portion above +// or below that point. If a .wvc file is being used, then this must be called +// for that file also. + +static uint32_t find_sample (WavpackContext *wpc, void *infile, uint32_t header_pos, uint32_t sample) +{ + WavpackStream *wps = wpc->streams [wpc->current_stream]; + uint32_t file_pos1 = 0, file_pos2 = wpc->reader->get_length (infile); + uint32_t sample_pos1 = 0, sample_pos2 = wpc->total_samples; + double ratio = 0.96; + int file_skip = 0; + + if (sample >= wpc->total_samples) + return -1; + + if (header_pos && wps->wphdr.block_samples) { + if (wps->wphdr.block_index > sample) { + sample_pos2 = wps->wphdr.block_index; + file_pos2 = header_pos; + } + else if (wps->wphdr.block_index + wps->wphdr.block_samples <= sample) { + sample_pos1 = wps->wphdr.block_index; + file_pos1 = header_pos; + } + else + return header_pos; + } + + while (1) { + double bytes_per_sample; + uint32_t seek_pos; + + bytes_per_sample = file_pos2 - file_pos1; + bytes_per_sample /= sample_pos2 - sample_pos1; + seek_pos = file_pos1 + (file_skip ? 32 : 0); + seek_pos += (uint32_t)(bytes_per_sample * (sample - sample_pos1) * ratio); + seek_pos = find_header (wpc->reader, infile, seek_pos, &wps->wphdr); + + if (seek_pos != (uint32_t) -1) + wps->wphdr.block_index -= wpc->initial_index; + + if (seek_pos == (uint32_t) -1 || seek_pos >= file_pos2) { + if (ratio > 0.0) { + if ((ratio -= 0.24) < 0.0) + ratio = 0.0; + } + else + return -1; + } + else if (wps->wphdr.block_index > sample) { + sample_pos2 = wps->wphdr.block_index; + file_pos2 = seek_pos; + } + else if (wps->wphdr.block_index + wps->wphdr.block_samples <= sample) { + + if (seek_pos == file_pos1) + file_skip = 1; + else { + sample_pos1 = wps->wphdr.block_index; + file_pos1 = seek_pos; + } + } + else + return seek_pos; + } +} + +#endif + +#ifndef NO_TAGS + +// This function attempts to load an ID3v1 or APEv2 tag from the specified +// file into the specified M_Tag structure. The ID3 tag fits in completely, +// but an APEv2 tag is variable length and so space must be allocated here +// to accomodate the data, and this will need to be freed later. A return +// value of TRUE indicates a valid tag was found and loaded. Note that the +// file pointer is undefined when this function exits. + +static int load_tag (WavpackContext *wpc) +{ + M_Tag *m_tag = &wpc->m_tag; + + CLEAR (*m_tag); + + while (1) { + + // attempt to find an APEv2 tag either at end-of-file or before a ID3v1 tag we found + + if (m_tag->id3_tag.tag_id [0] == 'T') + wpc->reader->set_pos_rel (wpc->wv_in, -(int32_t)(sizeof (APE_Tag_Hdr) + sizeof (ID3_Tag)), SEEK_END); + else + wpc->reader->set_pos_rel (wpc->wv_in, -(int32_t)sizeof (APE_Tag_Hdr), SEEK_END); + + if (wpc->reader->read_bytes (wpc->wv_in, &m_tag->ape_tag_hdr, sizeof (APE_Tag_Hdr)) == sizeof (APE_Tag_Hdr) && + !strncmp (m_tag->ape_tag_hdr.ID, "APETAGEX", 8)) { + + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + + if (m_tag->ape_tag_hdr.version == 2000 && m_tag->ape_tag_hdr.item_count && + m_tag->ape_tag_hdr.length > sizeof (m_tag->ape_tag_hdr) && + m_tag->ape_tag_hdr.length < (1024 * 1024) && + (m_tag->ape_tag_data = malloc (m_tag->ape_tag_hdr.length)) != NULL) { + + if (m_tag->id3_tag.tag_id [0] == 'T') + m_tag->tag_file_pos = -(int32_t)sizeof (ID3_Tag); + else + m_tag->tag_file_pos = 0; + + m_tag->tag_file_pos -= m_tag->ape_tag_hdr.length + sizeof (APE_Tag_Hdr); + wpc->reader->set_pos_rel (wpc->wv_in, m_tag->tag_file_pos, SEEK_END); + memset (m_tag->ape_tag_data, 0, m_tag->ape_tag_hdr.length); + + if (wpc->reader->read_bytes (wpc->wv_in, &m_tag->ape_tag_hdr, sizeof (APE_Tag_Hdr)) != sizeof (APE_Tag_Hdr) || + strncmp (m_tag->ape_tag_hdr.ID, "APETAGEX", 8)) { + free (m_tag->ape_tag_data); + CLEAR (*m_tag); + return FALSE; // something's wrong... + } + + little_endian_to_native (&m_tag->ape_tag_hdr, APE_Tag_Hdr_Format); + + if (m_tag->ape_tag_hdr.version != 2000 || !m_tag->ape_tag_hdr.item_count || + m_tag->ape_tag_hdr.length < sizeof (m_tag->ape_tag_hdr) || + m_tag->ape_tag_hdr.length > (1024 * 1024)) { + free (m_tag->ape_tag_data); + CLEAR (*m_tag); + return FALSE; // something's wrong... + } + + if (wpc->reader->read_bytes (wpc->wv_in, m_tag->ape_tag_data, m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr)) != + m_tag->ape_tag_hdr.length - sizeof (APE_Tag_Hdr)) { + free (m_tag->ape_tag_data); + CLEAR (*m_tag); + return FALSE; // something's wrong... + } + else { + CLEAR (m_tag->id3_tag); // ignore ID3v1 tag if we found APEv2 tag + return TRUE; + } + } + } + + if (m_tag->id3_tag.tag_id [0] == 'T') { // settle for the ID3v1 tag that we found + CLEAR (m_tag->ape_tag_hdr); + return TRUE; + } + + // look for ID3v1 tag if APEv2 tag not found during first pass + + m_tag->tag_file_pos = -(int32_t)sizeof (ID3_Tag); + wpc->reader->set_pos_rel (wpc->wv_in, m_tag->tag_file_pos, SEEK_END); + + if (wpc->reader->read_bytes (wpc->wv_in, &m_tag->id3_tag, sizeof (ID3_Tag)) != sizeof (ID3_Tag) || + strncmp (m_tag->id3_tag.tag_id, "TAG", 3)) { + CLEAR (*m_tag); + return FALSE; // neither type of tag found + } + } +} + +// Copy the specified ID3v1 tag value (with specified field size) from the +// source pointer to the destination, eliminating leading spaces and trailing +// spaces and nulls. + +static void tagcpy (char *dest, char *src, int tag_size) +{ + char *s1 = src, *s2 = src + tag_size - 1; + + if (*s2 && !s2 [-1]) + s2--; + + while (s1 <= s2) + if (*s1 == ' ') + ++s1; + else if (!*s2 || *s2 == ' ') + --s2; + else + break; + + while (*s1 && s1 <= s2) + *dest++ = *s1++; + + *dest = 0; +} + +static int tagdata (char *src, int tag_size) +{ + char *s1 = src, *s2 = src + tag_size - 1; + + if (*s2 && !s2 [-1]) + s2--; + + while (s1 <= s2) + if (*s1 == ' ') + ++s1; + else if (!*s2 || *s2 == ' ') + --s2; + else + break; + + return (*s1 && s1 <= s2); +} + +#endif + +#endif + +void WavpackLittleEndianToNative (void *data, char *format) +{ + little_endian_to_native (data, format); +} + +void WavpackNativeToLittleEndian (void *data, char *format) +{ + native_to_little_endian (data, format); +} + +uint32_t WavpackGetLibraryVersion () +{ + return (LIBWAVPACK_MAJOR<<16) + |(LIBWAVPACK_MINOR<<8) + |(LIBWAVPACK_MICRO<<0); +} + +const char *WavpackGetLibraryVersionString () +{ + return LIBWAVPACK_VERSION_STRING; +} +