CoreAudio: getting device count breaks when linking to Foundation on 10.6 - macos

I have a mixed C++/Objective-C project that uses AudioObjectGetPropertyDataSize to get the number of audio devices (such as USB headsets) plugged in. This API doesn't seem to work under certain conditions. For example, on 10.5 it will work but on 10.6 it won't detect when a new USB headset is plugged in.
I've pared down the problem to a small bit of code that reproduces the problem (it calls AudioObjectGetPropertyDataSize in a loop). The code will work on 10.6 (ie, it will detect when devices are plugged/unplugged) when its only linked against CoreAudio, but once you link against Foundation it will stop working.
I don't understand how linking to a framework can break code that otherwise works.
Here is the code (coreaudio-test.cpp):
#include <stdio.h>
#include <CoreAudio/AudioHardware.h>
int main(int argc, char **argv) {
printf("Press <enter> to refresh device list> \n");
while (1) {
getchar();
// get device count
UInt32 dataSize = 0;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mSelector = kAudioHardwarePropertyDevices;
propertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
propertyAddress.mElement = kAudioObjectPropertyElementMaster;
OSStatus result =
AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize);
int count = -1;
if (result == noErr) {
count = dataSize / sizeof(AudioDeviceID);
}
printf("num devices= %d \n", count);
}
return 0;
}
And here is the Makefile:
LFLAGS= -framework CoreAudio
all: coreaudio-test coreaudio-test.broken
# create a test that works
coreaudio-test: coreaudio-test.cpp
g++ -o $# $^ $(LFLAGS)
# linking to foundation will break the test
coreaudio-test.broken: coreaudio-test.cpp
g++ -o $# $^ $(LFLAGS) -framework Foundation
Any thoughts on this bizarre behavior? (btw, I've also posted this question on the CoreAudio list.)

The CoreAudio List answered my question. We need to tell CoreAudio to allocate its own event-dispatching thread:
CFRunLoopRef theRunLoop = NULL;
AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
AudioObjectSetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
I suspect what's happening is that when the program is linked to Foundation, CoreAudio assumes the main thread is acting as an event dispatcher loop (very common since Objective-C is usually used for GUI programs). When not linking against Foundation, I guess it figures that it needs to allocate its own event thread.

Related behavior, which is like 9 years ago someone reported:
http://lists.apple.com/archives/coreaudio-api/2001/May/msg00021.html

Related

Error in compilation : undefined reference to 'clGetPlatformInfo#20'

I'm such a newby concerning OpenCL programming, and I want to run a simple program which is in "OpenCL Parallel Programming Development Cookbook".
In fact, I want to query OpenCl platforms by this simple prog:
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
void displayPlatformInfo(cl_platform_id id,
cl_platform_info param_name,
const char* paramNameAsStr) {
cl_int error = 0;
size_t paramSize = 0;
error = clGetPlatformInfo( id, param_name, 0, NULL, &paramSize );
char* moreInfo = (char*)malloc( sizeof(char) * paramSize);
error = clGetPlatformInfo( id, param_name, paramSize,moreInfo, NULL );
if (error != CL_SUCCESS ) {
perror("Unable to find any OpenCL platform information");
return;
}
printf("%s: %s\n", paramNameAsStr, moreInfo);
}
int main() {
/* OpenCL 1.2 data structures */
cl_platform_id* platforms;
/* OpenCL 1.1 scalar data types */
cl_uint numOfPlatforms;
cl_int error;
/*
Get the number of platforms
Remember that for each vendor's SDK installed on the
Computer, the number of available platform also
*/
error = clGetPlatformIDs(0, NULL, &numOfPlatforms);
if(error < 0) {
perror("Unable to find any OpenCL platforms");
exit(1);
}
// Allocate memory for the number of installed platforms.
// alloca(...) occupies some stack space but is
// automatically freed on return
platforms = (cl_platform_id*) malloc(sizeof(cl_platform_id)
* numOfPlatforms);
printf("Number of OpenCL platforms found: %d\n",
numOfPlatforms);
// We invoke the API 'clPlatformInfo' twice for each
// parameter we're trying to extract
// and we use the return value to create temporary data
// structures (on the stack) to store
// the returned information on the second invocation.
for(cl_uint i = 0; i < numOfPlatforms; ++i) {
displayPlatformInfo( platforms[i],
CL_PLATFORM_PROFILE,
"CL_PLATFORM_PROFILE" );
displayPlatformInfo( platforms[i],
CL_PLATFORM_VERSION,
"CL_PLATFORM_VERSION" );
displayPlatformInfo( platforms[i],
CL_PLATFORM_NAME,
"CL_PLATFORM_NAME" );
displayPlatformInfo( platforms[i],
CL_PLATFORM_VENDOR,
"CL_PLATFORM_VENDOR" );
displayPlatformInfo( platforms[i],
CL_PLATFORM_EXTENSIONS,
"CL_PLATFORM_EXTENSIONS" );
}
return 0;
}
I'm on Qt Creator, and my pc's config concerning video is : NVIDIA GEFORCE GT 635M & Intel(R) HD Graphics 4000 under Windows 8.1
My .pro file is :
SOURCES += \
main.cpp
QMAKE_CXXFLAGS += -std=c++0x
INCLUDEPATH += \
$$quote(C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v6.5/include)
LIBS += \
$$quote(C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v6.5/lib/x64/OpenCL.lib)
Because of spaces in file path. So, my question is : Why, when i'm compiling my project, does the problem "undefined reference to clGetPlatformInfo#20'" appear? There's 2 others errors (one which exactly the same, the other is "undefined reference toclGetPlatformIDs#12'")
I search on the web for a lot of days and I can't find the answer (these prob has answer but on Linux or on Mac..)
Thanks in advance !
Mathieu
It looks like you are trying to build 32-bit application, while linking with 64-bit version of OpenCL.lib:
C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v6.5/lib/x64/OpenCL.lib
So, either build application in 64-bit mode, or fix the path to point to 32-bit version of OpenCL.lib.

Xcode Audiocomponent Symbols not found and somehow cant use methods

im new to coding in c++, I only programmed in php and Java but I want to learn something more.
It may be not the best to start with Audio things but I already know how programming works.
But, I thought to test, get a bit of code from the Apple website and look what happens.
I pasted the beginning of the Code in my Project and got errors. And I dont really know what they mean and searching didnt give me any results.
Thats the code:
#include <iostream>
#include <CoreAudio/CoreAudio.h>
#include <AudioToolbox/AudioToolbox.h>
#include <AudioUnit/AudioUnit.h>
int main(int argc, const char * argv[]) {
// insert code here...
AudioComponent comp;
AudioComponentDescription desc;
AudioComponentInstance auHAL;
//There are several different types of Audio Units.
//Some audio units serve as Outputs, Mixers, or DSP
//units. See AUComponent.h for listing
desc.componentType = kAudioUnitType_Output;
//Every Component has a subType, which will give a clearer picture
//of what this components function will be.
desc.componentSubType = kAudioUnitSubType_HALOutput;
//all Audio Units in AUComponent.h must use
//"kAudioUnitManufacturer_Apple" as the Manufacturer
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
//Finds a component that meets the desc spec's
comp = AudioComponentFindNext(NULL, & desc);
if (comp == NULL) exit(-1);
//gains access to the services provided by the component
AudioComponentInstanceNew(comp, & auHAL);
return 0;
}
and those are the errors i get:
Undefined symbols for architecture x86_64:
"_AudioComponentFindNext", referenced from:
_main in main.o
"_AudioComponentInstanceNew", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
thanks for helping me out!
You'll need to add the AudioUnit, CoreAudio and AudioToolbox frameworks to your project. See this answer for help on how to do that.
You are definitely jumping in the deep end if this is your first experience with C++. Good luck!

What periodic event and source (X server generated?) is this GTK app catching every second or so?

The following consists of just a button that when clicked can produce output on the console. (The output is just the value of a local loop counter and a global variable.)
EDIT: The point is the code is to investigate how gtk_main_interation() works; so I do not want to wrap that call around a gtk_events_pending() loop. The code is purely pedagogical in nature.
The strange part of the code is that instead the "clicked" event handler there's a loop that calls gtk_main_iteration(). gtk_main_iteration is supposed to block if there are no events pending. Yet playing around with this little app shows that the GTK main loop is catching some event every second or so even if nothing is happening. To see this, try just clicking and releasing the button and then letting go of the mouse (without moving the cursor at all).
Presumably this event is being generated by the X server (or the GTK main loop) as some sort of timing thing. I don't know what this event is called and google searches are failing me.
#include <gtk/gtk.h>
#include <glib.h>
#include <gmp.h>
#include <unistd.h>
#define UNUSED(x) (void)(x)
typedef struct _Data {
GtkWidget *window1,
*button1;
} Data;
int g=0;
void on_button1_clicked(GtkWidget *widget, Data *data) {
int l=0;
UNUSED(widget);
UNUSED(data);
for(l=0;l<10;++l) {
gtk_main_iteration();
printf("l=%d g=%d|",l,g++);
fflush(stdout);
}
printf("\n\n");
}
int main (int argc, char *argv[]) {
Data *data;
gtk_init(&argc, &argv);
data=g_slice_new0(Data);
/* add widgets and objects to our structure */
data->window1=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(data->window1),250,250);
data->button1=gtk_button_new_with_label("Start");
gtk_container_add(GTK_CONTAINER(data->window1),GTK_WIDGET(data->button1));
gtk_signal_connect(GTK_OBJECT(data->window1), "delete-event",
gtk_main_quit, NULL);
gtk_signal_connect(GTK_OBJECT(data->button1), "clicked",
G_CALLBACK(on_button1_clicked), NULL);
gtk_widget_show_all(GTK_WIDGET(data->window1));
gtk_main();
/* Don't forget to free the memory! */
g_slice_free(Data, data);
return 0;
}
I'm compiling with
gcc -Wall -Wextra -Wconversion -pedantic `pkg-config --cflags --libs gtk+-2.0` events.c -o events
this code may be pedagogical, but it's utterly broken, and not even remotely idiomatic:
the GtkButton::Clicked signal is not emitted by the windowing system: it's completely synthesized by GtkButton itself; it depends on receiving a button-release-event after a button-press-event while the pointer is still within the GtkButton that originated the press; X11 has no concept of "clicked" (within or without these semantics).
this example demonstrates basically nothing about the event stream that you may or may not get under X11. if you want to see the event stream, you can compile GTK+ with debugging messages enabled (./configure --enable-debug=yes) and set the GDK_DEBUG environment variable before running an application. GTK+ will print the details of each X event that it receives, including the event type.

