CFArrayRef CFCopySearchPathForDirectoriesInDomains(CFSearchPathDirectory directory, CFSearchPathDomainMask domainMask, Boolean expandTilde) {
    CFMutableArrayRef array;
    CFSearchPathEnumerationState state;
    CFIndex homeLen = -1;
    char cPath[CFMaxPathSize], home[CFMaxPathSize];

    array = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);
    state = __CFStartSearchPathEnumeration(directory, domainMask);
    while ((state = __CFGetNextSearchPathEnumeration(state, (uint8_t *)cPath, sizeof(cPath)))) {
	CFURLRef url = NULL;
	if (expandTilde && (cPath[0] == '~')) {
	    if (homeLen < 0) {
		CFURLRef homeURL = CFCopyHomeDirectoryURLForUser(NULL);
		if (homeURL) {
		    CFURLGetFileSystemRepresentation(homeURL, true, (uint8_t *)home, CFMaxPathSize);
		    homeLen = strlen(home);
		    CFRelease(homeURL);
		}
	    }
            if (homeLen + strlen(cPath) < CFMaxPathSize) {
		home[homeLen] = '\0';
		strlcat(home, &cPath[1], sizeof(home));
		url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t *)home, strlen(home), true);
	    }
	} else {
	    url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t *)cPath, strlen(cPath), true);
	}
	if (url) {
	    CFArrayAppendValue(array, url);
	    CFRelease(url);
	}
    }
    return array;
}
// Set the fallBackToHome parameter to true if we should fall back to the HOME environment variable if all else fails. Otherwise return NULL.
static CFURLRef _CFCopyHomeDirURLForUser(const char *username, bool fallBackToHome) {
    const char *fixedHomePath = issetugid() ? NULL : __CFgetenv("CFFIXED_USER_HOME");
    const char *homePath = NULL;
    
    // Calculate the home directory we will use
    // First try CFFIXED_USER_HOME (only if not setugid), then fall back to the upwd, then fall back to HOME environment variable
    CFURLRef home = NULL;
    if (!issetugid() && fixedHomePath) home = CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t *)fixedHomePath, strlen(fixedHomePath), true);
    if (!home) {
        struct passwd *upwd = NULL;
        if (username) {
            upwd = getpwnam(username);
        } else {
            uid_t euid;
            __CFGetUGIDs(&euid, NULL);
            upwd = getpwuid(euid ?: getuid());
        }
        if (upwd && upwd->pw_dir) {
            home = CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t *)upwd->pw_dir, strlen(upwd->pw_dir), true);
        }
    }
    if (fallBackToHome && !home) homePath = __CFgetenv("HOME");
    if (fallBackToHome && !home && homePath) home = CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t *)homePath, strlen(homePath), true);
    
    return home;
}
int main (int argc, const char * argv[]) {
    const char *inputFileName = NULL;
    char *outputFileName = NULL;
    CFURLRef inURL = NULL;
    
    if(argc != 2){
		fprintf(stderr, "Usage: %s [inputfile] \n", argv[0]);
        return 1;
    }

    inputFileName = argv[1];
    fprintf(stdout, "Beginning Document \"%s\"\n", inputFileName);

    inURL = CFURLCreateFromFileSystemRepresentation(NULL, inputFileName, 
				strlen(inputFileName), false);
    if(!inURL){
		fprintf(stderr, "Couldn't create URL for input file!\n");
		return 1;
    }
    
    dumpPageStreams(inURL, stdout);
    
    CFRelease(inURL);
    
    return 0;
}
bool ofxAudioUnitFilePlayer::setFile(const std::string &filePath) {
	CFURLRef fileURL;
	fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
	                                                  (const UInt8 *)filePath.c_str(),
	                                                  filePath.length(),
	                                                  NULL);
	
	if(_fileID[0]) {
		AudioFileClose(_fileID[0]);
		_fileID[0] = NULL;
	}
	
	OSStatus s = AudioFileOpenURL(fileURL, kAudioFileReadPermission, 0, _fileID);
	CFRelease(fileURL);
	
	_primed = false;
	
	if(s != noErr) {
		cout << "Error " << s << " while opening file at " << filePath << endl;
		return false;
	} else {
		// setting the file ID now since it seems to have some overhead.
		// Doing it now ensures you'll get sound pretty much instantly after
		// calling play() (subsequent calls don't have the overhead)
		OFXAU_RET_BOOL(AudioUnitSetProperty(*_unit,
											kAudioUnitProperty_ScheduledFileIDs,
											kAudioUnitScope_Global,
											0,
											_fileID,
											sizeof(_fileID)),
					   "setting file player's file ID");
	}
}
Exemple #5
0
//-----------------------------------------------------------------------------
int C700::CreatePGDataDic(CFDictionaryRef *data, int pgnum)
{
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable	(NULL, 0,
                                  &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    const InstParams	*vpSet = mEfx->GetVP();

    if (vpSet[pgnum].loop) {
        vpSet[pgnum].brr.data[vpSet[pgnum].brr.size - 9] |= 2;
    }
    else {
        vpSet[pgnum].brr.data[vpSet[pgnum].brr.size - 9] &= ~2;
    }
    CFDataRef	brrdata = CFDataCreate(NULL, vpSet[pgnum].brr.data, vpSet[pgnum].brr.size);
    CFDictionarySetValue(dict, kSaveKey_brrdata, brrdata);
    CFRelease(brrdata);

    AddNumToDictionary(dict, kSaveKey_looppoint, vpSet[pgnum].lp);
    CFNumberRef	num = CFNumberCreate(NULL, kCFNumberDoubleType, &vpSet[pgnum].rate);
    CFDictionarySetValue(dict, kSaveKey_samplerate, num);
    CFRelease(num);
    AddNumToDictionary(dict, kSaveKey_basekey, vpSet[pgnum].basekey);
    AddNumToDictionary(dict, kSaveKey_lowkey, vpSet[pgnum].lowkey);
    AddNumToDictionary(dict, kSaveKey_highkey, vpSet[pgnum].highkey);
    AddNumToDictionary(dict, kSaveKey_ar, vpSet[pgnum].ar);
    AddNumToDictionary(dict, kSaveKey_dr, vpSet[pgnum].dr);
    AddNumToDictionary(dict, kSaveKey_sl, vpSet[pgnum].sl);
    AddNumToDictionary(dict, kSaveKey_sr, vpSet[pgnum].sr);
    AddBooleanToDictionary(dict, kSaveKey_SustainMode, vpSet[pgnum].sustainMode);
    AddNumToDictionary(dict, kSaveKey_volL, vpSet[pgnum].volL);
    AddNumToDictionary(dict, kSaveKey_volR, vpSet[pgnum].volR);
    AddBooleanToDictionary(dict, kSaveKey_echo, vpSet[pgnum].echo);
    AddNumToDictionary(dict, kSaveKey_bank, vpSet[pgnum].bank);
    AddBooleanToDictionary(dict, kSaveKey_MonoMode, vpSet[pgnum].monoMode);
    AddBooleanToDictionary(dict, kSaveKey_PortamentoOn, vpSet[pgnum].portamentoOn);
    AddNumToDictionary(dict, kSaveKey_PortamentoRate, vpSet[pgnum].portamentoRate);
    AddNumToDictionary(dict, kSaveKey_NoteOnPriority, vpSet[pgnum].noteOnPriority);
    AddNumToDictionary(dict, kSaveKey_ReleasePriority, vpSet[pgnum].releasePriority);

    //元波形情報
    AddBooleanToDictionary(dict, kSaveKey_IsEmphasized, vpSet[pgnum].isEmphasized);
    if ( vpSet[pgnum].sourceFile[0] ) {
        CFURLRef	url =
            CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)vpSet[pgnum].sourceFile,
                    strlen(vpSet[pgnum].sourceFile), false);
        CFDataRef urlData = CFURLCreateData( NULL, url, kCFStringEncodingUTF8, false );
        CFDictionarySetValue(dict, kSaveKey_SourceFile, urlData);
        CFRelease(urlData);
        CFRelease(url);
    }

    //プログラム名
    if (vpSet[pgnum].pgname[0] != 0) {
        CFStringRef	str = CFStringCreateWithCString(NULL, vpSet[pgnum].pgname, kCFStringEncodingUTF8);
        CFDictionarySetValue(dict, kSaveKey_ProgName, str);
        CFRelease(str);
    }

    *data = dict;
    return 0;
}
MDSAttrParser::MDSAttrParser(
	const char *bundlePath,
	MDSSession &dl,
	CSSM_DB_HANDLE objectHand,
	CSSM_DB_HANDLE cdsaDirHand) :
		mBundle(NULL),
		mPath(NULL),
		mDl(dl),
		mObjectHand(objectHand),
		mCdsaDirHand(cdsaDirHand),
		mGuid(NULL),
		mDefaults(NULL)
{
	/* Only task here is to cook up a CFBundle for the specified path */
	unsigned pathLen = strlen(bundlePath);
	CFURLRef url = CFURLCreateFromFileSystemRepresentation(NULL,
		(unsigned char *)bundlePath,
		pathLen,
		false);
	if(url == NULL) {
		Syslog::alert("CFURLCreateFromFileSystemRepresentation(%s) failure", mPath);
		CssmError::throwMe(CSSMERR_DL_INVALID_DB_NAME);
	}
	
	/* FIXME - this leaks 28 bytes each time thru, even though we CFRelease the
	 * mBundle in out destructor. I think this is a CF leak. */
	mBundle = CFBundleCreate(NULL, url);
	CFRelease(url);
	if(mBundle == NULL) {
		Syslog::alert("CFBundleCreate(%s) failure", mPath);
		CssmError::throwMe(CSSMERR_DL_INVALID_DB_NAME);
	}
	mPath = new char[pathLen + 1];
	strcpy(mPath, bundlePath);
}
/* do a [NSString stringByDeletingPathExtension] equivalent */
CFStringRef impExpImportDeleteExtension(
	CFStringRef			fileStr)
{
	CFDataRef fileStrData = CFStringCreateExternalRepresentation(NULL, fileStr,
		kCFStringEncodingUTF8, 0);
	if(fileStrData == NULL) {
		return NULL;
	}

	CFURLRef urlRef = CFURLCreateFromFileSystemRepresentation(NULL,
		CFDataGetBytePtr(fileStrData), CFDataGetLength(fileStrData), false);
	if(urlRef == NULL) {
		CFRelease(fileStrData);
		return NULL;
	}
	CFURLRef rtnUrl = CFURLCreateCopyDeletingPathExtension(NULL, urlRef);
	CFStringRef rtnStr = NULL;
	CFRelease(urlRef);
	if(rtnUrl) {
		rtnStr = CFURLGetString(rtnUrl);
		CFRetain(rtnStr);
		CFRelease(rtnUrl);
	}
	CFRelease(fileStrData);
	return rtnStr;
}
Exemple #8
0
int diskarb_unmount( const char * dir, int flags )
{
    int status;

    status = -1;

    if ( dir )
    {
        DASessionRef session;

        session = DASessionCreate( kCFAllocatorDefault );

        if ( session )
        {
            CFURLRef path;

            path = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) dir, strlen( dir ), TRUE );

            if ( path )
            {
                DADiskRef disk;

                disk = DADiskCreateFromVolumePath( kCFAllocatorDefault, session, path );

                if ( disk )
                {
                    DADiskUnmountOptions options;

                    options = kDADiskUnmountOptionDefault;

                    if ( ( flags & MNT_FORCE ) )
                    {
                       options |= kDADiskUnmountOptionForce;
                    }

                    DASessionScheduleWithRunLoop( session, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode );

                    DADiskUnmount( disk, options, __diskarb_unmount, &status );
 
                    if ( status == -1 )
                    {
                        CFRunLoopRun( );
                    }

                    status = status ? -1 : 0;

                    DASessionUnscheduleFromRunLoop( session, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode );

                    CFRelease( disk );
                }

                CFRelease( path );
            }

            CFRelease( session );
        }
    }

    return status;
}
Exemple #9
0
CFPropertyListRef Resources::getPropertyList(const char* filename)
{
    CFDataRef xmlCFDataRef;
    CFStringRef error;
    char cerror[10240];
    CFPropertyListRef myCFPropertyListRef = NULL;
    Boolean readOK;
    char  filePathBuf[PATH_MAX];
    CFStringRef filePath = this->getResourcePath(filename);
    CFStringGetCString(filePath, filePathBuf, sizeof(filePathBuf), kCFStringEncodingUTF8);
    CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const unsigned char*)filePathBuf, strlen (filePathBuf), false);
    if (fileURL!=NULL)  {
        readOK = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, fileURL, &xmlCFDataRef, NULL, NULL, NULL);
        if (readOK)
        {
            myCFPropertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, xmlCFDataRef, kCFPropertyListImmutable, &error);
            if (error != NULL){
                CFStringGetCString(error, cerror, sizeof(cerror), kCFStringEncodingUTF8);
                scprintf("getPropertyList error: %s\n", cerror);
            }
            CFRelease(xmlCFDataRef);
        }
        else{
            scprintf("Couldn't read Plist File %s\n", filePathBuf);
        }
    }
    return myCFPropertyListRef;
}
/*  Examines a directory, treating it as a bundle, and determines whether it has an executable.
*   Examines the executable as a regular file to determine which architectures it matches.
*   Prints out the results.
*/
static void examine_bundle(const uint8_t *bundle_path) {
    CFURLRef bundleURL = CFURLCreateFromFileSystemRepresentation(NULL, bundle_path, strlen((const char *)bundle_path), true), executableURL = NULL;
    CFBundleRef bundle = NULL;       
    uint8_t path[PATH_MAX];
    struct stat statBuf;
    if (bundleURL && (bundle = CFBundleCreate(NULL, bundleURL))) {
        // Try to obtain a path to an executable within the bundle.
        executableURL = CFBundleCopyExecutableURL(bundle);
        if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, path, PATH_MAX) && stat((const char *)path, &statBuf) == 0) {
            // Make sure it is a regular file, and if so examine it as a regular file.
            if ((statBuf.st_mode & S_IFMT) == S_IFREG) {
                examine_file(path);
            } else {
                printf("Unsupported file type for file %s.\n", path);
            }
        } else {
            printf("No executable located for %s.\n", bundle_path);
        }
    } else {
        printf("Cannot read %s.\n", bundle_path);
    }
    if (executableURL) CFRelease(executableURL);
    if (bundle) CFRelease(bundle);
    if (bundleURL) CFRelease(bundleURL);
}
Exemple #11
0
/* ------------------------------------------------------------------
 *	read_user_settings ()
 */
