1:1 source port of the engine and game code; Windows build and system layer; docs. No game files or SDK headers.

This commit is contained in:
CRTkafa 2026-10-22 16:30:40 +08:00
parent c3b032a45a
commit 0ecb47e9cb
3871 changed files with 91080 additions and 1640063 deletions

36
port/external/openal/CAException.h vendored Normal file
View file

@ -0,0 +1,36 @@
// Port of pflib/external/openal/CAException.h (Apple Core Audio utility class, Playground SDK 4.0): the exception
// type that carries an OSStatus error code. Header-only in both builds: the constructor and the empty, non-virtual
// destructor are inline, so the class has no vtable; it is just mError (size 4).
//
// Game code: the game keeps one out-of-line copy of the (inline) destructor, game @0x001926c4 (D1, empty); the
// constructor is inlined at every throw site (a throw site allocates the exception, stores the error and throws
// with this destructor as the cleanup). sdk @0x18c4 (constructor) / @0x18d4 (destructor) in
// parity-out/sdk/dbgobj/CAMutex.o and sdk @0x1e38 / @0x1e48 in CAGuard.o.
//
// CATry / CACatch / CASwallowException are kept as declared (the ported code does not use them so far).
#ifndef CAEXCEPTION_H_INCLUDED
#define CAEXCEPTION_H_INCLUDED
#include <CoreAudio/CoreAudioTypes.h>
class CAException
{
public:
CAException(OSStatus inError) : mError(inError) {}
CAException(const CAException& inException) : mError(inException.mError) {}
CAException& operator=(const CAException& inException) { mError = inException.mError; return *this; }
~CAException() {}
OSStatus GetError() const { return mError; }
protected:
OSStatus mError;
};
#define CATry try{
#define CACatch }catch(const CAException& inException) {} catch(...) {}
#define CASwallowException(inExpression) try { inExpression; } catch(...) {}
#endif

132
port/external/openal/CAGuard.cpp vendored Normal file
View file

@ -0,0 +1,132 @@
// Port of pflib/external/openal/CAGuard.cpp (Apple Core Audio utility class, Playground SDK 4.0): CAGuard, a
// CAMutex with a condition variable for signalling. The Wait calls require the guard to be owned by the calling
// thread (otherwise they throw CAException(1)); they clear mOwner while the wait unlocks the pthread mutex and
// restore it before returning. WaitFor / WaitUntil return true when the timeout expired, false when notified.
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/CAGuard.o).
//
// Game vs. SDK (the game wins): the same code; the game inlines CAHostTimeBase::GetCurrentTimeInNanos into
// WaitUntil (the SDK calls it out of line). pthread_cond_timedwait_relative_np and the timespec split of WaitFor
// are Darwin-specific, as in both builds. The timeout error is compared against ETIMEDOUT (0x3c in the binaries),
// written by its portable name. The SDK's C2 / D2 copies (sdk @0x000 / @0x164) are the same code as C1 / D1; the
// game has only C1 (game @0x00145980) and D1 / D0.
#include "CAGuard.h"
#include "CAException.h"
#include "CAHostTimeBase.h"
#include <errno.h>
// game @0x00145980 (C1) sdk @0x000 / @0x0b2
CAGuard::CAGuard(const char* inName) :
CAMutex(inName)
{
OSStatus theError = pthread_cond_init(&mCondVar, NULL);
if (theError != 0)
{
throw CAException(theError);
}
}
// game @0x00145702 (D1)
// game @0x00145748 (D0) sdk @0x164 / @0x1e0 / @0x25c
CAGuard::~CAGuard()
{
pthread_cond_destroy(&mCondVar);
}
// game @0x00145a06 sdk @0x2d8
void CAGuard::Wait()
{
if (!pthread_equal(pthread_self(), mOwner))
{
throw CAException(1);
}
mOwner = NULL;
OSStatus theError = pthread_cond_wait(&mCondVar, &mMutex);
if (theError != 0)
{
throw CAException(theError);
}
mOwner = pthread_self();
}
// game @0x00145a9c sdk @0x3c4
bool CAGuard::WaitFor(UInt64 inNanos)
{
// The SDK object has a function-scoped kNanosPerSecond (__literal8 @0x20c8, 0x3b9aca00); both builds fold it
// into the comparison and the two divisions below.
static const UInt64 kNanosPerSecond = 1000000000;
bool theAnswer = false;
if (!pthread_equal(pthread_self(), mOwner))
{
throw CAException(1);
}
timespec theTimeSpec;
if (inNanos <= kNanosPerSecond)
{
theTimeSpec.tv_sec = 0;
theTimeSpec.tv_nsec = static_cast<long>(inNanos);
}
else
{
theTimeSpec.tv_sec = static_cast<long>(inNanos / kNanosPerSecond);
theTimeSpec.tv_nsec = static_cast<long>(inNanos % kNanosPerSecond);
}
mOwner = NULL;
OSStatus theError = pthread_cond_timedwait_relative_np(&mCondVar, &mMutex, &theTimeSpec);
if (theError != 0 && theError != ETIMEDOUT)
{
throw CAException(theError);
}
mOwner = pthread_self();
theAnswer = theError == ETIMEDOUT;
return theAnswer;
}
// game @0x00145796 sdk @0x548
bool CAGuard::WaitUntil(UInt64 inNanos)
{
bool theAnswer = false;
UInt64 theCurrentNanos = CAHostTimeBase::GetCurrentTimeInNanos();
if (theCurrentNanos < inNanos)
{
theAnswer = WaitFor(inNanos - theCurrentNanos);
}
return theAnswer;
}
// game @0x00145bc6 sdk @0x5c8
void CAGuard::Notify()
{
OSStatus theError = pthread_cond_signal(&mCondVar);
if (theError != 0)
{
throw CAException(theError);
}
}
// game @0x0014592c sdk @0x632
void CAGuard::NotifyAll()
{
OSStatus theError = pthread_cond_broadcast(&mCondVar);
if (theError != 0)
{
throw CAException(theError);
}
}

35
port/external/openal/CAGuard.h vendored Normal file
View file

@ -0,0 +1,35 @@
// Port of pflib/external/openal/CAGuard.h (Apple Core Audio utility class, Playground SDK 4.0): CAGuard, a CAMutex
// with a condition variable for signalling; Wait / WaitFor / WaitUntil require the calling thread to own the
// guard, release the ownership while waiting and take it back afterwards. CAGuard.cpp is ported next to this file.
// Layout from the DWARF of parity-out/sdk/dbgobj/CAGuard.o (size 84): the CAMutex base (+0x00..+0x37),
// +0x38 mCondVar.
//
// The SDK header's nested Locker helper class and its Log_Average_Latency members are not carried (no ported code
// uses them).
#ifndef CAGUARD_H_INCLUDED
#define CAGUARD_H_INCLUDED
#include "CAMutex.h"
#include <MacTypes.h>
#include <pthread.h>
class CAGuard : public CAMutex
{
public:
CAGuard(const char* inName);
virtual ~CAGuard();
virtual void Wait();
virtual bool WaitFor(UInt64 inNanos);
virtual bool WaitUntil(UInt64 inNanos);
virtual void Notify();
virtual void NotifyAll();
protected:
pthread_cond_t mCondVar;
};
#endif

48
port/external/openal/CAHostTimeBase.cpp vendored Normal file
View file

@ -0,0 +1,48 @@
// Port of pflib/external/openal/CAHostTimeBase.cpp (Apple Core Audio utility class, Playground SDK 4.0):
// CAHostTimeBase::Initialize and the static members. Initialize reads the mach time base once and stores the
// conversion factors; the conversions call it lazily through sIsInited.
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/CAHostTimeBase.o).
//
// Game vs. SDK (the game wins): the game binary has no sUseMicroseconds symbol, so it is not defined here (the SDK
// object defines it). Initialize stores the same values in the same order in both builds; the game folds the
// mach_timebase_info fields back into the reads that the SDK debug build does from the just-stored statics.
//
// Host difference: the local below needs the elaborated `struct` keyword with clang, because mach_timebase_info
// is also a function name in mach/mach_time.h; the SDK built with GCC 4.0 accepted the bare type name.
//
// The statics are zero in the shipped image (game __data @0x1e8200..0x1e821f): sIsInited 0x1e8200,
// sFromNanosDenominator 0x1e8204, sFromNanosNumerator 0x1e8208, sToNanosDenominator 0x1e820c,
// sToNanosNumerator 0x1e8210, sMinDelta 0x1e8214, sFrequency 0x1e8218.
#pragma STDC FP_CONTRACT OFF
#include "CAHostTimeBase.h"
bool CAHostTimeBase::sIsInited;
Float64 CAHostTimeBase::sFrequency;
UInt32 CAHostTimeBase::sMinDelta;
UInt32 CAHostTimeBase::sToNanosNumerator;
UInt32 CAHostTimeBase::sToNanosDenominator;
UInt32 CAHostTimeBase::sFromNanosNumerator;
UInt32 CAHostTimeBase::sFromNanosDenominator;
// game @0x00156d10 sdk @0x000
// The statement order is the SDK debug build's (sMinDelta first, sIsInited last); the game stores the same values
// in the same order. The two sFromNanos statics are copied from the just-stored sToNanos ones (the SDK code loads
// them back from the globals). sFrequency divides by numer first, then multiplies by 1e9 (both builds evaluate
// the quotient before the multiplication).
void CAHostTimeBase::Initialize()
{
struct mach_timebase_info theTimeBaseInfo;
mach_timebase_info(&theTimeBaseInfo);
sMinDelta = 1;
sToNanosNumerator = theTimeBaseInfo.numer;
sToNanosDenominator = theTimeBaseInfo.denom;
sFromNanosNumerator = sToNanosDenominator;
sFromNanosDenominator = sToNanosNumerator;
sFrequency = static_cast<Float64>(sToNanosDenominator) / static_cast<Float64>(sToNanosNumerator) * 1000000000.0;
sIsInited = true;
}

140
port/external/openal/CAHostTimeBase.h vendored Normal file
View file

@ -0,0 +1,140 @@
// Port of pflib/external/openal/CAHostTimeBase.h (Apple Core Audio utility class, Playground SDK 4.0): the host
// clock (mach_absolute_time) and the conversion between host ticks and nanoseconds; all members are static.
// CAHostTimeBase.cpp is ported next to this file.
//
// The members defined inline below are header code. The SDK build emits GetTheCurrentTime, ConvertToNanos and
// GetCurrentTimeInNanos out of line in CAGuard.o (sdk @0x1e50 / @0x1e78 / @0x207e); the game inlines them
// (CAGuard::WaitUntil expands GetCurrentTimeInNanos).
//
// Game vs. SDK: the game binary has no sUseMicroseconds symbol, so the member below stays declared but is not
// defined (the SDK's CAHostTimeBase.cpp defines it). The Track_Host_TimeBase tracking of the SDK header
// (sLastTime, DebugMessageN2) is debug-only and left out. The Windows branches of the SDK header are not carried
// (macOS build); the commented-out Assert() lines of its inline bodies are dropped like the other debug-only notes.
//
// The statics are zero in the shipped image (game __data @0x1e8200..0x1e821f): sIsInited 0x1e8200,
// sFromNanosDenominator 0x1e8204, sFromNanosNumerator 0x1e8208, sToNanosDenominator 0x1e820c,
// sToNanosNumerator 0x1e8210, sMinDelta 0x1e8214, sFrequency 0x1e8218.
#ifndef CAHOSTTIMEBASE_H_INCLUDED
#define CAHOSTTIMEBASE_H_INCLUDED
#include <CoreAudio/CoreAudioTypes.h>
#include <mach/mach_time.h>
class CAHostTimeBase
{
public:
static UInt64 ConvertToNanos(UInt64 inHostTime);
static UInt64 ConvertFromNanos(UInt64 inNanos);
static UInt64 GetTheCurrentTime();
static UInt64 GetCurrentTime() { return GetTheCurrentTime(); }
static UInt64 GetCurrentTimeInNanos();
static Float64 GetFrequency() { if(!sIsInited) { Initialize(); } return sFrequency; }
static UInt32 GetMinimumDelta() { if(!sIsInited) { Initialize(); } return sMinDelta; }
static UInt64 AbsoluteHostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime);
static SInt64 HostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime);
private:
static void Initialize();
static bool sIsInited;
static Float64 sFrequency;
static UInt32 sMinDelta;
static UInt32 sToNanosNumerator;
static UInt32 sToNanosDenominator;
static UInt32 sFromNanosNumerator;
static UInt32 sFromNanosDenominator;
static bool sUseMicroseconds; // SDK-only: no symbol in the game binary (see the note above)
};
inline UInt64 CAHostTimeBase::GetTheCurrentTime()
{
UInt64 theTime = 0;
theTime = mach_absolute_time();
return theTime;
}
inline UInt64 CAHostTimeBase::ConvertToNanos(UInt64 inHostTime)
{
if(!sIsInited)
{
Initialize();
}
Float64 theNumerator = static_cast<Float64>(sToNanosNumerator);
Float64 theDenominator = static_cast<Float64>(sToNanosDenominator);
Float64 theHostTime = static_cast<Float64>(inHostTime);
Float64 thePartialAnswer = theHostTime / theDenominator;
Float64 theFloatAnswer = thePartialAnswer * theNumerator;
UInt64 theAnswer = static_cast<UInt64>(theFloatAnswer);
return theAnswer;
}
inline UInt64 CAHostTimeBase::ConvertFromNanos(UInt64 inNanos)
{
if(!sIsInited)
{
Initialize();
}
Float64 theNumerator = static_cast<Float64>(sToNanosNumerator);
Float64 theDenominator = static_cast<Float64>(sToNanosDenominator);
Float64 theNanos = static_cast<Float64>(inNanos);
Float64 thePartialAnswer = theNanos / theNumerator;
Float64 theFloatAnswer = thePartialAnswer * theDenominator;
UInt64 theAnswer = static_cast<UInt64>(theFloatAnswer);
return theAnswer;
}
inline UInt64 CAHostTimeBase::GetCurrentTimeInNanos()
{
return ConvertToNanos(GetTheCurrentTime());
}
inline UInt64 CAHostTimeBase::AbsoluteHostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime)
{
UInt64 theAnswer;
if(inStartTime <= inEndTime)
{
theAnswer = inEndTime - inStartTime;
}
else
{
theAnswer = inStartTime - inEndTime;
}
return ConvertToNanos(theAnswer);
}
inline SInt64 CAHostTimeBase::HostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime)
{
SInt64 theAnswer;
SInt64 theSign = 1;
if(inStartTime <= inEndTime)
{
theAnswer = inEndTime - inStartTime;
}
else
{
theAnswer = inStartTime - inEndTime;
theSign = -1;
}
return theSign * ConvertToNanos(theAnswer);
}
#endif

126
port/external/openal/CAMutex.cpp vendored Normal file
View file

@ -0,0 +1,126 @@
// Port of pflib/external/openal/CAMutex.cpp (Apple Core Audio utility class, Playground SDK 4.0): CAMutex, a
// pthread mutex that also remembers its owning thread. Lock / Try return without touching the pthread mutex when
// the calling thread already owns the mutex (the answer tells the caller whether it must Unlock); all pthread
// errors throw CAException(theError).
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/CAMutex.o).
//
// Game vs. SDK (the game wins): the SDK's debug build writes a message in Unlock when a thread that does not own
// the mutex calls it ("CAMutex::Unlock: A thread is attempting to unlock a Mutex it doesn't own", a WriteDbg that
// touches no state); the game is a release build and has no code for that branch. Everything else matches. The
// SDK's C1 copy of the constructor (sdk @0x094) is the same code as C2; the game has only C2.
//
// Platform calls: POSIX threads as in both builds. The trylock error is compared against EBUSY (0x10 in the
// binaries), written by its portable name.
#include "CAMutex.h"
#include "CAException.h"
#include <errno.h>
// game @0x00145d8a (C2) sdk @0x000 / @0x094
CAMutex::CAMutex(const char* inName) :
mName(inName),
mOwner(NULL)
{
OSStatus theError = pthread_mutex_init(&mMutex, NULL);
if (theError != 0)
{
throw CAException(theError);
}
}
// game @0x00145c18 (D2)
// game @0x00145c40 (D1)
// game @0x00145c68 (D0) sdk @0x128 / @0x16a / @0x1ac
CAMutex::~CAMutex()
{
pthread_mutex_destroy(&mMutex);
}
// game @0x00145dfa sdk @0x1ee
bool CAMutex::Lock()
{
bool theAnswer = false;
pthread_t theCurrentThread = pthread_self();
if (!pthread_equal(theCurrentThread, mOwner))
{
OSStatus theError = pthread_mutex_lock(&mMutex);
if (theError != 0)
{
throw CAException(theError);
}
mOwner = theCurrentThread;
theAnswer = true;
}
return theAnswer;
}
// game @0x00145e7e sdk @0x294
void CAMutex::Unlock()
{
pthread_t theCurrentThread = pthread_self();
if (pthread_equal(theCurrentThread, mOwner))
{
mOwner = NULL;
OSStatus theError = pthread_mutex_unlock(&mMutex);
if (theError != 0)
{
throw CAException(theError);
}
}
// else: the SDK's debug build warns here (see the file note); the game has no code for this branch.
}
// game @0x00145c9a sdk @0x336
bool CAMutex::Try(bool& outWasLocked)
{
bool theAnswer = false;
outWasLocked = false;
pthread_t theCurrentThread = pthread_self();
if (!pthread_equal(theCurrentThread, mOwner))
{
int theError = pthread_mutex_trylock(&mMutex);
if (theError == 0)
{
mOwner = theCurrentThread;
theAnswer = true;
outWasLocked = true;
}
else if (theError == EBUSY)
{
theAnswer = false;
outWasLocked = false;
}
else
{
throw CAException(theError);
}
}
else
{
theAnswer = true;
outWasLocked = false;
}
return theAnswer;
}
// game @0x00145d4a sdk @0x416
bool CAMutex::IsFree() const
{
return mOwner == NULL;
}
// game @0x00145d5e sdk @0x42c
bool CAMutex::IsOwnedByCurrentThread() const
{
pthread_t theCurrentThread = pthread_self();
return pthread_equal(theCurrentThread, mOwner) != 0;
}