Dereferencing void* warnings on Xcode

I'm aware of this SO question and this SO question. The element
of novelty in this one is in its focus on Xcode, and in its use of
square brackets to dereference a pointer to void.
The following program compiles with no warning in Xcode 4.5.2, compiles
with a warning on GCC 4.2 and, even though I don't have Visual Studio
right now, I remember that it would consider this a compiler
error, and MSDN and Internet agree.
#include <stdio.h>
int main(int argc, const char * argv[])
{
int x = 24;
void *xPtr = &x;
int *xPtr2 = (int *)&xPtr[1];
printf("%p %p\n", xPtr, xPtr2);
}
If I change the third line of the body of main to:
int *xPtr2 = (int *)(xPtr + 1);
It compiles with no warnings on both GCC and Xcode.
I would like to know how can I turn this silence into warnings or errors, on
GDB and especially Xcode/LLVM, including the fact that function main is int but
does not explicitly return any value (By the way I think -Wall does
the trick on GDB).
that isnt wrong at all...
the compiler doesnt know how big the pointer is ... a void[] ~~ void*
thats why char* used as strings need to be \0-terminated
you cannot turn on a warning for that as it isnt possible to determine a 'size of memory pointer to by a pointer' at compile time
void *v = nil;
*v[1] = 0 //invalid
void *v = malloc(sizeof(int)*2);
*v[1] = 0 //valid
*note typed inline on SO -- sorry for any non-working code

