0

I have a memory reference, mBuffers.mData (from an AudioUnit bufferList), declared in the OS X and iOS framework headers as an:

UnsafeMutablePointer<Void>

What is an efficient way to write lots of Int16 values into memory referenced by this pointer?

A disassembly of this Swift source code:

for i in 0..<count {
    var x  : Int16 = someFastCalculation()
    let loByte : Int32 =  Int32(x)       & 0x00ff
    let hiByte : Int32 = (Int32(x) >> 8) & 0x00ff
    memset(mBuffers.mData + 2 * i    , loByte, 1)   
    memset(mBuffers.mData + 2 * i + 1, hiByte, 1)
}

shows lots of instructions setting up the memset() function calls (far more instructions than in my someFastCalculation). This is a loop inside a real-time audio callback, so efficient code to minimize latency and battery consumption is important.

Is there a faster way?

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
  • Is there any dependencies between previous calculated value and newly calculating value? If not we can try to execute this loop in parallel using GCD. – Aruna Mudnoor Jan 25 '16 at 05:53

1 Answers1

0

This Swift source allows array assignment of individual audio samples to an Audio Unit (or AUAudioUnit) audio buffer, and compiles down to a faster result than using memset.

let mutableData = UnsafeMutablePointer<Int16>(mBuffers.mData)
let sampleArray = UnsafeMutableBufferPointer<Int16>(
    start: mutableData,
    count: Int(mBuffers.mDataByteSize)/sizeof(Int16))

for i in 0..<count {
    let x : Int16 = mySampleSynthFunction(i)
    sampleArray[i]  =  x
}

More complete Gist here .

hotpaw2
  • 70,107
  • 14
  • 90
  • 153