32
port/external/openal/CAMutex.h vendored Normal file
View file

@ -0,0 +1,32 @@
// Port of pflib/external/openal/CAMutex.h (Apple Core Audio utility class, Playground SDK 4.0): CAMutex, a pthread
// mutex that remembers its owning thread, so Lock / Try on the owning thread return without touching the pthread
// mutex. CAMutex.cpp is ported next to this file. Layout from the DWARF of parity-out/sdk/dbgobj/CAMutex.o
// (size 56): +0x00 vtable, +0x04 mName, +0x08 mOwner, +0x0c mMutex.
//
// The SDK header's nested Locker helper class is not carried (no ported code uses it). Callers lock with
// `bool wasLocked = guard.Lock();` and unlock only when that returned true (DWARF local "wasLocked").
#ifndef CAMUTEX_H_INCLUDED
#define CAMUTEX_H_INCLUDED
#include <pthread.h>
class CAMutex
{
public:
CAMutex(const char* inName);
virtual ~CAMutex();
virtual bool Lock();
virtual void Unlock();
virtual bool Try(bool& outWasLocked);
virtual bool IsFree() const;
virtual bool IsOwnedByCurrentThread() const;
protected:
const char* mName;
pthread_t mOwner;
pthread_mutex_t mMutex;
};
#endif

View file

@ -0,0 +1,64 @@
// Port of the out-of-line operator==(AudioStreamBasicDescription, AudioStreamBasicDescription) of Apple's
// CAStreamBasicDescription (the game links it from the statically linked OpenAL; declared in
// CAStreamBasicDescription.h). Ported from the shipped game binary (release build): game @0x00145ef2, no SDK copy.
//
// Equality with wildcards: a zero field on either side matches anything. The sample rate is compared as double
// (equal and not NaN), the format ids, packet/frame/channel/bit fields by MATCH, and the format flags by
// MatchFormatFlags, which for linear PCM first drops the flags that do not matter (the all-clear bit 0x80000000;
// aligned-high 0x10 when both are packed; signed-integer 0x4 when both are float; big-endian 0x2 for packed formats
// of 8 bits or less; non-interleaved 0x20 when both have fewer than two channels). The game tests "< 2" channels
// (not "== 1") for the last rule.
#include "CAStreamBasicDescription.h"
#pragma STDC FP_CONTRACT OFF
#define CA_MATCH(field) (x.field == 0 || y.field == 0 || x.field == y.field)
// game @0x00145ef2
bool operator==(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y)
{
if (!(x.mSampleRate == 0.0 || y.mSampleRate == 0.0))
{
if (x.mSampleRate != y.mSampleRate)
return false;
if (x.mSampleRate != x.mSampleRate || y.mSampleRate != y.mSampleRate)
return false;
}
if (!CA_MATCH(mFormatID))
return false;
uint32_t xFlags = x.mFormatFlags;
uint32_t yFlags = y.mFormatFlags;
if (x.mFormatID != 0 && y.mFormatID != 0 && xFlags != 0 && yFlags != 0)
{
if (x.mFormatID == 0x6c70636d) // 'lpcm'
{
xFlags &= 0x7fffffff;
yFlags &= 0x7fffffff;
if (xFlags & yFlags & 8)
{
xFlags &= ~0x10u;
yFlags &= ~0x10u;
}
if (xFlags & yFlags & 1)
{
xFlags &= ~4u;
yFlags &= ~4u;
}
if (x.mBitsPerChannel < 9 && (xFlags & 8))
xFlags &= ~2u;
if (y.mBitsPerChannel < 9 && (yFlags & 8))
yFlags &= ~2u;
if (x.mChannelsPerFrame < 2 && y.mChannelsPerFrame < 2)
{
xFlags &= ~0x20u;
yFlags &= ~0x20u;
}
}
if (xFlags != yFlags)
return false;
}
return CA_MATCH(mBytesPerPacket) && CA_MATCH(mFramesPerPacket) && CA_MATCH(mBytesPerFrame) &&
CA_MATCH(mChannelsPerFrame) && CA_MATCH(mBitsPerChannel);
}

View file

@ -0,0 +1,61 @@
// Declarations of pflib/external/openal/CAStreamBasicDescription.h (Apple Core Audio utility class, Playground
// SDK 4.0). CAStreamBasicDescription.cpp is not part of this port slice: its out-of-line code is only declared
// here. Layout (DWARF, parity-out/sdk/dbgobj/CAStreamBasicDescription.o): an AudioStreamBasicDescription
// (size 40) with no members of its own.
//
// The inline members below are header code; the OpenAL objects emit them out of line in the SDK build
// (oalSource.o: CAStreamBasicDescription() sdk @0x349f6, SetFrom sdk @0x34a24, NumberChannels sdk @0x34a6c) and
// the game inlines them everywhere (the default constructor is the 10-word zero fill before every copy).
// operator==(const AudioStreamBasicDescription&, const AudioStreamBasicDescription&) is out of line in the game
// (game @0x00145ef2).
#ifndef CASTREAMBASICDESCRIPTION_H_INCLUDED
#define CASTREAMBASICDESCRIPTION_H_INCLUDED
#include <CoreAudio/CoreAudioTypes.h>
#include <string.h>
class CAStreamBasicDescription : public AudioStreamBasicDescription
{
public:
CAStreamBasicDescription() { memset(this, 0, sizeof(AudioStreamBasicDescription)); }
CAStreamBasicDescription(const AudioStreamBasicDescription& desc) { SetFrom(desc); }
CAStreamBasicDescription& operator=(const AudioStreamBasicDescription& v)
{
SetFrom(v);
return *this;
}
void SetFrom(const AudioStreamBasicDescription& desc)
{
memcpy(this, &desc, sizeof(AudioStreamBasicDescription));
}
UInt32 NumberChannels() const { return mChannelsPerFrame; }
// header code (sdk @0x907e in oalDevice.o; inlined in the game): native float, non-interleaved
// channels add kAudioFormatFlagIsNonInterleaved and use one sample per frame.
void SetCanonical(UInt32 nChannels, bool interleaved)
{
mFormatID = kAudioFormatLinearPCM;
mFormatFlags = kAudioFormatFlagsNativeFloatPacked; // kAudioFormatFlagsCanonical of the 10.4 SDK (9)
mBitsPerChannel = 8 * sizeof(Float32);
mChannelsPerFrame = nChannels;
mFramesPerPacket = 1;
if (interleaved)
{
mBytesPerPacket = mBytesPerFrame = nChannels * sizeof(Float32);
}
else
{
mBytesPerPacket = mBytesPerFrame = sizeof(Float32);
mFormatFlags |= kAudioFormatFlagIsNonInterleaved;
}
}
};
bool operator==(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y);
#endif

113
port/external/openal/OALCaptureDevice.h vendored Normal file
View file

@ -0,0 +1,113 @@
// Declarations of pflib/external/openal/OALCaptureDevice.h (Apple OpenAL, Playground SDK 4.0): OALCaptureDevice,
// an ALC capture device. Layout from the DWARF of parity-out/sdk/dbgobj/oalImp.o (size 180): +0x00 mSelfToken,
// +0x04 mCurrentError, +0x08 mCaptureOn, +0x0c mStoreSampleTime, +0x14 mFetchSampleTime, +0x1c mInputUnit,
// +0x20 mNativeFormat, +0x48 mRequestedFormat, +0x70 mOutputFormat, +0x98 mRingBuffer, +0x9c mBufferData,
// +0xa0 mAudioConverter, +0xa4 mSampleRateRatio, +0xac mRequestedRingFrames, +0xb0 mAudioInputPtrs.
//
// Of oalCaptureDevice.cpp only SetError has code in the game (ported in oalCaptureDevice.cpp); the rest of the
// class has no game code and is only declared (not part of this port slice). OALCaptureDeviceMap (also declared
// in Apple's OALCaptureDevice.h) is oalImp code and ported at the bottom of this header: its out-of-line code
// is in the SDK's oalImp.o (sdk @); the game inlines the Get call of SetDeviceError.
#ifndef OALCAPTUREDEVICE_H_INCLUDED
#define OALCAPTUREDEVICE_H_INCLUDED
#include "oal_sysdecls.h"
#include "CAStreamBasicDescription.h"
#include <map>
#include <stdint.h>
class CABufferList;
class OALRingBuffer;
class OALCaptureDevice
{
public:
OALCaptureDevice(const char* inDeviceName, uintptr_t inSelfToken, UInt32 inSampleRate, UInt32 inFormat,
UInt32 inBufferSize);
~OALCaptureDevice();
void StartCapture();
void StopCapture();
OSStatus GetFrames(UInt32 inFrameCount, UInt8* inBuffer);
UInt32 AvailableFrames();
void SetError(ALenum errorCode);
ALenum GetError();
private:
void InitializeAU(const char* inDeviceName);
static OSStatus InputProc(void* inRefCon, AudioUnitRenderActionFlags* inActionFlags,
const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames,
AudioBufferList* ioData);
static OSStatus ACComplexInputDataProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets,
AudioBufferList* ioData,
AudioStreamPacketDescription** outDataPacketDescription,
void* inUserData);
uintptr_t mSelfToken;
ALenum mCurrentError;
bool mCaptureOn;
SInt64 mStoreSampleTime;
SInt64 mFetchSampleTime;
AudioUnit mInputUnit;
CAStreamBasicDescription mNativeFormat;
CAStreamBasicDescription mRequestedFormat;
CAStreamBasicDescription mOutputFormat;
OALRingBuffer* mRingBuffer;
UInt8* mBufferData;
AudioConverterRef mAudioConverter;
Float64 mSampleRateRatio;
UInt32 mRequestedRingFrames;
CABufferList* mAudioInputPtrs;
};
// The capture-device map of oalImp.cpp (gOALCaptureDeviceMap). Get is the only member the game uses (inlined
// in SetDeviceError); every member's out-of-line code is in the SDK's oalImp.o (sdk @ below). Size() has no
// out-of-line code in either build (nothing calls it); the destructor is emitted out of line in the SDK build.
class OALCaptureDeviceMap : std::multimap<uintptr_t, OALCaptureDevice*, std::less<uintptr_t> >
{
public:
// sdk @0x5ce9c (oalImp.o)
OALCaptureDeviceMap() {}
// sdk @0x5cca4 (oalImp.o)
~OALCaptureDeviceMap() {}
// sdk @0x5e358 (oalImp.o)
void Add(const uintptr_t inDeviceToken, OALCaptureDevice** inDevice)
{
iterator it = upper_bound(inDeviceToken);
insert(it, value_type(inDeviceToken, *inDevice));
}
// sdk @0x5c188 (oalImp.o)
OALCaptureDevice* Get(uintptr_t inDeviceToken)
{
iterator it = find(inDeviceToken);
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5cb8c (oalImp.o)
void Remove(const uintptr_t inDeviceToken)
{
iterator it = find(inDeviceToken);
if (it != end())
{
erase(it);
}
}
// no out-of-line code in either build (nothing calls it)
UInt32 Size() const { return (UInt32)size(); }
// sdk @0x5af3c (oalImp.o)
bool Empty() const { return empty(); }
};
#endif

81
port/external/openal/oalAtomicStack.h vendored Normal file
View file

@ -0,0 +1,81 @@
// Port of pflib/external/openal/oalAtomicStack.h (Apple OpenAL, Playground SDK 4.0): TAtomicStack, a lock-free
// LIFO of objects with get_next / set_next (OALSource's PlaybackMessage queue). Header code: the SDK build emits
// the TAtomicStack<PlaybackMessage> members out of line in oalSource.o (__textcoal_nt: TAtomicStack()
// sdk @0x34fd2, push_NA sdk @0x351da, compare_and_swap sdk @0x35700, pop_all sdk @0x3572c, pop_all_reversed
// sdk @0x35772, push_atomic sdk @0x357c4); the game inlines all of them (the CompareAndSwap loops in
// OALSource::Pause, Stop, Play, ... and the reversal loop in DoPostRender).
// Layout (DWARF): +0x00 mHead.
//
// Host difference: compare_and_swap calls CompareAndSwap(UInt32, UInt32, UInt32*) on the pointers in both builds;
// on the LP64 host the pointers do not fit, so a pointer-sized atomic compare-and-swap with the same result
// (true when *pvalue was oldvalue and newvalue was stored) is used there.
#ifndef OALATOMICSTACK_H_INCLUDED
#define OALATOMICSTACK_H_INCLUDED
#include "oal_sysdecls.h"
template <class T>
class TAtomicStack
{
public:
TAtomicStack() : mHead(NULL) {}
// non-atomic push: only for a stack no other thread sees
void push_NA(T* item)
{
item->set_next(mHead);
mHead = item;
}
void push_atomic(T* item)
{
T* head;
do
{
head = mHead;
item->set_next(head);
} while (!compare_and_swap(head, item, &mHead));
}
T* pop_all()
{
T* result;
do
{
if ((result = mHead) == NULL)
{
break;
}
} while (!compare_and_swap(result, NULL, &mHead));
return result;
}
T* pop_all_reversed()
{
TAtomicStack<T> reversed;
T* p = pop_all();
T* next;
while (p != NULL)
{
next = p->get_next();
reversed.push_NA(p);
p = next;
}
return reversed.mHead;
}
static bool compare_and_swap(T* oldvalue, T* newvalue, T** pvalue)
{
#if __LP64__
return __sync_bool_compare_and_swap(pvalue, oldvalue, newvalue);
#else
return CompareAndSwap(UInt32(oldvalue), UInt32(newvalue), (UInt32*)pvalue);
#endif
}
protected:
T* mHead;
};
#endif

374
port/external/openal/oalBuffer.cpp vendored Normal file
View file

@ -0,0 +1,374 @@
// Port of pflib/external/openal/oalBuffer.cpp (Apple OpenAL, Playground SDK 4.0): OALBuffer, the data behind an AL
// buffer name. AddAudioData copies (or, for mono data when asked, pre-converts to native float with an
// AudioConverter) the caller's PCM data; the attached-source list counts how often each source has the buffer
// queued, under mSourceListGuard, so a buffer in use is neither modified nor deleted.
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/oalBuffer.o).
//
// Game vs. SDK (the game wins): the SDK's WriteDbg messages (AddAudioData's "waiting one render cycle" and
// "attached sources" messages, the catch messages) are not in the game. Everything else matches; the game inlines
// the AttachedSourceList helpers, CAStreamBasicDescription's constructor / SetFrom / NumberChannels and
// ~AttachedSourceList. ConvertDataForBuffer's UInt32(destFormat.mSampleRate) is the saturating SSE conversion of
// both builds (OALConvertFloat64ToUInt32).
//
// Exceptions: AddAudioData catches an OSStatus (alSetError(result), rethrown as OSStatus) and anything else
// (alSetError(AL_INVALID_OPERATION), throw -1) around its whole body (LSDA game @0x00217e3c: call sites
// @0x00122994..@0x00122ba4). ConvertDataForBuffer returns the caught OSStatus, or AL_INVALID_OPERATION for any
// other exception (LSDA @0x00217e10: @0x00122610..@0x00122815; the throws before @0x00122610 are inside the try
// as well in the source, with the same result).
//
// sdk only (no code in the game, not ported): GetFramesToBytes (sdk @0x476), CanBufferDataBeModified (sdk @0x4e4),
// AddAudioDataStatic (sdk @0x988). The OALBuffer(ALuint) / ~OALBuffer C2 / D2 copies of the SDK (sdk @0xfde /
// @0xe40) are the same code as the C1 / D1 ones.
//
// Strings (game __cstring): "OALBuffer::SourceListGuard" @0x00161ddc. The object has no static initializer.
#pragma STDC FP_CONTRACT OFF
#include "oalBuffer.h"
#include "oalImp.h"
#include "oalOSX.h"
#include "oalSource.h"
#include <stdlib.h>
#include <string.h>
// game @0x00122ec4 sdk @0xf0a
OALBuffer::OALBuffer(const ALuint inSelfToken) :
mSelfToken(inSelfToken),
mSourceListGuard("OALBuffer::SourceListGuard"),
mData(NULL),
mAppOwnsBufferMemory(false),
mDataSize(0),
mPreConvertedDataSize(0),
mDataHasBeenConverted(false),
mAttachedSourceList(NULL)
{
mAttachedSourceList = new AttachedSourceList();
}
// game @0x00122d82 sdk @0xd76
OALBuffer::~OALBuffer()
{
if (!mAppOwnsBufferMemory && mData)
{
free(mData);
}
bool wasLocked = mSourceListGuard.Lock();
if (mAttachedSourceList)
{
delete mAttachedSourceList;
}
if (wasLocked)
{
mSourceListGuard.Unlock();
}
}
// game @0x001225c4 sdk @0x0
// Converts the caller's data to native-endian packed float with the source's channel count (mono flagged
// non-interleaved) into mData. mPreConvertedDataFormat keeps the original format.
OSStatus OALBuffer::ConvertDataForBuffer(void* inData, UInt32 inDataSize, UInt32 inDataFormat, UInt32 inDataSampleRate)
{
OSStatus result = noErr;
try
{
AudioConverterRef converter;
CAStreamBasicDescription destFormat;
UInt32 framesOfSource = 0;
if (inData == NULL)
{
throw ((OALStatusException)AL_INVALID_OPERATION);
}
result = FillInASBD(mPreConvertedDataFormat, inDataFormat, inDataSampleRate);
if (result != noErr)
{
throw ((OALStatusException)result);
}
if (mPreConvertedDataFormat.NumberChannels() == 1)
{
mPreConvertedDataFormat.mFormatFlags |= kAudioFormatFlagIsNonInterleaved;
}
destFormat.mChannelsPerFrame = mPreConvertedDataFormat.NumberChannels();
destFormat.mSampleRate = mPreConvertedDataFormat.mSampleRate;
destFormat.mFormatID = kAudioFormatLinearPCM;
if (mPreConvertedDataFormat.NumberChannels() == 1)
{
destFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
}
else
{
destFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
}
destFormat.mFramesPerPacket = 1;
destFormat.mBitsPerChannel = sizeof(Float32) * 8;
destFormat.mBytesPerPacket = sizeof(Float32) * destFormat.NumberChannels();
destFormat.mBytesPerFrame = sizeof(Float32) * destFormat.NumberChannels();
result = FillInASBD(mDataFormat, inDataFormat, OALConvertFloat64ToUInt32(destFormat.mSampleRate));
if (result != noErr)
{
throw ((OALStatusException)result);
}
result = AudioConverterNew(&mPreConvertedDataFormat, &destFormat, &converter);
if (result != noErr)
{
throw ((OALStatusException)result);
}
framesOfSource = inDataSize / mPreConvertedDataFormat.mBytesPerFrame;
mDataSize = (UInt32)(framesOfSource * destFormat.mBytesPerFrame);
if (mData == NULL)
{
mData = (UInt8*)malloc(mDataSize);
}
if (mData == NULL)
{
throw ((OALStatusException)AL_INVALID_OPERATION);
}
result = AudioConverterConvertBuffer(converter, inDataSize, inData, &mDataSize, mData);
if (result == noErr)
{
mDataFormat.SetFrom(destFormat);
if (mPreConvertedDataFormat.NumberChannels() == 1)
{
mDataHasBeenConverted = true;
}
else
{
mDataHasBeenConverted = false;
}
}
AudioConverterDispose(converter);
}
catch (OALStatusException result)
{
return (OSStatus)result;
}
catch (...)
{
result = (OSStatus)AL_INVALID_OPERATION;
}
return result;
}
// game @0x001225ae sdk @0x4b0
UInt32 OALBuffer::GetFrameCount()
{
UInt32 totalPackets = mDataSize / mDataFormat.mBytesPerPacket;
return totalPackets * mDataFormat.mFramesPerPacket;
}
// game @0x00122976 sdk @0x58a
// The data of a buffer still attached to a source cannot change: after one render cycle the count is checked
// again and the call fails with AL_INVALID_OPERATION. Stereo data and data the caller does not want pre-converted
// is copied as is (mData is reused, reallocated to the new size, or allocated).
OSStatus OALBuffer::AddAudioData(char* inAudioData, UInt32 inAudioDataSize, ALenum format, ALsizei freq,
bool inPreConvertToHalFormat)
{
try
{
if (!IsFormatSupported(format))
{
throw ((OALStatusException)AL_INVALID_VALUE);
}
bool wasLocked = mSourceListGuard.Lock();
UInt32 attachedCount = mAttachedSourceList->Size();
if (wasLocked)
{
mSourceListGuard.Unlock();
}
if (attachedCount > 0)
{
WaitOneRenderCycle();
wasLocked = mSourceListGuard.Lock();
attachedCount = mAttachedSourceList->Size();
if (wasLocked)
{
mSourceListGuard.Unlock();
}
if (attachedCount > 0)
{
throw ((OALStatusException)AL_INVALID_OPERATION);
}
}
if (mAppOwnsBufferMemory)
{
mData = NULL;
mAppOwnsBufferMemory = false;
}
mPreConvertedDataSize = (UInt32)inAudioDataSize;
OSStatus result = noErr;
if (!inPreConvertToHalFormat || ((format == AL_FORMAT_STEREO16) || (format == AL_FORMAT_STEREO8)))
{
if (mData != NULL)
{
if (mDataSize != (UInt32)inAudioDataSize)
{
mDataSize = (UInt32)inAudioDataSize;
void* newDataPtr = realloc(mData, mDataSize);
mData = (UInt8*)newDataPtr;
}
}
else
{
mDataSize = (UInt32)inAudioDataSize;
mData = (UInt8*)malloc(mDataSize);
}
if (mData)
{
result = FillInASBD(mDataFormat, format, freq);
if (result != noErr)
{
throw ((OALStatusException)result);
}
mPreConvertedDataFormat.SetFrom(mDataFormat);
memcpy(mData, inAudioData, mDataSize);
}
}
else
{
result = ConvertDataForBuffer(inAudioData, inAudioDataSize, format, freq);
if (result != noErr)
{
throw ((OALStatusException)result);
}
}
}
catch (OALStatusException result)
{
alSetError((ALenum)result);
throw result;
}
catch (...)
{
alSetError(AL_INVALID_OPERATION);
throw -1;
}
return noErr;
}
// game @0x00122924 sdk @0xbd0
bool OALBuffer::IsPurgable()
{
bool returnValue = false;
bool wasLocked = mSourceListGuard.Lock();
if (mAttachedSourceList->Size() == 0)
{
returnValue = true;
}
if (wasLocked)
{
mSourceListGuard.Unlock();
}
return returnValue;
}
// game @0x00122c76 sdk @0xc24
// True when no source holds the buffer, or when every source holding it is about to flush its queues.
bool OALBuffer::CanBeRemovedFromBufferMap()
{
bool returnValue = true;
bool wasLocked = mSourceListGuard.Lock();
if (mAttachedSourceList->Size() == 0)
{
returnValue = true;
}
else
{
for (UInt32 i = 0; i < mAttachedSourceList->Size(); i++)
{
OALSource* curSource = mAttachedSourceList->GetSourceByIndex(i);
if (curSource != NULL)
{
if (!curSource->IsSourceTransitioningToFlushQ())
{
returnValue = false;
break;
}
}
}
}
if (wasLocked)
{
mSourceListGuard.Unlock();
}
return returnValue;
}
// game @0x00122856 sdk @0xcde
// Drops one attachment of inSource; true when that was its last one (the source is then removed from the list).
bool OALBuffer::ReleaseBuffer(OALSource* inSource)
{
bool returnValue = false;
bool wasLocked = mSourceListGuard.Lock();
if (mAttachedSourceList->SourceExists(inSource) == true)
{
UInt32 attachmentCount = mAttachedSourceList->DecreaseAttachmentCount(inSource);
if (attachmentCount == 0)
{
mAttachedSourceList->Remove(inSource);
returnValue = true;
}
}
if (wasLocked)
{
mSourceListGuard.Unlock();
}
return returnValue;
}
// game @0x00122e14 sdk @0x10b2
// Adds one attachment of inSource (a new list entry with count 1 the first time). Always returns false.
bool OALBuffer::UseThisBuffer(OALSource* inSource)
{
bool wasLocked = mSourceListGuard.Lock();
if (mAttachedSourceList->SourceExists(inSource) == true)
{
mAttachedSourceList->IncreaseAttachmentCount(inSource);
}
else
{
SourceAttachedInfo nuSourceInfo;
nuSourceInfo.mSource = inSource;
nuSourceInfo.mAttachedCount = 1;
mAttachedSourceList->Add(nuSourceInfo);
}
if (wasLocked)
{
mSourceListGuard.Unlock();
}
return false;
}