How to find the address & length of a C++ function at runtime (MinGW)

As this is my first post to stackoverflow I want to thank you all for your valuable posts that helped me a lot in the past.
I use MinGW (gcc 4.4.0) on Windows-7(64) - more specifically I use Nokia Qt + MinGW but Qt is not involved in my Question.
I need to find the address and -more important- the length of specific functions of my application at runtime, in order to encode/decode these functions and implement a software protection system.
I already found a solution on how to compute the length of a function, by assuming that static functions placed one after each other in a source-file, it is logical to be also sequentially placed in the compiled object file and subsequently in memory.
Unfortunately this is true only if the whole CPP file is compiled with option: "g++ -O0" (optimization level = 0).
If I compile it with "g++ -O2" (which is the default for my project) the compiler seems to relocate some of the functions and as a result the computed function length seems to be both incorrect and negative(!).
This is happening even if I put a "#pragma GCC optimize 0" line in the source file,
which is supposed to be the equivalent of a "g++ -O0" command line option.
I suppose that "g++ -O2" instructs the compiler to perform some global file-level optimization (some function relocation?) which is not avoided by using the #pragma directive.
Do you have any idea how to prevent this, without having to compile the whole file with -O0 option?
OR: Do you know of any other method to find the length of a function at runtime?
I prepare a small example for you, and the results with different compilation options, to highlight the case.
The Source:
// ===================================================================
// test.cpp
//
// Intention: To find the addr and length of a function at runtime
// Problem: The application output is correct when compiled with: "g++ -O0"
// but it's erroneous when compiled with "g++ -O2"
// (although a directive "#pragma GCC optimize 0" is present)
// ===================================================================
#include <stdio.h>
#include <math.h>
#pragma GCC optimize 0
static int test_01(int p1)
{
putchar('a');
putchar('\n');
return 1;
}
static int test_02(int p1)
{
putchar('b');
putchar('b');
putchar('\n');
return 2;
}
static int test_03(int p1)
{
putchar('c');
putchar('\n');
return 3;
}
static int test_04(int p1)
{
putchar('d');
putchar('\n');
return 4;
}
// Print a HexDump of a specific address and length
void HexDump(void *startAddr, long len)
{
unsigned char *buf = (unsigned char *)startAddr;
printf("addr:%ld, len:%ld\n", (long )startAddr, len);
len = (long )fabs(len);
while (len)
{
printf("%02x.", *buf);
buf++;
len--;
}
printf("\n");
}
int main(int argc, char *argv[])
{
printf("======================\n");
long fun_len = (long )test_02 - (long )test_01;
HexDump((void *)test_01, fun_len);
printf("======================\n");
fun_len = (long )test_03 - (long )test_02;
HexDump((void *)test_02, fun_len);
printf("======================\n");
fun_len = (long )test_04 - (long )test_03;
HexDump((void *)test_03, fun_len);
printf("Test End\n");
getchar();
// Just a trick to block optimizer from eliminating test_xx() functions as unused
if (argc > 1)
{
test_01(1);
test_02(2);
test_03(3);
test_04(4);
}
}
The (correct) Output when compiled with "g++ -O0":
[note the 'c3' byte (= assembly 'ret') at the end of all functions]
======================
addr:4199344, len:37
55.89.e5.83.ec.18.c7.04.24.61.00.00.00.e8.4e.62.00.00.c7.04.24.0a.00.00.00.e8.42
.62.00.00.b8.01.00.00.00.c9.c3.
======================
addr:4199381, len:49
55.89.e5.83.ec.18.c7.04.24.62.00.00.00.e8.29.62.00.00.c7.04.24.62.00.00.00.e8.1d
.62.00.00.c7.04.24.0a.00.00.00.e8.11.62.00.00.b8.02.00.00.00.c9.c3.
======================
addr:4199430, len:37
55.89.e5.83.ec.18.c7.04.24.63.00.00.00.e8.f8.61.00.00.c7.04.24.0a.00.00.00.e8.ec
.61.00.00.b8.03.00.00.00.c9.c3.
Test End
The erroneous Output when compiled with "g++ -O2":
(a) function test_01 addr & len seem correct
(b) functions test_02, test_03 have negative lengths,
and fun. test_02 length is also incorrect.
======================
addr:4199416, len:36
83.ec.1c.c7.04.24.61.00.00.00.e8.c5.61.00.00.c7.04.24.0a.00.00.00.e8.b9.61.00.00
.b8.01.00.00.00.83.c4.1c.c3.
======================
addr:4199452, len:-72
83.ec.1c.c7.04.24.62.00.00.00.e8.a1.61.00.00.c7.04.24.62.00.00.00.e8.95.61.00.00
.c7.04.24.0a.00.00.00.e8.89.61.00.00.b8.02.00.00.00.83.c4.1c.c3.57.56.53.83.ec.2
0.8b.5c.24.34.8b.7c.24.30.89.5c.24.08.89.7c.24.04.c7.04.
======================
addr:4199380, len:-36
83.ec.1c.c7.04.24.63.00.00.00.e8.e9.61.00.00.c7.04.24.0a.00.00.00.e8.dd.61.00.00
.b8.03.00.00.00.83.c4.1c.c3.
Test End
This is happening even if I put a "#pragma GCC optimize 0" line in the source file, which is supposed to be the equivalent of a "g++ -O0" command line option.
I don't believe this is true: it is supposed to be the equivalent of attaching __attribute__((optimize(0))) to subsequently defined functions, which causes those functions to be compiled with a different optimisation level. But this does not affect what goes on at the top level, whereas the command line option does.
If you really must do horrible things that rely on top level ordering, try the -fno-toplevel-reorder option. And I suspect that it would be a good idea to add __attribute__((noinline)) to the functions in question as well.

Resources