static CFPropertyListRef read_user_settings ( const char *in_file, CFPropertyListMutabilityOptions in_opts )
{
	CFPropertyListRef	cf_prop_list	= NULL;

	CFURLRef cf_url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)in_file, strlen(in_file), FALSE);
	if ( !cf_url ) {
		msg_error( "aod: could not create URL from %s", in_file);
		return( NULL );
	}

	SInt32 err;
	CFDataRef cf_data = NULL;
	if ( !CFURLCreateDataAndPropertiesFromResource(NULL, cf_url, &cf_data, NULL, NULL, &err) ) {
		if ( msg_verbose )
			msg_info("aod: no local user settings (%s), using defaults", in_file);
		CFRelease(cf_url);
		return( NULL );
	}

	CFStringRef cf_str_err = NULL;
	if ( cf_data ) {
		cf_prop_list = CFPropertyListCreateFromXMLData( kCFAllocatorDefault, cf_data, in_opts, &cf_str_err);
		if ( cf_prop_list )
			CFRetain(cf_prop_list);
	} else
		msg_error("aod: enable to create CFData ref for %s", in_file);

	CFRelease(cf_url);
	if ( cf_str_err )
		CFRelease( cf_str_err );
	if ( cf_data )
		CFRelease( cf_data );

	return( cf_prop_list );
} /* read_user_settings */
Exemple #12
0
QImage FileImageProvider::image(const QFileInfo &info, const QSize size) const
{
    QImage result;
#ifdef Q_OS_MAC
    QString path = info.absoluteFilePath();
    CGSize s;
    s.width = size.width();
    s.height = size.height();
    CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
                                                                (const UInt8*)path.toUtf8().data(),
                                                                path.length(),
                                                                true);
    if (url) {
        CGImageRef image = QLThumbnailImageCreate(kCFAllocatorDefault, url, s, 0);
        if (image) {
//            result = QPixmap::fromMacCGImageRef(image).toImage();
//            CFRelease(image);
        }

        CFRelease(url);
    }