265
port/external/openal/oalBuffer.h vendored Normal file
View file

@ -0,0 +1,265 @@
// Port of pflib/external/openal/oalBuffer.h (Apple OpenAL, Playground SDK 4.0): OALBuffer, the object behind an
// AL buffer name (the audio data, its format, and the sources it is attached to), with AttachedSourceList and
// SourceAttachedInfo. Layouts from the DWARF of parity-out/sdk/dbgobj/oalBuffer.o (game offsets identical):
//
// OALBuffer (size 192): +0x00 mSelfToken, +0x04 mSourceListGuard (CAGuard), +0x58 mData, +0x5c mAppOwnsBufferMemory,
// +0x60 mDataSize, +0x64 mDataFormat, +0x8c mPreConvertedDataSize, +0x90 mPreConvertedDataFormat,
// +0xb8 mDataHasBeenConverted, +0xbc mAttachedSourceList.
// SourceAttachedInfo (size 8): +0x00 mSource, +0x04 mAttachedCount.
// AttachedSourceList (size 8): a std::list<SourceAttachedInfo> (gcc 4.0 libstdc++; the port uses the host list,
// whose observable behaviour is the same).
//
// The inline members defined below are header code. The SDK build emits them out of line (oalSource.o / oalBuffer.o
// __textcoal_nt, addresses at each member); the game inlines all of them except AttachedSourceList's constructor
// (game @0x00192410, __textcoal_nt). AttachedSourceList::Size counts the nodes (gcc 4.0 list::size), as in the
// game's inlined loops. GetPreConvertedBitsPerChannel, GetPreConvertedDataSize, GetFramesToBytes,
// CanBufferDataBeModified, AddAudioDataStatic and PrintFormat are only declared (no game code, not ported).
#ifndef OALBUFFER_H_INCLUDED
#define OALBUFFER_H_INCLUDED
#include "oal_sysdecls.h"
#include "CAGuard.h"
#include "CAStreamBasicDescription.h"
#include <list>
#include <map>
class OALSource;
struct SourceAttachedInfo
{
OALSource* mSource;
UInt32 mAttachedCount;
};
class AttachedSourceList : std::list<SourceAttachedInfo>
{
public:
// game @0x00192410 sdk @0x1d7d4 (oalBuffer.o)
AttachedSourceList() {}
// sdk @0x1d928 (oalBuffer.o)
void Add(SourceAttachedInfo& inSourceInfo)
{
push_back(inSourceInfo);
}
// sdk @0x1d60e (oalBuffer.o)
void Remove(OALSource* inSource)
{
iterator it = begin();
while (it != end())
{
if ((*it).mSource == inSource)
{
erase(it);
return;
}
else
{
++it;
}
}
return;
}
// sdk @0x1d002 (oalBuffer.o)
bool SourceExists(OALSource* inSource)
{
iterator it = begin();
while (it != end())
{
if ((*it).mSource == inSource)
{
return true;
}
++it;
}
return false;
}
// sdk @0x1d106 (oalBuffer.o)
void IncreaseAttachmentCount(OALSource* inSource)
{
iterator it = begin();
while (it != end())
{
if ((*it).mSource == inSource)
{
(*it).mAttachedCount++;
return;
}
++it;
}
return;
}
// sdk @0x1d074 (oalBuffer.o)
UInt32 DecreaseAttachmentCount(OALSource* inSource)
{
iterator it = begin();
while (it != end())
{
if ((*it).mSource == inSource)
{
(*it).mAttachedCount--;
return (*it).mAttachedCount;
}
++it;
}
return 0;
}
// sdk @0x1d264 (oalBuffer.o)
OALSource* GetSourceByIndex(short inIndex)
{
iterator it = begin();
std::advance(it, inIndex);
if (it != end())
{
return ((*it).mSource);
}
return (NULL);
}
// sdk @0x1d4e6 (oalBuffer.o)
UInt32 Size() const { return (UInt32)size(); }
bool Empty() const { return empty(); }
};
class OALBuffer
{
public:
OALBuffer(const ALuint inSelfToken);
~OALBuffer();
OSStatus AddAudioData(char* inAudioData, UInt32 inAudioDataSize, ALenum format, ALsizei freq,
bool inPreConvertToHalFormat);
OSStatus AddAudioDataStatic(char* inAudioData, UInt32 inAudioDataSize, ALenum format, ALsizei freq);
bool IsPurgable();
// sdk @0x34df4 (oalSource.o)
bool HasBeenConverted() { return mDataHasBeenConverted; }
// sdk @0x34e0a (oalSource.o)
UInt32 GetToken() { return mSelfToken; }
UInt32 GetFrameCount();
UInt32 GetFramesToBytes(UInt32 inOffsetInFrames);
// sdk @0x34e18 (oalSource.o)
Float64 GetSampleRate() { return mDataFormat.mSampleRate; }
// sdk @0x34e30 (oalSource.o)
UInt32 GetBytesPerPacket() { return mDataFormat.mBytesPerPacket; }
// sdk @0x34e3e (oalSource.o)
UInt32 GetFramesPerPacket() { return mDataFormat.mFramesPerPacket; }
UInt32 GetPreConvertedBitsPerChannel();
// sdk @0x34e4c (oalSource.o)
UInt32 GetNumberChannels() { return mDataFormat.NumberChannels(); }
UInt32 GetPreConvertedDataSize();
// sdk @0x34e62 (oalSource.o)
UInt8* GetDataPtr() { return mData; }
// sdk @0x34e70 (oalSource.o)
UInt32 GetDataSize() { return mDataSize; }
// sdk @0x34e7e (oalSource.o)
CAStreamBasicDescription* GetFormat() { return &mDataFormat; }
bool CanBufferDataBeModified();
bool CanBeRemovedFromBufferMap();
bool UseThisBuffer(OALSource* inSource);
bool ReleaseBuffer(OALSource* inSource);
void PrintFormat();
private:
OSStatus ConvertDataForBuffer(void* inData, UInt32 inDataSize, UInt32 inDataFormat, UInt32 inDataSampleRate);
ALuint mSelfToken;
CAGuard mSourceListGuard;
UInt8* mData;
bool mAppOwnsBufferMemory;
UInt32 mDataSize;
CAStreamBasicDescription mDataFormat;
UInt32 mPreConvertedDataSize;
CAStreamBasicDescription mPreConvertedDataFormat;
bool mDataHasBeenConverted;
AttachedSourceList* mAttachedSourceList;
};
// The buffer maps of oalImp.cpp (gOALBufferMap and gDeadOALBufferMap). Every member with out-of-line code has
// it in the SDK's oalImp.o (sdk @ below); the game inlines all of them. GetFirstItem and Empty have no
// out-of-line code in either build (nothing calls them) and neither map is ever deleted (no ~OALBufferMap
// symbol in either build).
class OALBufferMap : std::multimap<ALuint, OALBuffer*, std::less<ALuint> >
{
public:
// sdk @0x5cda0 (oalImp.o)
OALBufferMap() {}
// sdk @0x5de98 (oalImp.o)
void Add(const ALuint inBufferToken, OALBuffer** inBuffer)
{
iterator it = upper_bound(inBufferToken);
insert(it, value_type(inBufferToken, *inBuffer));
}
// sdk @0x5b24c (oalImp.o)
OALBuffer* GetBufferByIndex(UInt32 inIndex)
{
iterator it = begin();
for (UInt32 i = 0; i < inIndex; i++)
{
if (it != end())
{
it++;
}
else
{
i = inIndex;
}
}
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5bf1e (oalImp.o)
OALBuffer* Get(ALuint inBufferToken)
{
iterator it = find(inBufferToken);
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5c902 (oalImp.o)
void Remove(const ALuint inBufferToken)
{
iterator it = find(inBufferToken);
if (it != end())
{
erase(it);
}
}
// no out-of-line code in either build (nothing calls it)
OALBuffer* GetFirstItem()
{
iterator it = begin();
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5aeee (oalImp.o)
UInt32 Size() const { return (UInt32)size(); }
// no out-of-line code in either build (nothing calls it)
bool Empty() const { return empty(); }
};
#endif

View file

@ -0,0 +1,25 @@
// Port of pflib/external/openal/oalCaptureDevice.cpp (Apple OpenAL, Playground SDK 4.0), the part with game code:
// OALCaptureDevice::SetError. Ported from the shipped game binary (release build, "game @"), with names from the
// SDK debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/oalCaptureDevice.o).
//
// Not part of this slice (no game code; the game links no capture code besides SetError): the constructor
// (sdk @0x728 / @0xd60), destructor (sdk @0x0 / @0x8e), GetError (sdk @0x138), InitializeAU (sdk @0x156),
// InputProc (sdk @0x1398), ACComplexInputDataProc (sdk @0x14a0), StartCapture (sdk @0x1578), StopCapture
// (sdk @0x15ea), AvailableFrames (sdk @0x165c), GetFrames (sdk @0x198e).
//
// The object has no strings used here and no static initializer.
#pragma STDC FP_CONTRACT OFF
#include "OALCaptureDevice.h"
// game @0x00122598 sdk @0x11c
// As in OALDevice::SetError, the new error is only stored while an error is already pending (both builds).
void OALCaptureDevice::SetError(ALenum errorCode)
{
if (mCurrentError == ALC_NO_ERROR)
{
return;
}
mCurrentError = errorCode;
}

621
port/external/openal/oalContext.cpp vendored Normal file
View file

@ -0,0 +1,621 @@
// Port of pflib/external/openal/oalContext.cpp (Apple OpenAL, Playground SDK 4.0): OALContext, an AL context. It
// adds a 3DMixer node to its device's graph and configures one input bus per source (the first stereo-count
// busses stereo pass-through, the rest mono and spatialized), hands busses out to playing sources, and owns the
// live source map plus a map of deleted sources that wait until the render thread is done with them.
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/oalContext.o).
//
// Game vs. SDK (the game wins): the SDK's WriteDbg messages (InitRenderQualityOnBusses' spatial setting messages,
// GetAvailableMonoBus / GetAvailableStereoBus failures) are not in the game. The OALSourceMap, OALDevice and
// CAStreamBasicDescription header members (Get, Remove, Add, GetSourceByIndex, Size, GetGraph, GetOutputAU,
// GetFramesPerSlice, GetMixerRate, SetCanonical, the multimap destructor) are inlined in the game. Same calls in the
// same order otherwise.
//
// Kept as in both builds: the constructor counts attribute *pairs* in mAttributeListSize (plus one for the
// terminator) and copies only that many ALCints; the destructor deletes the source at index 0 while counting i up
// against the shrinking map size, so only about half of the remaining sources are deleted there.
//
// Exceptions: InitializeMixer rethrows an OSStatus and turns anything else into -1 (LSDA game @0x00217d30, whole
// body); AddSource rethrows anything (catch (...) { throw; }, LSDA @0x00217d78). The bus getters throw -1 (int)
// when no bus is left.
//
// sdk only (no code in the game, not ported): CopyAttributeList (sdk @0x0), ProcessContext (sdk @0x20),
// SuspendContext (sdk @0x28), SetDopplerVelocity (sdk @0x4e), SetListenerGain (sdk @0x72),
// GetDesiredRenderChannels (sdk @0x102), SetRenderQuality (sdk @0x498), SetReverbRoomType (sdk @0x1434),
// SetReverbLevel (sdk @0x14da), SetReverbState (sdk @0x1584), SetReverbQuality (sdk @0x15f6), SetReverbEQGain
// (sdk @0x1654), SetReverbEQBandwidth (sdk @0x1700), SetReverbEQFrequency (sdk @0x17ac), GetReverbQuality
// (sdk @0x1858), GetReverbEQGain (sdk @0x186a), GetReverbEQBandwidth (sdk @0x18dc), GetReverbEQFrequency
// (sdk @0x194e), SetReverbPreset (sdk @0x19c0), SetListenerVelocity (sdk @0x1cce), SetSpeedOfSound (sdk @0x1d0a),
// SetDopplerFactor (sdk @0x1d46), SetDistanceModel (sdk @0x1d82), SetListenerPosition (sdk @0x2ba8),
// SetListenerOrientation (sdk @0x2cc0). The C2 / D2 copies of the constructor and destructor (sdk @0x26ce /
// @0x21c2) are the same code as the C1 / D1 ones.
//
// The object has no strings in the game and no static initializer.
#pragma STDC FP_CONTRACT OFF
#include "oalContext.h"
#include "CAStreamBasicDescription.h"
#include "oalImp.h"
#include "oalOSX.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define THROW_RESULT \
if (result != noErr) \
{ \
throw ((OALStatusException)result); \
}
// game @0x0012106c sdk @0x30
void OALContext::ConnectMixerToDevice()
{
mOwningDevice->ConnectContext(this);
}
// game @0x00121088 sdk @0x50c
// Before the 2.0 3DMixer the bus attenuation curve is a single exponent: the attenuation at the maximum distance
// (rolloff model) expressed as 1 / maxDistance^(exponent + 1).
void OALContext::SetDistanceAttenuation(UInt32 inBusIndex, Float64 inRefDist, Float64 inMaxDist, Float64 inRolloff)
{
if (Get3DMixerVersion() < k3DMixerVersion_2_0)
{
Float64 maxattenuationDB = 20 * log10(inRefDist / (((inMaxDist - inRefDist) * inRolloff) + inRefDist));
Float64 maxattenuation = pow(10, (maxattenuationDB / 20));
Float64 distAttenuation = (log(1 / maxattenuation)) / (log(inMaxDist)) - 1;
AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_3DMixerDistanceAtten, kAudioUnitScope_Input, inBusIndex,
&distAttenuation, sizeof(distAttenuation));
}
}
// game @0x001211ac sdk @0x11a6
// An available stereo bus, or (unless the application fixed the bus counts) any available bus switched to a
// stereo stream format with stereo pass-through. Throws -1 when none is left.
UInt32 OALContext::GetAvailableStereoBus()
{
for (UInt32 i = 0; i < mBusCount; i++)
{
if (mBusInfo[i].mIsAvailable == true && mBusInfo[i].mNumberChannels == 2)
{
mBusInfo[i].mIsAvailable = false;
return (i);
}
}
if (!mUserSpecifiedBusCounts)
{
for (UInt32 i = 0; i < mBusCount; i++)
{
if (mBusInfo[i].mIsAvailable == true)
{
OSStatus result = noErr;
CAStreamBasicDescription format;
format.mChannelsPerFrame = 2;
format.mSampleRate = GetMixerRate();
format.mFormatID = kAudioFormatLinearPCM;
format.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
format.mBytesPerPacket = sizeof(Float32);
format.mFramesPerPacket = 1;
format.mBytesPerFrame = sizeof(Float32);
format.mBitsPerChannel = sizeof(Float32) * 8;
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
i, &format, sizeof(format));
THROW_RESULT
mBusInfo[i].mIsAvailable = false;
mBusInfo[i].mNumberChannels = 2;
UInt32 spatAlgo = kSpatializationAlgorithm_StereoPassThrough;
AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_SpatializationAlgorithm, kAudioUnitScope_Input,
i, &spatAlgo, sizeof(spatAlgo));
return (i);
}
}
}
throw -1;
}
// game @0x00121390 sdk @0x1410
void OALContext::SetBusAsAvailable(UInt32 inBusIndex)
{
mBusInfo[inBusIndex].mIsAvailable = true;
}
// game @0x001213a8 sdk @0x1c9e
UInt32 OALContext::GetSourceCount()
{
if (mSourceMap)
{
return (mSourceMap->Size());
}
return (0);
}
// game @0x001213bc sdk @0x1f92
OALSource* OALContext::GetSource(ALuint inSourceToken)
{
return (mSourceMap->Get(inSourceToken));
}
// game @0x001213f6 sdk @0x186
// Spatialization for the mono busses: sound field above 2 render channels, equal power panning for the low
// quality setting, HRTF otherwise; distance attenuation (+ interaural delay at high quality, + distance diffusion
// and constant reverb blend while the reverb is on), no doppler shift.
void OALContext::InitRenderQualityOnBusses()
{
UInt32 channelCount = mOwningDevice->GetDesiredRenderChannelCount();
if (channelCount > 2)
{
mSpatialSetting = kSpatializationAlgorithm_SoundField;
}
else if (mRenderQuality == ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_LOW)
{
mSpatialSetting = kSpatializationAlgorithm_EqualPowerPanning;
}
else
{
mSpatialSetting = kSpatializationAlgorithm_HRTF;
}
UInt32 render_flags_3d = k3DMixerRenderingFlags_DistanceAttenuation;
if (mRenderQuality == ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_HIGH)
{
render_flags_3d += k3DMixerRenderingFlags_InterAuralDelay;
}
if (mASAReverbState > 0)
{
render_flags_3d += k3DMixerRenderingFlags_DistanceDiffusion;
render_flags_3d += k3DMixerRenderingFlags_ConstantReverbBlend;
}
OSStatus result = noErr;
CAStreamBasicDescription format;
for (UInt32 i = 0; i < mBusCount; i++)
{
UInt32 outSize = sizeof(format);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, i, &format,
&outSize);
if ((result == noErr) && (format.NumberChannels() == 1))
{
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_SpatializationAlgorithm,
kAudioUnitScope_Input, i, &mSpatialSetting, sizeof(mSpatialSetting));
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_3DMixerRenderingFlags,
kAudioUnitScope_Input, i, &render_flags_3d, sizeof(render_flags_3d));
UInt32 doppler = 0;
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_DopplerShift, kAudioUnitScope_Input, i,
&doppler, sizeof(doppler));
}
}
}
// game @0x0012155c sdk @0x390
// Mixer output: canonical non-interleaved float with the device's desired channel count at the mixer rate.
void OALContext::ConfigureMixerFormat()
{
OSStatus result = noErr;
CAStreamBasicDescription format;
UInt32 propSize = sizeof(format);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format,
&propSize);
format.SetCanonical(mOwningDevice->GetDesiredRenderChannelCount(), false);
format.mSampleRate = GetMixerRate();
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format,
sizeof(format));
THROW_RESULT
InitRenderQualityOnBusses();
}
// game @0x0012166e sdk @0x660
// Creates the 3DMixer node and configures it: default distances (2.0+ mixers), output format, maximum frames per
// slice (raised to the device's), internal reverb, bus count (64 before the 2.0 mixer), and every input bus
// (1/1000000/1 distance attenuation, stereo for the first inStereoBusCount busses, mono spatialized otherwise).
void OALContext::InitializeMixer(UInt32 inStereoBusCount)
{
OSStatus result = noErr;
try
{
if (Get3DMixerVersion() < k3DMixerVersion_1_3)
{
throw -1;
}
if (Get3DMixerVersion() == k3DMixerVersion_2_0)
{
mDistanceScalingRequired = true;
}
else if (Get3DMixerVersion() >= k3DMixerVersion_2_2)
{
mSettableMixerAttenuationCurves = true;
}
ComponentDescription mixerCD;
mixerCD.componentFlags = 0;
mixerCD.componentFlagsMask = 0;
mixerCD.componentType = kAudioUnitType_Mixer;
mixerCD.componentSubType = kAudioUnitSubType_3DMixer;
mixerCD.componentManufacturer = kAudioUnitManufacturer_Apple;
result = AUGraphNewNode(mOwningDevice->GetGraph(), &mixerCD, 0, NULL, &mMixerNode);
THROW_RESULT
result = AUGraphGetNodeInfo(mOwningDevice->GetGraph(), mMixerNode, 0, 0, 0, &mMixerUnit);
THROW_RESULT
if (Get3DMixerVersion() >= k3DMixerVersion_2_0)
{
MixerDistanceParams distanceParams;
UInt32 outSize = sizeof(distanceParams);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_3DMixerDistanceParams,
kAudioUnitScope_Input, 1, &distanceParams, &outSize);
if (result == noErr)
{
mDefaultReferenceDistance = distanceParams.mReferenceDistance;
mDefaultMaxDistance = distanceParams.mMaxDistance;
}
}
CAStreamBasicDescription format;
UInt32 propSize = sizeof(format);
result = AudioUnitGetProperty(mOwningDevice->GetOutputAU(), kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output, 0, &format, &propSize);
format.SetCanonical(mOwningDevice->GetDesiredRenderChannelCount(), false);
format.mSampleRate = GetMixerRate();
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0,
&format, sizeof(format));
THROW_RESULT
UInt32 mixerFramesPerSlice = 0;
UInt32 dataSize = sizeof(mixerFramesPerSlice);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0,
&mixerFramesPerSlice, &dataSize);
if (mOwningDevice->GetFramesPerSlice() > mixerFramesPerSlice)
{
mixerFramesPerSlice = mOwningDevice->GetFramesPerSlice();
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global, 0, &mixerFramesPerSlice,
sizeof(mixerFramesPerSlice));
THROW_RESULT
}
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_UsesInternalReverb, kAudioUnitScope_Global, 0,
&mASAReverbState, sizeof(mASAReverbState));
if (Get3DMixerVersion() < k3DMixerVersion_2_0)
{
mBusCount = 64;
}
else
{
UInt32 busCount;
UInt32 propSize = sizeof(busCount);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_ElementCount, kAudioUnitScope_Input, 0,
&busCount, &propSize);
if (result == noErr)
{
if (mBusCount != busCount)
{
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_ElementCount, kAudioUnitScope_Input,
0, &mBusCount, propSize);
if (result != noErr)
{
propSize = sizeof(mBusCount);
result = AudioUnitGetProperty(mMixerUnit, kAudioUnitProperty_ElementCount,
kAudioUnitScope_Input, 0, &mBusCount, &propSize);
}
}
}
}
CAStreamBasicDescription busFormat;
busFormat.mSampleRate = GetMixerRate();
busFormat.mFormatID = kAudioFormatLinearPCM;
busFormat.mFramesPerPacket = 1;
busFormat.mBytesPerFrame = sizeof(Float32);
busFormat.mBitsPerChannel = sizeof(Float32) * 8;
busFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
busFormat.mBytesPerPacket = sizeof(Float32);
for (UInt32 i = 0; i < mBusCount; i++)
{
SetDistanceAttenuation(i, 1.0, 1000000.0, 1.0);
busFormat.mChannelsPerFrame = (i < inStereoBusCount) ? 2 : 1;
OSStatus result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, i, &busFormat, sizeof(busFormat));
THROW_RESULT
mBusInfo[i].mNumberChannels = busFormat.mChannelsPerFrame;
mBusInfo[i].mIsAvailable = true;
mBusInfo[i].mReverbState = mASAReverbState;
UInt32 spatialSetting = (busFormat.mChannelsPerFrame == 2) ? kSpatializationAlgorithm_StereoPassThrough
: mSpatialSetting;
AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_SpatializationAlgorithm, kAudioUnitScope_Input, i,
&spatialSetting, sizeof(spatialSetting));
if (busFormat.mChannelsPerFrame == 1)
{
UInt32 render_flags_3d = k3DMixerRenderingFlags_DistanceAttenuation;
if (mRenderQuality == ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_HIGH)
{
render_flags_3d += k3DMixerRenderingFlags_InterAuralDelay;
}
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_3DMixerRenderingFlags,
kAudioUnitScope_Input, i, &render_flags_3d, sizeof(render_flags_3d));
}
}
InitRenderQualityOnBusses();
}
catch (OALStatusException result)
{
throw result;
}
catch (...)
{
throw -1;
}
}
// game @0x00121d58 sdk @0x230a
// The ALC_MONO_SOURCES / ALC_STEREO_SOURCES attributes mark the bus counts as user specified; the last stereo
// count (default 1) is the number of stereo busses.
OALContext::OALContext(const uintptr_t inSelfToken, OALDevice* inOALDevice, const ALCint* inAttributeList,
UInt32& inBusCount, Float64& inMixerRate) :
mSelfToken(inSelfToken),
mProcessingActive(true),
mOwningDevice(inOALDevice),
mMixerNode(0),
mMixerUnit(0),
mSourceMap(NULL),
mDistanceModel(AL_INVERSE_DISTANCE_CLAMPED),
mSpeedOfSound(343.3f),
mDopplerFactor(1.0f),
mDopplerVelocity(1.0f),
mListenerGain(1.0f),
mAttributeListSize(0),
mAttributeList(NULL),
mDistanceScalingRequired(false),
mCalculateDistance(true),
mStoredInverseAttenuation(1.0),
mRenderQuality(ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_LOW),
mSpatialSetting(0),
mBusCount(inBusCount),
mMixerOutputRate(inMixerRate),
mDefaultReferenceDistance(1.0f),
mDefaultMaxDistance(100000.0f),
mUserSpecifiedBusCounts(false),
mSettableMixerAttenuationCurves(false),
mASAReverbState(0),
mASAReverbRoomType(0),
mASAReverbGlobalLevel(0.0f),
mASAReverbQuality(32),
mASAReverbEQGain(0.0f),
mASAReverbEQBandwidth(3.0f),
mASAReverbEQFrequency(800.0f)
{
mBusInfo = (BusInfo*)calloc(1, sizeof(BusInfo) * mBusCount);
UInt32 monoSources = 0;
UInt32 stereoSources = 1;
if (inAttributeList)
{
ALCint* currentAttribute = (ALCint*)inAttributeList;
while (*currentAttribute != 0)
{
switch (*currentAttribute)
{
case ALC_MONO_SOURCES:
mUserSpecifiedBusCounts = true;
monoSources = currentAttribute[1];
break;
case ALC_STEREO_SOURCES:
mUserSpecifiedBusCounts = true;
stereoSources = currentAttribute[1];
break;
default:
break;
}
currentAttribute += 2;
mAttributeListSize++;
}
mAttributeListSize++;
mAttributeList = (ALCint*)calloc(1, mAttributeListSize * sizeof(ALCint));
memcpy(mAttributeList, inAttributeList, mAttributeListSize * sizeof(ALCint));
}
mListenerPosition[0] = 0.0f;
mListenerPosition[1] = 0.0f;
mListenerPosition[2] = 0.0f;
mListenerVelocity[0] = 0.0f;
mListenerVelocity[1] = 0.0f;
mListenerVelocity[2] = 0.0f;
mListenerOrientationForward[0] = 0.0f;
mListenerOrientationForward[1] = 0.0f;
mListenerOrientationForward[2] = -1.0f;
mListenerOrientationUp[0] = 0.0f;
mListenerOrientationUp[1] = 1.0f;
mListenerOrientationUp[2] = 0.0f;
InitializeMixer(stereoSources);
mSourceMap = new OALSourceMap();
mDeadSourceMap = new OALSourceMap();
}
// game @0x00121f84 sdk @0xeec
// An available mono bus, or (unless the application fixed the bus counts) any available bus switched to a mono
// stream format with the context's spatialization and rendering flags. Throws -1 when none is left.
UInt32 OALContext::GetAvailableMonoBus()
{
for (UInt32 i = 0; i < mBusCount; i++)
{
if (mBusInfo[i].mIsAvailable == true && mBusInfo[i].mNumberChannels == 1)
{
mBusInfo[i].mIsAvailable = false;
return (i);
}
}
if (!mUserSpecifiedBusCounts)
{
for (UInt32 i = 0; i < mBusCount; i++)
{
if (mBusInfo[i].mIsAvailable == true)
{
OSStatus result = noErr;
CAStreamBasicDescription format;
format.mChannelsPerFrame = 1;
format.mSampleRate = GetMixerRate();
format.mFormatID = kAudioFormatLinearPCM;
format.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
format.mBytesPerPacket = sizeof(Float32);
format.mFramesPerPacket = 1;
format.mBytesPerFrame = sizeof(Float32);
format.mBitsPerChannel = sizeof(Float32) * 8;
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
i, &format, sizeof(format));
THROW_RESULT
mBusInfo[i].mIsAvailable = false;
mBusInfo[i].mNumberChannels = 1;
AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_SpatializationAlgorithm, kAudioUnitScope_Input,
i, &mSpatialSetting, sizeof(mSpatialSetting));
UInt32 render_flags_3d = k3DMixerRenderingFlags_DistanceAttenuation;
if (mRenderQuality == ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_HIGH)
{
render_flags_3d += k3DMixerRenderingFlags_InterAuralDelay;
}
result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_3DMixerRenderingFlags,
kAudioUnitScope_Input, i, &render_flags_3d, sizeof(render_flags_3d));
return (i);
}
}
}
throw -1;
}
// game @0x001221ac sdk @0x1fb0
// Deletes the dead sources the render thread has let go of (IsSafeForDeletion).
void OALContext::CleanUpDeadSourceList()
{
if (mDeadSourceMap)
{
UInt32 index = 0;
for (UInt32 i = 0; i < mDeadSourceMap->Size(); i++)
{
OALSource* deadSource = mDeadSourceMap->GetSourceByIndex(index);
if (deadSource)
{
if (deadSource->IsSafeForDeletion())
{
mDeadSourceMap->Remove(deadSource->GetToken());
delete (deadSource);
}
else
{
index++;
}
}
else
{
index++;
}
}
}
}
// game @0x0012228e sdk @0x2a92
// The source stops through the render thread (SetUpDeconstruction) and waits in the dead source map.
void OALContext::RemoveSource(ALuint inSourceToken)
{
OALSource* oalSource = mSourceMap->Get(inSourceToken);
if (oalSource != NULL)
{
oalSource->SetUpDeconstruction();
mSourceMap->Remove(inSourceToken);
mDeadSourceMap->Add(inSourceToken, &oalSource);
CleanUpDeadSourceList();
}
}
// game @0x00122356 sdk @0x2b00
void OALContext::AddSource(ALuint inSourceToken)
{
try
{
OALSource* newSource = new OALSource(inSourceToken, this);
mSourceMap->Add(inSourceToken, &newSource);
CleanUpDeadSourceList();
}
catch (...)
{
throw;
}
}
// game @0x001223f6 sdk @0x207a
OALContext::~OALContext()
{
mOwningDevice->RemoveContext(this);
if (mSourceMap)
{
for (UInt32 i = 0; i < mSourceMap->Size(); i++)
{
OALSource* oalSource = mSourceMap->GetSourceByIndex(0);
if (oalSource)
{
mSourceMap->Remove(oalSource->GetToken());
delete (oalSource);
}
}
delete (mSourceMap);
}
if (mDeadSourceMap)
{
CleanUpDeadSourceList();
delete (mDeadSourceMap);
}
if (mAttributeList)
{
free(mAttributeList);
}
if (mBusInfo)
{
free(mBusInfo);
}
}

