static int collect_drive_stats(io_registry_entry_t driver, long *stats) { CFNumberRef number; CFDictionaryRef properties; CFDictionaryRef statistics; long value; kern_return_t status; int i; /* * If the drive goes away, we may not get any properties * for it. So take some defaults. Nb: use memset ?? */ for (i = 0; i < kIDXLast; i++) { stats[i] = 0; } /* retrieve the properties */ status = IORegistryEntryCreateCFProperties(driver, (CFMutableDictionaryRef *)&properties, kCFAllocatorDefault, kNilOptions); if (status != KERN_SUCCESS) { snmp_log(LOG_ERR, "diskio: device has no properties\n"); /* fprintf(stderr, "device has no properties\n"); */ return (1); } /* retrieve statistics from properties */ statistics = (CFDictionaryRef)CFDictionaryGetValue(properties, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (statistics) { /* Now hand me the crystals. */ if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) { CFNumberGetValue(number, kCFNumberSInt32Type, &value); stats[kIDXBytesRead] = value; } if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) { CFNumberGetValue(number, kCFNumberSInt32Type, &value); stats[kIDXBytesWritten] = value; } if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsReadsKey)))) { CFNumberGetValue(number, kCFNumberSInt32Type, &value); stats[kIDXNumReads] = value; } if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsWritesKey)))) { CFNumberGetValue(number, kCFNumberSInt32Type, &value); stats[kIDXNumWrites] = value; } } /* we're done with the properties, release them */ CFRelease(properties); return (0); }
void wxHIDKeyboard::DoBuildCookies(CFArrayRef Array) { //Now go through each possible cookie int i, nUsage; // bool bEOTriggered = false; for (i = 0; i < CFArrayGetCount(Array); ++i) { const void* ref = CFDictionaryGetValue( (CFDictionaryRef)CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementKey) ); if (ref != NULL) { DoBuildCookies((CFArrayRef) ref); } else { // // Get the usage # // CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue((CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsageKey) ), kCFNumberLongType, &nUsage); // // Now translate the usage # into a wx keycode // // // OK, this is strange - basically this kind of strange - // Starting from 0xEO these elements (like shift) appear twice in // the array! The ones at the end are bogus I guess - the funny part // is that besides the fact that the ones at the front have a Unit // and UnitExponent key with a value of 0 and a different cookie value, // there is no discernable difference between the two... // // Will the real shift please stand up? // // Something to spend a support request on, if I had one, LOL. // //if(nUsage == 0xE0) //{ // if(bEOTriggered) // break; // bEOTriggered = true; //} //Instead of that though we now just don't add duplicate keys if (nUsage >= kHIDUsage_KeyboardA && nUsage <= kHIDUsage_KeyboardZ) AddCookie(CFArrayGetValueAtIndex(Array, i), 'A' + (nUsage - kHIDUsage_KeyboardA) ); else if (nUsage >= kHIDUsage_Keyboard1 && nUsage <= kHIDUsage_Keyboard9) AddCookie(CFArrayGetValueAtIndex(Array, i), '1' + (nUsage - kHIDUsage_Keyboard1) ); else if (nUsage >= kHIDUsage_KeyboardF1 && nUsage <= kHIDUsage_KeyboardF12) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_F1 + (nUsage - kHIDUsage_KeyboardF1) ); else if (nUsage >= kHIDUsage_KeyboardF13 && nUsage <= kHIDUsage_KeyboardF24) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_F13 + (nUsage - kHIDUsage_KeyboardF13) ); else if (nUsage >= kHIDUsage_Keypad1 && nUsage <= kHIDUsage_Keypad9) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_NUMPAD1 + (nUsage - kHIDUsage_Keypad1) ); else switch (nUsage) { //0's (wx & ascii go 0-9, but HID goes 1-0) case kHIDUsage_Keyboard0: AddCookie(CFArrayGetValueAtIndex(Array, i), '0'); break; case kHIDUsage_Keypad0: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_NUMPAD0); break; //Basic case kHIDUsage_KeyboardReturnOrEnter: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_RETURN); break; case kHIDUsage_KeyboardEscape: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_ESCAPE); break; case kHIDUsage_KeyboardDeleteOrBackspace: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_BACK); break; case kHIDUsage_KeyboardTab: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_TAB); break; case kHIDUsage_KeyboardSpacebar: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_SPACE); break; case kHIDUsage_KeyboardPageUp: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_PAGEUP); break; case kHIDUsage_KeyboardEnd: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_END); break; case kHIDUsage_KeyboardPageDown: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_PAGEDOWN); break; case kHIDUsage_KeyboardRightArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_RIGHT); break; case kHIDUsage_KeyboardLeftArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_LEFT); break; case kHIDUsage_KeyboardDownArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_DOWN); break; case kHIDUsage_KeyboardUpArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_UP); break; //LEDS case kHIDUsage_KeyboardCapsLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_CAPITAL); break; case kHIDUsage_KeypadNumLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_NUMLOCK); break; case kHIDUsage_KeyboardScrollLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_SCROLL); break; //Menu keys, Shift, other specials case kHIDUsage_KeyboardLeftControl: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_CONTROL); break; case kHIDUsage_KeyboardLeftShift: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_SHIFT); break; case kHIDUsage_KeyboardLeftAlt: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_ALT); break; case kHIDUsage_KeyboardLeftGUI: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_MENU); break; case kHIDUsage_KeyboardRightControl: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RCONTROL); break; case kHIDUsage_KeyboardRightShift: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RSHIFT); break; case kHIDUsage_KeyboardRightAlt: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RALT); break; case kHIDUsage_KeyboardRightGUI: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RMENU); break; //Default default: //not in wx keycodes - do nothing.... break; } //end mightly long switch } //end if the current element is not an array... } //end for loop for Array }//end buildcookies
CFDictionaryRef getProcessInfo(CFStringRef targetCreator, CFStringRef targetName, CFStringRef targetIdentifier) { /* find an applicarion process specified by theSignature(creator type) from runnning process. if target application can be found, get information of the process and return as a result */ CFIndex nKey = 3; CFMutableArrayRef keyList = CFArrayCreateMutable(NULL,nKey,&kCFTypeArrayCallBacks); CFArrayAppendValue(keyList, CFSTR("FileCreator")); CFArrayAppendValue(keyList, CFSTR("CFBundleIdentifier")); CFArrayAppendValue(keyList, CFSTR("CFBundleName")); CFIndex firstKeyIndex; if (targetCreator != NULL) { firstKeyIndex = 0; } else if (targetIdentifier != NULL) { firstKeyIndex = 1; } else { firstKeyIndex = 2; } if (targetCreator == NULL) targetCreator = (CFStringRef)kCFNull; if (targetName == NULL) targetName = (CFStringRef)kCFNull; if (targetIdentifier == NULL) targetIdentifier = (CFStringRef)kCFNull; CFMutableArrayRef valueList = CFArrayCreateMutable(NULL, nKey,&kCFTypeArrayCallBacks); CFArrayAppendValue(valueList, targetCreator); CFArrayAppendValue(valueList, targetIdentifier); CFArrayAppendValue(valueList, targetName); CFStringRef dictKey = CFArrayGetValueAtIndex(keyList, firstKeyIndex); CFArrayRemoveValueAtIndex(keyList, firstKeyIndex); CFStringRef targetValue = CFArrayGetValueAtIndex(valueList, firstKeyIndex); CFArrayRemoveValueAtIndex(valueList, firstKeyIndex); Boolean isFound = false; ProcessSerialNumber psn = {kNoProcess, kNoProcess}; CFDictionaryRef pDict = NULL; CFComparisonResult isSameStr; OSErr err = GetNextProcess(&psn); while( err == noErr) { pDict = ProcessInformationCopyDictionary(&psn, kProcessDictionaryIncludeAllInformationMask); CFStringRef dictValue = CFDictionaryGetValue(pDict, dictKey); if (dictValue != NULL) { isSameStr = CFStringCompare(dictValue,targetValue,0); if (isSameStr == kCFCompareEqualTo){ isFound = true; for (CFIndex i=0; i < 2; i++) { CFStringRef secondValue = CFArrayGetValueAtIndex(valueList,i); if (secondValue != (CFStringRef)kCFNull) { CFStringRef nextKey = CFArrayGetValueAtIndex(keyList, i); dictValue = CFDictionaryGetValue(pDict,nextKey); isSameStr = CFStringCompare(dictValue,secondValue,0); if (isSameStr != kCFCompareEqualTo) { isFound = false; break; } } } if (isFound) break; } } CFRelease(pDict); err = GetNextProcess (&psn); } CFRelease(keyList); CFRelease(valueList); if (isFound) { #if useLog printf("getProcessInfo found PSN high:%d, low:%d \n", psn.highLongOfPSN, psn.lowLongOfPSN); #endif CFMutableDictionaryRef p_dict_psn = CFDictionaryCreateMutableCopy (NULL, 0, pDict); CFDictionaryAddValue(p_dict_psn, CFSTR("PSNLow"), CFNumberCreate(NULL, kCFNumberSInt32Type, &(psn.lowLongOfPSN))); CFDictionaryAddValue(p_dict_psn, CFSTR("PSNHigh"), CFNumberCreate(NULL, kCFNumberSInt32Type, &(psn.highLongOfPSN))); CFRelease(pDict); return p_dict_psn; } else{ return nil; } }
/*********************************************************************** * copy_display_modes * * Wrapper around CGDisplayCopyAllDisplayModes() to include additional * modes on Retina-capable systems, but filter those which would confuse * Windows apps (basically duplicates at different DPIs). * * For example, some Retina Macs support a 1920x1200 mode, but it's not * returned from CGDisplayCopyAllDisplayModes() without special options. * This is especially bad if that's the user's default mode, since then * no "available" mode matches the initial settings. */ static CFArrayRef copy_display_modes(CGDirectDisplayID display) { CFArrayRef modes = NULL; #if defined(MAC_OS_X_VERSION_10_8) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8 if (&kCGDisplayShowDuplicateLowResolutionModes != NULL && CGDisplayModeGetPixelWidth != NULL && CGDisplayModeGetPixelHeight != NULL) { CFDictionaryRef options; struct display_mode_descriptor* desc; CFMutableDictionaryRef modes_by_size; CFIndex i, count; CGDisplayModeRef* mode_array; options = CFDictionaryCreate(NULL, (const void**)&kCGDisplayShowDuplicateLowResolutionModes, (const void**)&kCFBooleanTrue, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); modes = CGDisplayCopyAllDisplayModes(display, options); if (options) CFRelease(options); if (!modes) return NULL; desc = create_original_display_mode_descriptor(display); modes_by_size = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); count = CFArrayGetCount(modes); for (i = 0; i < count; i++) { BOOL better = TRUE; CGDisplayModeRef new_mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i); BOOL new_is_original = display_mode_matches_descriptor(new_mode, desc); CFDictionaryRef key = create_mode_dict(new_mode, new_is_original); /* If a given mode is the user's default, then always list it in preference to any similar modes that may exist. */ if (new_is_original) better = TRUE; else { CFStringRef pixel_encoding = CGDisplayModeCopyPixelEncoding(new_mode); CGDisplayModeRef old_mode; if (pixel_encoding) { BOOL bpp30 = CFEqual(pixel_encoding, CFSTR(kIO30BitDirectPixels)); CFRelease(pixel_encoding); if (bpp30) { /* This is an odd pixel encoding. It seems it's only returned when using kCGDisplayShowDuplicateLowResolutionModes. It's 32bpp in terms of the actual raster layout, but it's 10 bits per component. I think that no Windows program is likely to need it and they will probably be confused by it. Skip it. */ CFRelease(key); continue; } } old_mode = (CGDisplayModeRef)CFDictionaryGetValue(modes_by_size, key); if (old_mode) { BOOL old_is_original = display_mode_matches_descriptor(old_mode, desc); if (old_is_original) better = FALSE; else { /* Otherwise, prefer a mode whose pixel size equals its point size over one which is scaled. */ size_t width_points = CGDisplayModeGetWidth(new_mode); size_t height_points = CGDisplayModeGetHeight(new_mode); size_t new_width_pixels = CGDisplayModeGetPixelWidth(new_mode); size_t new_height_pixels = CGDisplayModeGetPixelHeight(new_mode); size_t old_width_pixels = CGDisplayModeGetPixelWidth(old_mode); size_t old_height_pixels = CGDisplayModeGetPixelHeight(old_mode); BOOL new_size_same = (new_width_pixels == width_points && new_height_pixels == height_points); BOOL old_size_same = (old_width_pixels == width_points && old_height_pixels == height_points); if (new_size_same && !old_size_same) better = TRUE; else if (!new_size_same && old_size_same) better = FALSE; else { /* Otherwise, prefer the mode with the smaller pixel size. */ if (old_width_pixels < new_width_pixels || old_height_pixels < new_height_pixels) better = FALSE; } } } } if (better) CFDictionarySetValue(modes_by_size, key, new_mode); CFRelease(key); } free_display_mode_descriptor(desc); CFRelease(modes); count = CFDictionaryGetCount(modes_by_size); mode_array = HeapAlloc(GetProcessHeap(), 0, count * sizeof(mode_array[0])); CFDictionaryGetKeysAndValues(modes_by_size, NULL, (const void **)mode_array); modes = CFArrayCreate(NULL, (const void **)mode_array, count, &kCFTypeArrayCallBacks); HeapFree(GetProcessHeap(), 0, mode_array); CFRelease(modes_by_size); } else #endif modes = CGDisplayCopyAllDisplayModes(display, NULL); return modes; }
/* * Gets the device's product name. */ static int HIDGetDeviceProduct(io_service_t dev, char *name) { CFMutableDictionaryRef hidProperties, usbProperties; io_registry_entry_t parent1, parent2; kern_return_t ret; hidProperties = usbProperties = 0; ret = IORegistryEntryCreateCFProperties(dev, &hidProperties, kCFAllocatorDefault, kNilOptions); if ((ret != KERN_SUCCESS) || !hidProperties) { SDL_SetError("Haptic: Unable to create CFProperties."); return -1; } /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties */ if ((KERN_SUCCESS == IORegistryEntryGetParentEntry(dev, kIOServicePlane, &parent1)) && (KERN_SUCCESS == IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2)) && (KERN_SUCCESS == IORegistryEntryCreateCFProperties(parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) { if (usbProperties) { CFTypeRef refCF = 0; /* get device info * try hid dictionary first, if fail then go to usb dictionary */ /* Get product name */ refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey)); if (!refCF) refCF = CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name")); if (refCF) { if (!CFStringGetCString(refCF, name, 256, CFStringGetSystemEncoding())) { SDL_SetError ("Haptic: CFStringGetCString error retrieving pDevice->product."); return -1; } } CFRelease(usbProperties); } else { SDL_SetError ("Haptic: IORegistryEntryCreateCFProperties failed to create usbProperties."); return -1; } /* Release stuff. */ if (kIOReturnSuccess != IOObjectRelease(parent2)) { SDL_SetError("Haptic: IOObjectRelease error with parent2."); } if (kIOReturnSuccess != IOObjectRelease(parent1)) { SDL_SetError("Haptic: IOObjectRelease error with parent1."); } } else { SDL_SetError("Haptic: Error getting registry entries."); return -1; } return 0; }
// This function is much inspired by record_device() and devstats() from // http://opensource.apple.com/source/system_cmds/system_cmds-230/iostat.tproj/iostat.c static void reportDrive(dynamic_accumulator_t *ioLoad, io_registry_entry_t drive) { io_registry_entry_t parent; CFStringRef name; kern_return_t status; // get drive's parent status = IORegistryEntryGetParentEntry(drive, kIOServicePlane, &parent); if (status != KERN_SUCCESS) { return; } if (!IOObjectConformsTo(parent, "IOBlockStorageDriver")) { IOObjectRelease(parent); return; } // get drive properties CFDictionaryRef driveProperties; status = IORegistryEntryCreateCFProperties(drive, (CFMutableDictionaryRef *)&driveProperties, kCFAllocatorDefault, kNilOptions); if (status != KERN_SUCCESS) { return; } // get name from properties name = (CFStringRef)CFDictionaryGetValue(driveProperties, CFSTR(kIOBSDNameKey)); char cname[100]; CFStringGetCString(name, cname, sizeof(cname), CFStringGetSystemEncoding()); CFRelease(driveProperties); // get parent properties CFDictionaryRef parentProperties; status = IORegistryEntryCreateCFProperties(parent, (CFMutableDictionaryRef *)&parentProperties, kCFAllocatorDefault, kNilOptions); IOObjectRelease(parent); if (status != KERN_SUCCESS) { CFRelease(driveProperties); return; } CFDictionaryRef statistics; statistics = (CFDictionaryRef)CFDictionaryGetValue(parentProperties, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (!statistics) { CFRelease(parentProperties); return; } u_int64_t bytesRead = 0; u_int64_t bytesWritten = 0; CFNumberRef number; if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &bytesRead); } if ((number = (CFNumberRef)CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &bytesWritten); } CFRelease(parentProperties); dynamic_accumulator_report(ioLoad, cname, bytesRead, bytesWritten); }
void wxHIDJoystick::MakeCookies(CFArrayRef Array) { int i, nUsage, nPage; for (i = 0; i < CFArrayGetCount(Array); ++i) { const void* ref = CFDictionaryGetValue( (CFDictionaryRef)CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementKey) ); if (ref != NULL) { MakeCookies((CFArrayRef) ref); } else { CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue( (CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsageKey) ), kCFNumberIntType, &nUsage ); CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue( (CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsagePageKey) ), kCFNumberIntType, &nPage ); #if 0 wxLogSysError(wxT("[%i][%i]"), nUsage, nPage); #endif if (nPage == kHIDPage_Button && nUsage <= 40) AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), nUsage-1 ); else if (nPage == kHIDPage_GenericDesktop) { //axis... switch(nUsage) { case kHIDUsage_GD_X: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_X); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nXMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nXMin); break; case kHIDUsage_GD_Y: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_Y); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nYMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nYMin); break; case kHIDUsage_GD_Z: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_Z); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nZMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nZMin); break; default: break; } } else if (nPage == kHIDPage_Simulation && nUsage == kHIDUsage_Sim_Rudder) { //rudder... AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_RUDDER ); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nRudderMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nRudderMin); } } } }
static inline PangoCoreTextFace * pango_core_text_face_from_ct_font_descriptor (CTFontDescriptorRef desc) { int font_traits; char *buffer; CFStringRef str; CFNumberRef number; CGFloat value; CFDictionaryRef dict; CFCharacterSetRef charset; PangoCoreTextFace *face = g_object_new (PANGO_TYPE_CORE_TEXT_FACE, NULL); face->synthetic_italic = FALSE; /* Get font name */ str = CTFontDescriptorCopyAttribute (desc, kCTFontNameAttribute); buffer = gchar_from_cf_string (str); /* We strdup again to save space. */ face->postscript_name = g_strdup (buffer); CFRelease (str); g_free (buffer); /* Get style name */ str = CTFontDescriptorCopyAttribute (desc, kCTFontStyleNameAttribute); buffer = gchar_from_cf_string (str); face->style_name = g_strdup (buffer); CFRelease (str); g_free (buffer); /* Get font traits, symbolic traits */ dict = CTFontDescriptorCopyAttribute (desc, kCTFontTraitsAttribute); number = (CFNumberRef)CFDictionaryGetValue (dict, kCTFontWeightTrait); if (CFNumberGetValue (number, kCFNumberCGFloatType, &value)) { if (value < ct_weight_min || value > ct_weight_max) { face->weight = PANGO_WEIGHT_NORMAL; /* This is really an error */ } else { guint i; for (i = 0; i < G_N_ELEMENTS(ct_weight_limits); i++) if (value < ct_weight_limits[i].bound) { face->weight = ct_weight_limits[i].weight; break; } } } else face->weight = PANGO_WEIGHT_NORMAL; number = (CFNumberRef)CFDictionaryGetValue (dict, kCTFontSymbolicTrait); if (CFNumberGetValue (number, kCFNumberIntType, &font_traits)) { face->traits = font_traits; } CFRelease (dict); /* Get font coverage */ charset = CTFontDescriptorCopyAttribute (desc, kCTFontCharacterSetAttribute); face->coverage = pango_coverage_from_cf_charset (charset); CFRelease (charset); return face; }
static CFTypeRef fetchVolatileValue(CFTypeRef context, void *domain, CFStringRef key) { CFTypeRef result = CFDictionaryGetValue((CFMutableDictionaryRef )domain, key); if (result) CFRetain(result); return result; }
void CDarwinStorageProvider::GetLocalDrives(VECSOURCES &localDrives) { CMediaSource share; // User home folder share.strPath = getenv("HOME"); share.strName = g_localizeStrings.Get(21440); share.m_ignore = true; localDrives.push_back(share); // User desktop folder share.strPath = getenv("HOME"); share.strPath += "/Desktop"; share.strName = "Desktop"; share.m_ignore = true; localDrives.push_back(share); // Volumes (all mounts are present here) share.strPath = "/Volumes"; share.strName = "Volumes"; share.m_ignore = true; localDrives.push_back(share); // This will pick up all local non-removable disks including the Root Disk. DASessionRef session = DASessionCreate(kCFAllocatorDefault); if (session) { unsigned i, count = 0; struct statfs *buf = NULL; CStdString mountpoint, devicepath; count = getmntinfo(&buf, 0); for (i=0; i<count; i++) { mountpoint = buf[i].f_mntonname; devicepath = buf[i].f_mntfromname; DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, devicepath.c_str()); if (disk) { CFDictionaryRef details = DADiskCopyDescription(disk); if (details) { if (kCFBooleanFalse == CFDictionaryGetValue(details, kDADiskDescriptionMediaRemovableKey)) { CMediaSource share; share.strPath = mountpoint; Cocoa_GetVolumeNameFromMountPoint(mountpoint, share.strName); share.m_ignore = true; localDrives.push_back(share); } CFRelease(details); } CFRelease(disk); } } CFRelease(session); } }
PsychError SCREENReadNormalizedGammaTable(void) { int i, screenNumber, numEntries, reallutsize, physicalDisplay, outputId; float *redTable, *greenTable, *blueTable; double *gammaTable; //all subfunctions should have these two lines PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);}; PsychErrorExit(PsychCapNumOutputArgs(3)); PsychErrorExit(PsychCapNumInputArgs(2)); // Get optional physicalDisplay argument - It defaults to zero: physicalDisplay = -1; PsychCopyInIntegerArg(2, FALSE, &physicalDisplay); // Read in the screen number: // On OS/X we also accept screen indices for physical displays (as opposed to active dispays). // This only makes a difference in mirror-mode, where there is only 1 active display, but that // corresponds to two physical displays which can have different gamma setting requirements: if ((PSYCH_SYSTEM == PSYCH_OSX) && (physicalDisplay > 0)) { PsychCopyInIntegerArg(1, TRUE, &screenNumber); if (screenNumber < 1) PsychErrorExitMsg(PsychError_user, "A 'screenNumber' that is smaller than one provided, although 'physicalDisplay' flag set. This is not allowed!"); // Invert screenNumber as a sign its a physical display, not an active display: screenNumber = -1 * screenNumber; } else { PsychCopyInScreenNumberArg(1, TRUE, &screenNumber); } if ((PSYCH_SYSTEM == PSYCH_LINUX) && (physicalDisplay > -1)) { // Affect one specific display output for given screen: outputId = physicalDisplay; } else { // Other OS'es, and Linux with default setting: Affect all outputs // for a screen. outputId = -1; } // Retrieve gamma table: PsychReadNormalizedGammaTable(screenNumber, outputId, &numEntries, &redTable, &greenTable, &blueTable); // Copy it out to runtime: PsychAllocOutDoubleMatArg(1, FALSE, numEntries, 3, 0, &gammaTable); for(i=0;i<numEntries;i++){ gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 0, 0)]=(double)redTable[i]; gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 1, 0)]=(double)greenTable[i]; gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 2, 0)]=(double)blueTable[i]; } // Copy out optional DAC resolution value: PsychCopyOutDoubleArg(2, FALSE, (double) PsychGetDacBitsFromDisplay(screenNumber)); // We default to the assumption that the real size of the hardware LUT is identical to // the size of the returned LUT: reallutsize = numEntries; #if PSYCH_SYSTEM == PSYCH_OSX // On OS-X we query the real LUT size from the OS and return that value: CGDirectDisplayID displayID; CFMutableDictionaryRef properties; CFNumberRef cfGammaLength; SInt32 lutslotcount; io_service_t displayService; kern_return_t kr; CFMutableArrayRef framebufferTimings0 = 0; CFDataRef framebufferTimings1 = 0; IODetailedTimingInformationV2 *framebufferTiming = NULL; // Retrieve display handle for screen: PsychGetCGDisplayIDFromScreenNumber(&displayID, screenNumber); // Retrieve low-level IOKit service port for this display: displayService = CGDisplayIOServicePort(displayID); // Obtain the properties from that service kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0); if((kr == kIOReturnSuccess) && ((cfGammaLength = (CFNumberRef) CFDictionaryGetValue(properties, CFSTR(kIOFBGammaCountKey)))!=NULL)) { CFNumberGetValue(cfGammaLength, kCFNumberSInt32Type, &lutslotcount); CFRelease(properties); reallutsize = (int) lutslotcount; } else { // Failed! if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query real size of video LUT for screen %i! Will return safe default of %i slots.\n", screenNumber, reallutsize); } if (PsychPrefStateGet_Verbosity()>9) { CGDisplayModeRef currentMode; CFNumberRef n; int modeId; currentMode = CGDisplayCopyDisplayMode(displayID); modeId = (int) CGDisplayModeGetIODisplayModeID(currentMode); CGDisplayModeRelease(currentMode); printf("Current mode has id %i\n\n", modeId); kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0); if((kr == kIOReturnSuccess) && ((framebufferTimings0 = (CFMutableArrayRef) CFDictionaryGetValue(properties, CFSTR(kIOFBDetailedTimingsKey) ) )!=NULL)) { for (i=0; i<CFArrayGetCount(framebufferTimings0); i++) { if ((framebufferTimings1 = CFArrayGetValueAtIndex(framebufferTimings0, i)) != NULL) { if ((framebufferTiming = (IODetailedTimingInformationV2*) CFDataGetBytePtr(framebufferTimings1)) != NULL) { printf("[%i] : VActive = %li, VBL = %li, VSYNC = %li, VSYNCWIDTH = %li , VBORDERBOT = %li, VTOTAL = %li \n", i, framebufferTiming->verticalActive, framebufferTiming->verticalBlanking, framebufferTiming->verticalSyncOffset, framebufferTiming->verticalSyncPulseWidth, framebufferTiming->verticalBorderBottom, framebufferTiming->verticalActive + framebufferTiming->verticalBlanking); } } } CFRelease(properties); } else { // Failed! if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query STUFF for screen %i --> %p!\n", screenNumber, properties); } } #endif // Copy out optional real LUT size (number of slots): PsychCopyOutDoubleArg(3, FALSE, (double) reallutsize); return(PsychError_none); }
CFDictionaryRef remote_aes(int socket, CFDictionaryRef dict) { uint8_t* input2 = NULL; uint32_t len = 0; uint8_t* iv2 = NULL; uint32_t keyMask = 0; uint32_t mode = 0; uint32_t bits = 0; CFNumberRef km = CFDictionaryGetValue(dict, CFSTR("keyMask")); if(km == NULL || CFGetTypeID(km) != CFNumberGetTypeID()) return NULL; CFNumberGetValue(km, kCFNumberIntType, &keyMask); CFNumberRef m = CFDictionaryGetValue(dict, CFSTR("mode")); if(m == NULL || CFGetTypeID(m) != CFNumberGetTypeID()) return NULL; CFNumberGetValue(m, kCFNumberIntType, &mode); CFNumberRef b = CFDictionaryGetValue(dict, CFSTR("bits")); if(b == NULL || CFGetTypeID(b) != CFNumberGetTypeID()) return NULL; CFNumberGetValue(b, kCFNumberIntType, &bits); CFDataRef input = CFDictionaryGetValue(dict, CFSTR("input")); if(input == NULL || CFGetTypeID(input) != CFDataGetTypeID()) return NULL; CFDataRef iv = CFDictionaryGetValue(dict, CFSTR("iv")); if(iv != NULL) { if (CFGetTypeID(iv) != CFDataGetTypeID()) return NULL; iv2 = (uint8_t*) CFDataGetBytePtr(iv); } len = CFDataGetLength(input); if (len % 16 != 0) { return NULL; } input2 = malloc(len); if (input2 == NULL) { return NULL; } memcpy(input2, CFDataGetBytePtr(input), len); uint32_t ret = doAES(input2, input2, len, keyMask, NULL, iv2, mode, bits); CFMutableDictionaryRef out = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFNumberRef retCode = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &ret); CFDictionaryAddValue(out, CFSTR("returnCode"), retCode); CFRelease(retCode); if (ret == 0) { CFDataRef dd = CFDataCreate(kCFAllocatorDefault, input2, len); CFDictionaryAddValue(out, CFSTR("data"), dd); CFRelease(dd); } free(input2); return out; }
static void __deviceCallback(void * context, IOReturn result, void * sender, IOHIDDeviceRef device) { boolean_t terminated = context == 0; CFStringRef debugString = CFCopyDescription(device); char * c_debug_string = NULL; if( debugString ){ // DG: Bluetooth "Product" strings have Unicode encoding and no nul terminator and CFStringGetCStringPtr returns NULL // Need to manually copy to C string CFIndex length = CFStringGetLength(debugString); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, CFStringGetSystemEncoding()) + 1; c_debug_string = (char *)malloc(maxSize); CFStringGetCString(debugString, c_debug_string, maxSize, CFStringGetSystemEncoding()); CFRelease(debugString); } static CFMutableDictionaryRef s_timers = NULL; if ( !s_timers ) s_timers = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); uint64_t uuid = 0; CFNumberRef temp = IOHIDDeviceGetProperty( device, CFSTR(kIOHIDUniqueIDKey) ); if ( temp && CFGetTypeID(temp) == CFNumberGetTypeID() ) CFNumberGetValue( temp, kCFNumberLongLongType, &uuid ); CFNumberGetValue( IOHIDDeviceGetProperty( device, CFSTR(kIOHIDUniqueIDKey) ), kCFNumberLongLongType, &uuid ); printf("%-10.10s: %s UniqueID %llu\n", terminated ? "terminated" : "matched", c_debug_string ? c_debug_string : "", uuid ); if ( c_debug_string ) free(c_debug_string); if ( terminated ) { CFDictionaryRemoveValue(gOutputElements, device); CFRunLoopTimerRef timer = (CFRunLoopTimerRef)CFDictionaryGetValue(s_timers, device); if ( timer ) { CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes); } CFDictionaryRemoveValue(s_timers, device); } else { CFArrayRef outputElements = NULL; CFMutableDictionaryRef matching = NULL; if ( gPrintDescriptor ) { CFDataRef descriptor = NULL; descriptor = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDReportDescriptorKey)); if ( descriptor ) { PrintHIDDescriptor(CFDataGetBytePtr(descriptor), CFDataGetLength(descriptor)); } } if ( gPollInterval != 0.0 ) { CFRunLoopTimerContext context = {.info=device}; CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), gPollInterval, 0, 0, __timerCallback, &context); CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes); CFDictionaryAddValue(s_timers, device, timer); CFRelease(timer); printf("Adding polling timer @ %4.6f s\n", gPollInterval); } matching = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if ( matching ) { uint32_t value = kIOHIDElementTypeOutput; CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value); if ( number ) { CFDictionarySetValue(matching, CFSTR(kIOHIDElementTypeKey), number); outputElements = IOHIDDeviceCopyMatchingElements(device, matching, 0); if ( outputElements ) { CFDictionarySetValue(gOutputElements, device, outputElements); CFRelease(outputElements); } CFRelease(number); } CFRelease(matching); } }
int main( int argc, char * argv[] ) { mach_port_t masterPort; io_iterator_t iter; io_service_t service; kern_return_t kr; CFMutableDictionaryRef properties; CFStringRef cfStr; kr = IOMasterPort( MACH_PORT_NULL, &masterPort); assert( KERN_SUCCESS == kr ); // Look up the object we wish to open. This example uses simple class // matching (IOServiceMatching()) to look up the object that is the // AppleSamplePCI driver class instantiated by the kext. kr = IOServiceGetMatchingServices( masterPort, IOServiceMatching( kAppleSamplePCIClassName ), &iter); assert( KERN_SUCCESS == kr ); for( ; (service = IOIteratorNext(iter)); IOObjectRelease(service)) { io_string_t path; kr = IORegistryEntryGetPath(service, kIOServicePlane, path); assert( KERN_SUCCESS == kr ); printf("Found a device of class "kAppleSamplePCIClassName": %s\n", path); // print the value of kIONameMatchedKey property, as an example of // getting properties from the registry. Property based access // doesn't require a user client connection. // grab a copy of the properties kr = IORegistryEntryCreateCFProperties( service, &properties, kCFAllocatorDefault, kNilOptions ); assert( KERN_SUCCESS == kr ); cfStr = CFDictionaryGetValue( properties, CFSTR(kIONameMatchedKey) ); if( cfStr) { const char * c = NULL; char * buffer = NULL; c = CFStringGetCStringPtr(cfStr, kCFStringEncodingMacRoman); if(!c) { CFIndex bufferSize = CFStringGetLength(cfStr) + 1; buffer = malloc(bufferSize); if(buffer) { if(CFStringGetCString(cfStr, buffer, bufferSize, kCFStringEncodingMacRoman)) c = buffer; } } if(c) printf("it matched on name \"%s\"\n", c); if(buffer) free(buffer); } CFRelease( properties ); // test out the user client Test( masterPort, service ); } IOObjectRelease(iter); exit(0); return(0); }
void PolicyEngine::addToAuthority(CFMutableDictionaryRef parent, CFStringRef key, CFTypeRef value) { CFMutableDictionaryRef authority = CFMutableDictionaryRef(CFDictionaryGetValue(parent, kSecAssessmentAssessmentAuthority)); assert(authority); CFDictionaryAddValue(authority, key, value); }
QList<QNetworkProxy> macQueryInternal(const QNetworkProxyQuery &query) { QList<QNetworkProxy> result; // obtain a dictionary to the proxy settings: CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL); if (!dict) { qWarning("QNetworkProxyFactory::systemProxyForQuery: SCDynamicStoreCopyProxies returned NULL"); return result; // failed } if (isHostExcluded(dict, query.peerHostName())) return result; // no proxy for this host // is there a PAC enabled? If so, use it first. CFNumberRef pacEnabled; if ((pacEnabled = (CFNumberRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigEnable))) { int enabled; if (CFNumberGetValue(pacEnabled, kCFNumberIntType, &enabled) && enabled) { // PAC is enabled CFStringRef pacUrl = (CFStringRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigURLString); QString url = QCFString::toQString(pacUrl); // ### Use PAC somehow qDebug("Mac system proxy: found PAC script at \"%s\"", qPrintable(url)); } } // no PAC, decide which proxy we're looking for based on the query bool isHttps = false; QString protocol = query.protocolTag().toLower(); // try the protocol-specific proxy QNetworkProxy protocolSpecificProxy; if (protocol == QLatin1String("ftp")) { protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::FtpCachingProxy, kSCPropNetProxiesFTPEnable, kSCPropNetProxiesFTPProxy, kSCPropNetProxiesFTPPort); } else if (protocol == QLatin1String("http")) { protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort); } else if (protocol == QLatin1String("https")) { isHttps = true; protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort); } if (protocolSpecificProxy.type() != QNetworkProxy::DefaultProxy) result << protocolSpecificProxy; // let's add SOCKSv5 if present too QNetworkProxy socks5 = proxyFromDictionary(dict, QNetworkProxy::Socks5Proxy, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort); if (socks5.type() != QNetworkProxy::DefaultProxy) result << socks5; // let's add the HTTPS proxy if present (and if we haven't added // yet) if (!isHttps) { QNetworkProxy https = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort); if (https.type() != QNetworkProxy::DefaultProxy && https != protocolSpecificProxy) result << https; } return result; }
bool SetAPETagFromMetadata(const AudioMetadata& metadata, TagLib::APE::Tag *tag, bool setAlbumArt) { if(nullptr == tag) return false; // Standard tags SetAPETag(tag, "ALBUM", metadata.GetAlbumTitle()); SetAPETag(tag, "ARTIST", metadata.GetArtist()); SetAPETag(tag, "ALBUMARTIST", metadata.GetAlbumArtist()); SetAPETag(tag, "COMPOSER", metadata.GetComposer()); SetAPETag(tag, "GENRE", metadata.GetGenre()); SetAPETag(tag, "DATE", metadata.GetReleaseDate()); SetAPETag(tag, "DESCRIPTION", metadata.GetComment()); SetAPETag(tag, "TITLE", metadata.GetTitle()); SetAPETagNumber(tag, "TRACKNUMBER", metadata.GetTrackNumber()); SetAPETagNumber(tag, "TRACKTOTAL", metadata.GetTrackTotal()); SetAPETagBoolean(tag, "COMPILATION", metadata.GetCompilation()); SetAPETagNumber(tag, "DISCNUMBER", metadata.GetDiscNumber()); SetAPETagNumber(tag, "DISCTOTAL", metadata.GetDiscTotal()); SetAPETagNumber(tag, "BPM", metadata.GetBPM()); SetAPETagNumber(tag, "RATING", metadata.GetRating()); SetAPETag(tag, "ISRC", metadata.GetISRC()); SetAPETag(tag, "MCN", metadata.GetMCN()); SetAPETag(tag, "TITLESORT", metadata.GetTitleSortOrder()); SetAPETag(tag, "ALBUMTITLESORT", metadata.GetAlbumTitleSortOrder()); SetAPETag(tag, "ARTISTSORT", metadata.GetArtistSortOrder()); SetAPETag(tag, "ALBUMARTISTSORT", metadata.GetAlbumArtistSortOrder()); SetAPETag(tag, "COMPOSERSORT", metadata.GetComposerSortOrder()); SetAPETag(tag, "GROUPING", metadata.GetGrouping()); // Additional metadata CFDictionaryRef additionalMetadata = metadata.GetAdditionalMetadata(); if(nullptr != additionalMetadata) { CFIndex count = CFDictionaryGetCount(additionalMetadata); const void * keys [count]; const void * values [count]; CFDictionaryGetKeysAndValues(additionalMetadata, reinterpret_cast<const void **>(keys), reinterpret_cast<const void **>(values)); for(CFIndex i = 0; i < count; ++i) { CFIndex keySize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(reinterpret_cast<CFStringRef>(keys[i])), kCFStringEncodingASCII); char key [keySize + 1]; if(!CFStringGetCString(reinterpret_cast<CFStringRef>(keys[i]), key, keySize + 1, kCFStringEncodingASCII)) { LOGGER_ERR("org.sbooth.AudioEngine", "CFStringGetCString failed"); continue; } SetAPETag(tag, key, reinterpret_cast<CFStringRef>(values[i])); } } // ReplayGain info SetAPETagDouble(tag, "REPLAYGAIN_REFERENCE_LOUDNESS", metadata.GetReplayGainReferenceLoudness(), CFSTR("%2.1f dB")); SetAPETagDouble(tag, "REPLAYGAIN_TRACK_GAIN", metadata.GetReplayGainTrackGain(), CFSTR("%+2.2f dB")); SetAPETagDouble(tag, "REPLAYGAIN_TRACK_PEAK", metadata.GetReplayGainTrackPeak(), CFSTR("%1.8f")); SetAPETagDouble(tag, "REPLAYGAIN_ALBUM_GAIN", metadata.GetReplayGainAlbumGain(), CFSTR("%+2.2f dB")); SetAPETagDouble(tag, "REPLAYGAIN_ALBUM_PEAK", metadata.GetReplayGainAlbumPeak(), CFSTR("%1.8f")); // Album art if(setAlbumArt) { tag->removeItem("Cover Art (Front)"); tag->removeItem("Cover Art (Back)"); #if 0 tag->removeItem("METADATA_BLOCK_PICTURE"); #endif for(auto attachedPicture : metadata.GetAttachedPictures()) { // APE can handle front and back covers natively if(AttachedPicture::Type::FrontCover == attachedPicture->GetType() || AttachedPicture::Type::FrontCover == attachedPicture->GetType()) { TagLib::ByteVector data; if(attachedPicture->GetDescription()) data.append(TagLib::StringFromCFString(attachedPicture->GetDescription()).data(TagLib::String::UTF8)); data.append('\0'); data.append(TagLib::ByteVector((const char *)CFDataGetBytePtr(attachedPicture->GetData()), (TagLib::uint)CFDataGetLength(attachedPicture->GetData()))); if(AttachedPicture::Type::FrontCover == attachedPicture->GetType()) tag->setData("Cover Art (Front)", data); else if(AttachedPicture::Type::BackCover == attachedPicture->GetType()) tag->setData("Cover Art (Back)", data); } #if 0 else { CGImageSourceRef imageSource = CGImageSourceCreateWithData(attachedPicture->GetData(), nullptr); if(nullptr == imageSource) return false; TagLib::FLAC::Picture picture; picture.setData(TagLib::ByteVector((const char *)CFDataGetBytePtr(attachedPicture->GetData()), (TagLib::uint)CFDataGetLength(attachedPicture->GetData()))); picture.setType(static_cast<TagLib::FLAC::Picture::Type>(attachedPicture->GetType())); if(attachedPicture->GetDescription()) picture.setDescription(TagLib::StringFromCFString(attachedPicture->GetDescription())); // Convert the image's UTI into a MIME type CFStringRef mimeType = UTTypeCopyPreferredTagWithClass(CGImageSourceGetType(imageSource), kUTTagClassMIMEType); if(mimeType) { picture.setMimeType(TagLib::StringFromCFString(mimeType)); CFRelease(mimeType), mimeType = nullptr; } // Flesh out the height, width, and depth CFDictionaryRef imagePropertiesDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nullptr); if(imagePropertiesDictionary) { CFNumberRef imageWidth = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyPixelWidth); CFNumberRef imageHeight = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyPixelHeight); CFNumberRef imageDepth = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyDepth); int height, width, depth; // Ignore numeric conversion errors CFNumberGetValue(imageWidth, kCFNumberIntType, &width); CFNumberGetValue(imageHeight, kCFNumberIntType, &height); CFNumberGetValue(imageDepth, kCFNumberIntType, &depth); picture.setHeight(height); picture.setWidth(width); picture.setColorDepth(depth); CFRelease(imagePropertiesDictionary), imagePropertiesDictionary = nullptr; } TagLib::ByteVector encodedBlock = TagLib::EncodeBase64(picture.render()); tag->addValue("METADATA_BLOCK_PICTURE", TagLib::String(encodedBlock, TagLib::String::UTF8), false); CFRelease(imageSource), imageSource = nullptr; } #endif } } return true; }
static void startAppleTalk(CFRunLoopTimerRef timer, void *info) { int argc = 0; char *argv[8]; char *computerName = NULL; char *interface = NULL; CFStringRef mode = CFDictionaryGetValue(curStartup, CFSTR("APPLETALK")); CFStringRef name = CFDictionaryGetValue(curStartup, CFSTR("APPLETALK_HOSTNAME")); SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk startup")); if (!mode) { // Huh? return; } // set command name argv[argc++] = "appletalk"; // set hostname if (name) { computerName = _SC_cfstring_to_cstring(name, NULL, 0, kCFStringEncodingASCII); if (computerName) { argv[argc++] = "-C"; argv[argc++] = computerName; } else { // could not convert name goto done; } } // set mode if (CFEqual(mode, CFSTR("-ROUTER-"))) { argv[argc++] = "-r"; } else if (CFEqual(mode, CFSTR("-MULTIHOME-"))) { argv[argc++] = "-x"; } else { interface = _SC_cfstring_to_cstring(mode, NULL, 0, kCFStringEncodingASCII); if (interface) { argv[argc++] = "-u"; argv[argc++] = interface; } else { // could not convert interface goto done; } } // set non-interactive argv[argc++] = "-q"; // close argument list argv[argc++] = NULL; execCommand = _SCDPluginExecCommand(startComplete, // callback info, // context 0, // uid 0, // gid "/usr/sbin/appletalk", // path argv); // argv if (!timer) { execRetry = 5; // initialize retry count } done : if (computerName) CFAllocatorDeallocate(NULL, computerName); if (interface) CFAllocatorDeallocate(NULL, interface); return; }
/* * Creates a vector of driver bundle info structures from the hot-plug driver * directory. * * Returns NULL on error and a pointer to an allocated HPDriver vector on * success. The caller must free the HPDriver with a call to * HPDriversRelease(). */ static HPDriverVector HPDriversGetFromDirectory(const char *driverBundlePath) { #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Entering HPDriversGetFromDirectory: %s", driverBundlePath); #endif int readersNumber = 0; HPDriverVector bundleVector = NULL; CFArrayRef bundleArray; CFStringRef driverBundlePathString = CFStringCreateWithCString(kCFAllocatorDefault, driverBundlePath, kCFStringEncodingMacRoman); CFURLRef pluginUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, driverBundlePathString, kCFURLPOSIXPathStyle, TRUE); CFRelease(driverBundlePathString); if (!pluginUrl) { Log1(PCSC_LOG_ERROR, "error getting plugin directory URL"); return NULL; } bundleArray = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, pluginUrl, NULL); if (!bundleArray) { Log1(PCSC_LOG_ERROR, "error getting plugin directory bundles"); return NULL; } CFRelease(pluginUrl); size_t bundleArraySize = CFArrayGetCount(bundleArray); size_t i; /* get the number of readers (including aliases) */ for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return NULL; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { /* alias found, each reader count as 1 */ CFArrayRef propertyArray = blobValue; readersNumber += CFArrayGetCount(propertyArray); } else /* No alias, only one reader supported */ readersNumber++; } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Total of %d readers supported", readersNumber); #endif /* The last entry is an end marker (m_vendorId = 0) * see checks in HPDriversMatchUSBDevices:503 * and HPDriverVectorRelease:376 */ readersNumber++; bundleVector = calloc(readersNumber, sizeof(HPDriver)); if (!bundleVector) { Log1(PCSC_LOG_ERROR, "memory allocation failure"); return NULL; } HPDriver *driverBundle = bundleVector; for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); CFURLRef bundleUrl = CFBundleCopyBundleURL(currBundle); CFStringRef bundlePath = CFURLCopyPath(bundleUrl); driverBundle->m_libPath = strdup(CFStringGetCStringPtr(bundlePath, CFStringGetSystemEncoding())); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return bundleVector; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { CFArrayRef vendorArray = blobValue; CFArrayRef productArray; CFArrayRef friendlyNameArray; char *libPath = driverBundle->m_libPath; #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Driver with aliases: %s", libPath); #endif /* get list of ProductID */ productArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!productArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } /* get list of FriendlyName */ friendlyNameArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!friendlyNameArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } int reader_nb = CFArrayGetCount(vendorArray); if (reader_nb != CFArrayGetCount(productArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %ld products", reader_nb, CFArrayGetCount(productArray)); return bundleVector; } if (reader_nb != CFArrayGetCount(friendlyNameArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %ld friendlynames", reader_nb, CFArrayGetCount(friendlyNameArray)); return bundleVector; } int j; for (j=0; j<reader_nb; j++) { CFStringRef strValue = CFArrayGetValueAtIndex(vendorArray, j); driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(productArray, j); driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(friendlyNameArray, j); const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); if (!driverBundle->m_libPath) driverBundle->m_libPath = strdup(libPath); #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } else { CFStringRef strValue = blobValue; #ifdef DEBUG_HOTPLUG Log3(PCSC_LOG_DEBUG, "Driver without alias: %s %s", driverBundle->m_friendlyName, driverBundle->m_libPath); #endif driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product friendly name from bundle"); driverBundle->m_friendlyName = strdup("unnamed device"); } else { const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } CFRelease(bundleArray); return bundleVector; }
static CFDictionaryRef entity_one(SCDynamicStoreRef store, CFStringRef key) { CFDictionaryRef ent_dict = NULL; CFDictionaryRef if_dict = NULL; CFStringRef if_key = NULL; CFStringRef if_port; CFMutableDictionaryRef new_dict = NULL; static CFStringRef pre = NULL; CFStringRef serviceID = NULL; CFStringRef serviceType; if (!pre) { pre = SCDynamicStoreKeyCreate(NULL, CFSTR("%@/%@/%@/"), kSCDynamicStoreDomainSetup, kSCCompNetwork, kSCCompService); } /* * get entity dictionary for service */ ent_dict = cache_SCDynamicStoreCopyValue(store, key); if (!isA_CFDictionary(ent_dict)) { goto done; } /* * get interface dictionary for service */ serviceID = parse_component(key, pre); if (!serviceID) { goto done; } if_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceID, kSCEntNetInterface); if_dict = cache_SCDynamicStoreCopyValue(store, if_key); CFRelease(if_key); if (!isA_CFDictionary(if_dict)) { goto done; } /* check the interface type */ serviceType = CFDictionaryGetValue(if_dict, kSCPropNetInterfaceType); if (!isA_CFString(serviceType) || !CFEqual(serviceType, kSCValNetInterfaceTypeEthernet)) { /* sorry, no AT networking on this interface */ goto done; } /* * get port name (from interface dictionary). */ if_port = CFDictionaryGetValue(if_dict, kSCPropNetInterfaceDeviceName); if (!isA_CFString(if_port)) { goto done; } /* * add ServiceID and interface port name to entity dictionary. */ new_dict = CFDictionaryCreateMutableCopy(NULL, 0, ent_dict); CFDictionarySetValue(new_dict, CFSTR("ServiceID"), serviceID); CFDictionarySetValue(new_dict, kSCPropNetInterfaceDeviceName, if_port); done: if (ent_dict) CFRelease(ent_dict); if (if_dict) CFRelease(if_dict); if (serviceID) CFRelease(serviceID); return (CFDictionaryRef)new_dict; }
/* Status query */ NXEventSystemInfoType NXEventSystemInfo(NXEventHandle handle, char *flavor, NXEventSystemInfoType evs_info, unsigned int *evs_info_cnt) { kern_return_t kr; NXEventSystemDevice * info = (NXEventSystemDevice *) evs_info; int maxDeviceCount = (*evs_info_cnt) * sizeof( int) / sizeof( NXEventSystemDevice); int deviceCount = 0; int i; io_registry_entry_t hidsystem; CFArrayRef array; CFDictionaryRef dict; CFNumberRef num; SInt32 val; // Translate the one existing old case to new format if ( ((uintptr_t) flavor) == __OLD_NX_EVS_DEVICE_INFO ) flavor = NX_EVS_DEVICE_INFO; if( strcmp( flavor, NX_EVS_DEVICE_INFO)) kr = kIOReturnUnsupported; do { kr = IOConnectGetService( handle, &hidsystem ); if( KERN_SUCCESS != kr ) break; array = IORegistryEntryCreateCFProperty(hidsystem, CFSTR("NXSystemInfo"), kCFAllocatorDefault, kNilOptions); IOObjectRelease( hidsystem ); if( !array ) break; deviceCount = CFArrayGetCount(array); if ( deviceCount > maxDeviceCount ) deviceCount = maxDeviceCount; for ( i=0; i<deviceCount; i++) { dict = CFArrayGetValueAtIndex(array, i); if( !dict ) continue; if( (num = CFDictionaryGetValue( dict, CFSTR(kIOHIDKindKey )))) { CFNumberGetValue( num, kCFNumberSInt32Type, &val ); info[ i ].dev_type = val; if( (num = CFDictionaryGetValue( dict, CFSTR(kIOHIDInterfaceIDKey )))) CFNumberGetValue( num, kCFNumberSInt32Type, &val ); else val = 0; info[ i ].interface = val; if( (num = CFDictionaryGetValue( dict, CFSTR(kIOHIDSubinterfaceIDKey )))) CFNumberGetValue( num, kCFNumberSInt32Type, &val ); else val = 0; info[ i ].id = val; info[ i ].interface_addr = 0; } } CFRelease(array); } while( false ); if ( kr == KERN_SUCCESS ) *evs_info_cnt = (deviceCount * sizeof( NXEventSystemDevice) / sizeof( int)); else evs_info = (NXEventSystemInfoType) 0; return evs_info; }
static boolean_t updateConfiguration(int *newState) { boolean_t changed = FALSE; CFStringRef computerName; CFStringEncoding computerNameEncoding; CFArrayRef configuredServices = NULL; CFDictionaryRef dict; CFIndex i; CFIndex ifCount = 0; CFMutableArrayRef info = NULL; CFArrayRef interfaces = NULL; CFStringRef key; CFArrayRef keys; CFIndex n; CFMutableArrayRef newConfigFile; CFMutableDictionaryRef newDefaults; CFMutableDictionaryRef newDict; CFMutableDictionaryRef newGlobals; CFMutableDictionaryRef newGlobalsX; /* newGlobals without ServiceID */ CFMutableDictionaryRef newStartup; CFMutableDictionaryRef newZones; CFNumberRef num; CFMutableDictionaryRef curGlobalsX; /* curGlobals without ServiceID */ CFStringRef pattern; boolean_t postGlobals = FALSE; CFStringRef primaryPort = NULL; /* primary interface */ CFStringRef primaryZone = NULL; CFArrayRef serviceOrder = NULL; CFDictionaryRef setGlobals = NULL; cache_open(); /* * establish the "new" AppleTalk configuration */ *newState = curState; newConfigFile = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); newGlobals = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); newDefaults = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); newStartup = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); newZones = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); /* initialize overall state */ CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-NO-")); /* * get the global settings (ServiceOrder, ComputerName, ...) */ key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainSetup, kSCEntNetAppleTalk); setGlobals = cache_SCDynamicStoreCopyValue(store, key); CFRelease(key); if (setGlobals) { if (isA_CFDictionary(setGlobals)) { /* get service order */ serviceOrder = CFDictionaryGetValue(setGlobals, kSCPropNetServiceOrder); serviceOrder = isA_CFArray(serviceOrder); if (serviceOrder) { CFRetain(serviceOrder); } } else { CFRelease(setGlobals); setGlobals = NULL; } } /* * if we don't have an AppleTalk ServiceOrder, use IPv4's (if defined) */ if (!serviceOrder) { key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainSetup, kSCEntNetIPv4); dict = cache_SCDynamicStoreCopyValue(store, key); CFRelease(key); if (dict) { if (isA_CFDictionary(dict)) { serviceOrder = CFDictionaryGetValue(dict, kSCPropNetServiceOrder); serviceOrder = isA_CFArray(serviceOrder); if (serviceOrder) { CFRetain(serviceOrder); } } CFRelease(dict); } } /* * get the list of ALL configured services */ configuredServices = entity_all(store, kSCEntNetAppleTalk, serviceOrder); if (configuredServices) { ifCount = CFArrayGetCount(configuredServices); } if (serviceOrder) CFRelease(serviceOrder); /* * get the list of ALL active interfaces */ key = SCDynamicStoreKeyCreateNetworkInterface(NULL, kSCDynamicStoreDomainState); dict = cache_SCDynamicStoreCopyValue(store, key); CFRelease(key); if (dict) { if (isA_CFDictionary(dict)) { interfaces = CFDictionaryGetValue(dict, kSCDynamicStorePropNetInterfaces); interfaces = isA_CFArray(interfaces); if (interfaces) { CFRetain(interfaces); } } CFRelease(dict); } /* * get the list of previously configured services */ pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetAppleTalk); keys = SCDynamicStoreCopyKeyList(store, pattern); CFRelease(pattern); if (keys) { info = CFArrayCreateMutableCopy(NULL, 0, keys); CFRelease(keys); } /* * iterate over each configured service to establish the new * configuration. */ for (i = 0; i < ifCount; i++) { CFDictionaryRef service; CFStringRef ifName; CFStringRef configMethod; CFMutableStringRef portConfig = NULL; CFArrayRef networkRange; /* for seed ports, CFArray[2] of CFNumber (lo, hi) */ int sNetwork; int eNetwork; CFArrayRef zoneList; /* for seed ports, CFArray[] of CFString (zones names) */ CFIndex zCount; CFIndex j; CFMutableDictionaryRef ifDefaults = NULL; CFNumberRef defaultNetwork; CFNumberRef defaultNode; CFStringRef defaultZone; /* get AppleTalk service dictionary */ service = CFArrayGetValueAtIndex(configuredServices, i); /* get interface name */ ifName = CFDictionaryGetValue(service, kSCPropNetInterfaceDeviceName); /* check inteface availability */ if (!interfaces || !CFArrayContainsValue(interfaces, CFRangeMake(0, CFArrayGetCount(interfaces)), ifName)) { /* if interface not available */ goto nextIF; } /* check interface link status */ key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, ifName, kSCEntNetLink); dict = cache_SCDynamicStoreCopyValue(store, key); CFRelease(key); if (dict) { Boolean linkStatus = TRUE; /* assume the link is "up" */ Boolean ifDetaching = FALSE; /* assume link is not detaching */ /* the link key for this interface is available */ if (isA_CFDictionary(dict)) { CFBooleanRef bVal; bVal = CFDictionaryGetValue(dict, kSCPropNetLinkActive); if (isA_CFBoolean(bVal)) { linkStatus = CFBooleanGetValue(bVal); } /* check if interface is detaching - value doesn't really matter, only that it exists */ ifDetaching = CFDictionaryContainsKey(dict, kSCPropNetLinkDetaching); } CFRelease(dict); if (!linkStatus || ifDetaching) { /* if link status down or the interface is detaching */ goto nextIF; } } /* * Determine configuration method for this service */ configMethod = CFDictionaryGetValue(service, kSCPropNetAppleTalkConfigMethod); if (!isA_CFString(configMethod)) { /* if no ConfigMethod */ goto nextIF; } if (!CFEqual(configMethod, kSCValNetAppleTalkConfigMethodNode ) && !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter ) && !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) { /* if not one of the expected values, disable */ SCLog(TRUE, LOG_NOTICE, CFSTR("Unexpected AppleTalk ConfigMethod: %@"), configMethod); goto nextIF; } /* * the first service to be defined will always be "primary" */ if (CFArrayGetCount(newConfigFile) == 0) { CFDictionaryRef active; CFDictionarySetValue(newGlobals, kSCDynamicStorePropNetPrimaryService, CFDictionaryGetValue(service, CFSTR("ServiceID"))); CFDictionarySetValue(newGlobals, kSCDynamicStorePropNetPrimaryInterface, ifName); /* and check if AT newtorking is active on the primary interface */ key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, ifName, kSCEntNetAppleTalk); active = cache_SCDynamicStoreCopyValue(store, key); CFRelease(key); if (active) { if (isA_CFDictionary(active)) { postGlobals = TRUE; } CFRelease(active); } } /* * define the port */ portConfig = CFStringCreateMutable(NULL, 0); CFStringAppendFormat(portConfig, NULL, CFSTR("%@:"), ifName); if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) { CFNumberRef num; /* * we have been asked to configure this interface as a * seed port. Ensure that we have been provided at least * one network number, have been provided with at least * one zonename, ... */ networkRange = CFDictionaryGetValue(service, kSCPropNetAppleTalkSeedNetworkRange); if (!isA_CFArray(networkRange) || (CFArrayGetCount(networkRange) == 0)) { SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk configuration error (%@)"), kSCPropNetAppleTalkSeedNetworkRange); goto nextIF; } /* * establish the starting and ending network numbers */ num = CFArrayGetValueAtIndex(networkRange, 0); if (!isA_CFNumber(num)) { SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk configuration error (%@)"), kSCPropNetAppleTalkSeedNetworkRange); goto nextIF; } CFNumberGetValue(num, kCFNumberIntType, &sNetwork); eNetwork = sNetwork; if (CFArrayGetCount(networkRange) > 1) { num = CFArrayGetValueAtIndex(networkRange, 1); if (!isA_CFNumber(num)) { SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk configuration error (%@)"), kSCPropNetAppleTalkSeedNetworkRange); goto nextIF; } CFNumberGetValue(num, kCFNumberIntType, &eNetwork); } CFStringAppendFormat(portConfig, NULL, CFSTR("%d:%d:"), sNetwork, eNetwork); /* * establish the zones associated with this port */ zoneList = CFDictionaryGetValue(service, kSCPropNetAppleTalkSeedZones); if (!isA_CFArray(zoneList)) { SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk configuration error (%@)"), kSCPropNetAppleTalkSeedZones); goto nextIF; } zCount = CFArrayGetCount(zoneList); for (j = 0; j < zCount; j++) { CFStringRef zone; CFArrayRef ifList; CFMutableArrayRef newIFList; zone = CFArrayGetValueAtIndex(zoneList, j); if (!isA_CFString(zone)) { continue; } if (CFDictionaryGetValueIfPresent(newZones, zone, (const void **)&ifList)) { /* known zone */ newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList); } else { /* new zone */ newIFList = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } CFArrayAppendValue(newIFList, ifName); CFArraySortValues(newIFList, CFRangeMake(0, CFArrayGetCount(newIFList)), (CFComparatorFunction)CFStringCompare, NULL); CFDictionarySetValue(newZones, zone, newIFList); CFRelease(newIFList); /* * flag the default zone */ if (!primaryZone) { primaryZone = CFRetain(zone); } } if (!primaryZone) { SCLog(TRUE, LOG_NOTICE, CFSTR("AppleTalk configuration error (%@)"), kSCPropNetAppleTalkSeedZones); goto nextIF; } } /* get the (per-interface) "Computer Name" */ computerName = CFDictionaryGetValue(service, kSCPropNetAppleTalkComputerName); if (CFDictionaryGetValueIfPresent(service, kSCPropNetAppleTalkComputerNameEncoding, (const void **)&num) && isA_CFNumber(num)) { CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding); } else { computerNameEncoding = CFStringGetSystemEncoding(); } encodeName(computerName, computerNameEncoding, newStartup, newGlobals); /* * declare the first configured AppleTalk service / interface * as the "home port". */ if (CFArrayGetCount(newConfigFile) == 0) { CFStringAppend(portConfig, CFSTR("*")); primaryPort = CFRetain(ifName); } CFArrayAppendValue(newConfigFile, portConfig); /* * get the per-interface defaults */ ifDefaults = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); defaultNetwork = CFDictionaryGetValue(service, kSCPropNetAppleTalkNetworkID); defaultNode = CFDictionaryGetValue(service, kSCPropNetAppleTalkNodeID); if (isA_CFNumber(defaultNetwork) && isA_CFNumber(defaultNode)) { /* * set the default node and network */ CFDictionarySetValue(ifDefaults, kSCPropNetAppleTalkNetworkID, defaultNetwork); CFDictionarySetValue(ifDefaults, kSCPropNetAppleTalkNodeID, defaultNode); } if ((CFDictionaryGetValueIfPresent(service, kSCPropNetAppleTalkDefaultZone, (const void **)&defaultZone) == TRUE)) { /* * set the default zone for this interface */ CFDictionarySetValue(ifDefaults, kSCPropNetAppleTalkDefaultZone, defaultZone); } CFDictionarySetValue(newDefaults, ifName, ifDefaults); CFRelease(ifDefaults); switch (CFArrayGetCount(newConfigFile)) { case 1: /* * first AppleTalk interface */ CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), ifName); break; case 2: /* second AppleTalk interface */ if (!CFEqual(CFDictionaryGetValue(newStartup, CFSTR("APPLETALK")), CFSTR("-ROUTER-"))) { /* * if not routing (yet), configure as multi-home */ CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-MULTIHOME-")); } break; } if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter) || CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) { /* if not a simple node, enable routing */ CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-ROUTER-")); } /* * establish the State:/Network/Service/nnn/AppleTalk key info */ key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, CFDictionaryGetValue(service, CFSTR("ServiceID")), kSCEntNetAppleTalk); newDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(newDict, kSCPropInterfaceName, ifName); cache_SCDynamicStoreSetValue(store, key, newDict); CFRelease(newDict); if (info) { j = CFArrayGetFirstIndexOfValue(info, CFRangeMake(0, CFArrayGetCount(info)), key); if (j != kCFNotFound) { CFArrayRemoveValueAtIndex(info, j); } } CFRelease(key); nextIF : if (portConfig) CFRelease(portConfig); } if (primaryZone) { CFArrayRef ifList; CFMutableArrayRef newIFList; ifList = CFDictionaryGetValue(newZones, primaryZone); if (CFArrayContainsValue(ifList, CFRangeMake(0, CFArrayGetCount(ifList)), primaryPort)) { newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList); CFArrayAppendValue(newIFList, CFSTR("*")); CFDictionarySetValue(newZones, primaryZone, newIFList); CFRelease(newIFList); } CFRelease(primaryZone); } if (primaryPort) { CFRelease(primaryPort); } /* sort the ports */ i = CFArrayGetCount(newConfigFile); CFArraySortValues(newConfigFile, CFRangeMake(0, i), (CFComparatorFunction)CFStringCompare, NULL); /* add the zones to the configuration */ CFDictionaryApplyFunction(newZones, addZoneToPorts, newConfigFile); CFRelease(newZones); /* sort the zones */ CFArraySortValues(newConfigFile, CFRangeMake(i, CFArrayGetCount(newConfigFile)-i), (CFComparatorFunction)CFStringCompare, NULL); /* ensure that the last line of the configuration file is terminated */ CFArrayAppendValue(newConfigFile, CFSTR("")); /* * Check if we have a "ComputerName" and look elsewhere if we don't have * one yet. */ if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME")) && (setGlobals != NULL)) { computerName = CFDictionaryGetValue(setGlobals, kSCPropNetAppleTalkComputerName); if (CFDictionaryGetValueIfPresent(setGlobals, kSCPropNetAppleTalkComputerNameEncoding, (const void **)&num) && isA_CFNumber(num)) { CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding); } else { computerNameEncoding = CFStringGetSystemEncoding(); } encodeName(computerName, computerNameEncoding, newStartup, newGlobals); } if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) { computerName = SCDynamicStoreCopyComputerName(store, &computerNameEncoding); if (computerName) { encodeName(computerName, computerNameEncoding, newStartup, newGlobals); CFRelease(computerName); } } if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) { struct utsname name; if (uname(&name) == 0) { computerName = CFStringCreateWithCString(NULL, name.nodename, kCFStringEncodingASCII); if (computerName) { encodeName(computerName, kCFStringEncodingASCII, NULL, newGlobals); CFRelease(computerName); } } } /* compare the previous and current configurations */ curGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, curGlobals); CFDictionaryRemoveValue(curGlobalsX, kSCDynamicStorePropNetPrimaryService); newGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, newGlobals); CFDictionaryRemoveValue(newGlobalsX, kSCDynamicStorePropNetPrimaryService); key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetAppleTalk); if (CFEqual(curGlobalsX , newGlobalsX ) && CFEqual(curConfigFile , newConfigFile) && CFEqual(curDefaults , newDefaults ) && CFEqual(curStartup , newStartup ) ) { /* * the configuration has not changed. */ if (postGlobals) { /* * the requested configuration hasn't changed but we * now need to tell everyone that AppleTalk is active. */ if (!SCDynamicStoreSetValue(store, key, newGlobals)) { SCLog(TRUE, LOG_ERR, CFSTR("SCDynamicStoreSetValue() failed: %s"), SCErrorString(SCError())); } } CFRelease(newGlobals); CFRelease(newConfigFile); CFRelease(newDefaults); CFRelease(newStartup); } else if (CFArrayGetCount(newConfigFile) <= 1) { /* * the configuration has changed but there are no * longer any interfaces configured for AppleTalk * networking. */ /* * remove the global (State:/Network/Global/AppleTalk) key. * * Note: it will be restored later after AT networking has * been activated. */ /* remove the (/etc/appletalk.cfg) configuration file */ (void)unlink(AT_CFG_FILE); /* * update the per-service (and global) state */ cache_SCDynamicStoreRemoveValue(store, key); // remove State:/Network/Global/AppleTalk n = CFArrayGetCount(info); for (i = 0; i < n; i++) { CFStringRef xKey = CFArrayGetValueAtIndex(info, i); cache_SCDynamicStoreRemoveValue(store, xKey); } cache_write(store); /* flag this as a new configuration */ *newState = -(abs(curState) + 1); changed = TRUE; } else { /* * the configuration has changed. */ /* update the (/etc/appletalk.cfg) configuration file */ configWrite(AT_CFG_FILE, newConfigFile); /* * update the per-service (and global) state * * Note: if present, we remove any existing global state key and allow it * to be restored after the stack has been re-started. */ CFDictionaryApplyFunction(newDefaults, updateDefaults, NULL); cache_SCDynamicStoreRemoveValue(store, key); // remove State:/Network/Global/AppleTalk n = CFArrayGetCount(info); for (i = 0; i < n; i++) { CFStringRef xKey = CFArrayGetValueAtIndex(info, i); cache_SCDynamicStoreRemoveValue(store, xKey); } cache_write(store); /* flag this as a new configuration */ *newState = abs(curState) + 1; changed = TRUE; } CFRelease(curGlobalsX); CFRelease(newGlobalsX); CFRelease(key); if (changed) { CFRelease(curGlobals); curGlobals = newGlobals; CFRelease(curConfigFile); curConfigFile = newConfigFile; CFRelease(curDefaults); curDefaults = newDefaults; CFRelease(curStartup); curStartup = newStartup; } if (info) CFRelease(info); if (interfaces) CFRelease(interfaces); if (configuredServices) CFRelease(configuredServices); if (setGlobals) CFRelease(setGlobals); cache_close(); return changed; }
/* * Initializes the haptic subsystem. */ int SDL_SYS_HapticInit(void) { int numhaptics; IOReturn result; io_iterator_t iter; CFDictionaryRef match; io_service_t device; CFMutableDictionaryRef hidProperties; CFTypeRef refCF; /* Clear all the memory. */ SDL_memset(SDL_hapticlist, 0, sizeof(SDL_hapticlist)); /* Get HID devices. */ match = IOServiceMatching(kIOHIDDeviceKey); if (match == NULL) { SDL_SetError("Haptic: Failed to get IOServiceMatching."); return -1; } /* Now search I/O Registry for matching devices. */ result = IOServiceGetMatchingServices(kIOMasterPortDefault, match, &iter); if (result != kIOReturnSuccess) { SDL_SetError("Haptic: Couldn't create a HID object iterator."); return -1; } /* IOServiceGetMatchingServices consumes dictionary. */ if (!IOIteratorIsValid(iter)) { /* No iterator. */ numhaptics = 0; return 0; } numhaptics = 0; while ((device = IOIteratorNext(iter)) != IO_OBJECT_NULL) { /* Check for force feedback. */ if (FFIsForceFeedback(device) == FF_OK) { /* Set basic device data. */ HIDGetDeviceProduct(device, SDL_hapticlist[numhaptics].name); SDL_hapticlist[numhaptics].dev = device; SDL_hapticlist[numhaptics].haptic = NULL; /* Set usage pages. */ hidProperties = 0; refCF = 0; result = IORegistryEntryCreateCFProperties(device, &hidProperties, kCFAllocatorDefault, kNilOptions); if ((result == KERN_SUCCESS) && hidProperties) { refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey)); if (refCF) { if (!CFNumberGetValue(refCF, kCFNumberLongType, &SDL_hapticlist[numhaptics]. usagePage)) SDL_SetError ("Haptic: Recieving device's usage page."); refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsageKey)); if (refCF) { if (!CFNumberGetValue(refCF, kCFNumberLongType, &SDL_hapticlist[numhaptics]. usage)) SDL_SetError("Haptic: Recieving device's usage."); } } CFRelease(hidProperties); } /* Device has been added. */ numhaptics++; } else { /* Free the unused device. */ IOObjectRelease(device); } /* Reached haptic limit. */ if (numhaptics >= MAX_HAPTICS) break; } IOObjectRelease(iter); return numhaptics; }
char * _mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert) { CFTypeRef value; bson_string_t *retval; CFTypeRef subject_name; CFDictionaryRef cert_dict; cert_dict = SecCertificateCopyValues (cert, NULL, NULL); if (!cert_dict) { return NULL; } subject_name = CFDictionaryGetValue (cert_dict, kSecOIDX509V1SubjectName); if (!subject_name) { CFRelease (cert_dict); return NULL; } subject_name = CFDictionaryGetValue (subject_name, kSecPropertyKeyValue); if (!subject_name) { CFRelease (cert_dict); return NULL; } retval = bson_string_new ("");; value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCommonName); _bson_append_cftyperef (retval, "CN=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationalUnitName); if (value) { /* Can be either one unit name, or array of unit names */ if (CFGetTypeID(value) == CFStringGetTypeID()) { _bson_append_cftyperef (retval, ",OU=", value); } else if (CFGetTypeID(value) == CFArrayGetTypeID()) { CFIndex len = CFArrayGetCount(value); if (len > 0) { _bson_append_cftyperef (retval, ",OU=", CFArrayGetValueAtIndex(value, 0)); } if (len > 1) { _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex(value, 1)); } if (len > 2) { _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex(value, 2)); } } } value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName); _bson_append_cftyperef (retval, ",O=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName); _bson_append_cftyperef (retval, ",L=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStateProvinceName); _bson_append_cftyperef (retval, ",ST=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCountryName); _bson_append_cftyperef (retval, ",C=", value); /* This seems rarely used */ value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress); _bson_append_cftyperef (retval, ",STREET", value); CFRelease (cert_dict); return bson_string_free (retval, false); }
bool PluginPackage::fetchInfo() { if (!load()) return false; WTF::RetainPtr<CFDictionaryRef> mimeDict; WTF::RetainPtr<CFTypeRef> mimeTypesFileName = CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypesFilename")); if (mimeTypesFileName && CFGetTypeID(mimeTypesFileName.get()) == CFStringGetTypeID()) { WTF::RetainPtr<CFStringRef> fileName = (CFStringRef)mimeTypesFileName.get(); WTF::RetainPtr<CFStringRef> homeDir = homeDirectoryPath().createCFString(); WTF::RetainPtr<CFStringRef> path = CFStringCreateWithFormat(0, 0, CFSTR("%@/Library/Preferences/%@"), homeDir.get(), fileName.get()); WTF::RetainPtr<CFDictionaryRef> plist = readPListFile(path.get(), /*createFile*/ false, m_module); if (plist) { // If the plist isn't localized, have the plug-in recreate it in the preferred language. WTF::RetainPtr<CFStringRef> localizationName = (CFStringRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginLocalizationName")); CFLocaleRef locale = CFLocaleCopyCurrent(); if (localizationName != CFLocaleGetIdentifier(locale)) plist = readPListFile(path.get(), /*createFile*/ true, m_module); CFRelease(locale); } else { // Plist doesn't exist, ask the plug-in to create it. plist = readPListFile(path.get(), /*createFile*/ true, m_module); } if (plist) mimeDict = (CFDictionaryRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginMIMETypes")); } if (!mimeDict) mimeDict = (CFDictionaryRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypes")); if (mimeDict) { CFIndex propCount = CFDictionaryGetCount(mimeDict.get()); Vector<const void*, 128> keys(propCount); Vector<const void*, 128> values(propCount); CFDictionaryGetKeysAndValues(mimeDict.get(), keys.data(), values.data()); for (int i = 0; i < propCount; ++i) { String mimeType = (CFStringRef)keys[i]; mimeType = mimeType.lower(); WTF::RetainPtr<CFDictionaryRef> extensionsDict = (CFDictionaryRef)values[i]; WTF::RetainPtr<CFNumberRef> enabled = (CFNumberRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeEnabled")); if (enabled) { int enabledValue = 0; if (CFNumberGetValue(enabled.get(), kCFNumberIntType, &enabledValue) && enabledValue == 0) continue; } Vector<String> mimeExtensions; WTF::RetainPtr<CFArrayRef> extensions = (CFArrayRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginExtensions")); if (extensions) { CFIndex extensionCount = CFArrayGetCount(extensions.get()); for (CFIndex i = 0; i < extensionCount; ++i) { String extension =(CFStringRef)CFArrayGetValueAtIndex(extensions.get(), i); extension = extension.lower(); mimeExtensions.append(extension); } } m_mimeToExtensions.set(mimeType, mimeExtensions); String description = (CFStringRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeDescription")); m_mimeToDescriptions.set(mimeType, description); } m_name = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginName")); m_description = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginDescription")); } else { int resFile = CFBundleOpenBundleResourceMap(m_module); UseResFile(resFile); Vector<String> mimes = stringListFromResourceId(MIMEListStringStringNumber); if (mimes.size() % 2 != 0) return false; Vector<String> descriptions = stringListFromResourceId(MIMEDescriptionStringNumber); if (descriptions.size() != mimes.size() / 2) return false; for (size_t i = 0; i < mimes.size(); i += 2) { String mime = mimes[i].lower(); Vector<String> extensions; mimes[i + 1].lower().split(UChar(','), extensions); m_mimeToExtensions.set(mime, extensions); m_mimeToDescriptions.set(mime, descriptions[i / 2]); } Vector<String> names = stringListFromResourceId(PluginNameOrDescriptionStringNumber); if (names.size() == 2) { m_description = names[0]; m_name = names[1]; } CFBundleCloseBundleResourceMap(m_module, resFile); } LOG(Plugins, "PluginPackage::fetchInfo(): Found plug-in '%s'", m_name.utf8().data()); if (isPluginBlacklisted()) { LOG(Plugins, "\tPlug-in is blacklisted!"); return false; } return true; }
static void h264_enc_process(MSFilter *f) { VTH264EncCtx *ctx = (VTH264EncCtx *)f->data; mblk_t *frame; OSStatus err; CMTime p_time = CMTimeMake(f->ticker->time, 1000); if(!ctx->is_configured) { ms_queue_flush(f->inputs[0]); return; } #if 0 && TARGET_OS_IPHONE CVPixelBufferPoolRef pixbuf_pool = VTCompressionSessionGetPixelBufferPool(ctx->session); if(pixbuf_pool == NULL) { ms_error("VideoToolbox: fails to get the pixel buffer pool"); return; } #endif while((frame = ms_queue_get(f->inputs[0]))) { YuvBuf src_yuv_frame, dst_yuv_frame = {0}; CVPixelBufferRef pixbuf; CFMutableDictionaryRef enc_param = NULL; int i, pixbuf_fmt = kCVPixelFormatType_420YpCbCr8Planar; CFNumberRef value; CFMutableDictionaryRef pixbuf_attr; ms_yuv_buf_init_from_mblk(&src_yuv_frame, frame); #if 0 && TARGET_OS_IPHONE CVPixelBufferPoolCreatePixelBuffer(NULL, pixbuf_pool, &pixbuf); #else pixbuf_attr = CFDictionaryCreateMutable(NULL, 0, NULL, NULL); value = CFNumberCreate(NULL, kCFNumberIntType, &pixbuf_fmt); CFDictionarySetValue(pixbuf_attr, kCVPixelBufferPixelFormatTypeKey, value); CVPixelBufferCreate(NULL, ctx->conf.vsize.width, ctx->conf.vsize.height, kCVPixelFormatType_420YpCbCr8Planar, pixbuf_attr, &pixbuf); CFRelease(pixbuf_attr); #endif CVPixelBufferLockBaseAddress(pixbuf, 0); dst_yuv_frame.w = (int)CVPixelBufferGetWidth(pixbuf); dst_yuv_frame.h = (int)CVPixelBufferGetHeight(pixbuf); for(i=0; i<3; i++) { dst_yuv_frame.planes[i] = CVPixelBufferGetBaseAddressOfPlane(pixbuf, i); dst_yuv_frame.strides[i] = (int)CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i); } ms_yuv_buf_copy(src_yuv_frame.planes, src_yuv_frame.strides, dst_yuv_frame.planes, dst_yuv_frame.strides, (MSVideoSize){dst_yuv_frame.w, dst_yuv_frame.h}); CVPixelBufferUnlockBaseAddress(pixbuf, 0); freemsg(frame); ms_filter_lock(f); if(ctx->fps_changed || ctx->bitrate_changed || ctx->vfu_requested) { CFNumberRef value; enc_param = CFDictionaryCreateMutable(NULL, 0, NULL, NULL); if(ctx->fps_changed) { value = CFNumberCreate(NULL, kCFNumberFloatType, &ctx->conf.fps); CFDictionaryAddValue(enc_param, kVTCompressionPropertyKey_ExpectedFrameRate, value); ctx->fps_changed = FALSE; } if(ctx->bitrate_changed) { value = CFNumberCreate(NULL, kCFNumberIntType, &ctx->conf.required_bitrate); CFDictionaryAddValue(enc_param, kVTCompressionPropertyKey_AverageBitRate, value); ctx->bitrate_changed = FALSE; } if(ctx->vfu_requested) { int force_keyframe = 1; value = CFNumberCreate(NULL, kCFNumberIntType, &force_keyframe); CFDictionaryAddValue(enc_param, kVTEncodeFrameOptionKey_ForceKeyFrame, value); ctx->vfu_requested = FALSE; } } ms_filter_unlock(f); if(!ctx->enable_avpf) { if(ctx->first_frame) { ms_video_starter_first_frame(&ctx->starter, f->ticker->time); } if(ms_video_starter_need_i_frame(&ctx->starter, f->ticker->time)) { if(enc_param == NULL) enc_param = CFDictionaryCreateMutable(NULL, 0, NULL, NULL); if(CFDictionaryGetValue(enc_param, kVTEncodeFrameOptionKey_ForceKeyFrame) == NULL) { int force_keyframe = 1; CFNumberRef value = CFNumberCreate(NULL, kCFNumberIntType, &force_keyframe); CFDictionaryAddValue(enc_param, kVTEncodeFrameOptionKey_ForceKeyFrame, value); } } } if((err = VTCompressionSessionEncodeFrame(ctx->session, pixbuf, p_time, kCMTimeInvalid, enc_param, NULL, NULL)) != noErr) { ms_error("VideoToolbox: could not pass a pixbuf to the encoder: error code %d", err); } CFRelease(pixbuf); ctx->first_frame = FALSE; if(enc_param) CFRelease(enc_param); } ms_mutex_lock(&ctx->mutex); while ((frame = ms_queue_get(&ctx->queue))) { ms_mutex_unlock(&ctx->mutex); ms_queue_put(f->outputs[0], frame); ms_mutex_lock(&ctx->mutex); } ms_mutex_unlock(&ctx->mutex); }
// ---------------------------------------------------------------------------- // wxHIDDevice::Create // // nClass is the HID Page such as // kHIDPage_GenericDesktop // nType is the HID Usage such as // kHIDUsage_GD_Joystick,kHIDUsage_GD_Mouse,kHIDUsage_GD_Keyboard // nDev is the device number to use // // ---------------------------------------------------------------------------- bool wxHIDDevice::Create (int nClass, int nType, int nDev) { //Create the mach port if(IOMasterPort(bootstrap_port, &m_pPort) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create mach port")); return false; } //Dictionary that will hold first //the matching dictionary for determining which kind of devices we want, //then later some registry properties from an iterator (see below) // //The call to IOServiceMatching filters down the //the services we want to hid services (and also eats the //dictionary up for us (consumes one reference)) CFMutableDictionaryRef pDictionary = IOServiceMatching(kIOHIDDeviceKey); if(pDictionary == NULL) { wxLogSysError( _T("IOServiceMatching(kIOHIDDeviceKey) failed") ); return false; } //Here we'll filter down the services to what we want if (nType != -1) { CFNumberRef pType = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nType); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsageKey), pType); CFRelease(pType); } if (nClass != -1) { CFNumberRef pClass = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nClass); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsagePageKey), pClass); CFRelease(pClass); } //Now get the maching services io_iterator_t pIterator; if( IOServiceGetMatchingServices(m_pPort, pDictionary, &pIterator) != kIOReturnSuccess ) { wxLogSysError(_T("No Matching HID Services")); return false; } //Were there any devices matched? if(pIterator == 0) return false; // No devices found //Now we iterate through them io_object_t pObject; while ( (pObject = IOIteratorNext(pIterator)) != 0) { if(--nDev != 0) { IOObjectRelease(pObject); continue; } if ( IORegistryEntryCreateCFProperties ( pObject, &pDictionary, kCFAllocatorDefault, kNilOptions ) != KERN_SUCCESS ) { wxLogDebug(_T("IORegistryEntryCreateCFProperties failed")); } // // Now we get the attributes of each "product" in the iterator // //Get [product] name CFStringRef cfsProduct = (CFStringRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductKey)); m_szProductName = wxCFStringRef( wxCFRetain(cfsProduct) ).AsString(); //Get the Product ID Key CFNumberRef cfnProductId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductIDKey)); if (cfnProductId) { CFNumberGetValue(cfnProductId, kCFNumberIntType, &m_nProductId); } //Get the Vendor ID Key CFNumberRef cfnVendorId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDVendorIDKey)); if (cfnVendorId) { CFNumberGetValue(cfnVendorId, kCFNumberIntType, &m_nManufacturerId); } // // End attribute getting // //Create the interface (good grief - long function names!) SInt32 nScore; IOCFPlugInInterface** ppPlugin; if(IOCreatePlugInInterfaceForService(pObject, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &ppPlugin, &nScore) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create HID Interface for product")); return false; } //Now, the final thing we can check before we fall back to asserts //(because the dtor only checks if the device is ok, so if anything //fails from now on the dtor will delete the device anyway, so we can't break from this). //Get the HID interface from the plugin to the mach port if((*ppPlugin)->QueryInterface(ppPlugin, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void**) &m_ppDevice) != S_OK) { wxLogSysError(wxT("Could not get device interface from HID interface")); return false; } //release the plugin (*ppPlugin)->Release(ppPlugin); //open the HID interface... if ( (*m_ppDevice)->open(m_ppDevice, 0) != S_OK ) wxLogDebug(_T("HID device: open failed")); // //Now the hard part - in order to scan things we need "cookies" // CFArrayRef cfaCookies = (CFArrayRef)CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDElementKey)); BuildCookies(cfaCookies); //cleanup CFRelease(pDictionary); IOObjectRelease(pObject); //iterator cleanup IOObjectRelease(pIterator); return true; } //iterator cleanup IOObjectRelease(pIterator); return false; //no device }//end Create()
// // Executable code. // Read from disk, evaluate properly, cache as indicated. The whole thing, so far. // void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result, bool handleUnsignedCode /* = true */) { FileQuarantine qtn(cfString(path).c_str()); if (qtn.flag(QTN_FLAG_HARD)) MacOSError::throwMe(errSecCSFileHardQuarantined); CFRef<SecStaticCodeRef> code; MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref())); OSStatus rc = noErr; // last validation error const SecCSFlags validationFlags = kSecCSEnforceRevocationChecks; WhitelistPrescreen whitelistScreen(code); // pre-screening filter for whitelist pre-screening (only) SQLite::Statement query(*this, "SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority" " WHERE type = :type" " ORDER BY priority DESC;"); query.bind(":type").integer(type); SQLite3::int64 latentID = 0; // first (highest priority) disabled matching ID std::string latentLabel; // ... and associated label, if any while (query.nextRow()) { bool allow = int(query[0]); const char *reqString = query[1]; SQLite3::int64 id = query[2]; const char *label = query[3]; double expires = query[4]; sqlite3_int64 ruleFlags = query[5]; SQLite3::int64 disabled = query[6]; const char *filter = query[7]; const char *remarks = query[8]; CFRef<SecRequirementRef> requirement; MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref())); rc = SecStaticCodeCheckValidity(code, validationFlags, requirement); // ad-hoc sign unsigned code, skip of Gatekeeper is off or the rule is disabled; but always do it for whitelist recording if (rc == errSecCSUnsigned && handleUnsignedCode && (!(disabled || overrideAssessment()) || SYSPOLICY_RECORDER_MODE_ENABLED())) { if (!SYSPOLICY_RECORDER_MODE_ENABLED()) { // apply whitelist pre-screening to speed things up for non-matches if (ruleFlags & kAuthorityFlagDefault) // can't ever match standard rules with unsigned code continue; if (whitelistScreen.reject(filter, remarks)) // apply whitelist pre-filter continue; } try { // ad-hoc sign the code and attach the signature CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0); CFTemp<CFDictionaryRef> arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity); CFRef<SecCodeSignerRef> signer; MacOSError::check(SecCodeSignerCreate(arguments, kSecCSDefaultFlags, &signer.aref())); MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags)); MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags)); // if we're in GKE recording mode, save that signature and report its location if (SYSPOLICY_RECORDER_MODE_ENABLED()) { int status = recorder_code_unable; // ephemeral signature (not recorded) if (geteuid() == 0) { CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL); std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig"; try { UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT); fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature)); status = recorder_code_adhoc; // recorded signature SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str()); } catch (...) { } } // now report the D probe itself CFRef<CFDictionaryRef> info; MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref())); CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "", cdhash ? CFDataGetBytePtr(cdhash) : NULL, status); } // rerun the validation to update state rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, requirement); } catch (...) { } } switch (rc) { case noErr: // well signed and satisfies requirement... break; // ... continue below case errSecCSSignatureFailed: if (!codeInvalidityExceptions(code, result)) { if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED()) SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false); MacOSError::throwMe(rc); } if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED()) SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true); // treat as unsigned to fix problems in the field case errSecCSUnsigned: if (handleUnsignedCode) { cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); addAuthority(result, "no usable signature"); } return; case errSecCSReqFailed: // requirement missed, but otherwise okay continue; default: // broken in some way; all tests will fail like this so bail out MacOSError::throwMe(rc); } if (disabled) { if (latentID == 0) { latentID = id; if (label) latentLabel = label; } continue; // the loop } CFRef<CFDictionaryRef> info; // as needed if (flags & kSecAssessmentFlagRequestOrigin) { if (!info) MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates))) setOrigin(chain, result); } if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) { // cache inhibit if (!info) MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) { CFRef<CFDictionaryRef> xinfo; MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref())); if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) { this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id); } } } if (allow) { if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) { if (!info) MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL); } } else { if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) { if (!info) MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); std::string cpath = cfString(path); const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL; SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp); SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted); } } cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow); addAuthority(result, label, id); return; } if (rc == errSecCSUnsigned) { // skipped all applicable rules due to pre-screening cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); addAuthority(result, "no usable signature"); return; } // no applicable authority (but signed, perhaps temporarily). Deny by default CFRef<CFDictionaryRef> info; MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); if (flags & kSecAssessmentFlagRequestOrigin) { if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates))) setOrigin(chain, result); } if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) { CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL; std::string cpath = cfString(path); SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp); SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0); } if (!(flags & kSecAssessmentFlagNoCache)) this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID); cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false); addAuthority(result, latentLabel.c_str(), latentID); }
ProcessSerialNumber getPSNFromDict(CFDictionaryRef pDict) { ProcessSerialNumber psn; CFNumberGetValue(CFDictionaryGetValue(pDict,CFSTR("PSNLow")),kCFNumberSInt32Type,&(psn.lowLongOfPSN)); CFNumberGetValue(CFDictionaryGetValue(pDict,CFSTR("PSNHigh")),kCFNumberSInt32Type,&(psn.highLongOfPSN)); return psn; }
int main(int argc, const char * argv[]) { setbuf (stdout, NULL); #if TARGET_OS_MAC { thread_extended_policy_data_t theFixedPolicy; theFixedPolicy.timeshare = false; // set to true for a non-fixed thread thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT); // We keep a reference to the spawning thread's priority around (initialized in the constructor), // and set the importance of the child thread relative to the spawning thread's priority. thread_precedence_policy_data_t thePrecedencePolicy; thePrecedencePolicy.importance = 63 - 36; thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT); } #endif // These are the variables that are set up from the input parsing char* srcFilePath = NULL; char* destFilePath = NULL; char* auPresetFile = NULL; bool shortMemoryProfile = false; OSType manu, subType, type = 0; int userSetFrames = -1; for (int i = 1; i < argc; ++i) { if (strcmp (argv[i], "-au") == 0) { if ( (i + 3) < argc ) { StrToOSType (argv[i + 1], type); StrToOSType (argv[i + 2], subType); StrToOSType (argv[i + 3], manu); i += 3; } else { printf ("Which Audio Unit:\n%s", usageStr); exit(1); } } else if (strcmp (argv[i], "-i") == 0) { srcFilePath = const_cast<char*>(argv[++i]); } else if (strcmp (argv[i], "-o") == 0) { destFilePath = const_cast<char*>(argv[++i]); } else if (strcmp (argv[i], "-p") == 0) { auPresetFile = const_cast<char*>(argv[++i]); } else if (strcmp (argv[i], "-m") == 0) { shortMemoryProfile = true; } else if (strcmp (argv[i], "-f") == 0) { sscanf(argv[++i], "%d", &userSetFrames); } else { printf ("%s\n", usageStr); exit(1); } } if (!type || !srcFilePath) { printf ("%s\n", usageStr); exit(1); } if (!destFilePath) { if (!shortMemoryProfile) { printf ("%s\n", usageStr); exit(1); } } // delete pre-existing output file if (!shortMemoryProfile) { FSRef destFSRef; if (FSPathMakeRef((UInt8 *)destFilePath, &destFSRef, NULL) == noErr) { // output file exists - delete it if (FSDeleteObject(&destFSRef)) { printf ("Cannot Delete Output File\n"); exit(1); } } } CAComponentDescription desc(type, subType, manu); CFPropertyListRef presetDict = ReadPresetFromPresetFile(auPresetFile); // the num of frames to use when processing the file with the Render call UInt32 maxFramesToUse = shortMemoryProfile ? 512 : 32768; // not set from command line if (userSetFrames > 0) { maxFramesToUse = userSetFrames; } // in some settings (for instance a delay with 100% feedback) tail time is essentially infinite // so you should safeguard the final OL render stage (post process) which is aimed at pulling the tail through // if you want to bypass this completely, just set this to zero. Float64 maxTailTimeSecs = 10.; #pragma mark - #pragma mark __ The driving code #pragma mark - try { CAComponent comp(desc); // CAAUProcessor's constructor throws... so make sure the component is valid if (comp.IsValid() == false) { printf ("Can't Find Component\n"); desc.Print(); exit(1); } CAAUProcessor processor(comp); processor.AU().Print(); CAAudioFile srcFile; CAAudioFile destFile; srcFile.Open(srcFilePath); CAStreamBasicDescription procFormat (srcFile.GetFileDataFormat()); procFormat.SetCanonical (srcFile.GetFileDataFormat().NumberChannels(), false); printf ("Processing Format:\n\t"); procFormat.Print(); if (!shortMemoryProfile) { FSRef parentDir; CFStringRef filename; PosixPathToParentFSRefAndName(destFilePath, parentDir, filename); destFile.CreateNew (parentDir, filename, 'AIFF', srcFile.GetFileDataFormat()); destFile.SetClientFormat (procFormat); } srcFile.SetClientFormat (procFormat); AUOutputBL outputList(procFormat); ReadBuffer* readBuf = NULL; #if !CAAF_USE_EXTAUDIOFILE UInt64 numInputSamples = srcFile.GetNumberPackets(); #else UInt64 numInputSamples = srcFile.GetNumberFrames(); #endif if (shortMemoryProfile) { readBuf = new ReadBuffer; readBuf->readData = new AUOutputBL(procFormat); readBuf->readFrames = 0; UInt32 numFrames = UInt32(procFormat.mSampleRate / 2); readBuf->readData->Allocate (numFrames); // half a second of audio data readBuf->readData->Prepare(); // half a second of audio data // read 1/2 second of audio into this read buffer srcFile.Read (numFrames, readBuf->readData->ABL()); sInputCallback.inputProc = MemoryInputCallback; sInputCallback.inputProcRefCon = readBuf; numInputSamples = numFrames; } else { if (desc.IsFConv()) { maxFramesToUse = userSetFrames == -1 ? 512 : maxFramesToUse; // some format converter's can call you several times in small granularities // so you can't use a large buffer to render or you won't return all of the input data // this also lessens the final difference between what you should get and what you do // converter units *really* should have a version that are offline AU's to // handle this for you. sInputCallback.inputProc = FConvInputCallback; } else sInputCallback.inputProc = InputCallback; sInputCallback.inputProcRefCon = &srcFile; } OSStatus result; require_noerr (result = processor.EstablishInputCallback (sInputCallback), home); require_noerr (result = processor.SetMaxFramesPerRender (maxFramesToUse), home); processor.SetMaxTailTime (maxTailTimeSecs); require_noerr (result = processor.Initialize (procFormat, numInputSamples), home); if (presetDict) { require_noerr (result = processor.SetAUPreset (presetDict), home); CFRelease (presetDict); } // this does ALL of the preflighting.. could be specialise for an OfflineAU type // to do this piecemeal and do a progress bar by using the OfflineAUPreflight method require_noerr (result = processor.Preflight (), home); bool isDone; isDone = false; bool needsPostProcessing; bool isSilence; UInt32 numFrames; numFrames = processor.MaxFramesPerRender(); #if CA_AU_PROFILE_TIME sReadTime = 0; sRenderTime = 0; #endif PRINT_MARKS(); // this is the render loop while (!isDone) { #if CA_AU_PROFILE_TIME UInt64 now = CAHostTimeBase::GetTheCurrentTime(); #endif outputList.Prepare(); // have to do this every time... require_noerr (result = processor.Render (outputList.ABL(), numFrames, isSilence, &isDone, &needsPostProcessing), home); #if CA_AU_PROFILE_TIME sRenderTime += (CAHostTimeBase::GetTheCurrentTime() - now); #endif if (!shortMemoryProfile) PRINT_PROGRESS(processor.GetOLPercentComplete()); else PRINT_PROGRESS(((processor.SampleTime() / numInputSamples) * 100.)); if (numFrames && !shortMemoryProfile) destFile.Write (numFrames, outputList.ABL()); } // this is the postprocessing if needed if (!shortMemoryProfile && needsPostProcessing) { isDone = false; numFrames = processor.MaxFramesPerRender(); while (!isDone) { outputList.Prepare(); // have to do this every time... #if CA_AU_PROFILE_TIME UInt64 now = CAHostTimeBase::GetTheCurrentTime(); #endif require_noerr (result = processor.PostProcess (outputList.ABL(), numFrames, isSilence, isDone), home); #if CA_AU_PROFILE_TIME sRenderTime += (CAHostTimeBase::GetTheCurrentTime() - now); #endif PRINT_PROGRESS(processor.GetOLPercentComplete()); if (numFrames && !shortMemoryProfile) destFile.Write (numFrames, outputList.ABL()); } } printf ("\n"); home: if (result) { printf ("Exit with bad result:%ld\n", result); exit(result); } if (readBuf) { delete readBuf->readData; delete readBuf; } #if CA_AU_PROFILE_TIME if (!shortMemoryProfile) { // this flushes any remaing data to be written to the disk. // the source file is closed in its destructor of course destFile.Close(); // open the file again, to get stats about it for profiling destFile.Open(destFilePath); } SInt64 numWritten; if (shortMemoryProfile) numWritten = 0; else { #if !CAAF_USE_EXTAUDIOFILE numWritten = destFile.GetNumberPackets(); #else numWritten = destFile.GetNumberFrames(); #endif } printf ("Read File Time:%.2f secs for %lld packets (%.1f secs), wrote %lld packets\n", (CAHostTimeBase::ConvertToNanos (sReadTime) / 1.0e9), numInputSamples, (numInputSamples / procFormat.mSampleRate), numWritten); if (!shortMemoryProfile) { #if !CAAF_USE_EXTAUDIOFILE UInt64 numOutputSamples = destFile.GetNumberPackets(); #else UInt64 numOutputSamples = destFile.GetNumberFrames(); #endif if (numOutputSamples == numInputSamples) { printf ("\tWrote the same number of packets as read\n"); } else { bool expectationMet = !desc.IsOffline(); // we don't have any expectations for offline AU's if (processor.LatencySampleCount() || processor.TailSampleCount()) { if (numOutputSamples - numInputSamples == processor.TailSampleCount()) expectationMet = true; if (expectationMet) printf ("Correctly wrote \'Read Size + Tail\'. "); printf ("AU reports (samples): %ld latency, %ld tail\n", processor.LatencySampleCount(), processor.TailSampleCount()); } if (expectationMet == false) { if (numOutputSamples > numInputSamples) { printf ("\tWrote %lld packets (%.2f secs) more than read\n", (numOutputSamples - numInputSamples), ((numOutputSamples - numInputSamples) / procFormat.mSampleRate)); } else { printf ("\tRead %lld packets (%.2f secs) more than wrote\n", (numInputSamples - numOutputSamples), ((numInputSamples - numOutputSamples) / procFormat.mSampleRate)); } } } } Float64 renderTimeSecs = CAHostTimeBase::ConvertToNanos (sRenderTime - sReadTime) / 1.0e9; printf ("Total Render Time:%.2f secs, using render slice size of %ld frames\n", renderTimeSecs, maxFramesToUse); Float64 cpuUsage; if (shortMemoryProfile) cpuUsage = (renderTimeSecs / 0.5) * 100.; else cpuUsage = (renderTimeSecs / (numInputSamples / procFormat.mSampleRate)) * 100.; printf ("CPU Usage for Render Time:%.2f%%\n", cpuUsage); CFStringRef str = comp.GetCompName(); UInt32 compNameLen = CFStringGetLength (str); CFStringRef presetName = NULL; if (auPresetFile) { CFPropertyListRef dict; if (processor.AU().GetAUPreset (dict) == noErr) { presetName = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)dict, CFSTR("name")); CFRelease (dict); } } UInt32 presetLen = presetName ? CFStringGetLength(presetName) : 0; char* cstr = (char*)malloc (compNameLen + presetLen + 2 + 1); CFStringGetCString (str, cstr, (CFStringGetLength (str) + 1), kCFStringEncodingASCII); if (presetName) { cstr[compNameLen] = ':'; cstr[compNameLen+1] = ':'; CFStringGetCString (presetName, cstr + compNameLen + 2, (CFStringGetLength (presetName) + 1), kCFStringEncodingASCII); } PerfResult("AudioUnitProcess", EndianU32_NtoB(comp.Desc().componentSubType), cstr, cpuUsage, "%realtime"); free (cstr); #endif } catch (CAXException &e) { char buf[256]; printf("Error: %s (%s)\n", e.mOperation, e.FormatError(buf)); exit(1); } catch (...) { printf("An unknown error occurred\n"); exit(1); } return 0; }