Fatal error when using withMemoryRebound in iOS/Swift - ios

I have the following code to create a table for sampling an image in iOS using the Swift accelerate functions
When I rebound the memory to UInt16 which the table creation expects from Int which is the original type I get a fatal error.
var arr = Array<Float>(repeating: 0, count: 163840)
arr.withUnsafeBufferPointer{
arr_pointer in do {
arr_pointer.withMemoryRebound(to: UInt16.self){ // This causes a FATAL ERROR
arr_r_pointer in do {
let table = vImageMultidimensionalTable_Create( arr_r_pointer.baseAddress!,
3, 3, dims_r_pointer.baseAddress!, kvImageMDTableHint_Float,
vImage_Flags(kvImageNoFlags), nil )
vImageMultiDimensionalInterpolatedLookupTable_PlanarF( &srcBuffer,
&destBuffer,nil,table!,
kvImageFullInterpolation,
vImage_Flags(kvImageNoFlags))
}
}
}
}
Could anyone point out my mistake here?

You should've read Note for withMemoryRebound function:
Note
Only use this method to rebind the buffer’s memory to a type with the same size and stride as the currently bound Element type. To
bind a region of memory to a type that is a different size, convert
the buffer to a raw buffer and use the bindMemory(to:) method.
Size of Float is 32 bits, size of UInt16 is 16 bits, so they don't have same size and cannot be rebound.
So you should do something like this:
arr.withUnsafeBufferPointer { pointer in
let raw = UnsafeRawBufferPointer(pointer)
let uints = raw.bindMemory(to: UInt16.self)
// use buffer pointer to `UInt16`s here
}
But also note, that each Float from initial array will be split in two UInt16 that way. I don't know if that's what you need.

Your original array arr is an array of Floats
var arr = Array<Float>(repeating: 0, count: 163840)
but you're trying to bind the pointer to a UInt16
arr_pointer.withMemoryRebound(to: UInt16.self)

Related

Excess elements in scalar initializer in byte create in iOS

In my project, I create a byte:
Byte bytes = {0x7E, 0x7F};
But there comes a warning:
Excess elements in scalar initializer
What this mean? does it effect me?
You are trying to create single dimensional array where you are not declaring size of it there's no memory set aside for an array so that's why the compiler is generating a warning which may cause an runtime error ahead.
Set array size:
// single dimen
Byte bytes[2] = {0x7E, 0x7F};
// double dimen
Byte bytes[1][2] = {{0x7E, 0x7F}, {0x7E, 0x7F}};
how stupid! I create a byte array should be like this:
Byte bytes[] = {0x7E, 0x7F}
I did not write the [].

Spectrogram from AVAudioPCMBuffer using Accelerate framework in Swift

