本文整理匯總了C++中CFRunLoopGetCurrent函數的典型用法代碼示例。如果您正苦於以下問題:C++ CFRunLoopGetCurrent函數的具體用法?C++ CFRunLoopGetCurrent怎麽用?C++ CFRunLoopGetCurrent使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了CFRunLoopGetCurrent函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C++代碼示例。
示例1: cleanup
void Audio_Queue::init()
{
OSStatus err = noErr;
cleanup();
// create the audio queue
err = AudioQueueNewOutput(&m_streamDesc, audioQueueOutputCallback, this, CFRunLoopGetCurrent(), NULL, 0, &m_outAQ);
if (err) {
AQ_TRACE("%s: error in AudioQueueNewOutput\n", __PRETTY_FUNCTION__);
m_lastError = err;
if (m_delegate) {
m_delegate->audioQueueInitializationFailed();
}
return;
}
Stream_Configuration *configuration = Stream_Configuration::configuration();
// allocate audio queue buffers
for (unsigned int i = 0; i < configuration->bufferCount; ++i) {
err = AudioQueueAllocateBuffer(m_outAQ, configuration->bufferSize, &m_audioQueueBuffer[i]);
if (err) {
/* If allocating the buffers failed, everything else will fail, too.
* Dispose the queue so that we can later on detect that this
* queue in fact has not been initialized.
*/
AQ_TRACE("%s: error in AudioQueueAllocateBuffer\n", __PRETTY_FUNCTION__);
(void)AudioQueueDispose(m_outAQ, true);
m_outAQ = 0;
m_lastError = err;
if (m_delegate) {
m_delegate->audioQueueInitializationFailed();
}
return;
}
}
// listen for kAudioQueueProperty_IsRunning
err = AudioQueueAddPropertyListener(m_outAQ, kAudioQueueProperty_IsRunning, audioQueueIsRunningCallback, this);
if (err) {
AQ_TRACE("%s: error in AudioQueueAddPropertyListener\n", __PRETTY_FUNCTION__);
m_lastError = err;
return;
}
if (configuration->enableTimeAndPitchConversion) {
UInt32 enableTimePitchConversion = 1;
err = AudioQueueSetProperty (m_outAQ, kAudioQueueProperty_EnableTimePitch, &enableTimePitchConversion, sizeof(enableTimePitchConversion));
if (err != noErr) {
AQ_TRACE("Failed to enable time and pitch conversion. Play rate setting will fail\n");
}
}
if (m_initialOutputVolume != 1.0) {
setVolume(m_initialOutputVolume);
}
}
示例2: btpad_packet_handler
void btpad_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
{
bd_addr_t event_addr;
if (packet_type == HCI_EVENT_PACKET)
{
switch (packet[0])
{
case BTSTACK_EVENT_STATE:
{
RARCH_LOG("BTstack: HCI State %d\n", packet[2]);
switch (packet[2])
{
case HCI_STATE_WORKING:
btpad_queue_reset();
btpad_queue_hci_read_bd_addr();
bt_send_cmd_ptr(l2cap_register_service_ptr, PSM_HID_CONTROL, 672); // TODO: Where did I get 672 for mtu?
bt_send_cmd_ptr(l2cap_register_service_ptr, PSM_HID_INTERRUPT, 672);
btpad_queue_hci_inquiry(HCI_INQUIRY_LAP, 3, 1);
btpad_queue_run(1);
break;
case HCI_STATE_HALTING:
btpad_close_all_connections();
CFRunLoopStop(CFRunLoopGetCurrent());
break;
}
}
break;
case HCI_EVENT_COMMAND_STATUS:
btpad_queue_run(packet[3]);
break;
case HCI_EVENT_COMMAND_COMPLETE:
{
btpad_queue_run(packet[2]);
if (COMMAND_COMPLETE_EVENT(packet, (*hci_read_bd_addr_ptr)))
{
bt_flip_addr_ptr(event_addr, &packet[6]);
if (!packet[5])
RARCH_LOG("BTpad: Local address is %s\n", bd_addr_to_str_ptr(event_addr));
else
RARCH_LOG("BTpad: Failed to get local address (Status: %02X)\n", packet[5]);
}
}
break;
case HCI_EVENT_INQUIRY_RESULT:
{
if (packet[2])
{
bt_flip_addr_ptr(event_addr, &packet[3]);
struct apple_pad_connection* connection = (struct apple_pad_connection*)btpad_find_empty_connection();
if (connection)
{
RARCH_LOG("BTpad: Inquiry found device\n");
memset(connection, 0, sizeof(struct apple_pad_connection));
memcpy(connection->address, event_addr, sizeof(bd_addr_t));
connection->has_address = true;
connection->state = BTPAD_CONNECTING;
bt_send_cmd_ptr(l2cap_create_channel_ptr, connection->address, PSM_HID_CONTROL);
bt_send_cmd_ptr(l2cap_create_channel_ptr, connection->address, PSM_HID_INTERRUPT);
}
}
}
break;
case HCI_EVENT_INQUIRY_COMPLETE:
{
// This must be turned off during gameplay as it causes a ton of lag
inquiry_running = !inquiry_off;
if (inquiry_running)
btpad_queue_hci_inquiry(HCI_INQUIRY_LAP, 3, 1);
}
break;
case L2CAP_EVENT_CHANNEL_OPENED:
{
bt_flip_addr_ptr(event_addr, &packet[3]);
const uint16_t handle = READ_BT_16(packet, 9);
const uint16_t psm = READ_BT_16(packet, 11);
const uint16_t channel_id = READ_BT_16(packet, 13);
struct apple_pad_connection* connection = (struct apple_pad_connection*)btpad_find_connection_for(handle, event_addr);
if (!packet[2])
{
if (!connection)
{
RARCH_LOG("BTpad: Got L2CAP 'Channel Opened' event for unrecognized device\n");
//.........這裏部分代碼省略.........
示例3: ReceiveReports
PsychError ReceiveReports(int deviceIndex)
{
long error=0;
pRecDevice device;
IOHIDDeviceInterface122** interface=NULL;
int reason; // kCFRunLoopRunFinished, kCFRunLoopRunStopped, kCFRunLoopRunTimedOut, kCFRunLoopRunHandledSource
PsychHIDVerifyInit();
if(deviceIndex < 0 || deviceIndex >= MAXDEVICEINDEXS) PrintfExit("Sorry. Can't cope with deviceNumber %d (more than %d). Please tell [email protected]",deviceIndex,(int)MAXDEVICEINDEXS-1);
// Allocate report buffers if needed:
PsychHIDAllocateReports(deviceIndex);
CountReports("ReceiveReports beginning.");
if (freeReportsPtr[deviceIndex] == NULL) PrintfExit("No free reports.");
device=PsychHIDGetDeviceRecordPtrFromIndex(deviceIndex);
if(!HIDIsValidDevice(device))PrintfExit("PsychHID: Invalid device.\n");
interface = PsychHIDGetDeviceInterfacePtrFromIndex(deviceIndex);
if(interface==NULL)PrintfExit("PsychHID: No interface for device.\n");
CheckRunLoopSource(deviceIndex,"ReceiveReports",__LINE__);
if(!ready[deviceIndex]){
// setInterruptReportHandlerCallback
static unsigned char buffer[MAXREPORTSIZE];
psych_uint32 bufferSize=MAXREPORTSIZE;
psych_bool createSource;
createSource=(source[deviceIndex]==NULL);
if(createSource){
if(optionsPrintCrashers && createSource)printf("%d: createAsyncEventSource\n",deviceIndex);
error=(*interface)->createAsyncEventSource(interface,&(source[deviceIndex]));
if(error)PrintfExit("ReceiveReports - createAsyncEventSource error 0x%lx.",error);
if(0 && optionsPrintCrashers && createSource)
printf("%d: source %4.4lx validity %d, CFRunLoopContainsSource is %d.\n",deviceIndex,(unsigned long)source[deviceIndex]
,CFRunLoopSourceIsValid(source[deviceIndex])
,CFRunLoopContainsSource(CFRunLoopGetCurrent(),source[deviceIndex],myRunLoopMode));
}
if(optionsPrintCrashers && createSource)printf("%d: getAsyncEventSource\n",deviceIndex);
CheckRunLoopSource(deviceIndex,"ReceiveReports",__LINE__);
if(optionsPrintCrashers && createSource)printf("%d: CFRunLoopAddSource\n",deviceIndex);
CFRunLoopAddSource(CFRunLoopGetCurrent(),source[deviceIndex],myRunLoopMode);
if(0 && optionsPrintCrashers && createSource)printf("%d: source %4.4lx validity %d, CFRunLoopContainsSource is %d.\n",deviceIndex,(unsigned long)source[deviceIndex]
,CFRunLoopSourceIsValid(source[deviceIndex])
,CFRunLoopContainsSource(CFRunLoopGetCurrent(),source[deviceIndex],myRunLoopMode));
ready[deviceIndex]=1;
CheckRunLoopSource(deviceIndex,"ReceiveReports",__LINE__);
if(optionsPrintCrashers && createSource)printf("%d: setInterruptReportHandlerCallback\n",deviceIndex);
error=(*interface)->setInterruptReportHandlerCallback(interface,buffer,bufferSize,ReportCallback,buffer,(void *)(long int) deviceIndex);
if(error)PrintfExit("ReceiveReports - setInterruptReportHandlerCallback error 0x%lx.",error);
if(optionsPrintCrashers && createSource)printf("%d: CFRunLoopRunInMode.\n",deviceIndex);
}
//printf("%d: CFRunLoopRunInMode\n",deviceIndex);
reason=CFRunLoopRunInMode(myRunLoopMode,optionsSecs,false);
if(reason!=kCFRunLoopRunTimedOut && reason!=kCFRunLoopRunHandledSource){
char *s;
switch(reason){
case kCFRunLoopRunFinished: s="kCFRunLoopRunFinished"; break;
case kCFRunLoopRunStopped: s="kCFRunLoopRunStopped"; break;
case kCFRunLoopRunTimedOut: s="kCFRunLoopRunTimedOut"; break;
case kCFRunLoopRunHandledSource: s="kCFRunLoopRunHandledSource"; break;
default: s="of unknown reason.";
}
printf("RunLoop ended at %.3f s because %s.\n",CFAbsoluteTimeGetCurrent()-AInScanStart,s);
}
CountReports("ReceiveReports end.");
return error;
}
示例4: SetThreadName
int DeviceManagerThread::Run()
{
SetThreadName("OVR::DeviceManagerThread");
LogText("OVR::DeviceManagerThread - running (ThreadId=0x%p).\n", GetThreadId());
// Store out the run loop ref.
RunLoop = CFRunLoopGetCurrent();
// Create a 'source' to enable us to signal the run loop to process the command queue.
CFRunLoopSourceContext sourceContext;
memset(&sourceContext, 0, sizeof(sourceContext));
sourceContext.version = 0;
sourceContext.info = this;
sourceContext.perform = &staticCommandQueueSourceCallback;
CommandQueueSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0 , &sourceContext);
CFRunLoopAddSource(RunLoop, CommandQueueSource, kCFRunLoopDefaultMode);
// Signal to the parent thread that initialization has finished.
StartupEvent.SetEvent();
ThreadCommand::PopBuffer command;
while(!IsExiting())
{
// PopCommand will reset event on empty queue.
if (PopCommand(&command))
{
command.Execute();
}
else
{
SInt32 exitReason = 0;
do {
UInt32 waitMs = INT_MAX;
// If devices have time-dependent logic registered, get the longest wait
// allowed based on current ticks.
if (!TicksNotifiers.IsEmpty())
{
UInt64 ticksMks = Timer::GetTicks();
UInt32 waitAllowed;
for (UPInt j = 0; j < TicksNotifiers.GetSize(); j++)
{
waitAllowed = (UInt32)(TicksNotifiers[j]->OnTicks(ticksMks) / Timer::MksPerMs);
if (waitAllowed < waitMs)
waitMs = waitAllowed;
}
}
// Enter blocking run loop. We may continue until we timeout in which
// case it's time to service the ticks. Or if commands arrive in the command
// queue then the source callback will call 'CFRunLoopStop' causing this
// to return.
CFTimeInterval blockInterval = 0.001 * (double) waitMs;
exitReason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, blockInterval, false);
if (exitReason == kCFRunLoopRunFinished)
{
// Maybe this will occur during shutdown?
break;
}
else if (exitReason == kCFRunLoopRunStopped )
{
// Commands need processing or we're being shutdown.
break;
}
else if (exitReason == kCFRunLoopRunTimedOut)
{
// Timed out so that we can service our ticks callbacks.
continue;
}
else if (exitReason == kCFRunLoopRunHandledSource)
{
// Should never occur since the last param when we call
// 'CFRunLoopRunInMode' is false.
OVR_ASSERT(false);
break;
}
else
{
OVR_ASSERT_LOG(false, ("CFRunLoopRunInMode returned unexpected code"));
break;
}
}
while(true);
}
}
CFRunLoopRemoveSource(RunLoop, CommandQueueSource, kCFRunLoopDefaultMode);
CFRelease(CommandQueueSource);
LogText("OVR::DeviceManagerThread - exiting (ThreadId=0x%p).\n", GetThreadId());
//.........這裏部分代碼省略.........
示例5: SDL_SYS_JoystickInit
/* Function to scan the system for joysticks.
* Joystick 0 should be the system default joystick.
* This function should return the number of available joysticks, or -1
* on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
IOReturn result = kIOReturnSuccess;
mach_port_t masterPort = 0;
io_iterator_t hidObjectIterator = 0;
CFMutableDictionaryRef hidMatchDictionary = NULL;
io_object_t ioHIDDeviceObject = 0;
io_iterator_t portIterator = 0;
if (gpDeviceList) {
SDL_SetError("Joystick: Device list already inited.");
return -1;
}
result = IOMasterPort(bootstrap_port, &masterPort);
if (kIOReturnSuccess != result) {
SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
return -1;
}
/* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
if (hidMatchDictionary) {
/* Add key for device type (joystick, in this case) to refine the matching dictionary. */
/* NOTE: we now perform this filtering later
UInt32 usagePage = kHIDPage_GenericDesktop;
UInt32 usage = kHIDUsage_GD_Joystick;
CFNumberRef refUsage = NULL, refUsagePage = NULL;
refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
*/
} else {
SDL_SetError
("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
return -1;
}
/*/ Now search I/O Registry for matching devices. */
result =
IOServiceGetMatchingServices(masterPort, hidMatchDictionary,
&hidObjectIterator);
/* Check for errors */
if (kIOReturnSuccess != result) {
SDL_SetError("Joystick: Couldn't create a HID object iterator.");
return -1;
}
if (!hidObjectIterator) { /* there are no joysticks */
gpDeviceList = NULL;
return 0;
}
/* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
/* build flat linked list of devices from device iterator */
gpDeviceList = NULL;
while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
AddDeviceHelper( ioHIDDeviceObject );
}
result = IOObjectRelease(hidObjectIterator); /* release the iterator */
/* now connect notification for new devices */
notificationPort = IONotificationPortCreate(masterPort);
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notificationPort),
kCFRunLoopDefaultMode);
// Register for notifications when a serial port is added to the system
result = IOServiceAddMatchingNotification(notificationPort,
kIOFirstMatchNotification,
hidMatchDictionary,
JoystickDeviceWasAddedCallback,
NULL,
&portIterator);
while (IOIteratorNext(portIterator)) {}; // Run out the iterator or notifications won't start (you can also use it to iterate the available devices).
return SDL_SYS_NumJoysticks();
}
示例6: CFDictionaryCreate
//.........這裏部分代碼省略.........
CGEventMaskBit(kCGEventRightMouseUp) |
CGEventMaskBit(kCGEventRightMouseDragged) |
CGEventMaskBit(kCGEventOtherMouseDown) |
CGEventMaskBit(kCGEventOtherMouseUp) |
CGEventMaskBit(kCGEventOtherMouseDragged) |
CGEventMaskBit(kCGEventMouseMoved) |
CGEventMaskBit(kCGEventScrollWheel);
#ifdef USE_DEBUG
event_mask |= CGEventMaskBit(kCGEventNull);
#endif
CFMachPortRef event_port = CGEventTapCreate(
kCGSessionEventTap, // kCGHIDEventTap
kCGHeadInsertEventTap, // kCGTailAppendEventTap
kCGEventTapOptionListenOnly, // kCGEventTapOptionDefault See Bug #22
event_mask,
hook_event_proc,
NULL
);
if (event_port != NULL) {
logger(LOG_LEVEL_DEBUG, "%s [%u]: CGEventTapCreate Successful.\n",
__FUNCTION__, __LINE__);
event_source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, event_port, 0);
if (event_source != NULL) {
logger(LOG_LEVEL_DEBUG, "%s [%u]: CFMachPortCreateRunLoopSource successful.\n",
__FUNCTION__, __LINE__);
event_loop = CFRunLoopGetCurrent();
if (event_loop != NULL) {
logger(LOG_LEVEL_DEBUG, "%s [%u]: CFRunLoopGetCurrent successful.\n",
__FUNCTION__, __LINE__);
// Initialize Native Input Functions.
load_input_helper();
// Create run loop observers.
CFRunLoopObserverRef observer = CFRunLoopObserverCreate(
kCFAllocatorDefault,
kCFRunLoopEntry | kCFRunLoopExit, //kCFRunLoopAllActivities,
true,
0,
hook_status_proc,
NULL
);
if (observer != NULL) {
// Set the exit status.
*status = UIOHOOK_SUCCESS;
start_message_port_runloop();
CFRunLoopAddSource(event_loop, event_source, kCFRunLoopDefaultMode);
CFRunLoopAddObserver(event_loop, observer, kCFRunLoopDefaultMode);
CFRunLoopRun();
// Lock back up until we are done processing the exit.
CFRunLoopRemoveObserver(event_loop, observer, kCFRunLoopDefaultMode);
CFRunLoopRemoveSource(event_loop, event_source, kCFRunLoopDefaultMode);
示例7: DoAQOfflineRender
void DoAQOfflineRender(CFURLRef sourceURL, CFURLRef destinationURL)
{
// main audio queue code
try {
AQTestInfo myInfo;
myInfo.mDone = false;
myInfo.mFlushed = false;
myInfo.mCurrentPacket = 0;
// get the source file
XThrowIfError(AudioFileOpenURL(sourceURL, 0x01/*fsRdPerm*/, 0/*inFileTypeHint*/, &myInfo.mAudioFile), "AudioFileOpen failed");
UInt32 size = sizeof(myInfo.mDataFormat);
XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyDataFormat, &size, &myInfo.mDataFormat), "couldn't get file's data format");
printf ("File format: "); myInfo.mDataFormat.Print();
// create a new audio queue output
XThrowIfError(AudioQueueNewOutput(&myInfo.mDataFormat, // The data format of the audio to play. For linear PCM, only interleaved formats are supported.
AQTestBufferCallback, // A callback function to use with the playback audio queue.
&myInfo, // A custom data structure for use with the callback function.
CFRunLoopGetCurrent(), // The event loop on which the callback function pointed to by the inCallbackProc parameter is to be called.
// If you specify NULL, the callback is invoked on one of the audio queue’s internal threads.
kCFRunLoopCommonModes, // The run loop mode in which to invoke the callback function specified in the inCallbackProc parameter.
0, // Reserved for future use. Must be 0.
&myInfo.mQueue), // On output, the newly created playback audio queue object.
"AudioQueueNew failed");
UInt32 bufferByteSize;
// we need to calculate how many packets we read at a time and how big a buffer we need
// we base this on the size of the packets in the file and an approximate duration for each buffer
{
bool isFormatVBR = (myInfo.mDataFormat.mBytesPerPacket == 0 || myInfo.mDataFormat.mFramesPerPacket == 0);
// first check to see what the max size of a packet is - if it is bigger
// than our allocation default size, that needs to become larger
UInt32 maxPacketSize;
size = sizeof(maxPacketSize);
XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize), "couldn't get file's max packet size");
// adjust buffer size to represent about a second of audio based on this format
CalculateBytesForTime(myInfo.mDataFormat, maxPacketSize, 1.0/*seconds*/, &bufferByteSize, &myInfo.mNumPacketsToRead);
if (isFormatVBR) {
myInfo.mPacketDescs = new AudioStreamPacketDescription [myInfo.mNumPacketsToRead];
} else {
myInfo.mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM)
}
printf ("Buffer Byte Size: %d, Num Packets to Read: %d\n", (int)bufferByteSize, (int)myInfo.mNumPacketsToRead);
}
// if the file has a magic cookie, we should get it and set it on the AQ
size = sizeof(UInt32);
OSStatus result = AudioFileGetPropertyInfo (myInfo.mAudioFile, kAudioFilePropertyMagicCookieData, &size, NULL);
if (!result && size) {
char* cookie = new char [size];
XThrowIfError (AudioFileGetProperty (myInfo.mAudioFile, kAudioFilePropertyMagicCookieData, &size, cookie), "get cookie from file");
XThrowIfError (AudioQueueSetProperty(myInfo.mQueue, kAudioQueueProperty_MagicCookie, cookie, size), "set cookie on queue");
delete [] cookie;
}
// channel layout?
OSStatus err = AudioFileGetPropertyInfo(myInfo.mAudioFile, kAudioFilePropertyChannelLayout, &size, NULL);
AudioChannelLayout *acl = NULL;
if (err == noErr && size > 0) {
acl = (AudioChannelLayout *)malloc(size);
XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyChannelLayout, &size, acl), "get audio file's channel layout");
XThrowIfError(AudioQueueSetProperty(myInfo.mQueue, kAudioQueueProperty_ChannelLayout, acl, size), "set channel layout on queue");
}
//allocate the input read buffer
XThrowIfError(AudioQueueAllocateBuffer(myInfo.mQueue, bufferByteSize, &myInfo.mBuffer), "AudioQueueAllocateBuffer");
// prepare a canonical interleaved capture format
CAStreamBasicDescription captureFormat;
captureFormat.mSampleRate = myInfo.mDataFormat.mSampleRate;
captureFormat.SetAUCanonical(myInfo.mDataFormat.mChannelsPerFrame, true); // interleaved
XThrowIfError(AudioQueueSetOfflineRenderFormat(myInfo.mQueue, &captureFormat, acl), "set offline render format");
ExtAudioFileRef captureFile;
// prepare a 16-bit int file format, sample channel count and sample rate
CAStreamBasicDescription dstFormat;
dstFormat.mSampleRate = myInfo.mDataFormat.mSampleRate;
dstFormat.mChannelsPerFrame = myInfo.mDataFormat.mChannelsPerFrame;
dstFormat.mFormatID = kAudioFormatLinearPCM;
dstFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; // little-endian
dstFormat.mBitsPerChannel = 16;
dstFormat.mBytesPerPacket = dstFormat.mBytesPerFrame = 2 * dstFormat.mChannelsPerFrame;
dstFormat.mFramesPerPacket = 1;
// create the capture file
XThrowIfError(ExtAudioFileCreateWithURL(destinationURL, kAudioFileCAFType, &dstFormat, acl, kAudioFileFlags_EraseFile, &captureFile), "ExtAudioFileCreateWithURL");
// set the capture file's client format to be the canonical format from the queue
XThrowIfError(ExtAudioFileSetProperty(captureFile, kExtAudioFileProperty_ClientDataFormat, sizeof(AudioStreamBasicDescription), &captureFormat), "set ExtAudioFile client format");
//.........這裏部分代碼省略.........
示例8: fse_pipe_callback
static void fse_pipe_callback(CFFileDescriptorRef, CFOptionFlags, void*) {
w_log(W_LOG_DBG, "pipe signalled\n");
CFRunLoopStop(CFRunLoopGetCurrent());
}
示例9: fse_stream_make
//.........這裏部分代碼省略.........
cpath = CFStringCreateWithBytes(
nullptr,
(const UInt8*)root->root_path.data(),
root->root_path.size(),
kCFStringEncodingUTF8,
false);
if (!cpath) {
failure_reason =
w_string("CFStringCreateWithBytes failed", W_STRING_UNICODE);
goto fail;
}
CFArrayAppendValue(parray, cpath);
latency = root->config.getDouble("fsevents_latency", 0.01),
w_log(
W_LOG_DBG,
"FSEventStreamCreate for path %s with latency %f seconds\n",
root->root_path.c_str(),
latency);
fse_stream->stream = FSEventStreamCreate(
nullptr,
fse_callback,
&ctx,
parray,
since,
latency,
kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagWatchRoot |
kFSEventStreamCreateFlagFileEvents);
if (!fse_stream->stream) {
failure_reason = w_string("FSEventStreamCreate failed", W_STRING_UNICODE);
goto fail;
}
FSEventStreamScheduleWithRunLoop(fse_stream->stream,
CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
#ifdef HAVE_FSEVENTSTREAMSETEXCLUSIONPATHS
if (!root->ignore.dirs_vec.empty() &&
root->config.getBool("_use_fsevents_exclusions", true)) {
CFMutableArrayRef ignarray;
size_t i, nitems = std::min(root->ignore.dirs_vec.size(), MAX_EXCLUSIONS);
ignarray = CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
if (!ignarray) {
failure_reason =
w_string("CFArrayCreateMutable failed", W_STRING_UNICODE);
goto fail;
}
for (i = 0; i < nitems; ++i) {
const auto& path = root->ignore.dirs_vec[i];
CFStringRef ignpath;
ignpath = CFStringCreateWithBytes(
nullptr,
(const UInt8*)path.data(),
path.size(),
kCFStringEncodingUTF8,
false);
if (!ignpath) {
failure_reason =
w_string("CFStringCreateWithBytes failed", W_STRING_UNICODE);
CFRelease(ignarray);
goto fail;
}
CFArrayAppendValue(ignarray, ignpath);
CFRelease(ignpath);
}
if (!FSEventStreamSetExclusionPaths(fse_stream->stream, ignarray)) {
failure_reason =
w_string("FSEventStreamSetExclusionPaths failed", W_STRING_UNICODE);
CFRelease(ignarray);
goto fail;
}
CFRelease(ignarray);
}
#endif
out:
if (parray) {
CFRelease(parray);
}
if (cpath) {
CFRelease(cpath);
}
return fse_stream;
fail:
delete fse_stream;
fse_stream = nullptr;
goto out;
}
示例10: load
void
load(CFBundleRef bundle, Boolean bundleVerbose)
{
CFStringRef key;
CFMutableArrayRef keys = NULL;
CFStringRef pattern;
CFMutableArrayRef patterns = NULL;
CFRunLoopSourceRef rls;
if (bundleVerbose) {
_verbose = TRUE;
}
SCLog(_verbose, LOG_DEBUG, CFSTR("load() called"));
SCLog(_verbose, LOG_DEBUG, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle));
/* initialize a few globals */
curGlobals = CFDictionaryCreateMutable(NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
curConfigFile = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
curDefaults = CFDictionaryCreateMutable(NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
curStartup = CFDictionaryCreateMutable(NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
/* open a "configd" store to allow cache updates */
store = SCDynamicStoreCreate(NULL,
CFSTR("AppleTalk Configuraton plug-in"),
atConfigChangedCallback,
NULL);
if (!store) {
SCLog(TRUE, LOG_ERR, CFSTR("SCDynamicStoreCreate() failed: %s"), SCErrorString(SCError()));
goto error;
}
/* establish notificaiton keys and patterns */
keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
/* ...watch for (global) AppleTalk configuration changes */
key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
kSCDynamicStoreDomainSetup,
kSCEntNetAppleTalk);
CFArrayAppendValue(keys, key);
CFRelease(key);
/* ...watch for (per-service) AppleTalk configuration changes */
pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
kSCDynamicStoreDomainSetup,
kSCCompAnyRegex,
kSCEntNetAppleTalk);
CFArrayAppendValue(patterns, pattern);
CFRelease(pattern);
/* ...watch for network interface link status changes */
pattern = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
kSCDynamicStoreDomainState,
kSCCompAnyRegex,
kSCEntNetLink);
CFArrayAppendValue(patterns, pattern);
CFRelease(pattern);
/* ...watch for (per-interface) AppleTalk configuration changes */
pattern = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
kSCDynamicStoreDomainState,
kSCCompAnyRegex,
kSCEntNetAppleTalk);
CFArrayAppendValue(patterns, pattern);
CFRelease(pattern);
/* ...watch for computer name changes */
key = SCDynamicStoreKeyCreateComputerName(NULL);
CFArrayAppendValue(keys, key);
CFRelease(key);
/* register the keys/patterns */
if (!SCDynamicStoreSetNotificationKeys(store, keys, patterns)) {
SCLog(TRUE, LOG_ERR,
CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s"),
SCErrorString(SCError()));
goto error;
}
rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
if (!rls) {
SCLog(TRUE, LOG_ERR,
CFSTR("SCDynamicStoreCreateRunLoopSource() failed: %s"),
SCErrorString(SCError()));
goto error;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
//.........這裏部分代碼省略.........
示例11: GCActivityCallback
GCActivityCallback::GCActivityCallback(Heap* heap)
: GCActivityCallback(heap->vm(), CFRunLoopGetCurrent())
{
}
示例12: main
int main (int argc, const char * argv[])
// This program finds the first PPP connection service in the
// current network configuration and then connects and
// disconnects that service.
{
int err;
Boolean ok;
CFStringRef serviceToDial;
CFDictionaryRef optionsForDial;
SCNetworkConnectionRef connection;
CallbackParams params;
serviceToDial = NULL;
optionsForDial = NULL;
connection = NULL;
// If we're run without an argument, just print the usage.
err = 0;
if (argc != 1) {
const char *programName;
programName = strrchr(argv[0], '/');
if (programName == NULL) {
programName = argv[0];
} else {
programName += 1;
}
fprintf(stderr, "Usage: %s\n", programName);
err = ECANCELED;
}
// Find the serviceID of the PPP service to dial and the user's
// preferred dialling options. This routine picks up the last
// service dialled using Internet Connect (and the associated
// options) or, if Internet Connect has not been used, returns
// the first PPP service listed in the Network preferences pane.
if (err == 0) {
ok = SCNetworkConnectionCopyUserPreferences(
NULL,
&serviceToDial,
&optionsForDial
);
if ( ! ok ) {
err = SCError();
}
}
// Create a SCNetworkConnectionRef for it.
if (err == 0) {
SCNetworkConnectionContext context;
// Set up the parameters to our callback function.
params.magic = kCallbackParamsMagic;
params.forcePrintStatus = true;
params.lastMinorStatus = kSCNetworkConnectionDisconnected;
params.lastMinorStatus = kSCNetworkConnectionPPPDisconnected;
// Set up the context to reference those parameters.
context.version = 0;
context.info = (void *) ¶ms;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
connection = SCNetworkConnectionCreateWithServiceID(
NULL,
serviceToDial,
MyNetworkConnectionCallBack,
&context
);
if (connection == NULL) {
err = SCError();
}
}
// Schedule our callback with the runloop.
if (err == 0) {
ok = SCNetworkConnectionScheduleWithRunLoop(
connection,
CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode
);
if ( ! ok ) {
err = SCError();
}
}
// Check the status. If we're already connected tell the user.
// If we're not connected, initiate the connection.
if (err == 0) {
err = ECANCELED; // Most cases involve us bailing out,
// so set the error here.
//.........這裏部分代碼省略.........
示例13: MyNetworkConnectionCallBack
static void MyNetworkConnectionCallBack(
SCNetworkConnectionRef connection,
SCNetworkConnectionStatus status,
void *info
)
// Our network connection callback. Called out of the runloop
// when there's a change in the status of the network connection.
// It can be called as part of both a connection attempt and a
// disconnection attempt.
//
// In response to this callback we do two things:
//
// 1. Print the current connection status.
// 2. Once the [dis]connection attempt is resolved (the status
// hits either 'connected' or 'disconnected'), we stop
// the runloop. This has the effect of breaking the "main"
// function out of its called to CFRunLoopRun, after which
// it can examine the results of the connection.
//
// The "info" parameter is a pointer to our per-connection data.
// In this case we use this as a pointer to a CallbackParams
// structure. We use this to track the previous state of the
// connection so that we don't print redundant status changes.
{
CallbackParams * params;
SCNetworkConnectionPPPStatus minorStatus;
time_t now;
struct tm nowLocal;
char nowLocalStr[30];
Boolean printMinorStatus;
assert(connection != NULL);
assert(info != NULL);
params = (CallbackParams *) info;
assert(params->magic = kCallbackParamsMagic);
// Get a string that represents the current time.
(void) time(&now);
(void) localtime_r(&now, &nowLocal);
(void) strftime(nowLocalStr, sizeof(nowLocalStr), "%X", &nowLocal);
// Due to a bug <rdar://problem/3725976>, it's best to get the major status via
// SCNetworkConnectionGetStatus than rely on the value being passed into
// the callback.
status = SCNetworkConnectionGetStatus(connection);
// Get the minor status from the extended status associated with
// the connection.
minorStatus = GetMinorStatus(connection);
// Print any status changes.
printMinorStatus = (params->lastMinorStatus != minorStatus);
if ( (params->forcePrintStatus)
|| (params->lastMajorStatus != status)
) {
fprintf(
stderr,
"%s %s (%ld)\n",
nowLocalStr,
StatusToString(status),
(long) status
);
printMinorStatus = true;
params->forcePrintStatus = false;
}
if (printMinorStatus) {
fprintf(
stderr,
"%s %s (%ld)\n",
nowLocalStr,
MinorStatusToString(minorStatus),
(long) minorStatus
);
}
// If we hit either the connected or disconnected state,
// we signal the runloop to stop so that the main function
// can process the result of the [dis]connection attempt.
if ( ( minorStatus == kSCNetworkConnectionPPPDisconnected )
|| ( minorStatus == kSCNetworkConnectionPPPConnected )
) {
CFRunLoopStop(CFRunLoopGetCurrent());
}
// Record the new status.
params->lastMajorStatus = status;
params->lastMinorStatus = minorStatus;
}
示例14: main
int
main (int argc, const char *argv[])
{
CFURLRef audioFileURLRef;
OSStatus ret;
audioFileURLRef = CFURLCreateWithFileSystemPath (
kCFAllocatorDefault,
/* CFSTR ("../misc/test.wav"), */
CFSTR ("../misc/alin.wav"),
kCFURLPOSIXPathStyle,
FALSE
);
ret = AudioFileOpenURL(
audioFileURLRef,
kAudioFileReadWritePermission,
0,
&myInfo.mAudioFile);
if (ret != noErr) {
printf("fail to open audio file %x\n", ret);
return 1;
}
UInt32 propSize = sizeof(myInfo.mDataFormat);
ret = AudioFileGetProperty(
myInfo.mAudioFile,
kAudioFilePropertyDataFormat,
&propSize,
&myInfo.mDataFormat
);
if (ret != noErr) {
printf("AudioFileGetProperty error code %d\n", ret);
return 1;
}
printf("sample rate: %f\n"
"mFormatID: %u\n"
"mFormatFlags: %u\n"
"mBytesPerPacket: %u\n"
"mChannelsPerFrame: %u\n",
myInfo.mDataFormat.mSampleRate,
myInfo.mDataFormat.mFormatID,
myInfo.mDataFormat.mFormatFlags,
myInfo.mDataFormat.mBytesPerPacket,
myInfo.mDataFormat.mChannelsPerFrame
);
// Instantiate an audio queue object
ret = AudioQueueNewOutput(
&myInfo.mDataFormat,
AQTestBufferCallback,
&myInfo,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes,
0,
&myInfo.mQueue
);
if (ret != noErr) {
printf("AudioQueueNewOutput error code %d\n", ret);
return 1;
}
AudioQueueAddPropertyListener(myInfo.mQueue, kAudioQueueProperty_IsRunning,
AudioEnginePropertyListenerProc, &myInfo);
/* FIXME allocate AudioQueue buffer */
int i;
for (i = 0; i < 3; i++) {
AudioQueueAllocateBuffer(myInfo.mQueue, 441 * 4, &myInfo.mBuffers[i]);
}
AudioQueueStart(myInfo.mQueue, NULL);
printf("Run loop\n");
// create a system sound ID to represent the sound file
/* OSStatus error = AudioServicesCreateSystemSoundID (myURLRef, &mySSID); */
// Register the sound completion callback.
// Again, useful when you need to free memory after playing.
/* AudioServicesAddSystemSoundCompletion ( */
/* mySSID, */
/* NULL, */
/* NULL, */
/* MyCompletionCallback, */
/* (void *) myURLRef */
/* ); */
// Play the sound file.
/* AudioServicesPlaySystemSound (mySSID); */
// Invoke a run loop on the current thread to keep the application
// running long enough for the sound to play; the sound completion
// callback later stops this run loop.
CFRunLoopRun ();
return 0;
}
示例15: FskFSDirectoryChangeNotifierNew
FskErr FskFSDirectoryChangeNotifierNew(const char *path, UInt32 flags, FskDirectoryChangeNotifierCallbackProc callback, void *refCon, FskDirectoryChangeNotifier *dirChangeNotifier)
{
FskErr err = kFskErrNone;
FskFSDirectoryChangeNotifier directoryChangeNotifier;
struct kevent eventToAdd;
int errNum;
CFFileDescriptorContext context = {0, NULL, NULL, NULL, NULL};
CFRunLoopSourceRef rls;
err = FskMemPtrNewClear(sizeof(FskFSDirectoryChangeNotifierRecord), (FskMemPtr *)(&directoryChangeNotifier));
BAIL_IF_ERR(err);
directoryChangeNotifier->base.dispatch.dispatch = &gFSDispatch;
directoryChangeNotifier->callback = callback;
directoryChangeNotifier->refCon = refCon;
directoryChangeNotifier->path = FskStrDoCopy(path);
directoryChangeNotifier->dirFD = -1;
directoryChangeNotifier->kq = -1;
directoryChangeNotifier->dirKQRef = NULL;
directoryChangeNotifier->dirFD = open(path, O_EVTONLY);
if (directoryChangeNotifier->dirFD < 0)
{
BAIL(kFskErrFileNotFound);
}
directoryChangeNotifier->kq = kqueue();
if (directoryChangeNotifier->kq < 0)
{
BAIL(kFskErrOperationFailed);
}
eventToAdd.ident = directoryChangeNotifier->dirFD;
eventToAdd.filter = EVFILT_VNODE;
eventToAdd.flags = EV_ADD | EV_CLEAR;
eventToAdd.fflags = NOTE_WRITE;
eventToAdd.data = 0;
eventToAdd.udata = NULL;
errNum = kevent(directoryChangeNotifier->kq, &eventToAdd, 1, NULL, 0, NULL);
if (errNum != 0)
{
BAIL(kFskErrOperationFailed);
}
context.info = directoryChangeNotifier;
directoryChangeNotifier->dirKQRef = CFFileDescriptorCreate(NULL, directoryChangeNotifier->kq, true, KQCallback, &context);
if (directoryChangeNotifier->dirKQRef == NULL)
{
BAIL(kFskErrOperationFailed);
}
rls = CFFileDescriptorCreateRunLoopSource(NULL, directoryChangeNotifier->dirKQRef, 0);
if (rls == NULL)
{
BAIL(kFskErrOperationFailed);
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
CFRelease(rls);
CFFileDescriptorEnableCallBacks(directoryChangeNotifier->dirKQRef, kCFFileDescriptorReadCallBack);
bail:
if (err)
{
FskFSDirectoryChangeNotifierDispose((FskDirectoryChangeNotifier)directoryChangeNotifier);
directoryChangeNotifier = NULL;
}
*dirChangeNotifier = (FskDirectoryChangeNotifier)directoryChangeNotifier;
return err;
}