278
port/external/openal/oalContext.h vendored Normal file
View file

@ -0,0 +1,278 @@
// Port of pflib/external/openal/oalContext.h (Apple OpenAL, Playground SDK 4.0): OALContext, an AL context: one
// 3DMixer node in its device's AUGraph with one bus per source (BusInfo), the listener state and the source maps.
// Layout from the DWARF of parity-out/sdk/dbgobj/oalContext.o (game offsets identical, constructor
// game @0x00121d58):
//
// OALContext (size 184): +0x00 mSelfToken, +0x04 mProcessingActive, +0x08 mOwningDevice, +0x0c mMixerNode,
// +0x10 mMixerUnit, +0x14 mSourceMap, +0x18 mDeadSourceMap, +0x1c mDistanceModel, +0x20 mSpeedOfSound,
// +0x24 mDopplerFactor, +0x28 mDopplerVelocity, +0x2c mListenerPosition[3], +0x38 mListenerVelocity[3],
// +0x44 mListenerGain, +0x48 mListenerOrientationForward[3], +0x54 mListenerOrientationUp[3],
// +0x60 mAttributeListSize, +0x64 mAttributeList, +0x68 mDistanceScalingRequired, +0x69 mCalculateDistance,
// +0x6c mStoredInverseAttenuation, +0x74 mRenderQuality, +0x78 mSpatialSetting, +0x7c mBusCount,
// +0x80 mMixerOutputRate, +0x88 mDefaultReferenceDistance, +0x8c mDefaultMaxDistance,
// +0x90 mUserSpecifiedBusCounts, +0x94 mBusInfo, +0x98 mSettableMixerAttenuationCurves, +0x9c mASAReverbState,
// +0xa0 mASAReverbRoomType, +0xa4 mASAReverbGlobalLevel, +0xa8 mASAReverbQuality, +0xac mASAReverbEQGain,
// +0xb0 mASAReverbEQBandwidth, +0xb4 mASAReverbEQFrequency.
// BusInfo (size 12): +0x00 mIsAvailable, +0x04 mNumberChannels, +0x08 mReverbState.
//
// Header code (inline members below) is emitted out of line in the SDK objects (addresses at each member) and
// inlined in the game. OALContextMap (also declared in Apple's oalContext.h) is oalImp code and ported at the
// bottom of this header: its out-of-line code is in the SDK's oalImp.o (sdk @); the game inlines its calls.
// Members declared without a definition have no game code and are not ported (sdk only, listed in
// oalContext.cpp).
#ifndef OALCONTEXT_H_INCLUDED
#define OALCONTEXT_H_INCLUDED
#include "oal_sysdecls.h"
#include "oalDevice.h"
#include "oalSource.h"
#include <iterator>
#include <map>
#include <stdint.h>
struct BusInfo
{
bool mIsAvailable;
UInt32 mNumberChannels;
UInt32 mReverbState;
};
class OALContext
{
public:
OALContext(const uintptr_t inSelfToken, OALDevice* inOALDevice, const ALCint* inAttributeList,
UInt32& inBusCount, Float64& inMixerRate);
~OALContext();
// sdk @0x34a9c (oalSource.o)
bool DoSetDistance() { return mCalculateDistance; }
UInt32 GetDesiredRenderChannels(UInt32 inDeviceChannels);
// sdk @0x34aae (oalSource.o)
AudioUnit GetMixerUnit() { return mMixerUnit; }
// sdk @0x34abc (oalSource.o)
AUNode GetMixerNode() { return mMixerNode; }
// sdk @0x34aca (oalSource.o)
AUGraph GetGraph() { return mOwningDevice->GetGraph(); }
// sdk @0x5a964 (oalImp.o)
UInt32 GetRenderQuality() { return mRenderQuality; }
// sdk @0x5a972 (oalImp.o)
Float32 GetFramesPerSlice() { return mOwningDevice->GetFramesPerSlice(); }
// sdk @0x34ae0 (oalSource.o)
Float64 GetMixerRate() const { return mMixerOutputRate; }
// sdk @0x34afc (oalSource.o)
Float32 GetDefaultReferenceDistance() { return mDefaultReferenceDistance; }
// sdk @0x34b1e (oalSource.o)
Float32 GetDefaultMaxDistance() { return mDefaultMaxDistance; }
// sdk @0x34b40 (oalSource.o)
bool IsDistanceScalingRequired() { return mDistanceScalingRequired; }
UInt32 GetAvailableMonoBus();
UInt32 GetAvailableStereoBus();
// sdk @0x5a9da (oalImp.o)
UInt32 GetBusCount() { return mBusCount; }
// sdk @0x5a9e8 (oalImp.o)
uintptr_t GetDeviceToken() { return mOwningDevice->GetDeviceToken(); }
// sdk @0x34b52 (oalSource.o)
UInt32 GetDistanceModel() { return mDistanceModel; }
// sdk @0x34b60 (oalSource.o)
Float32 GetSpeedOfSound() { return mSpeedOfSound; }
// sdk @0x34b7e (oalSource.o)
Float32 GetDopplerFactor() { return mDopplerFactor; }
// sdk @0x5aa48 (oalImp.o)
Float32 GetDopplerVelocity() { return mDopplerVelocity; }
// sdk @0x5aa66 (oalImp.o)
Float32 GetListenerGain() { return mListenerGain; }
// sdk @0x34b9c (oalSource.o)
void GetListenerPosition(Float32* posX, Float32* posY, Float32* posZ)
{
*posX = mListenerPosition[0];
*posY = mListenerPosition[1];
*posZ = mListenerPosition[2];
}
// sdk @0x34bc6 (oalSource.o)
void GetListenerVelocity(Float32* posX, Float32* posY, Float32* posZ)
{
*posX = mListenerVelocity[0];
*posY = mListenerVelocity[1];
*posZ = mListenerVelocity[2];
}
// sdk @0x34bf0 (oalSource.o)
void GetListenerOrientation(Float32* forwardX, Float32* forwardY, Float32* forwardZ, Float32* upX,
Float32* upY, Float32* upZ)
{
*forwardX = mListenerOrientationForward[0];
*forwardY = mListenerOrientationForward[1];
*forwardZ = mListenerOrientationForward[2];
*upX = mListenerOrientationUp[0];
*upY = mListenerOrientationUp[1];
*upZ = mListenerOrientationUp[2];
}
// sdk @0x5ab22 (oalImp.o)
UInt32 GetAttributeListSize() { return mAttributeListSize; }
void CopyAttributeList(ALCint* outAttrList);
void SetReverbQuality(UInt32 inQuality);
void SetReverbEQGain(Float32 inGain);
void SetReverbEQBandwidth(Float32 inBandwidth);
void SetReverbEQFrequency(Float32 inFrequency);
UInt32 GetReverbQuality();
Float32 GetReverbEQGain();
Float32 GetReverbEQBandwidth();
Float32 GetReverbEQFrequency();
void SetBusAsAvailable(UInt32 inBusIndex);
void SetDistanceAttenuation(UInt32 inBusIndex, Float64 inRefDist, Float64 inMaxDist, Float64 inRolloff);
void SetRenderQuality(UInt32 inRenderQuality);
void SetDistanceModel(UInt32 inDistanceModel);
void SetDopplerFactor(Float32 inDopplerFactor);
void SetDopplerVelocity(Float32 inDopplerVelocity);
void SetSpeedOfSound(Float32 inSpeedOfSound);
void SetListenerPosition(Float32 posX, Float32 posY, Float32 posZ);
void SetListenerVelocity(Float32 posX, Float32 posY, Float32 posZ);
void SetListenerGain(Float32 inGain);
void SetListenerOrientation(Float32 forwardX, Float32 forwardY, Float32 forwardZ, Float32 upX, Float32 upY,
Float32 upZ);
void SetReverbPreset(FSRef* inRef);
void SetReverbState(UInt32 inReverbState);
// sdk @0x34c3a (oalSource.o)
UInt32 GetReverbState() { return mASAReverbState; }
void SetReverbRoomType(UInt32 inRoomType);
void SetReverbLevel(Float32 inReverbLevel);
UInt32 GetReverbRoomType();
Float32 GetReverbLevel();
void ProcessContext();
void SuspendContext();
void AddSource(ALuint inSourceToken);
void RemoveSource(ALuint inSourceToken);
OALSource* GetSource(ALuint inSourceToken);
UInt32 GetSourceCount();
void CleanUpDeadSourceList();
void ConnectMixerToDevice();
void InitRenderQualityOnBusses();
void ConfigureMixerFormat();
private:
void InitializeMixer(UInt32 inStereoBusCount);
uintptr_t mSelfToken;
bool mProcessingActive;
OALDevice* mOwningDevice;
AUNode mMixerNode;
AudioUnit mMixerUnit;
OALSourceMap* mSourceMap;
OALSourceMap* mDeadSourceMap;
UInt32 mDistanceModel;
Float32 mSpeedOfSound;
Float32 mDopplerFactor;
Float32 mDopplerVelocity;
Float32 mListenerPosition[3];
Float32 mListenerVelocity[3];
Float32 mListenerGain;
Float32 mListenerOrientationForward[3];
Float32 mListenerOrientationUp[3];
UInt32 mAttributeListSize;
ALCint* mAttributeList;
bool mDistanceScalingRequired;
bool mCalculateDistance;
Float64 mStoredInverseAttenuation;
UInt32 mRenderQuality;
UInt32 mSpatialSetting;
UInt32 mBusCount;
Float64 mMixerOutputRate;
Float32 mDefaultReferenceDistance;
Float32 mDefaultMaxDistance;
bool mUserSpecifiedBusCounts;
BusInfo* mBusInfo;
bool mSettableMixerAttenuationCurves;
UInt32 mASAReverbState;
UInt32 mASAReverbRoomType;
Float32 mASAReverbGlobalLevel;
UInt32 mASAReverbQuality;
Float32 mASAReverbEQGain;
Float32 mASAReverbEQBandwidth;
Float32 mASAReverbEQFrequency;
};
// The context map of oalImp.cpp (gOALContextMap). Every member with out-of-line code has it in the SDK's
// oalImp.o (sdk @ below); the game inlines all of them. Empty() has no out-of-line code in either build
// (nothing calls it) and the map is never deleted (no ~OALContextMap symbol in either build).
class OALContextMap : std::multimap<uintptr_t, OALContext*, std::less<uintptr_t> >
{
public:
// sdk @0x5d094 (oalImp.o)
OALContextMap() {}
// sdk @0x5d9d8 (oalImp.o)
void Add(const uintptr_t inContextToken, OALContext** inContext)
{
iterator it = upper_bound(inContextToken);
insert(it, value_type(inContextToken, *inContext));
}
// sdk @0x5bc76 (oalImp.o)
OALContext* Get(uintptr_t inContextToken)
{
iterator it = find(inContextToken);
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5c666 (oalImp.o)
bool Remove(const uintptr_t inContextToken)
{
iterator it = find(inContextToken);
if (it != end())
{
erase(it);
return true; // success
}
return false;
}
// sdk @0x5b9ee (oalImp.o)
OALContext* GetContextByIndex(UInt32 inIndex, uintptr_t& outContextToken)
{
iterator it = begin();
std::advance(it, inIndex);
if (it != end())
{
outContextToken = (*it).first;
return (*it).second;
}
return (NULL);
}
// sdk @0x5bcd4 (oalImp.o)
uintptr_t GetDeviceTokenForContext(uintptr_t inContextToken)
{
OALContext* context = Get(inContextToken);
if (context != NULL)
{
return (context->GetDeviceToken());
}
else
{
return (0);
}
}
// sdk @0x5ae98 (oalImp.o)
UInt32 Size() const { return (UInt32)size(); }
// no out-of-line code in either build (nothing calls it)
bool Empty() const { return empty(); }
};
#endif

553
port/external/openal/oalDevice.cpp vendored Normal file
View file

@ -0,0 +1,553 @@
// Port of pflib/external/openal/oalDevice.cpp (Apple OpenAL, Playground SDK 4.0): OALDevice, an ALC device. It
// owns an AUGraph with the default output unit; the current context's 3DMixer node is connected to the output
// node with the device's render channel count (stereo, or the HAL device's preferred surround layout as far as
// the 3DMixer can render it). A stream format change on the output unit re-checks the channel count.
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/oalDevice.o).
//
// Game vs. SDK (the game wins):
// - Constructor: the SDK copies inDeviceName and then clears it, so its CFString / kAudioHardwarePropertyDeviceForUID
// branch (sdk @0x784..@0x834) can never run; the game has no code for it and always takes the default output
// device. The port follows the game (the device name is ignored).
// - TeardownGraph (sdk @0xb9c) and StopGraph are inlined in the destructor, GetChannelLayoutTag (sdk @0xca6) in
// ConnectContext and ResetRenderChannelSettings, IsGraphStillRunning in ConnectContext, SetCanonical and the
// CAStreamBasicDescription constructor everywhere. Same calls in the same order.
// - SetRenderChannelSetting's catch (OSStatus) handler only prints a WriteDbg message in the SDK (debug only).
//
// Exceptions: OSStatus failures are thrown as OSStatus (OALStatusException, see oal_sysdecls.h). The constructor
// rethrows anything (catch (...) { throw; }, LSDA game @0x00217ee0), ConnectContext restores mConnectedContext
// and rethrows an OSStatus, or throws -1 for anything else (LSDA @0x00217f3c), GraphFormatPropertyListener
// swallows everything (LSDA @0x00217f14).
//
// sdk only (no code in the game; ported from the SDK disassembly): GetError (sdk @0x1c), TeardownGraph
// (sdk @0xb9c), GetChannelLayoutTag (sdk @0xca6), SetRenderChannelSetting (sdk @0x162a). The C2 / D2 copies of the
// constructor and destructor (sdk @0x8f2 / @0xbe6) are the same code as the C1 / D1 ones. IsValidRenderQuality and
// Print are declared in oalDevice.h but have no code in either build.
//
// Host difference: the AudioChannelLayout passed to kAudioUnitProperty_AudioChannelLayout is 32 bytes on both
// i386 and the host (one AudioChannelDescription); sizeof is used.
//
// The object has no strings and no static initializer.
#pragma STDC FP_CONTRACT OFF
#include "oalDevice.h"
#include "CAStreamBasicDescription.h"
#include "oalContext.h"
#include "oalImp.h"
#include "oalOSX.h"
#include <stdlib.h>
#define THROW_RESULT \
if (result != noErr) \
{ \
throw ((OALStatusException)result); \
}
// game @0x00122f80 sdk @0x0
// As in both builds, the new error is only stored while an error is already pending.
void OALDevice::SetError(ALenum errorCode)
{
if (mCurrentError == ALC_NO_ERROR)
{
return;
}
mCurrentError = errorCode;
}
// sdk only sdk @0x1c
ALenum OALDevice::GetError()
{
ALenum latestError = mCurrentError;
mCurrentError = ALC_NO_ERROR;
return latestError;
}
// game @0x00123242 sdk @0x3a
// Creates the graph with the default output unit, listens for its stream format changes, sets the unit's
// maximum frames per slice to the HAL device's buffer frame size and keeps the output sample rate.
void OALDevice::InitializeGraph(const char* inDeviceName)
{
if (mAUGraph)
{
throw ((OALStatusException)'init');
}
OSStatus result = noErr;
result = NewAUGraph(&mAUGraph);
THROW_RESULT
ComponentDescription cd;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_DefaultOutput;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
result = AUGraphNewNode(mAUGraph, &cd, 0, NULL, &mOutputNode);
THROW_RESULT
result = AUGraphOpen(mAUGraph);
THROW_RESULT
result = AUGraphGetNodeInfo(mAUGraph, mOutputNode, 0, 0, 0, &mOutputUnit);
THROW_RESULT
result = AudioUnitInitialize(mOutputUnit);
THROW_RESULT
result = AudioUnitAddPropertyListener(mOutputUnit, kAudioUnitProperty_StreamFormat, GraphFormatPropertyListener,
(void*)this);
THROW_RESULT
AudioDeviceID device = 0;
UInt32 propSize = sizeof(device);
result = AudioUnitGetProperty(mOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,
&device, &propSize);
if (result == noErr)
{
propSize = sizeof(mFramesPerSlice);
result = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyBufferFrameSize, &propSize,
&mFramesPerSlice);
if (result == noErr)
{
result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global, 0, &mFramesPerSlice, sizeof(mFramesPerSlice));
}
}
CAStreamBasicDescription format;
propSize = sizeof(format);
result = AudioUnitGetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format,
&propSize);
if (result == noErr)
{
mDeviceSampleRate = format.mSampleRate;
}
}
// game @0x00122f98 sdk @0x3ee
// 2 when the application asked for stereo; otherwise the channel count of the HAL device's preferred channel
// layout (named tags, or the described channels other than unknown and LFE), limited by
// GetDesiredRenderChannelsFor3DMixer.
UInt32 OALDevice::GetDesiredRenderChannelCount()
{
UInt32 returnValue = 2;
if (mRenderChannelSetting == ALC_MAC_OSX_RENDER_CHANNEL_COUNT_STEREO)
{
return returnValue;
}
AudioDeviceID device;
UInt32 propSize = sizeof(device);
OSStatus result = AudioUnitGetProperty(mOutputUnit, kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Output, 1, &device, &propSize);
THROW_RESULT
result = AudioDeviceGetPropertyInfo(device, 0, false, kAudioDevicePropertyPreferredChannelLayout, &propSize,
NULL);
if (result != noErr)
{
return returnValue;
}
AudioChannelLayout* layout = NULL;
layout = (AudioChannelLayout*)calloc(1, propSize);
if (layout != NULL)
{
result = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyPreferredChannelLayout, &propSize,
layout);
if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions)
{
if (layout->mNumberChannelDescriptions == 2)
{
returnValue = 2;
}
else
{
returnValue = 0;
for (UInt32 i = 0; i < layout->mNumberChannelDescriptions; i++)
{
if ((layout->mChannelDescriptions[i].mChannelLabel != kAudioChannelLabel_Unknown) &&
(layout->mChannelDescriptions[i].mChannelLabel != kAudioChannelLabel_LFEScreen))
{
returnValue++;
}
}
}
}
else
{
switch (layout->mChannelLayoutTag)
{
case kAudioChannelLayoutTag_AudioUnit_5_0:
case kAudioChannelLayoutTag_AudioUnit_5_1:
returnValue = 5;
break;
case kAudioChannelLayoutTag_AudioUnit_6_0:
case kAudioChannelLayoutTag_AudioUnit_6_1:
returnValue = 6;
break;
case kAudioChannelLayoutTag_AudioUnit_7_0:
case kAudioChannelLayoutTag_AudioUnit_7_1:
returnValue = 7;
break;
case kAudioChannelLayoutTag_AudioUnit_8:
returnValue = 8;
break;
case kAudioChannelLayoutTag_AudioUnit_4:
returnValue = 4;
break;
default:
returnValue = 2;
break;
}
}
free(layout);
}
returnValue = GetDesiredRenderChannelsFor3DMixer(returnValue);
return returnValue;
}
// game @0x001234b0 sdk @0x67c
// Only the stereo and multichannel render settings are accepted (AL_INVALID_VALUE otherwise). The device is
// always the HAL's default output device (see the file comment).
OALDevice::OALDevice(const char* inDeviceName, uintptr_t inSelfToken, UInt32 inRenderChannelSetting) :
mSelfToken(inSelfToken),
mCurrentError(ALC_NO_ERROR),
mHALDevice(0),
mDistanceScalingRequired(false),
mGraphInitialized(false),
mAUGraph(0),
mOutputNode(0),
mOutputUnit(0),
mMixerNode(0),
mConnectedContext(NULL),
mDeviceSampleRate(44100.0),
mRenderChannelCount(0),
mRenderChannelSetting(inRenderChannelSetting),
mFramesPerSlice(512)
{
OSStatus result = noErr;
UInt32 size = 0;
try
{
if ((mRenderChannelSetting != ALC_MAC_OSX_RENDER_CHANNEL_COUNT_MULTICHANNEL) &&
(mRenderChannelSetting != ALC_MAC_OSX_RENDER_CHANNEL_COUNT_STEREO))
{
throw ((OALStatusException)AL_INVALID_VALUE);
}
size = sizeof(mHALDevice);
result = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size, &mHALDevice);
THROW_RESULT
InitializeGraph(NULL);
mRenderChannelCount = GetDesiredRenderChannelCount();
}
catch (...)
{
throw;
}
}
// sdk only sdk @0xb9c (inlined in the game's destructor)
void OALDevice::TeardownGraph()
{
if (mAUGraph)
{
StopGraph();
DisposeAUGraph(mAUGraph);
mAUGraph = 0;
}
}
// game @0x001235dc sdk @0xbd2
OALDevice::~OALDevice()
{
TeardownGraph();
}
// game @0x00123178 sdk @0xb68
// Stops the graph and spins until it reports that it is no longer running (the status is not checked).
void OALDevice::StopGraph()
{
AUGraphStop(mAUGraph);
Boolean flag;
do
{
AUGraphIsRunning(mAUGraph, &flag);
} while (flag);
}
// game @0x001231f4 sdk @0xbfa
void OALDevice::DisconnectContext(OALContext* inContext)
{
if (inContext == mConnectedContext)
{
mConnectedContext = NULL;
}
AUGraphDisconnectNodeInput(mAUGraph, inContext->GetMixerNode(), 0);
AUGraphUpdate(mAUGraph, NULL);
}
// game @0x001231ae sdk @0xc54
void OALDevice::RemoveContext(OALContext* inContext)
{
if (inContext == mConnectedContext)
{
mConnectedContext = NULL;
}
AUGraphRemoveNode(mAUGraph, inContext->GetMixerNode());
AUGraphUpdate(mAUGraph, NULL);
}
// sdk only sdk @0xca6 (inlined in the game's ConnectContext and ResetRenderChannelSettings)
// The surround layouts need a 2.0 (quad) or 2.3 (6..8 channels) or later 3DMixer; stereo otherwise.
UInt32 OALDevice::GetChannelLayoutTag()
{
if (mRenderChannelCount == 5)
{
return kAudioChannelLayoutTag_AudioUnit_5_0;
}
else if ((mRenderChannelCount == 4) && (Get3DMixerVersion() >= k3DMixerVersion_2_0))
{
return kAudioChannelLayoutTag_AudioUnit_4;
}
else if ((mRenderChannelCount == 6) && (Get3DMixerVersion() >= k3DMixerVersion_2_3))
{
return kAudioChannelLayoutTag_AudioUnit_6_0;
}
else if ((mRenderChannelCount == 7) && (Get3DMixerVersion() >= k3DMixerVersion_2_3))
{
return kAudioChannelLayoutTag_AudioUnit_7_0;
}
else if ((mRenderChannelCount == 8) && (Get3DMixerVersion() >= k3DMixerVersion_2_3))
{
return kAudioChannelLayoutTag_AudioUnit_8;
}
return kAudioChannelLayoutTag_Stereo;
}
// game @0x0012396e sdk @0xd92
// Connects inContext's mixer to the output unit: canonical non-interleaved float with the device's render channel
// count at the mixer's output rate on both sides, the matching channel layout, then initializes (first time) or
// updates the graph and starts it when it is not running.
void OALDevice::ConnectContext(OALContext* inContext)
{
OSStatus result = noErr;
OALContext* currentContext = mConnectedContext;
if (inContext == mConnectedContext)
{
return;
}
try
{
if ((mConnectedContext != NULL) && (inContext->GetMixerNode() != mMixerNode))
{
result = AUGraphDisconnectNodeInput(mAUGraph, mOutputNode, 0);
THROW_RESULT
mMixerNode = 0;
mConnectedContext = NULL;
}
CAStreamBasicDescription format;
UInt32 propSize = sizeof(format);
result = AudioUnitGetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0,
&format, &propSize);
THROW_RESULT
format.SetCanonical(mRenderChannelCount, false);
format.mSampleRate = inContext->GetMixerRate();
result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0,
&format, sizeof(format));
THROW_RESULT
result = AudioUnitSetProperty(inContext->GetMixerUnit(), kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output, 0, &format, sizeof(format));
THROW_RESULT
AudioChannelLayout layout;
layout.mChannelLayoutTag = GetChannelLayoutTag();
layout.mChannelBitmap = 0;
layout.mNumberChannelDescriptions = 0;
result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0,
&layout, sizeof(layout));
THROW_RESULT
result = AUGraphConnectNodeInput(mAUGraph, inContext->GetMixerNode(), 0, mOutputNode, 0);
THROW_RESULT
mMixerNode = inContext->GetMixerNode();
mConnectedContext = inContext;
if (!mGraphInitialized)
{
AUGraphInitialize(mAUGraph);
mGraphInitialized = true;
}
else
{
result = AUGraphUpdate(mAUGraph, NULL);
THROW_RESULT
}
if (!IsGraphStillRunning())
{
AUGraphStart(mAUGraph);
}
}
catch (OALStatusException result)
{
mConnectedContext = currentContext;
throw result;
}
catch (...)
{
mConnectedContext = currentContext;
throw -1;
}
}
// game @0x00123628 sdk @0x127c
// When the desired channel count changed: stop the graph if it runs, disconnect the mixer, set the output unit's
// input format and channel layout for the new count, let every context of the device reconfigure its mixer,
// reconnect and restart.
void OALDevice::ResetRenderChannelSettings()
{
UInt32 desiredRenderChannels = GetDesiredRenderChannelCount();
if (mRenderChannelCount == desiredRenderChannels)
{
return;
}
mRenderChannelCount = desiredRenderChannels;
Boolean graphWasRunning = false;
AUGraphIsRunning(mAUGraph, &graphWasRunning);
if (graphWasRunning)
{
StopGraph();
}
OSStatus result = noErr;
if (mMixerNode)
{
result = AUGraphDisconnectNodeInput(mAUGraph, mOutputNode, 0);
THROW_RESULT
result = AUGraphUpdate(mAUGraph, NULL);
THROW_RESULT
}
CAStreamBasicDescription format;
UInt32 propSize = sizeof(format);
result = AudioUnitGetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format,
&propSize);
THROW_RESULT
format.SetCanonical(mRenderChannelCount, false);
result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format,
sizeof(format));
THROW_RESULT
AudioChannelLayout layout;
layout.mChannelLayoutTag = GetChannelLayoutTag();
layout.mChannelBitmap = 0;
layout.mNumberChannelDescriptions = 0;
result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0,
&layout, sizeof(layout));
THROW_RESULT
ReconfigureContextsOfThisDevice(mSelfToken);
if (mMixerNode)
{
result = AUGraphConnectNodeInput(mAUGraph, mMixerNode, 0, mOutputNode, 0);
THROW_RESULT
result = AUGraphUpdate(mAUGraph, NULL);
THROW_RESULT
}
if (graphWasRunning)
{
AUGraphStart(mAUGraph);
}
}
// sdk only sdk @0x162a
// Only the stereo / multichannel settings are accepted; the channel count is re-checked when the setting changes,
// except when stereo is already rendered or multichannel is asked for with more than 2 channels already. The
// whole body is inside the try (SDK LSDA GCC_except_table3: call sites from the AL_INVALID_VALUE throw on), so an
// invalid setting and failures of the re-check are swallowed (the SDK only prints them in its catch (OSStatus)).
void OALDevice::SetRenderChannelSetting(UInt32 inRenderChannelSetting)
{
try
{
if ((inRenderChannelSetting != ALC_MAC_OSX_RENDER_CHANNEL_COUNT_MULTICHANNEL) &&
(inRenderChannelSetting != ALC_MAC_OSX_RENDER_CHANNEL_COUNT_STEREO))
{
throw ((OALStatusException)AL_INVALID_VALUE);
}
if (inRenderChannelSetting == mRenderChannelSetting)
{
return;
}
mRenderChannelSetting = inRenderChannelSetting;
if (inRenderChannelSetting == ALC_MAC_OSX_RENDER_CHANNEL_COUNT_STEREO)
{
if (mRenderChannelCount == 2)
{
return;
}
}
else
{
if (mRenderChannelCount > 2)
{
return;
}
}
ResetRenderChannelSettings();
}
catch (OALStatusException result)
{
}
catch (...)
{
}
}
// game @0x00123944 sdk @0x1734
// Output unit stream format listener: a change of the output scope re-checks the render channel count.
void OALDevice::GraphFormatPropertyListener(void* inRefCon, AudioUnit ci, AudioUnitPropertyID inID,
AudioUnitScope inScope, AudioUnitElement inElement)
{
try
{
if (inScope == kAudioUnitScope_Output)
{
((OALDevice*)inRefCon)->ResetRenderChannelSettings();
}
}
catch (...)
{
}
}