I'm trying to generate a spectrogram from an AVAudioPCMBuffer in Swift. I install a tap on an AVAudioMixerNode and receive a callback with the audio buffer. I'd like to convert the signal in the buffer to a [Float:Float] dictionary where the key represents the frequency and the value represents the magnitude of the audio on the corresponding frequency.
I tried using Apple's Accelerate framework but the results I get seem dubious. I'm sure it's just in the way I'm converting the signal.
I looked at this blog post amongst other things for a reference.
Here is what I have:
self.audioEngine.mainMixerNode.installTapOnBus(0, bufferSize: 1024, format: nil, block: { buffer, when in
let bufferSize: Int = Int(buffer.frameLength)
// Set up the transform
let log2n = UInt(round(log2(Double(bufferSize))))
let fftSetup = vDSP_create_fftsetup(log2n, Int32(kFFTRadix2))
// Create the complex split value to hold the output of the transform
var realp = [Float](count: bufferSize/2, repeatedValue: 0)
var imagp = [Float](count: bufferSize/2, repeatedValue: 0)
var output = DSPSplitComplex(realp: &realp, imagp: &imagp)
// Now I need to convert the signal from the buffer to complex value, this is what I'm struggling to grasp.
// The complexValue should be UnsafePointer<DSPComplex>. How do I generate it from the buffer's floatChannelData?
vDSP_ctoz(complexValue, 2, &output, 1, UInt(bufferSize / 2))
// Do the fast Fournier forward transform
vDSP_fft_zrip(fftSetup, &output, 1, log2n, Int32(FFT_FORWARD))
// Convert the complex output to magnitude
var fft = [Float](count:Int(bufferSize / 2), repeatedValue:0.0)
vDSP_zvmags(&output, 1, &fft, 1, vDSP_length(bufferSize / 2))
// Release the setup
vDSP_destroy_fftsetup(fftsetup)
// TODO: Convert fft to [Float:Float] dictionary of frequency vs magnitude. How?
})
My questions are
How do I convert the buffer.floatChannelData to UnsafePointer<DSPComplex> to pass to the vDSP_ctoz function? Is there a different/better way to do it maybe even bypassing vDSP_ctoz?
Is this different if the buffer contains audio from multiple channels? How is it different when the buffer audio channel data is or isn't interleaved?
How do I convert the indices in the fft array to frequencies in Hz?
Anything else I may be doing wrong?
Update
Thanks everyone for suggestions. I ended up filling the complex array as suggested in the accepted answer. When I plot the values and play a 440 Hz tone on a tuning fork it registers exactly where it should.
Here is the code to fill the array:
var channelSamples: [[DSPComplex]] = []
for var i=0; i<channelCount; ++i {
channelSamples.append([])
let firstSample = buffer.format.interleaved ? i : i*bufferSize
for var j=firstSample; j<bufferSize; j+=buffer.stride*2 {
channelSamples[i].append(DSPComplex(real: buffer.floatChannelData.memory[j], imag: buffer.floatChannelData.memory[j+buffer.stride]))
}
}
The channelSamples array then holds separate array of samples for each channel.
To calculate the magnitude I used this:
var spectrum = [Float]()
for var i=0; i<bufferSize/2; ++i {
let imag = out.imagp[i]
let real = out.realp[i]
let magnitude = sqrt(pow(real,2)+pow(imag,2))
spectrum.append(magnitude)
}
Hacky way: you can just cast a float array. Where reals and imag values are going one after another.
It depends on if audio is interleaved or not. If it's interleaved (most of the cases) left and right channels are in the array with STRIDE 2
Lowest frequency in your case is frequency of a period of 1024 samples. In case of 44100kHz it's ~23ms, lowest frequency of the spectrum will be 1/(1024/44100) (~43Hz). Next frequency will be twice of this (~86Hz) and so on.
4: You have installed a callback handler on an audio bus. This is likely run with real-time thread priority and frequently. You should not do anything that has potential for blocking (it will likely result in priority inversion and glitchy audio):
Allocate memory (realp, imagp - [Float](.....) is shorthand for Array[float] - and likely allocated on the heap`. Pre-allocate these
Call lengthy operations such as vDSP_create_fftsetup() - which also allocates memory and initialises it. Again, you can allocate this once outside of your function.

What is UnsafeMutablePointer<Void>? How to modify the underlying memory?

I am trying to work with SpriteKit's SKMutableTexture class but I don't know how to work with UnsafeMutablePointer< Void >. I have a vague idea that it is a pointer to a succession of byte data in memory. But how can I update it? What would this actually look like in code?
Edit
Here is a basic code sample to work with. How would I get this to do something as simple as create a red square on the screen?
let tex = SKMutableTexture(size: CGSize(width: 10, height: 10))
tex.modifyPixelDataWithBlock { (ptr:UnsafeMutablePointer<Void>, n:UInt) -> Void in
/* ??? */
}
From the docs for SKMutableTexture.modifyPixelDataWithBlock:
The texture bytes are assumed to be stored as tightly packed 32 bpp, 8bpc (unsigned integer) RGBA pixel data. The color components you provide should have already been multiplied by the alpha value.
So, while you’re given a void*, the underlying data is in the form of a stream of 4x8 bits.
You could manipulate such a structure like so:
// struct of 4 bytes
struct RGBA {
var r: UInt8
var g: UInt8
var b: UInt8
var a: UInt8
}
let tex = SKMutableTexture(size: CGSize(width: 10, height: 10))
tex.modifyPixelDataWithBlock { voidptr, len in
// convert the void pointer into a pointer to your struct
let rgbaptr = UnsafeMutablePointer<RGBA>(voidptr)
// next, create a collection-like structure from that pointer
// (this second part isn’t necessary but can be nicer to work with)
// note the length you supply to create the buffer is the number of
// RGBA structs, so you need to convert the supplied length accordingly...
let pixels = UnsafeMutableBufferPointer(start: rgbaptr, count: Int(len / sizeof(RGBA))
// now, you can manipulate the pixels buffer like any other mutable collection type
for i in indices(pixels) {
pixels[i].r = 0x00
pixels[i].g = 0xff
pixels[i].b = 0x00
pixels[i].a = 0x20
}
}
UnsafeMutablePointer<Void> is the Swift equivalent of void* - a pointer to anything at all. You can access the underlying memory as its memory property. Typically, if you know what the underlying type is, you'll coerce to a pointer to that type first. You can then use subscripting to reach a particular "slot" in memory.
For example, if the data is really a sequence of UInt8 values, you could say:
let buffer = UnsafeMutablePointer<UInt8>(ptr)
You can now access the individual UIInt8 values as buffer[0], buffer[1], and so forth.

Swift pointer arithmetic and dereferencing; converting some C-like map code to Swift

I have this little bit of Swift code that does not seem to be working...
// earlier, in Obj C...
typedef struct _Room {
uint8_t *map;
int width;
int height;
} Room;
A Room is part of a stab at a roguelike game if you're curious. I'm trying to rewrite a couple of parts in Swift. Here's the code that appears broken, and what I hope I am doing as comments:
let ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct
let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining
let locationPointer = ptr + offset // pointer advances to point to the offset I want
var pointValue = ptr.memory // What I used to get with *ptr
Something is wrong here because simple tests show the value of pointValue is not what I know I am looking at on the map, having set a very simple location (1, 1) to a known value. It seems pretty obvious that Swift is not supposed to be doing this kind of thing but it's a conversion with the aim of learning the Way of Swift when I know the syntax well enough.
I expect the error is in the swift code - since this was all working in the objective C version. Where's the error?
You are assigning locationPointer to point to the new location, but still using ptr in the next line, and the value of ptr has not been changed. Change your last line to:
var pointValue = locationPointer.memory
or you could change your pointer to a var and advance it:
var ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct
let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining
ptr = ptr + offset // pointer advances to point to the offset I want
var pointValue = ptr.memory // What I used to get with *ptr

Using cvGet2D OpenCV function

I'm trying to get information from an image using the function cvGet2D in OpenCV.
I created an array of 10 IplImage pointers:
IplImage *imageArray[10];
and I'm saving 10 images from my webcam:
imageArray[numPicture] = cvQueryFrame(capture);
when I call the function:
info = cvGet2D(imageArray[0], 250, 100);
where info:
CvScalar info;
I got the error:
OpenCV Error: Bad argument (unrecognized or unsupported array type) in cvPtr2D, file /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp, line 1824
terminate called after throwing an instance of 'cv::Exception'
what(): /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp:1824: error: (-5) unrecognized or unsupported array type in function cvPtr2D
If I use the function cvLoadImage to initialize an IplImage pointer and then I pass it to the cvGet2D function, the code works properly:
IplImage* imagen = cvLoadImage("test0.jpg");
info = cvGet2D(imagen, 250, 100);
however, I want to use the information already stored in my array.
Do you know how can I solve it?
Even though its a very late response, but I guess someone might be still searching for the solution with CvGet2D. Here it is.
For CvGet2D, we need to pass the arguments in the order of Y first and then X.
Example:
CvScalar s = cvGet2D(img, Y, X);
Its not mentioned anywhere in the documentation, but you find it only inside core.h/ core_c.h. Try to go to the declaration of CvGet2D(), and above the function prototypes, there are few comments that explain this.
Yeah the message is correct.
If you want to store a pixel value you need to do something like this.
int value = 0;
value = ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels +0];
cout << "pixel value for Blue Channel and (i,j) coordinates: " << value << endl;
Summarizing, to plot or store data you must create an integer value (pixel value varies between 0 and 255). But if you only want to test pixel value (like in an if closure or something similar) you can access directly to pixel value without using an integer value.
I think thats a little bit weird when you start but when you work with it 2 o 3 times you will work without difficulties.
Sorry, cvGet2D is not the best way to obtain pixel value. I know its the shortest and clear way because you in only one line of code and knowing coordinates obtain the pixel value.
I suggest you this option. When you see this code you you wiil think that is so complicated but is more effecient.
int main()
{
// Acquire the image (I'm reading it from a file);
IplImage* img = cvLoadImage("image.bmp",1);
int i,j,k;
// Variables to store image properties
int height,width,step,channels;
uchar *data;
// Variables to store the number of white pixels and a flag
int WhiteCount,bWhite;
// Acquire image unfo
height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
data = (uchar *)img->imageData;
// Begin
WhiteCount = 0;
for(i=0;i<height;i++)
{
for(j=0;j<width;j++)
{ // Go through each channel of the image (R,G, and B) to see if it's equal to 255
bWhite = 0;
for(k=0;k<channels;k++)
{ // This checks if the pixel's kth channel is 255 - it can be faster.
if (data[i*step+j*channels+k]==255) bWhite = 1;
else
{
bWhite = 0;
break;
}
}
if(bWhite == 1) WhiteCount++;
}
}
printf("Percentage: %f%%",100.0*WhiteCount/(height*width));
return 0;
This code count white pixels and gives you a percetage of white pixels in the image.

Resources