#else
#endif
    if (result.isNull())
        result = icon(info).pixmap(size).toImage();

    return result;
}
static CFBundleRef _CFXBundleCreateFromImageName (CFAllocatorRef allocator, const char* image_name)
{
    CFURLRef myBundleExecutableURL = CFURLCreateFromFileSystemRepresentation (allocator, (const unsigned char*)image_name, strlen (image_name), false);
    if (myBundleExecutableURL == 0)
        return 0;

    CFURLRef myBundleContentsMacOSURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleExecutableURL); // Delete Versions/Current/Executable
    CFRelease (myBundleExecutableURL);
    if (myBundleContentsMacOSURL == 0)
        return 0;

    CFURLRef myBundleContentsURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleContentsMacOSURL); // Delete Current
    CFRelease (myBundleContentsMacOSURL);
    if (myBundleContentsURL == 0)
        return 0;

    CFURLRef theBundleURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleContentsURL); // Delete Versions
    CFRelease (myBundleContentsURL);
    if (theBundleURL == 0)
        return 0;

    CFBundleRef result = CFBundleCreate (allocator, theBundleURL);
    CFRelease (theBundleURL);

    return result;
}
bool ImageIODecoder::readHeader()
{
    CFURLRef         imageURLRef;
    CGImageSourceRef sourceRef;
    // diciu, if ReadHeader is called twice in a row make sure to release the previously allocated imageRef
    if (imageRef != NULL)
        CGImageRelease(imageRef);
    imageRef = NULL;

    imageURLRef = CFURLCreateFromFileSystemRepresentation( NULL,
        (const UInt8*)m_filename.c_str(), m_filename.size(), false );

    sourceRef = CGImageSourceCreateWithURL( imageURLRef, NULL );
    CFRelease( imageURLRef );
    if ( !sourceRef )
        return false;

    imageRef = CGImageSourceCreateImageAtIndex( sourceRef, 0, NULL );
    CFRelease( sourceRef );
    if( !imageRef )
        return false;

    m_width = CGImageGetWidth( imageRef );
    m_height = CGImageGetHeight( imageRef );

    CGColorSpaceRef colorSpace = CGImageGetColorSpace( imageRef );
    if( !colorSpace )
        return false;

    m_type = CGColorSpaceGetNumberOfComponents( colorSpace ) > 1 ? CV_8UC3 : CV_8UC1;

    return true;
}
Exemple #15
0
static CFURLRef _CFCopyHomeDirURLForUser(struct passwd *upwd) {
    CFURLRef home = NULL;
    if (upwd && upwd->pw_dir) {
        home = CFURLCreateFromFileSystemRepresentation(NULL, upwd->pw_dir, strlen(upwd->pw_dir), true);
    }
    return home;
}
Exemple #16
0
char* getBundleVersion(const char* bundlePath) {
    CFURLRef bundlePackageURL = NULL;
    bundlePackageURL = CFURLCreateFromFileSystemRepresentation(
        kCFAllocatorDefault,
        (const UInt8*)bundlePath,
        strlen(bundlePath),
        true);

    assert(bundlePackageURL);

    CFBundleRef bundle = NULL;
    bundle = CFBundleCreate(kCFAllocatorDefault, bundlePackageURL);
    assert(bundle);

    CFStringRef versionStr = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(
        bundle, kCFBundleVersionKey);

    int length = CFStringGetLength(versionStr)+1;
    char* ret = (char*)malloc(length);

    Boolean v = CFStringGetCString(versionStr, ret, length, kCFStringEncodingASCII);
    assert(v);

    CFRelease(bundle);
    CFRelease(bundlePackageURL);

    return ret;
}
Exemple #17
0
void
rbobj_to_alias_handle (VALUE obj, AliasHandle *alias)
{
    FSRef       ref;
    CFURLRef    URL;
    Boolean     ok;
    OSErr       error;

    Check_Type (obj, T_STRING);
    *alias = NULL;

    URL = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, 
                                                   (const UInt8 *)RSTRING (obj)->ptr, 
                                                   RSTRING (obj)->len,
                                                   0 /* XXX: normally passing 0 even if it's a directory should
                                                        not hurt, as we are just getting the FSRef. */); 
    if (URL == NULL)
        rb_raise (rb_eArgError, "Invalid path given");
    ok = CFURLGetFSRef (URL, &ref);
    CFRelease (URL);
    if (ok) {
        error = FSNewAlias (NULL, &ref, alias);
        if (error != noErr)
            rb_raise (rb_eArgError, "Cannot create alias handle for given filename '%s' : %s (%d)",
                      RSTRING (obj)->ptr, GetMacOSStatusErrorString (error), error); 
    }
    else {
        rb_raise (rb_eArgError, "Cannot obtain the filesystem reference for given filename '%s'",
                  RSTRING (obj)->ptr);
    }
}
Exemple #18
0
void InitMachOLibrary ()
{
	Dl_info info;
	if (dladdr ((const void*)InitMachOLibrary, &info))
	{
		if (info.dli_fname)
		{
			std::string name;
			name.assign (info.dli_fname);
			for (int i = 0; i < 3; i++)
			{
				int delPos = name.find_last_of ('/');
				if (delPos == -1)
				{
					fprintf (stdout, "Could not determine bundle location.\n");
					return; // unexpected
				}
				name.erase (delPos, name.length () - delPos);
			}
			CFURLRef bundleUrl = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*)name.c_str (), name.length (), true);
			if (bundleUrl)
			{
				VSTGUI_BUNDLEREF = CFBundleCreate (0, bundleUrl);
				CFRelease (bundleUrl);
			}
		}
	}
}
Exemple #19
0
CFStringRef Resources::getResourcesPathFromDyldImage(){
	const mach_header* header;
	header = (mach_header*)&_mh_bundle_header;
	const char* image_name = 0;
	char buffer[PATH_MAX];

	int cnt = _dyld_image_count();
	for (int i = 1; i < cnt; i++)
	{
		if (_dyld_get_image_header((unsigned long)i) == header)
		{
			image_name = _dyld_get_image_name(i);
			break;
		}
	}

	CFURLRef executableURL = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const unsigned char*)image_name, strlen (image_name), false);
	CFURLRef bundleContentsMacOSURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, executableURL);
	CFRelease (executableURL);
    CFURLRef bundleContentsURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, bundleContentsMacOSURL);
    CFRelease (bundleContentsMacOSURL);
    CFURLRef bundleURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, bundleContentsURL);
    CFRelease (bundleContentsURL);
    CFBundleRef bundle = CFBundleCreate (kCFAllocatorDefault, bundleURL);
    CFURLRef bundleResourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
	CFURLGetFileSystemRepresentation(bundleResourcesURL, TRUE, (UInt8*)buffer,PATH_MAX);
	CFStringRef path = CFStringCreateWithCString(NULL,buffer, kCFStringEncodingUTF8);
	return path;
}
// ----------------------------------------------------------
bool ofxAudioUnitSampler::setSamples(const std::vector<std::string> &samplePaths)
// ----------------------------------------------------------
{
	CFURLRef sampleURLs[samplePaths.size()];
	
	for(int i = 0; i < samplePaths.size(); i++)
	{
		sampleURLs[i] = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
																(const UInt8 *)samplePaths[i].c_str(),
																samplePaths[i].length(),
																NULL);
	}
	
	CFArrayRef samples = CFArrayCreate(NULL, (const void **)&sampleURLs, samplePaths.size(), &kCFTypeArrayCallBacks);
	
	OSStatus s = AudioUnitSetProperty(*_unit,
									 kAUSamplerProperty_LoadAudioFiles,
									 kAudioUnitScope_Global,
									 0,
									 &samples,
									 sizeof(samples));
	
	OFXAU_PRINT(s, "setting ofxAudioUnitSampler's source samples");
	
	for(int i = 0; i < samplePaths.size(); i++) CFRelease(sampleURLs[i]);
	
	CFRelease(samples);
	
	return s == noErr;
}
Exemple #21
0
static void _CFUpdateUserInfo(void) {
    struct passwd *upwd;

    __CFEUID = geteuid();
    __CFUID = getuid();
    if (__CFHomeDirectory)  CFRelease(__CFHomeDirectory);
    __CFHomeDirectory = NULL;
    if (__CFUserName) CFRelease(__CFUserName);
    __CFUserName = NULL;

    upwd = getpwuid(__CFEUID ? __CFEUID : __CFUID);
    __CFHomeDirectory = _CFCopyHomeDirURLForUser(upwd);
    if (!__CFHomeDirectory) {
        const char *cpath = getenv("HOME");
        if (cpath) {
            __CFHomeDirectory = CFURLCreateFromFileSystemRepresentation(NULL, cpath, strlen(cpath), true);
        }
    }

    // This implies that UserManager stores directory info in CString
    // rather than FileSystemRep.  Perhaps this is wrong & we should
    // expect NeXTSTEP encodings.  A great test of our localized system would
    // be to have a user "O-umlat z e r".  XXX
    if (upwd && upwd->pw_name) {
        __CFUserName = CFStringCreateWithCString(NULL, upwd->pw_name, kCFPlatformInterfaceStringEncoding);
    } else {
        const char *cuser = getenv("USER");
        if (cuser)
            __CFUserName = CFStringCreateWithCString(NULL, cuser, kCFPlatformInterfaceStringEncoding);
    }
}
// ----------------------------------------------------------
bool ofxAudioUnitFilePlayer::setFile(std::string filePath)
// ----------------------------------------------------------
{
	CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
																														 (const UInt8 *)filePath.c_str(),
																														 filePath.length(),
																														 NULL);
	
	if(fileID[0]) AudioFileClose(fileID[0]);
	
	OSStatus s = AudioFileOpenURL(fileURL, kAudioFileReadPermission, 0, fileID);
	
	CFRelease(fileURL);
	
	if(s != noErr)
	{
		if(s == fnfErr)
		{
			cout << "File not found : " << filePath << endl;
		}
		else 
		{
			cout << "Error " << s << " while opening file at " << filePath << endl;
		}
		return false;
	}
	
	UInt64 numPackets = 0;
	UInt32 dataSize = sizeof(numPackets);
	
	AudioFileGetProperty(fileID[0], kAudioFilePropertyAudioDataPacketCount, &dataSize, &numPackets);
	
	AudioStreamBasicDescription asbd = {0};
	dataSize = sizeof(asbd);
	
	AudioFileGetProperty(fileID[0], kAudioFilePropertyDataFormat, &dataSize, &asbd);
	
	// defining a region which basically says "play the whole file"
	memset(&region, 0, sizeof(region));
	region.mTimeStamp.mFlags = kAudioTimeStampSampleTimeValid;
	region.mTimeStamp.mSampleTime = 0;
	region.mCompletionProc = NULL;
	region.mCompletionProcUserData = NULL;
	region.mAudioFile = fileID[0];
	region.mLoopCount = 0;
	region.mStartFrame = 0;
	region.mFramesToPlay = numPackets * asbd.mFramesPerPacket;
	
	// setting the file ID now since it seems to have some overhead.
	// Doing it now ensures you'll get sound pretty much instantly after
	// calling play()
	return ERR_CHK_BOOL(AudioUnitSetProperty(*_unit,
																					 kAudioUnitProperty_ScheduledFileIDs,
																					 kAudioUnitScope_Global,
																					 0, 
																					 fileID, 
																					 sizeof(fileID)),
											"setting file player's file ID");
}
Exemple #23
0
int main (int argc, char * const argv[]) 
{
    char inputFile[]="blip.mp3";

    static const double threshold=0.50;
    int hardware=macbookpro;
    double x,y,z,prev_x,prev_y,prev_z;

    AudioFileID audioFile;

    CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inputFile, strlen(inputFile), false);

    
    XThrowIfError (AudioFileOpenURL (theURL, kAudioFileReadPermission, 0, &audioFile), "AudioFileOpenURL");
		    
		    // get the number of channels of the file
    CAStreamBasicDescription fileFormat;
    UInt32 propsize = sizeof(CAStreamBasicDescription);
    XThrowIfError (AudioFileGetProperty(audioFile, kAudioFilePropertyDataFormat, &propsize, &fileFormat), "AudioFileGetProperty");

