// Utility functions CFStringRef diff_CFStringCreateFromUnichar(UniChar ch) { CFStringRef c = CFStringCreateWithCharacters(kCFAllocatorDefault, &ch, 1); return c; }
QStringList Q3FileDialog::macGetOpenFileNames(const QString &filter, QString *pwd, QWidget *parent, const char* /*name*/, const QString& caption, QString *selectedFilter, bool multi, bool directory) { OSErr err; QStringList retstrl; NavDialogCreationOptions options; NavGetDefaultDialogCreationOptions(&options); options.modality = kWindowModalityAppModal; options.optionFlags |= kNavDontConfirmReplacement | kNavSupportPackages; if (!multi) options.optionFlags &= ~kNavAllowMultipleFiles; if(!caption.isEmpty()) options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(), caption.length()); static const int w = 450, h = 350; options.location.h = options.location.v = -1; if(parent && parent->isVisible()) { Qt::WindowType wt = parent->window()->windowType(); if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) { options.modality = kWindowModalityWindowModal; options.parentWindow = qt_mac_window_for(parent); } else { parent = parent->window(); QString s = parent->windowTitle(); options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length()); options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2); options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2); QRect r = QApplication::desktop()->screenGeometry( QApplication::desktop()->screenNumber(parent)); if(options.location.h + w > r.right()) options.location.h -= (options.location.h + w) - r.right() + 10; if(options.location.v + h > r.bottom()) options.location.v -= (options.location.v + h) - r.bottom() + 10; } } else if(QWidget *p = qApp->mainWidget()) { static int last_screen = -1; int scr = QApplication::desktop()->screenNumber(p); if(last_screen != scr) { QRect r = QApplication::desktop()->screenGeometry(scr); options.location.h = (r.x() + (r.width() / 2)) - (w / 2); options.location.v = (r.y() + (r.height() / 2)) - (h / 2); } } QList<qt_mac_filter_name*> filts = makeFiltersList(filter); qt_mac_nav_filter_type t; t.index = 0; t.filts = &filts; if(filts.count() > 1) { int i = 0; CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count()); for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) { QString rg = (*it)->description; arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length()); } options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL); } NavDialogRef dlg; if(directory) { if(NavCreateChooseFolderDialog(&options, make_navProcUPP(), NULL, NULL, &dlg)) { qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__); return retstrl; } } else { if(NavCreateGetFileDialog(&options, NULL, make_navProcUPP(), NULL, make_navFilterUPP(), (void *) (filts.isEmpty() ? NULL : &t), &dlg)) { qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__); return retstrl; } } if(pwd && !pwd->isEmpty()) { FSRef fsref; if(qt_mac_create_fsref(*pwd, &fsref) == noErr) { AEDesc desc; if(AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr) NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc); } } NavDialogRun(dlg); if (selectedFilter) { NavMenuItemSpec navSpec; bzero(&navSpec, sizeof(NavMenuItemSpec)); qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0); for (int i = 0; i < filts.count(); ++i) { const qt_mac_filter_name *filter = filts.at(i); if (sel_filt_name->description == filter->description && sel_filt_name->regxp == filter->regxp && sel_filt_name->filter == filter->filter) { navSpec.menuType = i; break; } } NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec); } if(options.modality == kWindowModalityWindowModal) { //simulate modality QWidget modal_widg(parent, __FILE__ "__modal_dlg", Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder); modal_widg.createWinId(); QApplicationPrivate::enterModal(&modal_widg); while(g_nav_blocking) qApp->processEvents(QEventLoop::WaitForMoreEvents); QApplicationPrivate::leaveModal(&modal_widg); } if(!(NavDialogGetUserAction(dlg) & (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) { NavDialogDispose(dlg); return retstrl; } NavReplyRecord ret; NavDialogGetReply(dlg, &ret); NavDialogDispose(dlg); long count; err = AECountItems(&(ret.selection), &count); if(!ret.validRecord || err != noErr || !count) { NavDisposeReply(&ret); return retstrl; } for(long index = 1; index <= count; index++) { FSRef ref; err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0); if(err != noErr) break; if(!str_buffer) { qAddPostRoutine(cleanup_str_buffer); str_buffer = (UInt8 *)malloc(1024); } FSRefMakePath(&ref, str_buffer, 1024); retstrl.append(QString::fromUtf8((const char *)str_buffer)); } NavDisposeReply(&ret); if(selectedFilter) *selectedFilter = filts.at(t.index)->filter; while (!filts.isEmpty()) delete filts.takeFirst(); return retstrl; }
void TTFoundationLoadExternalClassesFromFolder(const TTString& fullpath) { #ifdef TT_PLATFORM_MAC FSRef ref; Boolean isDirectory; OSStatus status = noErr; ItemCount count = 0; FSIterator iterator; HFSUniStr255* names = NULL; CFStringRef name; char cname[4096]; TTString path; TTCString cpath = (char*)fullpath.c_str(); void* handle; TTExtensionInitializationMethod initializer; TTErr err; status = FSPathMakeRef((UInt8*)cpath, &ref, &isDirectory); if (status != noErr) { #ifdef TT_DEBUG TTLogMessage("TTFoundation - no extensions location found @ %s\n", cpath); #endif return; } status = FSOpenIterator(&ref, kFSIterateFlat, &iterator); if (!status) { names = (HFSUniStr255 *)malloc(sizeof(HFSUniStr255) * 4096); if (names) { // Request information about files in the given directory, // until we get a status code back from the File Manager do{ status = FSGetCatalogInfoBulk(iterator, 4096, &count, NULL, kFSCatInfoNone, NULL, NULL, NULL, names); // Process all items received if (status == OSStatus(noErr) || status == OSStatus(errFSNoMoreItems)) { for (UInt32 i=0; i < count; i += 1) { name = CFStringCreateWithCharacters(kCFAllocatorDefault, names[i].unicode, names[i].length); // TODO: filter on name. We only want to try and load .ttdylib files CFStringGetCString(name, cname, 4096, kCFStringEncodingUTF8); path = fullpath; path += "/"; path += cname; handle = dlopen(path.c_str(), RTLD_LAZY); // TODO: assert -- or at least do a log post -- if handle is NULL initializer = (TTExtensionInitializationMethod)dlsym(handle, "loadTTExtension"); if (initializer) err = initializer(); CFRelease(name); } } } while (status == OSStatus(noErr)); // errFSNoMoreItems tells us we have successfully processed all // items in the directory -- not really an error if (status == OSStatus(errFSNoMoreItems)) status = noErr; // Free the array memory free( (void *) names ); } FSCloseIterator(iterator); } #elif TT_PLATFORM_WIN HANDLE fdHandle; WIN32_FIND_DATA findFileData; TTString path; HANDLE hLib = NULL; TTExtensionInitializationMethod initializer; TTErr err; path = fullpath; path += "*.ttdll"; fdHandle = FindFirstFile(path.c_str(), &findFileData); if (fdHandle && (fdHandle != INVALID_HANDLE_VALUE)) { while (fdHandle) { path = fullpath; path += findFileData.cFileName; hLib = LoadLibrary(path.c_str()); if (hLib) { initializer = (TTExtensionInitializationMethod)GetProcAddress((HMODULE)hLib, "loadTTExtension"); if (initializer) err = initializer(); } if (!FindNextFile(fdHandle, &findFileData)) break; } } #else ; #endif }
//-------------------------------------------------------------------------- // UStringToCFString //-------------------------------------------------------------------------- // Caller is responsible for releasing the returned CFStringRef CFStringRef UStringToCFString(const UString& inUString) { return CFStringCreateWithCharacters(0, (const UniChar*)inUString.data(), inUString.size()); }
CFStringRef lastfm::QStringToCFString( const QString &s ) { return CFStringCreateWithCharacters( 0, (UniChar*)s.unicode(), s.length() ); }
int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks) { OSStatus result = -1; FSIterator iterator; ItemCount actualObjects; FSRef rootDirectory; FSRef ref; HFSUniStr255 nameStr; result = FSGetVolumeInfo (theVolume, 0, NULL, kFSVolInfoFSInfo, NULL, NULL, &rootDirectory); if (result != noErr) { SDL_SetError ("ListTrackFiles: FSGetVolumeInfo returned %d", result); return result; } result = FSOpenIterator (&rootDirectory, kFSIterateFlat, &iterator); if (result == noErr) { do { result = FSGetCatalogInfoBulk (iterator, 1, &actualObjects, NULL, kFSCatInfoNone, NULL, &ref, NULL, &nameStr); if (result == noErr) { CFStringRef name; name = CFStringCreateWithCharacters (NULL, nameStr.unicode, nameStr.length); if (CFStringHasSuffix (name, CFSTR(".aiff")) || CFStringHasSuffix (name, CFSTR(".cdda"))) { int trackID = 0, i = 0; while (i < nameStr.length && !isdigit(nameStr.unicode[i])) { ++i; } while (i < nameStr.length && isdigit(nameStr.unicode[i])) { trackID = 10 * trackID +(nameStr.unicode[i] - '0'); ++i; } #if DEBUG_CDROM printf("Found AIFF for track %d: '%s'\n", trackID, CFStringGetCStringPtr (name, CFStringGetSystemEncoding())); #endif trackID--; assert(0 <= trackID && trackID <= SDL_MAX_TRACKS); if (trackID < numTracks) memcpy (&trackFiles[trackID], &ref, sizeof(FSRef)); } CFRelease (name); } } while(noErr == result); FSCloseIterator (iterator); } return 0; }
// soundsource overrides Result SoundSourceCoreAudio::open() { //Open the audio file. OSStatus err; /** This code blocks works with OS X 10.5+ only. DO NOT DELETE IT for now. */ CFStringRef urlStr = CFStringCreateWithCharacters( 0, reinterpret_cast<const UniChar *>(getFilename().unicode()), getFilename().size()); CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false); err = ExtAudioFileOpenURL(urlRef, &m_audioFile); CFRelease(urlStr); CFRelease(urlRef); /** TODO: Use FSRef for compatibility with 10.4 Tiger. Note that ExtAudioFileOpen() is deprecated above Tiger, so we must maintain both code paths if someone finishes this part of the code. FSRef fsRef; CFURLGetFSRef(reinterpret_cast<CFURLRef>(url.get()), &fsRef); err = ExtAudioFileOpen(&fsRef, &m_audioFile); */ if (err != noErr) { qDebug() << "SSCA: Error opening file " << getFilename(); return ERR; } // get the input file format CAStreamBasicDescription inputFormat; UInt32 size = sizeof(inputFormat); m_inputFormat = inputFormat; err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileDataFormat, &size, &inputFormat); if (err != noErr) { qDebug() << "SSCA: Error getting file format (" << getFilename() << ")"; return ERR; } //Debugging: //printf ("Source File format: "); inputFormat.Print(); //printf ("Dest File format: "); outputFormat.Print(); // create the output format m_outputFormat = CAStreamBasicDescription( inputFormat.mSampleRate, 2, CAStreamBasicDescription::kPCMFormatInt16, true); // set the client format err = ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(m_outputFormat), &m_outputFormat); if (err != noErr) { qDebug() << "SSCA: Error setting file property"; return ERR; } setChannels(m_outputFormat.NumberChannels()); //get the total length in frames of the audio file - copypasta: http://discussions.apple.com/thread.jspa?threadID=2364583&tstart=47 UInt32 dataSize; SInt64 totalFrameCount; dataSize = sizeof(totalFrameCount); //XXX: This looks sketchy to me - Albert err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileLengthFrames, &dataSize, &totalFrameCount); if (err != noErr) { qDebug() << "SSCA: Error getting number of frames"; return ERR; } // // WORKAROUND for bug in ExtFileAudio // AudioConverterRef acRef; UInt32 acrsize=sizeof(AudioConverterRef); err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_AudioConverter, &acrsize, &acRef); //_ThrowExceptionIfErr(@"kExtAudioFileProperty_AudioConverter", err); AudioConverterPrimeInfo primeInfo; UInt32 piSize=sizeof(AudioConverterPrimeInfo); memset(&primeInfo, 0, piSize); err = AudioConverterGetProperty(acRef, kAudioConverterPrimeInfo, &piSize, &primeInfo); if (err != kAudioConverterErr_PropertyNotSupported) { // Only if decompressing //_ThrowExceptionIfErr(@"kAudioConverterPrimeInfo", err); m_headerFrames=primeInfo.leadingFrames; } m_samples = (totalFrameCount/* - m_headerFrames*/) * getChannels(); setDuration(m_samples / (inputFormat.mSampleRate * getChannels())); setSampleRate(inputFormat.mSampleRate); qDebug() << m_samples << totalFrameCount << getChannels(); //Seek to position 0, which forces us to skip over all the header frames. //This makes sure we're ready to just let the Analyser rip and it'll //get the number of samples it expects (ie. no header frames). seek(0); return OK; }
bool mailcore::checkCertificate(mailstream * stream, String * hostname) { #if __APPLE__ bool result = false; CFStringRef hostnameCFString; SecPolicyRef policy; CFMutableArrayRef certificates; SecTrustRef trust = NULL; SecTrustResultType trustResult; OSStatus status; carray * cCerts = mailstream_get_certificate_chain(stream); if (cCerts == NULL) { fprintf(stderr, "warning: No certificate chain retrieved"); goto err; } hostnameCFString = CFStringCreateWithCharacters(NULL, (const UniChar *) hostname->unicodeCharacters(), hostname->length()); policy = SecPolicyCreateSSL(true, hostnameCFString); certificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); for(unsigned int i = 0 ; i < carray_count(cCerts) ; i ++) { MMAPString * str; str = (MMAPString *) carray_get(cCerts, i); CFDataRef data = CFDataCreate(NULL, (const UInt8 *) str->str, (CFIndex) str->len); SecCertificateRef cert = SecCertificateCreateWithData(NULL, data); CFArrayAppendValue(certificates, cert); CFRelease(data); CFRelease(cert); } static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // The below API calls are not thread safe. We're making sure not to call the concurrently. pthread_mutex_lock(&lock); status = SecTrustCreateWithCertificates(certificates, policy, &trust); if (status != noErr) { pthread_mutex_unlock(&lock); goto free_certs; } status = SecTrustEvaluate(trust, &trustResult); if (status != noErr) { pthread_mutex_unlock(&lock); goto free_certs; } pthread_mutex_unlock(&lock); switch (trustResult) { case kSecTrustResultUnspecified: case kSecTrustResultProceed: // certificate chain is ok result = true; break; default: // certificate chain is invalid break; } CFRelease(trust); free_certs: CFRelease(certificates); mailstream_certificate_chain_free(cCerts); CFRelease(policy); CFRelease(hostnameCFString); err: return result; #else bool result = false; X509_STORE * store = NULL; X509_STORE_CTX * storectx = NULL; STACK_OF(X509) * certificates = NULL; #if defined(ANDROID) || defined(__ANDROID__) DIR * dir = NULL; struct dirent * ent = NULL; FILE * f = NULL; #endif int status; carray * cCerts = mailstream_get_certificate_chain(stream); if (cCerts == NULL) { fprintf(stderr, "warning: No certificate chain retrieved"); goto err; } store = X509_STORE_new(); if (store == NULL) { goto free_certs; } #ifdef _MSC_VER HCERTSTORE systemStore = CertOpenSystemStore(NULL, L"ROOT"); PCCERT_CONTEXT previousCert = NULL; while (1) { PCCERT_CONTEXT nextCert = CertEnumCertificatesInStore(systemStore, previousCert); if (nextCert == NULL) { break; } X509 * openSSLCert = d2i_X509(NULL, (const unsigned char **)&nextCert->pbCertEncoded, nextCert->cbCertEncoded); if (openSSLCert != NULL) { X509_STORE_add_cert(store, openSSLCert); X509_free(openSSLCert); } previousCert = nextCert; } CertCloseStore(systemStore, 0); #elif defined(ANDROID) || defined(__ANDROID__) dir = opendir("/system/etc/security/cacerts"); while (ent = readdir(dir)) { if (ent->d_name[0] == '.') { continue; } char filename[1024]; snprintf(filename, sizeof(filename), "/system/etc/security/cacerts/%s", ent->d_name); f = fopen(filename, "rb"); if (f != NULL) { X509 * cert = PEM_read_X509(f, NULL, NULL, NULL); if (cert != NULL) { X509_STORE_add_cert(store, cert); X509_free(cert); } fclose(f); } } closedir(dir); #endif status = X509_STORE_set_default_paths(store); if (status != 1) { printf("Error loading the system-wide CA certificates"); } certificates = sk_X509_new_null(); for(unsigned int i = 0 ; i < carray_count(cCerts) ; i ++) { MMAPString * str; str = (MMAPString *) carray_get(cCerts, i); if (str == NULL) { goto free_certs; } BIO *bio = BIO_new_mem_buf((void *) str->str, str->len); X509 *certificate = d2i_X509_bio(bio, NULL); BIO_free(bio); if (!sk_X509_push(certificates, certificate)) { goto free_certs; } } storectx = X509_STORE_CTX_new(); if (storectx == NULL) { goto free_certs; } status = X509_STORE_CTX_init(storectx, store, sk_X509_value(certificates, 0), certificates); if (status != 1) { goto free_certs; } status = X509_verify_cert(storectx); if (status == 1) { result = true; } free_certs: mailstream_certificate_chain_free(cCerts); if (certificates != NULL) { sk_X509_pop_free((STACK_OF(X509) *) certificates, X509_free); }
XERCES_CPP_NAMESPACE_BEGIN URLAccessCFBinInputStream::URLAccessCFBinInputStream(const XMLURL& urlSource) : mBytesProcessed(0), mDataRef(NULL) { // Figure out what we're dealing with const XMLCh* urlText = urlSource.getURLText(); unsigned int urlLength = XMLString::stringLen(urlText); // Create a CFString from the path CFStringRef stringRef = NULL; if (urlText) { stringRef = CFStringCreateWithCharacters( kCFAllocatorDefault, urlText, urlLength ); } // Create a URLRef from the CFString CFURLRef urlRef = NULL; if (stringRef) { urlRef = CFURLCreateWithString( kCFAllocatorDefault, stringRef, NULL // CFURLRef baseURL ); } // Fetch the data mDataRef = NULL; SInt32 errorCode = 0; Boolean success = false; if (stringRef) { success = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, urlRef, &mDataRef, NULL, // CFDictionaryRef *properties, NULL, // CFArrayRef desiredProperties, &errorCode ); } // Cleanup temporary stuff if (stringRef) CFRelease(stringRef); if (urlRef) CFRelease(urlRef); // Check for an error in fetching the data if (!success || errorCode) { // Dispose any potential dataRef if (mDataRef) { CFRelease(mDataRef); mDataRef = NULL; } // Do a best attempt at mapping some errors switch (errorCode) { case kCFURLUnknownSchemeError: ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto); break; case kCFURLRemoteHostUnavailableError: ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, urlSource.getHost()); break; case kCFURLUnknownError: ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, urlText); break; case kCFURLResourceNotFoundError: case kCFURLResourceAccessViolationError: case kCFURLTimeoutError: ThrowXML1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, urlText); break; case kCFURLImproperArgumentsError: case kCFURLUnknownPropertyKeyError: case kCFURLPropertyKeyUnavailableError: default: ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, urlText); break; } } }
sqInt dir_Lookup(char *pathString, sqInt pathStringLength, sqInt index, /* outputs: */ char *name, sqInt *nameLength, sqInt *creationDate, sqInt *modificationDate, sqInt *isDirectory, squeakFileOffsetType *sizeIfFile) { /* Lookup the index-th entry of the directory with the given path, starting at the root of the file system. Set the name, name length, creation date, creation time, directory flag, and file size (if the entry is a file). Return: 0 if a entry is found at the given index 1 if the directory has fewer than index entries 2 if the given path has bad syntax or does not reach a directory */ sqInt okay; FSSpec spec; long parentDirectory; OSErr err; Str255 longFileName; FSVolumeInfoParam fsVolumeParam; HFSUniStr255 uniStr; FSVolumeInfo volumeInfo; /* default return values */ *name = 0; *nameLength = 0; *creationDate = 0; *modificationDate = 0; *isDirectory = false; *sizeIfFile = 0; if ((pathStringLength == 0)) { /* get volume info */ fsVolumeParam.volumeName = &uniStr; fsVolumeParam.ioVRefNum = kFSInvalidVolumeRefNum; fsVolumeParam.volumeIndex = index; fsVolumeParam.whichInfo = 0; fsVolumeParam.volumeInfo = &volumeInfo; fsVolumeParam.ref = NULL; fsVolumeParam.whichInfo = kFSVolInfoCreateDate + kFSVolInfoModDate; okay = PBGetVolumeInfoSync( &fsVolumeParam) == noErr; /* FSGetVolumeInfo (kFSInvalidVolumeRefNum, index, NULL, ) */ if (okay) { CFStringRef strRef = CFStringCreateWithCharacters( kCFAllocatorDefault, uniStr.unicode, uniStr.length ); CFMutableStringRef mStr = CFStringCreateMutableCopy(NULL, 0, strRef); // HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements if (gCurrentVMEncoding == kCFStringEncodingUTF8) CFStringNormalize(mStr, kCFStringNormalizationFormKC); // pre-combined Boolean result = CFStringGetCString(mStr, name, 256, gCurrentVMEncoding); // buffer size is to see primitiveDirectoryLookup CFRelease(strRef); CFRelease(mStr); if (result == true) { // strncpy(name, &(uniStr.unicode), uniStr.length); // *nameLength = uniStr.length; *nameLength = strlen(name); { LocalDateTime local; ConvertUTCToLocalDateTime(&fsVolumeParam.volumeInfo->createDate,&local); *creationDate = convertToSqueakTime(local.lowSeconds); } { LocalDateTime local; ConvertUTCToLocalDateTime(&fsVolumeParam.volumeInfo->modifyDate,&local); *modificationDate = convertToSqueakTime(local.lowSeconds); } *isDirectory = true; *sizeIfFile = 0; return ENTRY_FOUND; } else { return NO_MORE_ENTRIES; } } else { return NO_MORE_ENTRIES; } } else { /* get file or directory info */ if (!equalsLastPath(pathString, pathStringLength)) { /* lookup and cache the refNum for this path */ err = lookupPath(pathString, pathStringLength, &spec,false,true); if (err == noErr) recordPath(pathString, pathStringLength, &spec); else return BAD_PATH; } spec = lastSpec; *sizeIfFile = 0; okay = fetchFileInfo(index,&spec,(unsigned char *) name,true, &parentDirectory,isDirectory,creationDate, modificationDate,sizeIfFile,&longFileName); if (okay == noErr) { CFStringRef cfs= CFStringCreateWithPascalString(NULL, longFileName, gCurrentVMEncoding); CFMutableStringRef mStr= CFStringCreateMutableCopy(NULL, 0, cfs); CFRelease(cfs); // HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements if (gCurrentVMEncoding == kCFStringEncodingUTF8) CFStringNormalize(mStr, kCFStringNormalizationFormKC); // pre-combined CFStringGetCString(mStr, name, 256, gCurrentVMEncoding); CFRelease(mStr); *nameLength = strlen(name); *creationDate = convertToSqueakTime(*creationDate); *modificationDate = convertToSqueakTime(*modificationDate); return ENTRY_FOUND; } else return okay == fnfErr ? NO_MORE_ENTRIES : BAD_PATH; } }
CFStringRef NatronCFString::toCFStringRef(const QString &string) { return CFStringCreateWithCharacters( 0, reinterpret_cast<const UniChar *>( string.unicode() ), string.length() ); }
/***************************************************** * * Handle_TextShouldChangeInRange(inHandlerCallRef, inEvent, inUserData) * * Purpose: called to intercept text changes which are destined for a text control * * Inputs: inHandlerCallRef - reference to the current handler call chain * inEvent - the event * inUserData - app-specified data you passed in the call to InstallEventHandler * * Returns: OSStatus - noErr indicates the event was handled * eventNotHandledErr indicates the event was not handled and the Toolbox should take over */ static pascal OSStatus Handle_TextShouldChangeInRange(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData) { OSStatus status; CFStringRef theCFString = NULL; status = GetEventParameter(inEvent, kEventParamCandidateText, typeCFStringRef, NULL, sizeof(theCFString), NULL, &theCFString); require_noerr(status, ExitShouldChange); require_action(theCFString != NULL, ExitShouldChange, status = userCanceledErr); UniChar *buffer = NULL; CFIndex i, j, len = CFStringGetLength(theCFString); if (len == 0) goto ExitShouldChange; // there's nothing to filter // Grabbing the characters as Unicode chars buffer = (UniChar *)malloc(len * sizeof(UniChar)); require(buffer != NULL, ExitShouldChange); CFStringGetCharacters(theCFString, CFRangeMake(0, len), buffer); // Checking if we just have the return code if ((len == 1) && (buffer[0] == kReturnCharCode)) { EventRef theEvent; CreateEvent(NULL, kEventClassCommand, kEventCommandProcess, GetCurrentEventTime(), kEventAttributeUserEvent, &theEvent); HICommandExtended theCommand; theCommand.attributes = kHICommandFromControl; theCommand.commandID = 'SVet'; theCommand.source.control = (ControlRef)inUserData; SetEventParameter(theEvent, kEventParamDirectObject, typeHICommand, sizeof(theCommand), &theCommand); SendEventToEventTarget(theEvent, GetWindowEventTarget(GetControlOwner((ControlRef)inUserData))); ReleaseEvent(theEvent); // we don't want the return character to be added to the text so we abort the input status = userCanceledErr; } else { // Checking to see if we have only digits Boolean ok = true; for (i = 0; (i < len) && ok; i++) ok = (buffer[i] >= '0') && (buffer[i] <= '9'); if (!ok) { // if not, we remove the offending characters for (i = 0, j = 0; i < len; i++) if ((buffer[i] >= '0') && (buffer[i] <= '9')) buffer[j++] = buffer[i]; if (j == 0) // not a single digit in the candidate text, we abort the inout status = userCanceledErr; else { theCFString = CFStringCreateWithCharacters(NULL, buffer, j); require_action(theCFString != NULL, ExitShouldChange, status = userCanceledErr); status = SetEventParameter(inEvent, kEventParamReplacementText, typeCFStringRef, sizeof(theCFString), &theCFString); require_noerr(status, ExitShouldChange); // if we reach here, status is already set to noErr so we don't set it again } } else // only digits, we just let the HIToolbox do its job status = eventNotHandledErr; } ExitShouldChange: if (buffer != NULL) free(buffer); return status; } // Handle_TextShouldChangeInRange
bool wxFsEventsFileSystemWatcher::AddTree(const wxFileName& path, int events, const wxString& filespec) { if (!path.DirExists()) { return false; } wxString canonical = GetCanonicalPath(path); if ( canonical.empty() ) { return false; } CFRunLoopRef cfLoop = CFRunLoopGetCurrent(); wxASSERT_MSG( cfLoop, "there must be a current event loop; this file watcher needs it." ); if ( ! cfLoop ) { return false; } if ( m_streams.find(canonical) != m_streams.end() ) { // How to take into account filespec // if client adds a watch for /home/*.cpp // and then on another call wants to add a // call to /home/*.h // Ideally we should not create another watch // however we would need to keep both filespecs // around, which we don't do now. return false; } // Will need to pass the desired event flags // and filespec to our callback via the context // we make sure to give the context a cleanup // callback. FSEventStreamContext ctx; wxFSEventWatcherContext* watcherContext = new wxFSEventWatcherContext( this, events, filespec.Clone() ); ctx.version = 0; ctx.info = watcherContext; ctx.retain = NULL; ctx.release = &wxDeleteContext; ctx.copyDescription = NULL; CFTimeInterval latency = 0.2; wxMacUniCharBuffer pathChars(path.GetPath()); CFStringRef pathRef = CFStringCreateWithCharacters( kCFAllocatorDefault, pathChars.GetBuffer(), pathChars.GetChars() ); CFArrayRef pathRefs = CFArrayCreate( kCFAllocatorDefault, (const void**)&pathRef, 1, NULL ); FSEventStreamCreateFlags flags = kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagFileEvents; FSEventStreamRef stream = FSEventStreamCreate( kCFAllocatorDefault, &wxFSEventCallback, &ctx, pathRefs, kFSEventStreamEventIdSinceNow, latency, flags); bool started = false; if ( stream ) { FSEventStreamScheduleWithRunLoop(stream, cfLoop, kCFRunLoopDefaultMode); started = FSEventStreamStart(stream); if ( started ) { m_streams[canonical] = stream; } } // cleanup the paths, as we own the pointers CFRelease(pathRef); CFRelease(pathRefs); wxASSERT_MSG(stream, "could not create FS stream"); return started; }
QString Q3FileDialog::macGetSaveFileName(const QString &start, const QString &filter, QString *, QWidget *parent, const char* /*name*/, const QString& caption, QString *selectedFilter) { OSErr err; QString retstr; NavDialogCreationOptions options; NavGetDefaultDialogCreationOptions(&options); static const int w = 450, h = 350; options.optionFlags |= kNavDontConfirmReplacement; options.modality = kWindowModalityAppModal; options.location.h = options.location.v = -1; QString workingDir; QString initialSelection; if (!start.isEmpty()) { Q3UrlOperator u(encodeFileName(start)); if (u.isLocalFile() && QFileInfo(u.path()).isDir()) { workingDir = start; } else { if (u.isLocalFile()) { QFileInfo fi(u.dirPath()); if (fi.exists()) { workingDir = u.dirPath(); initialSelection = u.fileName(); } } else { workingDir = u.toString(); } } if (!initialSelection.isEmpty()) options.saveFileName = CFStringCreateWithCharacters(0, (UniChar *)initialSelection.unicode(), initialSelection.length()); } if(!caption.isEmpty()) options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(), caption.length()); if(parent && parent->isVisible()) { Qt::WindowType wt = parent->window()->windowType(); if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) { options.modality = kWindowModalityWindowModal; options.parentWindow = qt_mac_window_for(parent); } else { parent = parent->window(); QString s = parent->windowTitle(); options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length()); options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2); options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2); QRect r = QApplication::desktop()->screenGeometry( QApplication::desktop()->screenNumber(parent)); if(options.location.h + w > r.right()) options.location.h -= (options.location.h + w) - r.right() + 10; if(options.location.v + h > r.bottom()) options.location.v -= (options.location.v + h) - r.bottom() + 10; } } else if(QWidget *p = qApp->mainWidget()) { static int last_screen = -1; int scr = QApplication::desktop()->screenNumber(p); if(last_screen != scr) { QRect r = QApplication::desktop()->screenGeometry(scr); options.location.h = (r.x() + (r.width() / 2)) - (w / 2); options.location.v = (r.y() + (r.height() / 2)) - (h / 2); } } QList<qt_mac_filter_name*> filts = makeFiltersList(filter); qt_mac_nav_filter_type t; t.index = 0; t.filts = &filts; if(filts.count() > 1) { int i = 0; CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count()); for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) { QString rg = (*it)->description; arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length()); } options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL); } NavDialogRef dlg; if(NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(), (void *) (filts.isEmpty() ? NULL : &t), &dlg)) { qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__); return retstr; } if (!workingDir.isEmpty()) { FSRef fsref; if (qt_mac_create_fsref(workingDir, &fsref) == noErr) { AEDesc desc; if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr) NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc); } } NavDialogRun(dlg); if (selectedFilter) { NavMenuItemSpec navSpec; bzero(&navSpec, sizeof(NavMenuItemSpec)); qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0); for (int i = 0; i < filts.count(); ++i) { const qt_mac_filter_name *filter = filts.at(i); if (sel_filt_name->description == filter->description && sel_filt_name->regxp == filter->regxp && sel_filt_name->filter == filter->filter) { navSpec.menuType = i; break; } } NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec); } if(options.modality == kWindowModalityWindowModal) { //simulate modality QWidget modal_widg(parent, __FILE__ "__modal_dlg", Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder); modal_widg.createWinId(); QApplicationPrivate::enterModal(&modal_widg); while(g_nav_blocking) qApp->processEvents(QEventLoop::WaitForMoreEvents); QApplicationPrivate::leaveModal(&modal_widg); } if(NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) { NavDialogDispose(dlg); return retstr; } NavReplyRecord ret; NavDialogGetReply(dlg, &ret); NavDialogDispose(dlg); long count; err = AECountItems(&(ret.selection), &count); if(!ret.validRecord || err != noErr || !count) { NavDisposeReply(&ret); return retstr; } AEKeyword keyword; DescType type; Size size; FSRef ref; err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword, &type, &ref, sizeof(ref), &size); if(err == noErr) { if(!str_buffer) { qAddPostRoutine(cleanup_str_buffer); str_buffer = (UInt8 *)malloc(1024); } FSRefMakePath(&ref, str_buffer, 1024); retstr = QString::fromUtf8((const char *)str_buffer); //now filename CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8); retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer); } NavDisposeReply(&ret); if(selectedFilter) *selectedFilter = filts.at(t.index)->filter; while (!filts.isEmpty()) delete filts.takeFirst(); return retstr; }
/* YASTControlGetData is dispatched from our control event handler. It is where we handle all calls to GetControlData directed to our control. */ static OSStatus YASTControlGetData( YASTControlVarsPtr varsp, ResType inTagName, void * inBuffer, Size inBufferSize, Size *outBufferSize) { OSStatus err, returnedResult; /* default result */ returnedResult = eventNotHandledErr; /* dispatch event */ switch (inTagName) { case kYASTControlAllTextTag: case kYASTControlSelectedTextTag: { Handle oDataHandle; Size bytesCopied; TXNOffset oStartOffset, oEndOffset; if (inTagName == kYASTControlSelectedTextTag) TXNGetSelection( varsp->fTXNObject, &oStartOffset, &oEndOffset); else { oStartOffset = kTXNStartOffset; oEndOffset = kTXNEndOffset; } err = TXNGetDataEncoded( varsp->fTXNObject, oStartOffset, oEndOffset, &oDataHandle, kTXNTextData); if (err == noErr) { bytesCopied = GetHandleSize(oDataHandle); if (bytesCopied > inBufferSize) bytesCopied = inBufferSize; BlockMoveData(*oDataHandle, inBuffer, bytesCopied); if (outBufferSize != NULL) *outBufferSize = bytesCopied; DisposeHandle(oDataHandle); } } returnedResult = err; break; case kYASTControlAllUnicodeTextTag: /* CFStringRef */ case kYASTControlSelectedUnicodeTextTag: /* CFStringRef */ if (inBufferSize != sizeof(CFStringRef)) { err = paramErr; } else { TXNOffset oStartOffset, oEndOffset; Handle oDataHandle; if (inTagName == kYASTControlSelectedUnicodeTextTag) TXNGetSelection( varsp->fTXNObject, &oStartOffset, &oEndOffset); else { oStartOffset = kTXNStartOffset; oEndOffset = kTXNEndOffset; } err = TXNGetDataEncoded( varsp->fTXNObject, oStartOffset, oEndOffset, &oDataHandle, kTXNUnicodeTextData); if (err == noErr) { CFStringRef theString; HLock(oDataHandle); theString = CFStringCreateWithCharacters(NULL, (UniChar *) (*oDataHandle), GetHandleSize(oDataHandle)/sizeof(UniChar)); if (theString != NULL) { * (CFStringRef*) inBuffer = theString; if (outBufferSize != NULL) *outBufferSize = sizeof(CFStringRef); err = noErr; } else { err = memFullErr; } DisposeHandle(oDataHandle); } } returnedResult = err; break; case kYASTControlSelectionRangeTag: /* YASTControlEditTextSelectionRec */ if (inBufferSize != sizeof(YASTControlEditTextSelectionRec)) { err = paramErr; } else { YASTControlEditTextSelectionPtr range; range = (YASTControlEditTextSelectionPtr) inBuffer; TXNGetSelection( varsp->fTXNObject, &range->selStart, &range->selEnd); if (outBufferSize != NULL) *outBufferSize = sizeof(YASTControlEditTextSelectionRec); err = noErr; } returnedResult = err; break; case kYASTControlTXNObjectTag: /* fTXNObject - GetControlData only */ if (inBufferSize != sizeof(TXNObject)) { err = paramErr; } else { * (TXNObject*) inBuffer = varsp->fTXNObject; if (outBufferSize != NULL) *outBufferSize = sizeof(TXNObject); err = noErr; } returnedResult = err; break; case kYASTControlTabsAdvanceFocusTag: /* Boolean (default true) */ if (inBufferSize != sizeof(Boolean)) { err = paramErr; } else { * (Boolean*) inBuffer = varsp->fTabMovesFocus; if (outBufferSize != NULL) *outBufferSize = sizeof(Boolean); err = noErr; } returnedResult = err; break; case kYASTControlDoDrawFocusTag: /* Boolean (default true) */ if (inBufferSize != sizeof(Boolean)) { err = paramErr; } else { * (Boolean*) inBuffer = varsp->fDrawFocusBox; if (outBufferSize != NULL) *outBufferSize = sizeof(Boolean); err = noErr; } returnedResult = err; break; case kYASTControlReadOnlyTag: if (inBufferSize != sizeof(Boolean)) { err = paramErr; } else { * (Boolean*) inBuffer = varsp->fIsReadOnly; if (outBufferSize != NULL) *outBufferSize = sizeof(Boolean); err = noErr; } returnedResult = err; break; case kYASTControlTabSizeTag: if (inBufferSize != sizeof(SInt16)) { err = paramErr; } else { TXNTab txnTabData; TXNControlTag txnControlTag; txnControlTag = kTXNTabSettingsTag; err = TXNGetTXNObjectControls( varsp->fTXNObject, 1, &txnControlTag, &txnTabData ); if (err == noErr) { * (SInt16*) inBuffer = txnTabData.value; if (outBufferSize != NULL) *outBufferSize = sizeof(SInt16); } } returnedResult = err; break; } return returnedResult; }
// soundsource overrides int SoundSourceCoreAudio::open() { //m_file.open(QIODevice::ReadOnly); //Open the audio file. OSStatus err; //QUrl blah(m_qFilename); QString qurlStr = m_qFilename;//blah.toString(); qDebug() << qurlStr; /** This code blocks works with OS X 10.5+ only. DO NOT DELETE IT for now. */ CFStringRef urlStr = CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>( qurlStr.unicode()), qurlStr.size()); CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false); err = ExtAudioFileOpenURL(urlRef, &m_audioFile); CFRelease(urlStr); CFRelease(urlRef); /** TODO: Use FSRef for compatibility with 10.4 Tiger. Note that ExtAudioFileOpen() is deprecated above Tiger, so we must maintain both code paths if someone finishes this part of the code. FSRef fsRef; CFURLGetFSRef(reinterpret_cast<CFURLRef>(url.get()), &fsRef); err = ExtAudioFileOpen(&fsRef, &m_audioFile); */ if (err != noErr) { qDebug() << "SSCA: Error opening file."; return ERR; } // get the input file format CAStreamBasicDescription inputFormat; UInt32 size = sizeof(inputFormat); m_inputFormat = inputFormat; err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileDataFormat, &size, &inputFormat); if (err != noErr) { qDebug() << "SSCA: Error getting file format"; return ERR; } //Debugging: //printf ("Source File format: "); inputFormat.Print(); //printf ("Dest File format: "); outputFormat.Print(); // create the output format CAStreamBasicDescription outputFormat; bzero(&outputFormat, sizeof(AudioStreamBasicDescription)); outputFormat.mFormatID = kAudioFormatLinearPCM; outputFormat.mSampleRate = inputFormat.mSampleRate; outputFormat.mChannelsPerFrame = 2; outputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger; /* switch(inputFormat.mBitsPerChannel) { case 16: outputFormat.mFormatFlags = kAppleLosslessFormatFlag_16BitSourceData; break; case 20: outputFormat.mFormatFlags = kAppleLosslessFormatFlag_20BitSourceData; break; case 24: outputFormat.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData; break; case 32: outputFormat.mFormatFlags = kAppleLosslessFormatFlag_32BitSourceData; break; }*/ // get and set the client format - it should be lpcm CAStreamBasicDescription clientFormat = (inputFormat.mFormatID == kAudioFormatLinearPCM ? inputFormat : outputFormat); clientFormat.mBytesPerPacket = 4; clientFormat.mFramesPerPacket = 1; clientFormat.mBytesPerFrame = 4; clientFormat.mChannelsPerFrame = 2; clientFormat.mBitsPerChannel = 16; clientFormat.mReserved = 0; m_clientFormat = clientFormat; size = sizeof(clientFormat); err = ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, size, &clientFormat); if (err != noErr) { qDebug() << "SSCA: Error setting file property"; return ERR; } //Set m_iChannels and m_samples; m_iChannels = clientFormat.NumberChannels(); //get the total length in frames of the audio file - copypasta: http://discussions.apple.com/thread.jspa?threadID=2364583&tstart=47 UInt32 dataSize; SInt64 totalFrameCount; dataSize = sizeof(totalFrameCount); //XXX: This looks sketchy to me - Albert err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileLengthFrames, &dataSize, &totalFrameCount); if (err != noErr) { qDebug() << "SSCA: Error getting number of frames"; return ERR; } // // WORKAROUND for bug in ExtFileAudio // AudioConverterRef acRef; UInt32 acrsize=sizeof(AudioConverterRef); err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_AudioConverter, &acrsize, &acRef); //_ThrowExceptionIfErr(@"kExtAudioFileProperty_AudioConverter", err); AudioConverterPrimeInfo primeInfo; UInt32 piSize=sizeof(AudioConverterPrimeInfo); memset(&primeInfo, 0, piSize); err = AudioConverterGetProperty(acRef, kAudioConverterPrimeInfo, &piSize, &primeInfo); if(err != kAudioConverterErr_PropertyNotSupported) // Only if decompressing { //_ThrowExceptionIfErr(@"kAudioConverterPrimeInfo", err); m_headerFrames=primeInfo.leadingFrames; } m_samples = (totalFrameCount/*-m_headerFrames*/)*m_iChannels; m_iDuration = m_samples / (inputFormat.mSampleRate * m_iChannels); m_iSampleRate = inputFormat.mSampleRate; qDebug() << m_samples << totalFrameCount << m_iChannels; //Seek to position 0, which forces us to skip over all the header frames. //This makes sure we're ready to just let the Analyser rip and it'll //get the number of samples it expects (ie. no header frames). seek(0); return OK; }
//-------------------------------------------------------------------------- // UStringToCFString //-------------------------------------------------------------------------- // Caller is responsible for releasing the returned CFStringRef CFStringRef UStringToCFString(const UString& inUString) { return CFStringCreateWithCharacters(0, (const UniChar*)inUString.characters(), inUString.length()); }
CFStringRef CoreAudioSystem::QStringToCFString(const QString &str) { return CFStringCreateWithCharacters(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(str.unicode()), str.length()); }
CFStringRef JSStringCopyCFString(CFAllocatorRef alloc, JSStringRef string) { return CFStringCreateWithCharacters(alloc, reinterpret_cast<const UniChar*>(string->characters()), string->length()); }
// soundsource overrides Result SoundSourceCoreAudio::tryOpen(const AudioSourceConfig& audioSrcCfg) { const QString fileName(getLocalFileName()); //Open the audio file. OSStatus err; /** This code blocks works with OS X 10.5+ only. DO NOT DELETE IT for now. */ CFStringRef urlStr = CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(fileName.unicode()), fileName.size()); CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false); err = ExtAudioFileOpenURL(urlRef, &m_audioFile); CFRelease(urlStr); CFRelease(urlRef); /** TODO: Use FSRef for compatibility with 10.4 Tiger. Note that ExtAudioFileOpen() is deprecated above Tiger, so we must maintain both code paths if someone finishes this part of the code. FSRef fsRef; CFURLGetFSRef(reinterpret_cast<CFURLRef>(url.get()), &fsRef); err = ExtAudioFileOpen(&fsRef, &m_audioFile); */ if (err != noErr) { qDebug() << "SSCA: Error opening file " << fileName; return ERR; } // get the input file format UInt32 inputFormatSize = sizeof(m_inputFormat); err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileDataFormat, &inputFormatSize, &m_inputFormat); if (err != noErr) { qDebug() << "SSCA: Error getting file format (" << fileName << ")"; return ERR; } m_bFileIsMp3 = m_inputFormat.mFormatID == kAudioFormatMPEGLayer3; // create the output format const UInt32 numChannels = audioSrcCfg.hasChannelCount() ? audioSrcCfg.getChannelCount() : 2; m_outputFormat = CAStreamBasicDescription(m_inputFormat.mSampleRate, numChannels, CAStreamBasicDescription::kPCMFormatFloat32, true); // set the client format err = ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(m_outputFormat), &m_outputFormat); if (err != noErr) { qDebug() << "SSCA: Error setting file property"; return ERR; } //get the total length in frames of the audio file - copypasta: http://discussions.apple.com/thread.jspa?threadID=2364583&tstart=47 SInt64 totalFrameCount; UInt32 totalFrameCountSize = sizeof(totalFrameCount); err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileLengthFrames, &totalFrameCountSize, &totalFrameCount); if (err != noErr) { qDebug() << "SSCA: Error getting number of frames"; return ERR; } // // WORKAROUND for bug in ExtFileAudio // AudioConverterRef acRef; UInt32 acrsize = sizeof(AudioConverterRef); err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_AudioConverter, &acrsize, &acRef); //_ThrowExceptionIfErr(@"kExtAudioFileProperty_AudioConverter", err); AudioConverterPrimeInfo primeInfo; UInt32 piSize = sizeof(AudioConverterPrimeInfo); memset(&primeInfo, 0, piSize); err = AudioConverterGetProperty(acRef, kAudioConverterPrimeInfo, &piSize, &primeInfo); if (err != kAudioConverterErr_PropertyNotSupported) { // Only if decompressing //_ThrowExceptionIfErr(@"kAudioConverterPrimeInfo", err); m_headerFrames = primeInfo.leadingFrames; } else { m_headerFrames = 0; } setChannelCount(m_outputFormat.NumberChannels()); setSamplingRate(m_inputFormat.mSampleRate); // NOTE(uklotzde): This is what I found when migrating // the code from SoundSource (sample-oriented) to the new // AudioSource (frame-oriented) API. It is not documented // when m_headerFrames > 0 and what the consequences are. setFrameCount(totalFrameCount/* - m_headerFrames*/); //Seek to position 0, which forces us to skip over all the header frames. //This makes sure we're ready to just let the Analyser rip and it'll //get the number of samples it expects (ie. no header frames). seekSampleFrame(0); return OK; }
static OSStatus AddCCLsInFolderToArray(const FSRef *folderRef, CFMutableArrayRef result) // Iterates through the contents of the folder specified by folderRef, // adding the name of each CCL file (ie any file that's visible) to // the result array. { OSStatus err; OSStatus junk; FSRef * scriptRefs; HFSUniStr255 * scriptNames; FSIterator iter; ItemCount actCount; ItemCount thisItemIndex; Boolean done; iter = NULL; scriptRefs = NULL; scriptNames = NULL; // Allocate buffers for the FSRefs and long Unicode names. Given that // we're processing 50 files at a time, these buffers are way too big // to store on the stack (25 KB for scriptNames alone). scriptRefs = (FSRef *) malloc( kFolderItemsPerBulkCall * sizeof(FSRef) ); scriptNames = (HFSUniStr255 *) malloc( kFolderItemsPerBulkCall * sizeof(HFSUniStr255) ); err = noErr; if (scriptRefs == NULL || scriptNames == NULL) { err = memFullErr; } // Create the iterator. if (err == noErr) { err = FSOpenIterator(folderRef, kFSIterateFlat, &iter); } // Iterate over the contents of the directory. For each item found // we check whether it's a visible plain file and, if it is, add its // name to the array. if (err == noErr) { done = false; do { err = FSGetCatalogInfoBulk(iter, kFolderItemsPerBulkCall, &actCount, NULL, kFSCatInfoNone, NULL, scriptRefs, NULL, scriptNames); if (err == errFSNoMoreItems) { // We ran off the end of the directory. Record that we're // done, but set err to noErr so that we process any partial // results. done = true; err = noErr; } if (err == noErr) { for (thisItemIndex = 0; thisItemIndex < actCount; thisItemIndex++) { Boolean visible; err = MyIsVisibleFile(&scriptRefs[thisItemIndex], &visible); if ( (err == noErr) && visible ) { CFStringRef thisItemName; thisItemName = CFStringCreateWithCharacters(NULL, scriptNames[thisItemIndex].unicode, scriptNames[thisItemIndex].length); if (thisItemName == NULL) { err = coreFoundationUnknownErr; } if (err == noErr) { CFArrayAppendValue(result, thisItemName); } CFQRelease(thisItemName); } if (err != noErr) { break; } } } } while (err == noErr && !done); } // Clean up. if (iter != NULL) { junk = FSCloseIterator(iter); assert(junk == noErr); } if (scriptRefs != NULL) { free(scriptRefs); } if (scriptNames != NULL) { free(scriptNames); } return err; }