155
port/external/openal/oalDevice.h vendored Normal file
View file

@ -0,0 +1,155 @@
// Port of pflib/external/openal/oalDevice.h (Apple OpenAL, Playground SDK 4.0): OALDevice, an ALC device: an
// AUGraph with the default output unit, the context mixer connected to it, and the render channel count of the
// HAL device. Layout from the DWARF of parity-out/sdk/dbgobj/oalDevice.o (game offsets identical, constructor
// game @0x001234b0):
//
// OALDevice (size 56): +0x00 mSelfToken, +0x04 mCurrentError, +0x08 mHALDevice, +0x0c mDistanceScalingRequired,
// +0x0d mGraphInitialized, +0x10 mAUGraph, +0x14 mOutputNode, +0x18 mOutputUnit, +0x1c mMixerNode,
// +0x20 mConnectedContext, +0x24 mDeviceSampleRate, +0x2c mRenderChannelCount, +0x30 mRenderChannelSetting,
// +0x34 mFramesPerSlice.
//
// Header code (inline members below) is emitted out of line in the SDK objects (addresses at each member) and
// inlined in the game. OALDeviceMap (also declared in Apple's oalDevice.h) is oalImp code and ported at the
// bottom of this header: its out-of-line code is in the SDK's oalImp.o (sdk @); the game inlines its calls.
// Members declared without a definition have no game code and are not ported (listed in oalDevice.cpp).
#ifndef OALDEVICE_H_INCLUDED
#define OALDEVICE_H_INCLUDED
#include "oal_sysdecls.h"
#include <iterator>
#include <map>
#include <stdint.h>
class OALContext;
class OALDevice
{
public:
OALDevice(const char* inDeviceName, uintptr_t inSelfToken, UInt32 inRenderChannelSetting);
~OALDevice();
void ConnectContext(OALContext* inContext);
void DisconnectContext(OALContext* inContext);
void RemoveContext(OALContext* inContext);
void StopGraph();
void SetRenderChannelSetting(UInt32 inRenderChannelSetting);
void SetError(ALenum errorCode);
// sdk @0x5a8da (oalImp.o)
uintptr_t GetDeviceToken() const { return mSelfToken; }
// sdk @0x5a8e8 (oalImp.o)
Float64 GetDeviceSampleRate() const { return mDeviceSampleRate; }
// sdk @0x5a900 (oalImp.o)
UInt32 GetRenderChannelSetting() { return mRenderChannelSetting; }
ALenum GetError();
// sdk @0x1f6e2 (oalContext.o)
UInt32 GetFramesPerSlice() { return mFramesPerSlice; }
// sdk @0x34a8e (oalSource.o), @0x1f6f0 (oalContext.o)
AUGraph GetGraph() { return mAUGraph; }
// sdk @0x1f6fe (oalContext.o)
AudioUnit GetOutputAU() { return mOutputUnit; }
UInt32 GetDesiredRenderChannelCount();
bool IsValidRenderQuality(UInt32 inRenderQuality);
static void GraphFormatPropertyListener(void* inRefCon, AudioUnit ci, AudioUnitPropertyID inID,
AudioUnitScope inScope, AudioUnitElement inElement);
// sdk @0x9108 (oalDevice.o; inlined in the game's ConnectContext)
bool IsGraphStillRunning()
{
Boolean running;
OSStatus result = AUGraphIsRunning(mAUGraph, &running);
if (result != noErr)
{
throw ((OALStatusException)result);
}
return bool(running);
}
void Print();
private:
void InitializeGraph(const char* inDeviceName);
void TeardownGraph();
void ResetRenderChannelSettings();
UInt32 GetChannelLayoutTag();
uintptr_t mSelfToken;
ALenum mCurrentError;
AudioDeviceID mHALDevice;
bool mDistanceScalingRequired;
bool mGraphInitialized;
AUGraph mAUGraph;
AUNode mOutputNode;
AudioUnit mOutputUnit;
AUNode mMixerNode;
OALContext* mConnectedContext;
Float64 mDeviceSampleRate;
UInt32 mRenderChannelCount;
UInt32 mRenderChannelSetting;
UInt32 mFramesPerSlice;
};
// The device map of oalImp.cpp (gOALDeviceMap). Every member's out-of-line code is in the SDK's oalImp.o
// (sdk @ below); the game inlines all of them. The map is deleted in alcCloseDevice once it is empty (the
// destructor is emitted out of line in the SDK build).
class OALDeviceMap : std::multimap<uintptr_t, OALDevice*, std::less<uintptr_t> >
{
public:
// sdk @0x5cf98 (oalImp.o)
OALDeviceMap() {}
// sdk @0x5c4e0 (oalImp.o)
~OALDeviceMap() {}
// sdk @0x5d518 (oalImp.o)
void Add(const uintptr_t inDeviceToken, OALDevice** inDevice)
{
iterator it = upper_bound(inDeviceToken);
insert(it, value_type(inDeviceToken, *inDevice));
}
// sdk @0x5b7e4 (oalImp.o)
OALDevice* Get(uintptr_t inDeviceToken)
{
iterator it = find(inDeviceToken);
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x5b8da (oalImp.o)
OALDevice* GetDeviceByIndex(UInt32 inIndex, uintptr_t& outDeviceToken)
{
iterator it = begin();
std::advance(it, inIndex);
if (it != end())
{
outDeviceToken = (*it).first;
return (*it).second;
}
return (NULL);
}
// sdk @0x5c3c8 (oalImp.o)
void Remove(const uintptr_t inDeviceToken)
{
iterator it = find(inDeviceToken);
if (it != end())
{
erase(it);
}
}
// sdk @0x5ae14 (oalImp.o)
UInt32 Size() const { return (UInt32)size(); }
// sdk @0x5ae54 (oalImp.o)
bool Empty() const { return empty(); }
};
#endif

1344
port/external/openal/oalImp.cpp vendored Normal file

File diff suppressed because it is too large Load diff

56
port/external/openal/oalImp.h vendored Normal file
View file

@ -0,0 +1,56 @@
// Declarations of pflib/external/openal/oalImp.h (Apple OpenAL, Playground SDK 4.0): the implementation-wide
// helpers of oalImp.cpp that the OpenAL classes call. oalImp.cpp (the al* / alc* C API, these helpers and the
// map globals) is ported in oalImp.cpp; the helpers below are its callers' declarations.
//
// Game code of the declared helpers: Get3DMixerVersion @0x000f8b9c, WaitOneRenderCycle @0x000f917a,
// GetBufferObjectFromToken @0x000f9f8e, alSetError(int) (__Z10alSetErrori), ReconfigureContextsOfThisDevice
// (__Z31ReconfigureContextsOfThisDevicem).
//
// The mixer version and Mac OS X extension constants have no DWARF (they are enums / #defines of Apple's sources,
// MacOSX_OALExtensions.h for the 'rq..' / 'rc..' tokens); the names are Apple's, the values are the ones the game
// compares with.
#ifndef OALIMP_H_INCLUDED
#define OALIMP_H_INCLUDED
#include "oal_sysdecls.h"
#include <stdint.h>
class OALBuffer;
// Get3DMixerVersion() results
enum
{
kUnknown3DMixerVersion = 0,
kUnsupported3DMixer = 1,
k3DMixerVersion_1_3 = 13,
k3DMixerVersion_2_0 = 14,
k3DMixerVersion_2_1 = 15,
k3DMixerVersion_2_2 = 16,
k3DMixerVersion_2_3 = 17
};
// Mac OS X OpenAL extension tokens (MacOSX_OALExtensions.h)
#define ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_HIGH 'rqhi'
#define ALC_MAC_OSX_SPATIAL_RENDERING_QUALITY_LOW 'rdlo'
#define ALC_MAC_OSX_RENDER_CHANNEL_COUNT_STEREO 'rcst'
#define ALC_MAC_OSX_RENDER_CHANNEL_COUNT_MULTICHANNEL 'rcmc'
// AL_EXT_float32 formats
#define AL_FORMAT_MONO_FLOAT32 0x10010
#define AL_FORMAT_STEREO_FLOAT32 0x10011
// Limits and defaults of oalImp.cpp (same #defines as the SDK's oalImp.h)
#define AL_MAXBUFFERS 1024
#define AL_MAXSOURCES 256
#define kDefaultMaximumMixerBusCount 64
UInt32 Get3DMixerVersion();
void WaitOneRenderCycle();
void ReconfigureContextsOfThisDevice(uintptr_t inDeviceToken);
void alSetError(ALenum errorCode);
OALBuffer* GetBufferObjectFromToken(ALuint inBID);
#endif

215
port/external/openal/oalOSX.cpp vendored Normal file
View file

@ -0,0 +1,215 @@
// Port of pflib/external/openal/oalOSX.cpp (Apple OpenAL, Playground SDK 4.0), the part the OpenAL classes use:
// the token generators, the supported-format check, FillInASBD (an AL buffer format -> linear PCM stream
// description), CalculateNeededMixerBusses (bus count from an alcCreateContext attribute list) and
// GetDesiredRenderChannelsFor3DMixer (device channel count -> channel count the 3DMixer can render).
// Ported from the shipped game binary (release build, addresses "game @"), with names and structure from the SDK
// debug build's DWARF and disassembly ("sdk @", parity-out/sdk/dbgobj/oalOSX.o).
//
// Game vs. SDK: no difference in behaviour. FillInASBD converts the UInt32 sample rate to Float64 with the same
// unsigned SSE sequence in both builds (exact); the game merges the common tails of the format cases.
//
// Not part of this slice (rest of oalOSX.o): IsRelativePath, MakeAbsolutePath, GetOALFormatFromASBD,
// GetFormatString, GetALAttributeString, GetALCAttributeString, IsValidRenderQuality, GetDefaultDeviceName,
// SwapWords, SwapBytes, alutInit, alutExit, alutLoadWAVFile, alutLoadWAVMemory, alutUnloadWAV, alInit, alExit,
// OALRingBuffer.
//
// Strings (game __cstring): "AL_EXT_float32" @0x00161dcc.
// Data (game __data): GetNewPtrToken()::currentToken @0x001e0140 = 24, GetNewToken()::currentToken @0x001e0144 =
// 2400 (sdk __data @0x9418 / @0x941c, same values). The object has no static initializer.
//
// Host difference: GetNewPtrToken's counter is a uintptr_t, 32-bit on i386 (it would wrap after 2^32 tokens).
#pragma STDC FP_CONTRACT OFF
#include "oalOSX.h"
#include "CAStreamBasicDescription.h"
#include "oalImp.h"
// game @0x00120bfc sdk @0x0
uintptr_t GetNewPtrToken(void)
{
static uintptr_t currentToken = 24;
uintptr_t returnValue = currentToken;
currentToken++;
return returnValue;
}
// game @0x00120c16 sdk @0x2e
ALuint GetNewToken(void)
{
static ALuint currentToken = 2400;
ALuint returnValue = currentToken;
currentToken++;
return returnValue;
}
// game @0x00120c32 sdk @0xa8e
// AL_FORMAT_MONO8..AL_FORMAT_STEREO16 (0x1100..0x1103) are always supported, the float32 formats only while
// alIsExtensionPresent reports AL_EXT_float32.
bool IsFormatSupported(UInt32 inFormatID)
{
switch (inFormatID)
{
case AL_FORMAT_MONO8:
case AL_FORMAT_MONO16:
case AL_FORMAT_STEREO8:
case AL_FORMAT_STEREO16:
return true;
case AL_FORMAT_MONO_FLOAT32:
case AL_FORMAT_STEREO_FLOAT32:
return alIsExtensionPresent("AL_EXT_float32") != 0;
default:
break;
}
return false;
}
// game @0x00120c88 sdk @0xaf4
// Fills in a packed, interleaved linear PCM description; flags 8 = kAudioFormatFlagIsPacked, 0xc = packed signed
// integer, 1 = float. Unknown formats return AL_INVALID_VALUE and leave inASBD untouched.
OSStatus FillInASBD(CAStreamBasicDescription& inASBD, UInt32 inFormatID, UInt32 inSampleRate)
{
OSStatus err = noErr;
switch (inFormatID)
{
case AL_FORMAT_STEREO16:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
inASBD.mBytesPerPacket = 4;
inASBD.mBytesPerFrame = 4;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 16;
inASBD.mChannelsPerFrame = 2;
inASBD.mReserved = 0;
break;
case AL_FORMAT_MONO16:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
inASBD.mBytesPerPacket = 2;
inASBD.mBytesPerFrame = 2;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 16;
inASBD.mChannelsPerFrame = 1;
inASBD.mReserved = 0;
break;
case AL_FORMAT_STEREO8:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsPacked;
inASBD.mBytesPerPacket = 2;
inASBD.mBytesPerFrame = 2;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 8;
inASBD.mChannelsPerFrame = 2;
inASBD.mReserved = 0;
break;
case AL_FORMAT_MONO8:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsPacked;
inASBD.mBytesPerPacket = 1;
inASBD.mBytesPerFrame = 1;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 8;
inASBD.mChannelsPerFrame = 1;
inASBD.mReserved = 0;
break;
case AL_FORMAT_STEREO_FLOAT32:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsFloat;
inASBD.mBytesPerPacket = 8;
inASBD.mBytesPerFrame = 8;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 32;
inASBD.mChannelsPerFrame = 2;
inASBD.mReserved = 0;
break;
case AL_FORMAT_MONO_FLOAT32:
inASBD.mSampleRate = (Float64)inSampleRate;
inASBD.mFormatID = kAudioFormatLinearPCM;
inASBD.mFormatFlags = kAudioFormatFlagIsFloat;
inASBD.mBytesPerPacket = 4;
inASBD.mBytesPerFrame = 4;
inASBD.mFramesPerPacket = 1;
inASBD.mBitsPerChannel = 32;
inASBD.mChannelsPerFrame = 1;
inASBD.mReserved = 0;
break;
default:
err = AL_INVALID_VALUE;
break;
}
return err;
}
// game @0x00120fb0 sdk @0x119c
// The last ALC_MONO_SOURCES / ALC_STEREO_SOURCES pair of the zero-terminated attribute list wins. Their sum
// replaces the default when it is larger than the default or larger than 64.
UInt32 CalculateNeededMixerBusses(const ALCint* attrList, UInt32 inDefaultBusCount)
{
UInt32 monoSources = 0;
UInt32 stereoSources = 0;
UInt32 returnValue = inDefaultBusCount;
ALCint* currentAttribute = (ALCint*)attrList;
if (attrList != NULL)
{
while (*currentAttribute != 0)
{
switch (*currentAttribute)
{
case ALC_MONO_SOURCES:
monoSources = currentAttribute[1];
break;
case ALC_STEREO_SOURCES:
stereoSources = currentAttribute[1];
break;
default:
break;
}
currentAttribute += 2;
}
if ((monoSources == 0) && (stereoSources == 0))
{
returnValue = inDefaultBusCount;
}
else if (((monoSources + stereoSources) > 64) || ((monoSources + stereoSources) > inDefaultBusCount))
{
returnValue = monoSources + stereoSources;
}
}
return returnValue;
}
// game @0x00121012 sdk @0x1240
// Quad needs a 2.0 or later mixer, more than 5 channels a 2.3 or later one; at most 8 channels.
UInt32 GetDesiredRenderChannelsFor3DMixer(UInt32 inDeviceChannels)
{
UInt32 returnValue = inDeviceChannels;
if ((Get3DMixerVersion() < k3DMixerVersion_2_0) && (returnValue == 4))
{
returnValue = 2;
}
else if (inDeviceChannels < 4)
{
returnValue = 2;
}
else if ((inDeviceChannels > 5) && (Get3DMixerVersion() < k3DMixerVersion_2_3))
{
returnValue = 5;
}
else if (inDeviceChannels > 8)
{
returnValue = 8;
}
return returnValue;
}

23
port/external/openal/oalOSX.h vendored Normal file
View file

@ -0,0 +1,23 @@
// Port of pflib/external/openal/oalOSX.h (Apple OpenAL, Playground SDK 4.0): the Mac OS X helper functions of
// oalOSX.cpp. Only the six helpers the OpenAL classes need are declared here (ported in oalOSX.cpp); the rest of
// oalOSX.cpp (IsRelativePath, MakeAbsolutePath, GetOALFormatFromASBD, the Get*String helpers,
// IsValidRenderQuality, GetDefaultDeviceName, OALRingBuffer, the alut* functions) is not part of this port slice.
#ifndef OALOSX_H_INCLUDED
#define OALOSX_H_INCLUDED
#include "oal_sysdecls.h"
#include <stdint.h>
class CAStreamBasicDescription;
class OALRingBuffer;
uintptr_t GetNewPtrToken(void);
ALuint GetNewToken(void);
bool IsFormatSupported(UInt32 inFormatID);
OSStatus FillInASBD(CAStreamBasicDescription& inASBD, UInt32 inFormatID, UInt32 inSampleRate);
UInt32 CalculateNeededMixerBusses(const ALCint* attrList, UInt32 inDefaultBusCount);
UInt32 GetDesiredRenderChannelsFor3DMixer(UInt32 inDeviceChannels);
#endif

3044
port/external/openal/oalSource.cpp vendored Normal file

File diff suppressed because it is too large Load diff

559
port/external/openal/oalSource.h vendored Normal file
View file

@ -0,0 +1,559 @@
// Port of pflib/external/openal/oalSource.h (Apple OpenAL, Playground SDK 4.0): OALSource (an AL source playing
// through one bus of its context's 3DMixer), its buffer queues (BufferQueue / BufferInfo), the per-format
// AudioConverters (ACMap / ACInfo), the render-thread message queue (PlaybackMessage) and OALSourceMap.
// Layouts from the DWARF of parity-out/sdk/dbgobj/oalSource.o; the game uses the same offsets (OALSource
// constructor game @0x00124984).
//
// OALSource (size 364): +0x000 mSelfToken, +0x004 mSafeForDeletion, +0x008 mOwningContext, +0x00c mIsSuspended,
// +0x00d mCalculateDistance, +0x00e mResetBusFormat, +0x00f mResetPitch, +0x010 mBufferQueueActive,
// +0x014 mBufferQueueInactive, +0x018 mCurrentBufferIndex, +0x01c mQueueIsProcessed, +0x020 mRenderThreadID,
// +0x024 mPlayGuard (CAGuard), +0x078 mPlayCallback, +0x080 mCurrentPlayBus, +0x084 mACMap, +0x088 mOutputSilence,
// +0x08c mPosition[3], +0x098 mVelocity[3], +0x0a4 mConeDirection[3], +0x0b0 mLooping, +0x0b4 mSourceRelative,
// +0x0b8 mSourceType, +0x0bc mConeInnerAngle, +0x0c0 mConeOuterAngle, +0x0c4 mConeOuterGain, +0x0c8 mConeGainScaler,
// +0x0cc mAttenuationGainScaler, +0x0d0 mReadIndex, +0x0d4 mCachedInputL1, +0x0d8 mCachedInputL2,
// +0x0dc mCachedInputR1, +0x0e0 mCachedInputR2, +0x0e4 mTempSourceStorageBufferSize, +0x0e8 mTempSourceStorage,
// +0x0ec mState, +0x0f0 mGain, +0x0f4 mPitch, +0x0f8 mDopplerScaler, +0x0fc mRollOffFactor,
// +0x100 mReferenceDistance, +0x104 mMaxDistance, +0x108 mMinGain, +0x10c mMaxGain, +0x110 mRampState,
// +0x114 mBufferCountToUnqueueInPostRender, +0x118 mTransitioningToFlushQ, +0x11c mPlaybackHeadPosition,
// +0x120 mASAReverbSendLevel, +0x124 mASAOcclusion, +0x128 mASAObstruction, +0x12c mRogerBeepNode,
// +0x130 mRogerBeepAU, +0x134 mASARogerBeepEnable, +0x135 mASARogerBeepOn, +0x138 mASARogerBeepGain,
// +0x13c mASARogerBeepSensitivity, +0x140 mASARogerBeepType, +0x144 mASARogerBeepPreset, +0x148 mDistortionNode,
// +0x14c mDistortionAU, +0x150 mASADistortionEnable, +0x151 mASADistortionOn, +0x154 mASADistortionMix,
// +0x158 mASADistortionType, +0x15c mASADistortionPreset, +0x160 mRenderUnit, +0x164 mRenderElement,
// +0x168 mMessageQueue.
// BufferInfo (size 20): +0x00 mBufferToken, +0x04 mBuffer, +0x08 mOffset, +0x0c mProcessedState, +0x10 mACToken.
// BufferQueue (size 8): a std::list<BufferInfo>. ACInfo (size 44): +0x00 mConverter, +0x04 mInputFormat.
// ACMap and OALSourceMap (size 24): std::multimap<ALuint, ACInfo> / std::multimap<ALuint, OALSource*>.
// PlaybackMessage (size 16): +0x00 mNext, +0x04 mMessageID, +0x08 mAppendBuffer, +0x0c mBuffersToUnqueueInPostRender.
// The containers are gcc 4.0 libstdc++ ones in the binary; the port uses the host std::list / std::multimap
// (same ordering: multimap insertions of an equal key go after the existing ones, as insert_equal does).
//
// Header code (inline members below) is emitted out of line in the SDK's oalSource.o / oalContext.o
// (__textcoal_nt, addresses at each member) and inlined everywhere in the game, except OALSourceMap's and
// BufferQueue's constructors (game @0x001923e8 / @0x001926b4, __textcoal_nt). BufferQueue::Get takes a short
// index (std::advance with a negative count walks backwards), as the game's inlined copies do with the low 16
// bits of mCurrentBufferIndex; Size counts the nodes (gcc 4.0 list::size).
//
// Constants without names in the binary (Apple's #defines; names from Apple's OpenAL sources where known): the
// render states AL_INITIAL / AL_PLAYING / AL_PAUSED / AL_STOPPED (al.h) plus kTransitionToStop 'tste' (the state
// while the render thread finishes a stop), the PlaybackMessage IDs kMQ_*, the BufferInfo processed states and
// the ramp states.
#ifndef OALSOURCE_H_INCLUDED
#define OALSOURCE_H_INCLUDED
#include "oal_sysdecls.h"
#include "CAGuard.h"
#include "CAStreamBasicDescription.h"
#include "oalAtomicStack.h"
#include "oalBuffer.h"
#include <list>
#include <map>
class OALContext;
class OALSource;
// mState while the render thread finishes a stop (GetState reports AL_STOPPED)
#define kTransitionToStop 'tste'
// returned by ACComplexInputDataProc when the converter has to be called again
#define OALSourceError_CallConverterAgain 'agan'
// BufferInfo::mProcessedState
enum
{
kPendingProcessing = 0,
kInProgress = 1,
kProcessed = 2
};
// OALSource::mRampState
enum
{
kRampingComplete = -2,
kRampDown = -1,
kNoRamping = 0,
kRampUp = 1
};
// PlaybackMessage::mMessageID
enum
{
kMQ_NoMessage = 0,
kMQ_Stop = 1,
kMQ_Rewind = 2,
kMQ_SetBuffer = 3,
kMQ_Play = 4,
kMQ_Pause = 5,
kMQ_Resume = 6,
kMQ_SetFramePosition = 7,
kMQ_ClearBuffersFromQueue = 8,
kMQ_DeconstructionStop = 9
};
struct BufferInfo
{
ALuint mBufferToken;
OALBuffer* mBuffer;
UInt32 mOffset;
UInt32 mProcessedState;
ALuint mACToken;
};
class BufferQueue : std::list<BufferInfo>
{
public:
// game @0x001926b4 sdk @0x360f6 (oalSource.o)
BufferQueue() {}
void AppendBuffer(OALSource* thisSource, ALuint inBufferToken, OALBuffer* inBuffer, ALuint inACToken);
ALuint RemoveQueueEntryByIndex(OALSource* thisSource, UInt32 inIndex, bool inReleaseIt);
UInt32 GetQueueSizeInFrames();
UInt32 GetBufferFrameCount(UInt32 inBufferIndex);
void SetFirstBufferOffset(UInt32 inFrameOffset);
ALuint GetBufferTokenByIndex(UInt32 inBufferIndex);
UInt32 GetCurrentFrame(UInt32 inBufferIndex);
// sdk @0x35378 (oalSource.o)
BufferInfo* Get(short inBufferIndex)
{
iterator it = begin();
std::advance(it, inBufferIndex);
if (it != end())
{
return (&(*it));
}
return (NULL);
}
// sdk @0x3528e (oalSource.o)
void SetBufferAsProcessed(UInt32 inBufferIndex)
{
iterator it = begin();
std::advance(it, inBufferIndex);
if (it != end())
{
(*it).mProcessedState = kProcessed;
}
}
// sdk @0x350ee (oalSource.o)
void ResetBuffers()
{
iterator it = begin();
while (it != end())
{
(*it).mProcessedState = kPendingProcessing;
(*it).mOffset = 0;
++it;
}
}
// sdk @0x358de (oalSource.o)
UInt32 Size() const { return (UInt32)size(); }
// sdk @0x34d00 (oalSource.o)
bool Empty() const { return empty(); }
private:
UInt32 GetPacketSize();
UInt32 FrameOffsetToPacketOffset(UInt32 inFrameOffset);
};
struct ACInfo
{
AudioConverterRef mConverter;
CAStreamBasicDescription mInputFormat;
};
class ACMap : std::multimap<ALuint, ACInfo, std::less<ALuint> >
{
public:
// sdk @0x367be (oalSource.o)
void Add(const ALuint inACToken, ACInfo* inACInfo)
{
iterator it = upper_bound(inACToken);
insert(it, value_type(inACToken, *inACInfo));
}
// sdk @0x35afe (oalSource.o)
AudioConverterRef Get(ALuint inACToken)
{
iterator it = find(inACToken);
iterator theEnd = end();
if (it != theEnd)
{
return ((*it).second.mConverter);
}
return (NULL);
}
// sdk @0x354fc (oalSource.o)
void GetACForFormat(CAStreamBasicDescription* inFormat, ALuint& outToken)
{
iterator it = begin();
outToken = 0;
while (it != end())
{
if ((*it).second.mInputFormat == *inFormat)
{
outToken = (*it).first;
it = end();
}
else
{
++it;
}
}
return;
}
void Remove(const ALuint inACToken);
// sdk @0x35594 (oalSource.o)
void RemoveAllConverters()
{
iterator it = begin();
iterator theEnd = end();
while (it != theEnd)
{
AudioConverterDispose((*it).second.mConverter);
++it;
}
}
UInt32 Size() const { return (UInt32)size(); }
bool Empty() const { return empty(); }
};
class PlaybackMessage
{
public:
// sdk @0x34c4c (oalSource.o)
PlaybackMessage(UInt32 inMessage, OALBuffer* inBuffer, UInt32 inNumBuffers) :
mMessageID(inMessage),
mAppendBuffer(inBuffer),
mBuffersToUnqueueInPostRender(inNumBuffers)
{
}
// sdk @0x34c70 (oalSource.o)
~PlaybackMessage() {}
// sdk @0x34c78 (oalSource.o)
PlaybackMessage* get_next() { return mNext; }
// sdk @0x34c86 (oalSource.o)
void set_next(PlaybackMessage* next) { mNext = next; }
PlaybackMessage* mNext;
UInt32 mMessageID;
OALBuffer* mAppendBuffer;
UInt32 mBuffersToUnqueueInPostRender;
};
class OALSource
{
public:
OALSource(const ALuint inSelfToken, OALContext* inOwningContext);
~OALSource();
// set methods - public
void SetPitch(Float32 inPitch);
void SetGain(Float32 inGain);
void SetMinGain(Float32 inMinGain);
void SetMaxGain(Float32 inMaxGain);
void SetReferenceDistance(Float32 inReferenceDistance);
void SetMaxDistance(Float32 inMaxDistance);
void SetRollOffFactor(Float32 inRollOffFactor);
void SetLooping(UInt32 inLooping);
void SetPosition(Float32 inX, Float32 inY, Float32 inZ);
void SetVelocity(Float32 inX, Float32 inY, Float32 inZ);
void SetDirection(Float32 inX, Float32 inY, Float32 inZ);
void SetSourceRelative(UInt32 inSourceRelative);
void SetChannelParameters();
void SetConeInnerAngle(Float32 inConeInnerAngle);
void SetConeOuterAngle(Float32 inConeOuterAngle);
void SetConeOuterGain(Float32 inConeOuterGain);
void SetQueueOffset(UInt32 inOffsetType, Float32 inOffset);
void SetUpDeconstruction();
// get methods - public
Float32 GetPitch();
Float32 GetDopplerScaler();
Float32 GetGain();
Float32 GetMinGain();
Float32 GetMaxGain();
Float32 GetReferenceDistance();
Float32 GetMaxDistance();
Float32 GetRollOffFactor();
UInt32 GetLooping();
void GetPosition(Float32& inX, Float32& inY, Float32& inZ);
void GetVelocity(Float32& inX, Float32& inY, Float32& inZ);
void GetDirection(Float32& inX, Float32& inY, Float32& inZ);
UInt32 GetSourceRelative();
UInt32 GetSourceType();
Float32 GetConeInnerAngle();
Float32 GetConeOuterAngle();
Float32 GetConeOuterGain();
UInt32 GetState();
ALuint GetToken();
UInt32 GetQueueOffset(UInt32 inOffsetType);
// buffer queue methods - public
UInt32 GetQLength();
UInt32 GetBuffersProcessed();
void SetBuffer(ALuint inBufferToken, OALBuffer* inBuffer);
ALuint GetBuffer();
void AddToQueue(ALuint inBufferToken, OALBuffer* inBuffer);
void RemoveBuffersFromQueue(UInt32 inCount, ALuint* outBufferTokens);
bool IsSourceTransitioningToFlushQ();
bool IsBufferInActiveQueue(ALuint inBufferToken);
// sdk @0x1f728 (oalContext.o)
bool IsSafeForDeletion() { return (mSafeForDeletion); }
// playback methods - public
void Play();
void Pause();
void Resume();
void Rewind();
void Stop();
void Suspend();
void Unsuspend();
// ASA methods - public (sdk only, not ported)
void SetReverbSendLevel(Float32 inReverbLevel);
void SetOcclusion(Float32 inOcclusion);
void SetObstruction(Float32 inObstruction);
void SetRogerBeepEnable(Boolean inEnable);
void SetRogerBeepOn(Boolean inOn);
void SetRogerBeepGain(Float32 inGain);
void SetRogerBeepSensitivity(UInt32 inSensitivity);
void SetRogerBeepType(UInt32 inType);
void SetRogerBeepPreset(FSRef* inRef);
void SetDistortionEnable(Boolean inEnable);
void SetDistortionOn(Boolean inOn);
void SetDistortionMix(Float32 inMix);
void SetDistortionType(SInt32 inType);
void SetDistortionPreset(FSRef* inRef);
Float32 GetReverbSendLevel();
Float32 GetOcclusion();
Float32 GetObstruction();
Boolean GetRogerBeepEnable();
Boolean GetRogerBeepOn();
Float32 GetRogerBeepGain();
UInt32 GetRogerBeepSensitivity();
UInt32 GetRogerBeepType();
Boolean GetDistortionEnable();
Boolean GetDistortionOn();
Float32 GetDistortionMix();
SInt32 GetDistortionType();
private:
void JoinBufferLists();
void LoopToBeginning();
void ChangeChannelSettings();
void InitSource();
void SetState(UInt32 inState);
OSStatus DoPreRender();
OSStatus DoRender(AudioBufferList* ioData);
OSStatus DoSRCRender(AudioBufferList* ioData);
OSStatus DoPostRender();
bool ConeAttenuation();
void CalculateDistanceAndAzimuth(Float32* outDistance, Float32* outAzimuth, Float32* outElevation,
Float32* outDopplerShift);
// sdk @0x34dd6 (oalSource.o)
bool CallingInRenderThread() const { return (pthread_self() == mRenderThreadID); }
void UpdateBusGain();
void UpdateBusFormat();
void UpdateBusReverb();
void UpdateBusOcclusion();
void UpdateBusObstruction();
void UpdateQueue();
void RampDown(AudioBufferList* ioData);
void RampUp(AudioBufferList* ioData);
void ClearActiveQueue();
void SkipALNONEBuffers();
void AddNotifyAndRenderProcs();
void ReleaseNotifyAndRenderProcs();
void DisconnectFromBus();
void SetupMixerBus();
void SetupDistortionAU();
void SetupRogerBeepAU();
bool PrepBufferQueueForPlayback();
UInt32 SecondsToFrames(Float32 inSeconds);
UInt32 BytesToFrames(Float32 inBytes);
void AppendBufferToQueue(ALuint inBufferToken, OALBuffer* inBuffer);
UInt32 FramesToSeconds(UInt32 inFrames);
UInt32 FramesToBytes(UInt32 inFrames);
void PostRenderSetBuffer(ALuint inBufferToken, OALBuffer* inBuffer);
void PostRenderRemoveBuffersFromQueue(UInt32 inBuffersToUnqueue);
void FlushBufferQueue();
void StopFromDestructor();
void AdvanceQueueToFrameIndex(UInt32 inFrameOffset);
OSStatus SetDistanceParams(bool inChangeReferenceDistance, bool inChangeMaxDistance);
Float32 GetMaxAttenuation(Float32 inRefDistance, Float32 inMaxDistance, Float32 inRolloff);
BufferInfo* NextPlayableBufferInActiveQ();
static OSStatus SourceNotificationProc(void* inRefCon, AudioUnitRenderActionFlags* inActionFlags,
const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber,
UInt32 inNumberFrames, AudioBufferList* ioData);
static OSStatus SourceInputProc(void* inRefCon, AudioUnitRenderActionFlags* inActionFlags,
const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames,
AudioBufferList* ioData);
static OSStatus ACComplexInputDataProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets,
AudioBufferList* ioData,
AudioStreamPacketDescription** outDataPacketDescription,
void* inUserData);
ALuint mSelfToken;
bool mSafeForDeletion;
OALContext* mOwningContext;
bool mIsSuspended;
bool mCalculateDistance;
bool mResetBusFormat;
bool mResetPitch;
BufferQueue* mBufferQueueActive;
BufferQueue* mBufferQueueInactive;
ALuint mCurrentBufferIndex;
bool mQueueIsProcessed;
pthread_t mRenderThreadID;
CAGuard mPlayGuard;
AURenderCallbackStruct mPlayCallback;
int mCurrentPlayBus;
ACMap* mACMap;
bool mOutputSilence;
Float32 mPosition[3];
Float32 mVelocity[3];
Float32 mConeDirection[3];
UInt32 mLooping;
UInt32 mSourceRelative;
UInt32 mSourceType;
Float32 mConeInnerAngle;
Float32 mConeOuterAngle;
Float32 mConeOuterGain;
Float32 mConeGainScaler;
Float32 mAttenuationGainScaler;
float mReadIndex;
float mCachedInputL1;
float mCachedInputL2;
float mCachedInputR1;
float mCachedInputR2;
UInt32 mTempSourceStorageBufferSize;
AudioBufferList* mTempSourceStorage;
UInt32 mState;
float mGain;
Float32 mPitch;
Float32 mDopplerScaler;
Float32 mRollOffFactor;
Float32 mReferenceDistance;
Float32 mMaxDistance;
Float32 mMinGain;
Float32 mMaxGain;
SInt32 mRampState;
UInt32 mBufferCountToUnqueueInPostRender;
bool mTransitioningToFlushQ;
UInt32 mPlaybackHeadPosition;
Float32 mASAReverbSendLevel;
Float32 mASAOcclusion;
Float32 mASAObstruction;
AUNode mRogerBeepNode;
AudioUnit mRogerBeepAU;
Boolean mASARogerBeepEnable;
Boolean mASARogerBeepOn;
Float32 mASARogerBeepGain;
UInt32 mASARogerBeepSensitivity;
UInt32 mASARogerBeepType;
char* mASARogerBeepPreset;
AUNode mDistortionNode;
AudioUnit mDistortionAU;
Boolean mASADistortionEnable;
Boolean mASADistortionOn;
Float32 mASADistortionMix;
SInt32 mASADistortionType;
char* mASADistortionPreset;
AudioUnit mRenderUnit;
UInt32 mRenderElement;
TAtomicStack<PlaybackMessage> mMessageQueue;
};
class OALSourceMap : std::multimap<ALuint, OALSource*, std::less<ALuint> >
{
public:
// game @0x001923e8 sdk @0x20062 (oalContext.o)
OALSourceMap() {}
// sdk @0x204e6 (oalContext.o)
void Add(const ALuint inSourceToken, OALSource** inSource)
{
iterator it = upper_bound(inSourceToken);
insert(it, value_type(inSourceToken, *inSource));
}
// sdk @0x1f900 (oalContext.o)
OALSource* GetSourceByIndex(UInt32 inIndex)
{
iterator it = begin();
for (UInt32 i = 0; i < inIndex; i++)
{
if (it != end())
{
it++;
}
else
{
i = inIndex;
}
}
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x1fc62 (oalContext.o)
OALSource* Get(ALuint inSourceToken)
{
iterator it = find(inSourceToken);
if (it != end())
{
return ((*it).second);
}
return (NULL);
}
// sdk @0x1f8a2 (oalContext.o)
void MarkAllSourcesForRecalculation()
{
iterator it = begin();
while (it != end())
{
(*it).second->SetChannelParameters();
it++;
}
return;
}
void SuspendAllSources();
void UnsuspendAllSources();
// sdk @0x1fe4e (oalContext.o)
void Remove(const ALuint inSourceToken)
{
iterator it = find(inSourceToken);
if (it != end())
{
erase(it);
}
}
// sdk @0x1f7c4 (oalContext.o)
UInt32 Size() const { return (UInt32)size(); }
bool Empty() const { return empty(); }
};
#endif

56
port/external/openal/oal_sysdecls.h vendored Normal file
View file

@ -0,0 +1,56 @@
// System API declarations for the port of Apple's OpenAL implementation (pflib/external/openal, Playground SDK 4.0).
// Not an SDK file: it gathers the system headers the OpenAL sources include and states the host differences that
// concern every file of this directory.
//
// The SDK was built against the Mac OS X 10.4u SDK for i386. The AudioUnit / AUGraph / AudioConverter / CoreAudio
// HAL / Component Manager calls are kept exactly as the game calls them. The current macOS SDK still declares all
// of them with their original signatures (several only as deprecated): AUGraphNewNode and AUGraphGetNodeInfo
// (AUGraph.h, deprecated in 10.5, with struct ComponentDescription from CarbonCore Components.h),
// AudioDeviceGetPropertyInfo / AudioDeviceGetProperty / AudioHardwareGetProperty (AudioHardwareDeprecated.h) and
// CompareAndSwap (DriverSynchronization.h), so nothing has to be declared here by hand.
//
// Host differences (i386 / 10.4u SDK -> LP64 / current SDK):
// - UInt32 / SInt32 were unsigned long / long on i386 (the mangled names of the game use 'm' = unsigned long);
// the port keeps Apple's UInt32 / SInt32, which are 32-bit on the host as well.
// - OSStatus was SInt32 = long on i386. Exceptions thrown as OSStatus therefore have the type long in the game
// (typeinfo __ZTIl, non-lazy pointer @0x002264dc) and are distinct from the int of `throw -1` (__ZTIi,
// @0x002264d8): catch (OSStatus) does not catch -1. On the host OSStatus is int, which would merge both, so
// OSStatus exceptions are thrown and caught as OALStatusException (long) and -1 stays an int.
// - AudioUnit is a ComponentInstance (ComponentInstanceRecord*) in both SDKs on the desktop.
// - Pointers are 64-bit: TAtomicStack's CompareAndSwap on a pointer is done with a pointer-sized compare-and-swap
// on the host (oalAtomicStack.h).
#ifndef OAL_SYSDECLS_H_INCLUDED
#define OAL_SYSDECLS_H_INCLUDED
#include <AudioToolbox/AudioToolbox.h>
#include <AudioUnit/AudioUnit.h>
#include <CoreAudio/CoreAudio.h>
#include <CoreServices/CoreServices.h>
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <pthread.h>
// The type of an OSStatus thrown by the OpenAL implementation (long on i386, see above).
typedef long OALStatusException;
// Float64 -> UInt32 conversion exactly as gcc 4.0 compiles `(UInt32)x` for i386 with SSE2 (game e.g.
// @0x0012267f..@0x001226c4): the value is clamped with minsd(x, 4294967295.0) and maxsd(.., 0.0), 2^31 is
// subtracted when 2^31 <= x, cvttsd2si truncates (0x80000000 when out of range) and the sign bit is put back.
// Defined for every input, including NaN (-> 0x80000000) and out-of-range values, where a plain C++ conversion
// is undefined on the host.
inline UInt32 OALConvertFloat64ToUInt32(Float64 x)
{
bool high = (2147483648.0 <= x);
Float64 v = (x < 4294967295.0) ? x : 4294967295.0;
v = (v > 0.0) ? v : 0.0;
if (high)
{
v -= 2147483648.0;
}
UInt32 i = (v < 2147483648.0) ? (UInt32)(SInt32)v : 0x80000000u;
return high ? (i ^ 0x80000000u) : i;
}
#endif