// lets set up our playing state now
    AUGraph theGraph;
    CAAudioUnit fileAU;

// this makes the graph, the file AU and sets it all up for playing
    MakeSimpleGraph (theGraph, fileAU, fileFormat, audioFile);
	    

// now we load the file contents up for playback before we start playing
// this has to be done the AU is initialized and anytime it is reset or uninitialized
    Float64 fileDuration = PrepareFileAU (fileAU, fileFormat, audioFile);
    printf ("file duration: %f secs\n", fileDuration);

    read_sms_real(hardware,&x,&y,&z);
    prev_x=x;
    prev_y=y;
    prev_z=z;
    for(;;) {
	read_sms_real(hardware,&x,&y,&z);
	//printf("x: %f y: %f z: %f\n",x,y,z);
	if(isDelta(threshold,x,y,z,prev_x,prev_y,prev_z))
	    XThrowIfError (AUGraphStart (theGraph), "AUGraphStart");
	prev_x=x;
	prev_y=y;
	prev_z=z;
    }

// sleep until the file is finished
    //usleep ((int)(fileDuration * 1000. * 1000.));

// lets clean up
    XThrowIfError (AUGraphStop (theGraph), "AUGraphStop");
    XThrowIfError (AUGraphUninitialize (theGraph), "AUGraphUninitialize");
    XThrowIfError (AudioFileClose (audioFile), "AudioFileClose");
    XThrowIfError (AUGraphClose (theGraph), "AUGraphClose");
    
    return 0;
}	
Exemple #24
0
 music_obj<audio_queue_driver>::music_obj(const std::string& file_path, bool loop, float gain,
                                          float start, float end)
 : packet_index_(0)
 , start_packet_index_(0)
 , stop_packet_index_(0)
 , volume_(gain)
 , loop_(loop)
 , is_paused_(false)
 {
     CFURLRef file_url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)file_path.c_str(), file_path.size(), false);
     OSStatus res = AudioFileOpenURL(file_url, kAudioFileReadPermission, kAudioFileCAFType, &audio_file_);
     CFRelease(file_url);
     
     if(res)
     {
         throw sys_exception("audio_queue_driver: couldn't open audio file at '" + file_path + "'");
     }
     
     UInt32 size = sizeof(data_format_);
     AudioFileGetProperty(audio_file_, kAudioFilePropertyDataFormat, &size, &data_format_);
     
     AudioQueueNewOutput(&data_format_, &music_obj<audio_queue_driver>::buffer_cb, this, NULL, NULL, 0, &queue_);        
     AudioQueueAddPropertyListener(queue_, kAudioQueueProperty_IsRunning, &music_obj<audio_queue_driver>::playback_cb, this);
     
     if (data_format_.mBytesPerPacket == 0 || data_format_.mFramesPerPacket == 0)
     {
         size = sizeof(max_packet_size_);
         AudioFileGetProperty(audio_file_, kAudioFilePropertyPacketSizeUpperBound, &size, &max_packet_size_);
         if (max_packet_size_ > BUFFER_SIZE_BYTES)
         {
             max_packet_size_ = BUFFER_SIZE_BYTES;
         }
         
         num_packets_to_read_ = BUFFER_SIZE_BYTES / max_packet_size_;
         packet_descriptions_ = (AudioStreamPacketDescription*)malloc(sizeof(AudioStreamPacketDescription) * num_packets_to_read_);
     }
     else
     {
         num_packets_to_read_ = BUFFER_SIZE_BYTES / data_format_.mBytesPerPacket;
         packet_descriptions_ = NULL;
     }
     
     AudioFileGetPropertyInfo(audio_file_, kAudioFilePropertyMagicCookieData, &size, NULL);
     if (size > 0)
     {
         char* cookie = (char*)malloc(sizeof(char) * size);
         AudioFileGetProperty(audio_file_, kAudioFilePropertyMagicCookieData, &size, cookie);
         AudioQueueSetProperty(queue_, kAudioQueueProperty_MagicCookie, cookie, size);
         free(cookie);
     }
     
     calculate_seek(start, end);
     volume(volume_);
     prime();
 }
Exemple #25
0
CFBundleRef Bundle::cfBundle() const
{
	if (!mBundle) {
		secdebug("bundle", "instantiating CFBundle for %s", mPath.c_str());
		CFRef<CFURLRef> url = CFURLCreateFromFileSystemRepresentation(NULL,
			(const UInt8 *)mPath.c_str(), mPath.length(), true);
		if (!url || !(mBundle = CFBundleCreate(NULL, url)))
			CFError::throwMe();
	}
	return mBundle;
}
Exemple #26
0
//-----------------------------------------------------------------------------
bool CGBitmap::load (const CResourceDescription& desc)
{
	if (bits)
		return false;

	bool result = false;
	if (getBundleRef ())
	{
		// find the bitmap in our Bundle.
		// If the resource description is of type integer, it must be in the form of bmp00123.png, where the resource id would be 123.
		// else it just uses the name
		char filename [PATH_MAX];
		if (desc.type == CResourceDescription::kIntegerType)
			sprintf (filename, "bmp%05d", (int32_t)desc.u.id);
		else
			strcpy (filename, desc.u.name);
		CFStringRef cfStr = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
		if (cfStr)
		{
			CFURLRef url = NULL;
			if (filename[0] == '/')
				url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*)filename, strlen (filename), false);
			int32_t i = 0;
			while (url == NULL)
			{
				static CFStringRef resTypes [] = { CFSTR("png"), CFSTR("bmp"), CFSTR("jpg"), CFSTR("pict"), NULL };
				url = CFBundleCopyResourceURL (getBundleRef (), cfStr, desc.type == CResourceDescription::kIntegerType ? resTypes[i] : 0, NULL);
				if (resTypes[++i] == NULL)
					break;
			}
			CFRelease (cfStr);
			if (url)
			{
				CGImageSourceRef source = CGImageSourceCreateWithURL (url, NULL);
				if (source)
				{
					result = loadFromImageSource (source);
					CFRelease (source);
				}
				CFRelease (url);
			}
		}
	}
#if DEBUG
	if (result == false)
	{
		if (desc.type == CResourceDescription::kIntegerType)
			DebugPrint ("*** Bitmap Nr.:%d not found.\n", desc.u.id);
		else
			DebugPrint ("*** Bitmap '%s' not found.\n", desc.u.name);
	}
#endif
	return result;
}
Exemple #27
0
bool OSystem_MacOSX::displayLogFile() {
	// Use LaunchServices to open the log file, if possible.

	if (_logFilePath.empty())
		return false;

    CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)_logFilePath.c_str(), _logFilePath.size(), false);
    OSStatus err = LSOpenCFURLRef(url, NULL);
    CFRelease(url);

	return err != noErr;
}
Exemple #28
0
void QuartzBitmap_Output(QuartzDesc_t dev, QuartzBitmapDevice *qbd)
{
    if(qbd->path && qbd->uti) {
        /* On 10.4+ we can employ the CGImageDestination API to create a
           variety of different bitmap formats */
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
	char buf[PATH_MAX+1];
	snprintf(buf, PATH_MAX, qbd->path, qbd->page); buf[PATH_MAX] = '\0';
        CFStringRef pathString = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) buf, strlen(buf), kCFStringEncodingUTF8, FALSE);
        CFURLRef path;
        if(CFStringFind(pathString, CFSTR("://"), 0).location != kCFNotFound) {
            CFStringRef pathEscaped = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, pathString, NULL, NULL, kCFStringEncodingUTF8);
            path = CFURLCreateWithString(kCFAllocatorDefault, pathEscaped, NULL);
            CFRelease(pathEscaped);
        } else {
            path = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*) buf, strlen(buf), FALSE);
        }
        CFRelease(pathString);

        CFStringRef scheme = CFURLCopyScheme(path);
       	CFStringRef type  = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) qbd->uti, strlen(qbd->uti), kCFStringEncodingUTF8, FALSE);
    	CGImageRef image = CGBitmapContextCreateImage(qbd->bitmap);
        if(CFStringCompare(scheme,CFSTR("file"), 0) == 0) { /* file output */
            CGImageDestinationRef dest = CGImageDestinationCreateWithURL(path, type, 1, NULL);
	    if(dest) {
		CGImageDestinationAddImage(dest, image, NULL);
		CGImageDestinationFinalize(dest);
		CFRelease(dest);
	    } else 
		error(_("QuartzBitmap_Output - unable to open file '%s'"), buf);
        } else if(CFStringCompare(scheme, CFSTR("clipboard"), 0) == 0) { /* clipboard output */
            CFMutableDataRef      data = CFDataCreateMutable(kCFAllocatorDefault, 0);
            CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, type, 1, NULL);
            CGImageDestinationAddImage(dest, image, NULL);
            CGImageDestinationFinalize(dest);
            CFRelease(dest);
            PasteboardRef pb = NULL;
            if(PasteboardCreate(kPasteboardClipboard, &pb) == noErr) {
                PasteboardClear(pb);
                PasteboardSynchronize(pb);
                PasteboardPutItemFlavor(pb, (PasteboardItemID) 1, type, data, 0);
            }
            CFRelease(data);
        } else
            warning(_("not a supported scheme, no image data written"));
        CFRelease(scheme);
       	CFRelease(type);
        CFRelease(path);
        CFRelease(image);
#endif
    }
}
Exemple #29
0
OSStatus LoadSMF(const char *filename, MusicSequence& sequence, MusicSequenceLoadFlags loadFlags)
{
	OSStatus result = noErr;
	
	require_noerr (result = NewMusicSequence(&sequence), home);
	
	CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*)filename, strlen(filename), false);
	
	require_noerr (result = MusicSequenceFileLoad (sequence, url, 0, loadFlags), home);
	
home:
	return result;
}
Exemple #30
0
static CFURLRef
str_to_url(VALUE path) {
#ifdef FilePathValue
  VALUE p = FilePathValue(path);
#else
  VALUE p = rb_String(path);
#endif
  CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)RSTRING_PTR(p), RSTRING_LEN(p), false);
  if (!fileURL) {
    rb_raise(rb_eArgError, "Unable to create CFURL from `%s'.", RSTRING_PTR(rb_inspect(path)));
  }
  return fileURL;
}