bool 	createMovieFromPath(char * path, Movie &movie){



	Boolean 	isdir			= false;
	OSErr 		result 			= 0;
	FSSpec 		theFSSpec;

	short 		actualResId 	= DoTheRightThing;

	#ifdef TARGET_WIN32
		result = NativePathNameToFSSpec (path, &theFSSpec, 0);
		if (result != noErr) {
			ofLog(OF_LOG_ERROR,"NativePathNameToFSSpec failed %d", result);
			ofLog(OF_LOG_ERROR,"Error loading movie");
			return false;
		}

	#endif



	#ifdef TARGET_OSX
		FSRef 		fsref;
		result = FSPathMakeRef((const UInt8*)path, &fsref, &isdir);
		if (result) {
			ofLog(OF_LOG_ERROR,"FSPathMakeRef failed %d", result);
			ofLog(OF_LOG_ERROR,"Error loading movie");
			return false;
		}
		result = FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &theFSSpec, NULL);
		if (result) {
			ofLog(OF_LOG_ERROR,"FSGetCatalogInfo failed %d", result);
			ofLog(OF_LOG_ERROR,"Error loading movie");
			return false;
		}
	#endif


	short movieResFile;
	result = OpenMovieFile (&theFSSpec, &movieResFile, fsRdPerm);
	if (result == noErr) {

		short   movieResID = 0;
		result = NewMovieFromFile(&movie, movieResFile, &movieResID, (unsigned char *) 0, newMovieActive, (Boolean *) 0);
		if (result == noErr){
			CloseMovieFile (movieResFile);
		} else {
			ofLog(OF_LOG_ERROR,"NewMovieFromFile failed %d", result);
			return false;
		}
	} else {
		ofLog(OF_LOG_ERROR,"OpenMovieFile failed %d", result);
		return false;
	}

	return true;
}
void ofQtVideoSaver::addAudioTrack(string audioPath)
{
	if(audioPath == "")
        return;
    OSErr err;
    Handle dataRef = NULL;

    FSSpec    fileSpec;
    short audioMovieRefNum = 0;
    short audioMovieResId = 0;

    Movie audioMovie = NULL;
    Track audioCopyTrack = NULL;
    Media audioCopyMedia = NULL;

    Track destTrack = NULL;
    Media destMedia = NULL;

    destTrack =    NewMovieTrack (movie, 0, 0, kFullVolume);

    destMedia = NewTrackMedia (destTrack, SoundMediaType,
                            30. * 100, /* Video Time Scale */
                            nil, 0);

    err = BeginMediaEdits (destMedia);
   
 
    char * p = new char[audioPath.length()+1];
    strcpy(p, audioPath.c_str());

    NativePathNameToFSSpec(p, &fileSpec, 0L);
    err = OpenMovieFile(&fileSpec, &audioMovieRefNum, fsRdPerm);

    err = NewMovieFromFile(&audioMovie, audioMovieRefNum, &audioMovieResId, NULL, newMovieActive, NULL);

    err = CloseMovieFile(audioMovieRefNum);

    SetMovieTimeScale(audioMovie, 30.*100);

    audioCopyTrack = GetMovieTrack(audioMovie, 1);

    audioCopyMedia = GetTrackMedia(audioCopyTrack);

    long duration = GetMovieDuration(audioMovie);

    err = AddEmptyTrackToMovie (audioCopyTrack, movie, nil, nil, &destTrack);

    err = InsertTrackSegment(audioCopyTrack, destTrack, 0, duration, 0);

	err = EndMediaEdits(destMedia);

}
Ejemplo n.º 3
0
bool 	createMovieFromPath(char * path, Movie &movie){

	Boolean 	isdir			= false;
	OSErr 		result 			= 0;
	FSSpec 		theFSSpec;

	short 		actualResId 	= DoTheRightThing;

	#ifdef TARGET_WIN32
		result = NativePathNameToFSSpec (path, &theFSSpec, 0);
		if (result != noErr) {
			ofLogError("ofQuickTimePlayer") << "createMovieFromPath(): couldn't load movie, NativePathNameToFSSpec failed: OSErr " << result;
			return false;
		}

	#endif

	#ifdef TARGET_OSX
		FSRef 		fsref;
		result = FSPathMakeRef((const UInt8*)path, &fsref, &isdir);
		if (result) {
			ofLogError("ofQuickTimePlayer") << "createMovieFromPath(): couldn't load movie, FSPathMakeRef failed: OSErr " << result;
			return false;
		}
		result = FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &theFSSpec, NULL);
		if (result) {
			ofLogError("ofQuickTimePlayer") << "createMovieFromPath(): couldn't load movie, FSGetCatalogInfo failed: OSErr ", result;
			return false;
		}
	#endif

	short movieResFile;
	result = OpenMovieFile (&theFSSpec, &movieResFile, fsRdPerm);
	if (result == noErr) {

		short   movieResID = 0;
		result = NewMovieFromFile(&movie, movieResFile, &movieResID, (unsigned char *) 0, newMovieActive, (Boolean *) 0);
		if (result == noErr){
			CloseMovieFile (movieResFile);
		} else {
			ofLogError("ofQuickTimePlayer") << "createMovieFromPath(): couldn't load movie, NewMovieFromFile failed: OSErr " << result;
			return false;
		}
	} else {
		ofLogError("ofQuickTimePlayer") << "createMovoeFromPath(): couldn't load movie, OpenMovieFile failed: OSErr " << result;
		return false;
	}

	return true;
}
void ofxQtVideoSaver::addAudioTrack(string audioPath)
{
	OSErr err;
	Handle dataRef = NULL;
	FSSpec    fileSpec;
	short audioMovieRefNum = 0;
	short audioMovieResId = 0;
	Movie audioMovie = NULL;
	Track audioCopyTrack = NULL;
	Media audioCopyMedia = NULL;
	Track destTrack = NULL;
	Media destMedia = NULL;

	destTrack = NewMovieTrack (movie, 0, 0, kFullVolume);
	destMedia = NewTrackMedia (destTrack, SoundMediaType,
							   (TimeScale) (30.f * 100), /* Video Time Scale */
							   nil, 0);

	err = BeginMediaEdits (destMedia);

	char * p = new char[audioPath.length()+1];
    strcpy(p, audioPath.c_str());
#ifdef TARGET_WIN32
    NativePathNameToFSSpec(p, &fileSpec, 0L);
#endif
#ifdef TARGET_OSX
	Boolean isdir;
	FSPathMakeRef((const UInt8*)p, &fsref, &isdir);
	FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL);
#endif

	err = OpenMovieFile(&fileSpec, &audioMovieRefNum, fsRdPerm);
	err = NewMovieFromFile(&audioMovie, audioMovieRefNum, &audioMovieResId, NULL, newMovieActive, NULL);
	err = CloseMovieFile(audioMovieRefNum);

	SetMovieTimeScale(audioMovie, (TimeScale) (30.*100));

	audioCopyTrack = GetMovieTrack(audioMovie, 1);
	audioCopyMedia = GetTrackMedia(audioCopyTrack);

	long duration = GetMovieDuration(audioMovie);

	err = AddEmptyTrackToMovie (audioCopyTrack, movie, 0, 0, &destTrack);
	err = InsertTrackSegment(audioCopyTrack, destTrack, 0, duration, 0);
	err = EndMediaEdits(destMedia);
}
Ejemplo n.º 5
0
OSErr QTCode_NewMovieFromWinPathname(char	*pathName,		/* c-string path to movie */
									Movie	*theMovie,		/* Movie returned here */
									short	*movieRefNum,	/* Movie RefNum returned here */
									short	*movieResId)	/* Movie Resource ID returned here */
{
	FSSpec	fileSpec;
	OSErr	err;


	*theMovie = NULL;
	*movieRefNum = 0;
	*movieResId = 0;

	// Open up the movie file...

	// Fill in an FSSpec.
	NativePathNameToFSSpec(pathName, &fileSpec, 0L);

	err = OpenMovieFile(&fileSpec, movieRefNum, fsRdWrPerm);
	if (err)
	{
		err = OpenMovieFile(&fileSpec, movieRefNum, fsRdPerm);
	}

	if (!err)
	{
		err = NewMovieFromFile(theMovie, *movieRefNum, movieResId, NULL, newMovieActive, NULL);
	}

	if (err)
	{
		if (*theMovie)
		{
			DisposeMovie(*theMovie);
		}
	}

	return err;
}
Ejemplo n.º 6
0
GLuint texture_load(const char *filename)
{
    FSSpec fss;
    ComponentInstance gi;
    Rect rect;
    GWorldPtr world;
	
    int width;
    int height;
    int pitch;
    unsigned char *buffer;
	
    GLuint id;
	
    NativePathNameToFSSpec(filename, &fss);
    GetGraphicsImporterForFile(&fss, &gi);
    GraphicsImportGetNaturalBounds(gi, &rect);
	
    width = rect.right;
    height = rect.bottom;
    pitch = width * 4;
    buffer = malloc(pitch * height);
    QTNewGWorldFromPtr(&world, k32ARGBPixelFormat, &rect, NULL, NULL, 0,
                       buffer, pitch);
	
    GraphicsImportSetGWorld(gi, world, NULL);
    GraphicsImportDraw(gi);
    DisposeGWorld(world);
    CloseComponent(gi);
	
    id = texture_load_data(buffer, width, height,
                           4, -pitch,
                           GL_RGBA, ARGB_FORMAT, ARGB_TYPE);
    free(buffer);
	
    return id;
}
void ofQtVideoSaver::setup( int width , int height, string movieName){

	w = width;
	h = height;
    
   
    fileName = (ofToDataPath(movieName));
    //pszFlatFilename = flatFileName;
    
    initializeQuicktime();
    	/*  Load the FSSpec structure to describe the receiving file.  For a 
    description of this and related calls see 
    http://developer.apple.com/quicktime/icefloe/dispatch004.html.
    ================================================================  */


	#ifdef TARGET_WIN32
		//FILE * pFile = NULL;
		//pFile = fopen (fileName.c_str(),"w");
		//fclose (pFile);
		char fileNameStr[255];
		sprintf(fileNameStr, "%s", fileName.c_str());
		osErr = NativePathNameToFSSpec (fileNameStr, &fsSpec, 0);
		
	#endif
	#ifdef TARGET_OSX
	
		/// kill a file and make a new one if needed:		
		FILE * pFile;
		pFile = fopen (fileName.c_str(),"w");
		fclose (pFile);
	
		Boolean isdir;
		osErr = FSPathMakeRef((const UInt8*)fileName.c_str(), &fsref, &isdir);
		osErr = FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fsSpec, NULL);
	#endif

    if (osErr && (osErr != fnfErr))    /* File-not-found error is ok         */
      { 
      printf ("getting FSS spec failed %d\n", osErr); 
      goto bail; 
     }
	 

	/*  Step 1:  Create a new, empty movie file and a movie that references that 
    file (CreateMovieFile).  
    ======================================================================== */
            
    osErr = CreateMovieFile 
      (
      &fsSpec,                         /* FSSpec specifier                   */
      FOUR_CHAR_CODE('TVOD'),          /* file creator type, TVOD = QT player*/
      smCurrentScript,                 /* movie script system to use         */
      createMovieFileDeleteCurFile     /* movie file creation flags          */
        | createMovieFileDontCreateResFile,
      &sResRefNum,                     /* returned file ref num to data fork */
      &movie                           /* returned handle to open empty movie*/
                                       /*   that references the created file */
      );
    if (osErr) 
      { 
      printf ("CreateMovieFile failed %d\n", osErr); 
      goto bail; 
      }


	/*  Step 2:  Add a new track to that movie (NewMovieTrack).
    =======================================================  */

    track = NewMovieTrack 
      (
      movie,                           /* the movie to add track to          */
      ((long) w << 16),              /* width of track in pixels (Fixed)   */
      FixRatio (h, 1),               /* height of track in pixels (Fixed)  */ 
      kNoVolume                        /* default volume level               */
      );
    osErr = GetMoviesError ();
    if (osErr) 
      { 
      printf ("NewMovieTrack failed %d\n", osErr); 
      goto bail; 
      }
    

	/*  Step 3:  Add a new media to that track (NewTrackMedia).
    =======================================================  */
    
    media = NewTrackMedia 
      (
      track,                           /* the track to add the media to      */
      VideoMediaType,                  /* media type, e.g. SoundMediaType    */
      600,                             /* num media time units that elapse/sec*/
      NULL,                            /* ptr to file that holds media sampls*/
      0                                /* type of ptr to media samples       */
      );
    osErr = GetMoviesError ();
    if (osErr) 
      { 
      printf ("NewTrackMedia failed %d\n", osErr); 
      goto bail; 
      }

	/*  Step 4:  Add media samples to the media. 
    ========================================  */
    
    BeginMediaEdits (media);           /* Inform the Movie Toolbox that we   */
                                       /*   want to change the media samples */
                                       /*   referenced by a track's media.   */
                                       /*   This opens the media container   */
                                       /*   and makes it ready to receive    */
                                       /*   and/or remove sample data.       */
    
    
    

    // Step 5: setup graphics port for qt movie and compression type ---
    
    /*  Create a new offscreen graphics world that will hold the movie's
    drawing surface.  draw_image() copies the image of IceFlow to this
    surface with varying amounts of transparency.
    =================================================================  */
    
    MacSetRect (&rect, 0, 0, w, h);

    osErr = NewGWorld 
      (
      &pMovieGWorld,                   /* receives the new GWorld.           */
      24,                              /* pixel depth in bits/pixel          */
      &rect,                           /* desired size of the GWorld.        */
      NULL, 
      NULL, 
      (GWorldFlags) 0
      );
    if (osErr != noErr) 
      { 
      printf ("NewGWorld 1 failed %d\n", osErr); 
      goto bail; 
      }


/*  Retrieve the pixel map associated with that graphics world and lock 
    the pixel map in memory.  GetMaxCompressionSize() and CompressImage()
    only operate on pixel maps, not graphics worlds.
    =====================================================================  */
    
    pixMapHandle = GetGWorldPixMap (pMovieGWorld);
    if (pixMapHandle == NULL) 
      { 
      printf ("GetGWorldPixMap failed\n"); 
      goto bail; 
      }
    LockPixels (pixMapHandle);


/*  Get the maximum number of bytes required to hold an image having the 
    specified characteristics compressed using the specified compressor.
    ====================================================================  */

     
    osErr = GetMaxCompressionSize 
      (
      pixMapHandle,							/* the pixel map to compress from.    */
      &rect,								/* the image rectangle.               */
      0,									/* let ICM choose image bit depth.    */
      codecHighQuality,						/* compression quality specifier.     */
      kRawCodecType,						/* desired compression type           */   // < set to RAW in case we set to a new compression type...
      (CompressorComponent) anyCodec,		/* codec specifier.                   */
      &lMaxCompressionSize					/* receives max bytes needed for cmp. */
      );
    if (osErr != noErr) 
      { 
      printf ("GetMaxCompressionSize failed %d\n", osErr); 
      goto bail; 
      }


/*  Allocate a buffer to hold the compressed image data by creating a new
    handle.
    =====================================================================  */
    hCompressedData = NewHandle (lMaxCompressionSize);
    if (hCompressedData == NULL) 
      { 
      printf ("NewHandle(%ld) failed\n", lMaxCompressionSize); 
      goto bail; 
      }

/*  Lock the handle and then dereference it to obtain a pointer to the data 
    buffer because CompressImage() wants us to pass it a pointer, not a 
    handle. 
    =======================================================================  */

    HLockHi (hCompressedData);
    pCompressedData = *hCompressedData;

/*  Create an image description object in memory of minimum size to pass 
    to CompressImage().  CompressImage() will resize the memory as 
    necessary so create it small here.
    ====================================================================  */
    
    hImageDescription = (ImageDescriptionHandle) NewHandle (4);
    if (hImageDescription == NULL) 
      { 
      printf ("NewHandle(4) failed\n"); 
      goto bail; 
      }
	
	
	
	bSetupForRecordingMovie = true;
    return;
    
    
    
    
  bail:    
	printf("got to bail somehows \n");
    if (sResRefNum != 0) CloseMovieFile (sResRefNum);
    if (movie     != NULL) DisposeMovie (movie);

    //ExitMovies ();                     /* Finalize Quicktime                 */
    
    return;
}
Ejemplo n.º 8
0
void QTSound_CreateMySoundTrack (Movie theMovie)
{
    Track theTrack;
    Media theMedia;
    Handle sndHandle = nil;
    SoundDescriptionHandle sndDesc = nil;
    long sndDataOffset;
    long sndDataSize;
    long numSamples;
    OSErr err = noErr;
#if TARGET_OS_WIN32

    char path[MAX_PATH+1];
    short resID;
    FSSpec fsspec;


    fsspec.vRefNum = 0;
    fsspec.parID = 0;
    GetModuleFileName( NULL, path, MAX_PATH+1);

    NativePathNameToFSSpec((char *)&path, &fsspec, 0);

    /* open our application resource file so we
    	can access the Macintosh 'snd ' resource */
    resID = FSpOpenResFile(&fsspec, fsRdPerm);
    CheckError (ResError(), "FSpOpenResFile error" );

#endif



    sndHandle = GetResource ('snd ', kOurSoundResourceID);
    CheckError (ResError(), "GetResource error" );
    if (sndHandle == nil)
    {
        return;
    }

    sndDesc = (SoundDescriptionHandle) NewHandle(4);
    CheckError (MemError(), "NewHandle error" );

    QTSound_CreateSoundDescription (sndHandle,
                                    sndDesc,
                                    &sndDataOffset,
                                    &numSamples,
                                    &sndDataSize );

    theTrack = NewMovieTrack (theMovie, 0, 0, kFullVolume);
    CheckError (GetMoviesError(), "NewMovieTrack error" );

    theMedia = NewTrackMedia (theTrack, SoundMediaType,
                              FixRound ((**sndDesc).sampleRate),
                              nil, 0);
    CheckError (GetMoviesError(), "NewTrackMedia error" );

    err = BeginMediaEdits (theMedia);
    CheckError( err, "BeginMediaEdits error" );

    err = AddMediaSample(theMedia,
                         sndHandle,
                         sndDataOffset,/* offset in data */
                         sndDataSize,
                         kSoundSampleDuration,/* duration of each sound sample */
                         (SampleDescriptionHandle) sndDesc,
                         numSamples,
                         kSyncSample,/* self-contained samples */
                         nil);
    CheckError( err, "AddMediaSample error" );

    err = EndMediaEdits (theMedia);
    CheckError( err, "EndMediaEdits error" );

    err = InsertMediaIntoTrack (theTrack,
                                kTrackStart,/* track start time */
                                kMediaStart,/* media start time */
                                GetMediaDuration (theMedia),
                                fixed1);
    CheckError( err, "InsertMediaIntoTrack error" );

    if (sndDesc != nil)
    {
        DisposeHandle( (Handle)sndDesc);
    }
}
Ejemplo n.º 9
0
GLuint platformLoadTextureFile(string theFilename, bool generateMipmaps, int *width, int *height)
{
#ifdef QuickTimeInstalled
	GLuint					textureName;				// the "name" by which OpenGL knows the texture
	unsigned char 			*pImageBuffer;				// the buffer that contains the image data 
	GWorldPtr				pGWorld;					// a gworld to load the image into
	
	int						imageDepth;
	
	FSSpec 					fsspecImage;				// FSSpec of the image to load
#ifdef __APPLE__	
	CFURLRef				imageURL;
	FSRef					imagefsRef;
#endif
	
	OSStatus				err = noErr;				// err return value
	long					rowStride;					// length, in bytes, of a pixel row in the image
	GraphicsImportComponent giComp;						// component for importing image
	MatrixRecord			matrix;
	Rect 					rectImage;					// rectangle of source image
	PixMapHandle			hPixMap;					// handle to image pix map
	ImageDescriptionHandle	hImageDesc;					// handle to image description used to get image depth

	long					imageWidth;
	long					imageHeight;
	float					imageAspect;
	long					textureWidth;
	long					textureHeight;



	// get the full path to the texture file
	string fileLocation;
	fileLocation = pathToResourceDirectory() + theFilename;



#ifdef __APPLE__	
	// create a URL to the file from the C string
	imageURL = CFURLCreateWithBytes (kCFAllocatorDefault, (UInt8 *)fileLocation.c_str(), fileLocation.length(), kCFStringEncodingASCII, NULL);
	if (imageURL == NULL)
	{
		cout << "error getting URL for image file (image file may not exist): " << theFilename << endl;
		return 0;
	}


	// get a FSRef from the URL
	if (!CFURLGetFSRef(imageURL, &imagefsRef))
	{
		cout << "error getting FSRef for image file:: " << theFilename << endl;
		CFRelease(imageURL);
		return 0;
	}
	

	// get the FSSpec from the FSRef
	if (FSGetCatalogInfo (&imagefsRef, kFSCatInfoNone, NULL, NULL, &fsspecImage, NULL))
	{
		cout << "error getting FSSpec for image file: " << theFilename << endl;
		CFRelease(imageURL);
		return 0;
	}
	
	
	// release the URL (not needed any more)
	CFRelease(imageURL);
#endif

#ifdef _WIN32
	// get an FSSpec from the pathname
	if (NativePathNameToFSSpec ((char *)fileLocation.c_str(), &fsspecImage, kErrorIfFileNotFound))
	{
		cout << "error getting FSSpec for image file: " << fileLocation << endl;
		return 0;
	}
#endif


	// save the onscreen graphics port
	GDHandle	origDevice;
	CGrafPtr	origPort;
	GetGWorld (&origPort, &origDevice);


	// get an importer for the file
	err = GetGraphicsImporterForFileWithFlags (&fsspecImage, &giComp, kDontUseValidateToFindGraphicsImporter);
	if (err != noErr) return 0;

	
	// get the image bounds
	err = GraphicsImportGetNaturalBounds (giComp, &rectImage); 
	if (err != noErr) return 0;


	// create a handle for the image description and lock it
	hImageDesc = (ImageDescriptionHandle) NewHandle (sizeof (ImageDescriptionHandle)); 
	HLock ((Handle) hImageDesc);


	// retrieve the image description
	err = GraphicsImportGetImageDescription (giComp, &hImageDesc); 
	if (err != noErr) return 0;
	
	
	// find width and height
	imageWidth = (int) (rectImage.right - rectImage.left);
	imageHeight = (int) (rectImage.bottom - rectImage.top);

	
	// now calculate the aspect ratio (width/height), used to restore image correctly
	imageAspect = ((float) imageWidth) / ((float) imageHeight);

	
	// get the image's pixel depth
	imageDepth = (**hImageDesc).depth;

	
	// find nearest acceptable texture size (width and height) for the image
	textureWidth = GetTextureDimFromImageDim (imageWidth);
	textureHeight = GetTextureDimFromImageDim (imageHeight);
	
	
	// pass the optimised (and scaled) size back out to the caller
	*width = textureWidth;
	*height = textureHeight;


	// set texture rectangle for creation of GWorld
#ifdef __APPLE__
	SetRect (&rectImage, 0, 0, (int) textureWidth, (int) textureHeight);
#endif
#ifdef _WIN32
	MacSetRect (&rectImage, 0, 0, (int) textureWidth, (int) textureHeight);
#endif

	// set stride in bytes width of image * 4 bytes per pixel
	rowStride = textureWidth * 4;
	
	// build new buffer exact size of image (stride * height)
	pImageBuffer = (unsigned char *) NewPtr (rowStride * textureHeight); 


	// check we got the buffer we wanted
	if (pImageBuffer == NULL)
	{
		// failed - release the component and return an error
		CloseComponent(giComp);
		return 0;
	}

	
	// create a new gworld using our unpadded buffer, setting the pixel type correctly for the expected image depth
#ifdef __BIG_ENDIAN__
	QTNewGWorldFromPtr (&(pGWorld), k32ARGBPixelFormat, &rectImage, NULL, NULL, 0, pImageBuffer, rowStride);
#else
	QTNewGWorldFromPtr (&(pGWorld), k32RGBAPixelFormat, &rectImage, NULL, NULL, 0, pImageBuffer, rowStride);
#endif
	
	
	// could we allocate the GWorld?
	if (pGWorld == NULL)
	{
		// failed - release the buffer, component and return an error
		DisposePtr ((Ptr) pImageBuffer);
		CloseComponent(giComp);
		return 0;
	}


	// build a transformation matrix to scale the image to the texture size
	// this also flips the image horizontally, so that texture coordinates map correctly
	float	horizontalScale = (float) textureWidth / (float) imageWidth;
	float	verticalScale = (float) textureHeight / (float) imageHeight;

	SetIdentityMatrix (&matrix);
	ScaleMatrix (&matrix, X2Fix(horizontalScale), X2Fix(-verticalScale), 0, 0);
	TranslateMatrix (&matrix, 0, X2Fix((float)textureHeight));


	// set the matrix as the importer matrix
	err = GraphicsImportSetMatrix(giComp, &matrix); 

	// set the destination of the importer component
	if (err == noErr) err = GraphicsImportSetGWorld (giComp, pGWorld, NULL);
	
	// ensure lossless decompression (if the CODEC supports this)
	if (err == noErr) err = GraphicsImportSetQuality(giComp, codecLosslessQuality); 

	if (err != noErr)
	{
		// failed - release the GWorld, buffer, component and return an error
		DisposeGWorld (pGWorld);
		DisposePtr ((Ptr) pImageBuffer);
		CloseComponent(giComp);
		return 0;
	}

	// get the address of the GWorld's pixmap
	hPixMap = GetGWorldPixMap (pGWorld);
	
	// if everything looks good draw the image to the locked pixmap
	if ((hPixMap) && (LockPixels (hPixMap)))
		GraphicsImportDraw (giComp);
	else
	{
		// the pixmap doesn't exist, or we couldn't lock it
		// release the GWorld, buffer, component and return an error
		DisposeGWorld (pGWorld);
		DisposePtr ((Ptr) pImageBuffer);
		CloseComponent(giComp);
		return 0;
	}


	// for images without an alpha channel, initialise the alpha bytes since QuickTime won't
	if (imageDepth < 32)
	{
#ifdef __BIG_ENDIAN__
		for( unsigned char *p = pImageBuffer; p < pImageBuffer + (rowStride * textureHeight); p+=4)
			*p = 0xFF;
#else
		for( unsigned char *p = pImageBuffer+3; p < pImageBuffer + (rowStride * textureHeight) +3; p+=4)
			*p = 0xFF;
#endif
	}

	// unlock the pixmap
	UnlockPixels (hPixMap);
	
	
	// dump the component
	CloseComponent(giComp);

	
	// set image width in groups (pixels), accounts for border this ensures proper image alignment row to row
	glPixelStorei (GL_UNPACK_ROW_LENGTH, textureWidth);


	// generate a "name" for the texture
	glGenTextures (1, &textureName);
	
	
	// create the texture in OpenGL
	glBindTexture(GL_TEXTURE_2D, textureName);



	// tell OpenGL about the texture and have GLU build mipmaps
#ifdef __BIG_ENDIAN__
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pImageBuffer);
#else
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pImageBuffer);
#endif
	if (generateMipmaps)
#ifdef __BIG_ENDIAN__
	if (gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, textureWidth, textureHeight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pImageBuffer) != 0)
#else
	if (gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, textureWidth, textureHeight, GL_RGBA, GL_UNSIGNED_BYTE, pImageBuffer) != 0)
#endif
	
	
	// good time to check for errors?
	openGLCheckError();
	

	// finished with the GWorld but not the image buffer (it's used by OpenGL as the "live" image buffer)
	DisposeGWorld (pGWorld);

	// restore the current graphics port we saved earlier
	SetGWorld(origPort, origDevice);


	// all done - return the texture name
	return textureName; 
#endif // QuickTimeInstalled
}
Ejemplo n.º 10
0
long platformLoadSoundFile (string theFilename)
{
#ifdef QuickTimeInstalled
	short			myRefNum;
	OSStatus		err = noErr;
	Movie			theMovie;
	FSSpec			theSoundFile;

#ifdef __APPLE__
	CFURLRef		musicURL;
	FSRef			musicfsRef;
#endif


	// get the full path to the sound file
	string fileLocation;
	fileLocation = pathToResourceDirectory() + theFilename;


#ifdef __APPLE__
	// create a URL to the file from the C string
	musicURL = CFURLCreateWithBytes (kCFAllocatorDefault, (UInt8 *)fileLocation.c_str(), fileLocation.length(), kCFStringEncodingASCII, NULL);
	if (musicURL == NULL)
	{
		cout << "error getting URL for sound file " << fileLocation << " (sound file may not exist)";
		return 0L;
	}

	// get a FSRef from the URL
	if (!CFURLGetFSRef(musicURL, &musicfsRef))
	{
		cout << "error getting FSRef for sound file " << fileLocation << " (sound file may not exist)";
		CFRelease(musicURL);
		return 0L;
	}
	
	// get the FSSpec from the FSRef
	if (FSGetCatalogInfo (&musicfsRef, kFSCatInfoNone, NULL, NULL, &theSoundFile, NULL))
	{
		cout << "error getting FSSpec for sound file " << fileLocation << " (sound file may not exist)";
		CFRelease(musicURL);
		return 0L;
	}
		
	// release the URL (not needed any more)
	CFRelease(musicURL);
#endif

#ifdef _WIN32
	// get an FSSpec from the pathname
	if (NativePathNameToFSSpec ((char *)fileLocation.c_str(), &theSoundFile, 0))
	{
		cout << "error getting FSSpec for sound file " << fileLocation << " (sound file may not exist)" << endl;
		return 0L;
	}
#endif
	


	// tell QuickTime to open the sound file
	err = OpenMovieFile(&theSoundFile, &myRefNum, fsRdPerm);
	if (err)
	{
		cout << "OpenMovieFile returned " << (long)err << endl;
		return 0L;
	}
	else
	{
		// tell QuickTime to imagine that this is a movie
		NewMovieFromFile(&theMovie, myRefNum, NULL, (StringPtr)NULL, newMovieActive, NULL);
		if (myRefNum != 0)
			CloseMovieFile(myRefNum);
	}
	
	
	// return the reference to the sound
	return (long)theMovie;

#endif // QuickTimeInstalled
}
Ejemplo n.º 11
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {

  if (nlhs < 0) { mexErrMsgTxt("Too few output arguments."); return; }
  if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); return; }
  if (nrhs < 1) { mexErrMsgTxt("Too few input arguments."); return; }
  if (nrhs > 3) { mexErrMsgTxt("Too many input arguments."); return; }

  TimeValue duration;
  TimeRecord myTimeRecord;
  Rect bounds;
  OSErr result = 0;
  short resRefNum = -1;
  short actualResId = DoTheRightThing;
  FSSpec theFSSpec;
  GWorldPtr offWorld;
  Movie theMovie = nil;
  MovieController thePlayer = nil;
  MovieDrawingCompleteUPP myDrawCompleteProc;
  long frame_end;
  long myStep = 1;
  char location[PATH_BUFFER_SIZE];
  long frame_count;
  mwSize cdims[2];

  mxGetString(prhs[0], location, PATH_BUFFER_SIZE);

  if (nrhs > 2) {
    frame_start = rint(mxGetScalar(prhs[1]));
    frame_end = rint(mxGetScalar(prhs[2]));
  } else if (nrhs > 1) {
    frame_start = 1;
    frame_end = rint(mxGetScalar(prhs[1]));
  } else {
    frame_start = 1;
    frame_end = 0;
  }

  if (frame_start < 1) {
    mexErrMsgTxt("Error: the starting frame must be positive\n"); 
    return; 
  }

  if (frame_end < 0) {
    mexErrMsgTxt("Error: the ending frame must be positive\n"); 
    return; 
  }

  if (frame_end != 0 && frame_end < frame_start) {
    mexErrMsgTxt("Error: the ending frame must not be less than the starting frame\n"); 
    return; 
  }

  myDrawCompleteProc = NewMovieDrawingCompleteUPP(DrawCompleteProc);

  EnterMovies();            

  if (NativePathNameToFSSpec(location, &theFSSpec, 0) ||
      OpenMovieFile(&theFSSpec, &resRefNum, 0) ||
      NewMovieFromFile(&theMovie, resRefNum, &actualResId, 0, 0, 0)) {
    mexErrMsgTxt("Error: failed to open movie\n"); 
    return; 
  }

  if (resRefNum != -1) CloseMovieFile(resRefNum);

  GetMovieBox(theMovie, &bounds);
  QTNewGWorld(&offWorld, k32ARGBPixelFormat, &bounds, NULL, NULL, 0);
  LockPixels(GetGWorldPixMap(offWorld));
  SetGWorld(offWorld, NULL);

  thePlayer = NewMovieController(theMovie, &bounds, mcTopLeftMovie | mcNotVisible);
  SetMovieGWorld(theMovie, offWorld, NULL);
  SetMovieActive(theMovie, true);
  SetMovieDrawingCompleteProc(theMovie, movieDrawingCallWhenChanged, myDrawCompleteProc, (long) offWorld);
  GetMovieTime(theMovie, &myTimeRecord);
  duration = GetMovieDuration(theMovie);

  // Compute the number of frames for allocation of output structure
  frame_count = 0;
  while ((frame_end == 0 || frame_count < frame_end) && GetMovieTime(theMovie, NULL) < duration) {
    frame_count++;
    MCDoAction(thePlayer, mcActionStep, (Ptr) myStep);
  }
  SetMovieTime(theMovie, &myTimeRecord);
  
  // Ignore frames greater than those in the file
  if (frame_end == 0 || frame_count < frame_end) frame_end = frame_count;
  
  cdims[0] = frame_end - frame_start + 1; // Indices are one-based
  cdims[1] = 1; 

  plhs[0] = mxCreateCellArray(2, cdims);

  // Step through the movie and save the frame when in the chosen interval
  // Note: the step size seems to be handled as a short internally. 
  //       Using anything greater than 32758 will seek to an incorrect frame
  frame_num = 1;
  while (frame_num <= frame_end) {
    MCDoAction(thePlayer, mcActionStep, (Ptr) myStep);
    if (frame_num >= frame_start) {
      MCIdle(thePlayer);
      mxSetCell(plhs[0], frame_num - frame_start, framedata);
    }
    frame_num++;
  }

  UnlockPixels(GetGWorldPixMap (offWorld));
  DisposeGWorld(offWorld);
  DisposeMovieController (thePlayer);
  DisposeMovie(theMovie);
  DisposeMovieDrawingCompleteUPP(myDrawCompleteProc);
  ExitMovies();

  return;
}
Ejemplo n.º 12
0
void
PlaySound_QuickTime(const char *cSoundFilename)
{
    int err;
    Str255 pSoundFilename;      /* file pathname in Pascal-string format */
    FSSpec fsSoundFile;         /* movie file location descriptor */
    short resRefNum;            /* open movie file reference */

    if (!fQTInitialised) {
        pthread_mutex_init(&mutexQTAccess, NULL);
        ListCreate(&movielist);
        fQTInitialised = TRUE;
    }

    /* QuickTime is NOT reentrant in Mac OS (it is in MS Windows!) */
    pthread_mutex_lock(&mutexQTAccess);

    EnterMovies();              /* can be called multiple times */

    err = NativePathNameToFSSpec(cSoundFilename, &fsSoundFile, 0);
    if (err != 0) {
        outputf(_("PlaySound_QuickTime: error #%d, can't find %s.\n"), err, cSoundFilename);
    } else {
        /* open movie (WAV or whatever) file */
        err = OpenMovieFile(&fsSoundFile, &resRefNum, fsRdPerm);
        if (err != 0) {
            outputf(_("PlaySound_QuickTime: error #%d opening %s.\n"), err, cSoundFilename);
        } else {
            /* create movie from movie file */
            Movie *movie = (Movie *) malloc(sizeof(Movie));
            err = NewMovieFromFile(movie, resRefNum, NULL, NULL, 0, NULL);
            CloseMovieFile(resRefNum);
            if (err != 0) {
                outputf(_("PlaySound_QuickTime: error #%d reading %s.\n"), err, cSoundFilename);
            } else {
                /* reset movie timebase */
                TimeRecord t = { 0 };
                t.base = GetMovieTimeBase(*movie);
                SetMovieTime(*movie, &t);
                /* add movie to list of running movies */
                ListInsert(&movielist, movie);
                /* run movie */
                StartMovie(*movie);
            }
        }
    }

    pthread_mutex_unlock(&mutexQTAccess);

    if (!fQTPlaying) {
        /* launch playing thread if necessary */
        int err;
        pthread_t qtthread;
        fQTPlaying = TRUE;
        err = pthread_create(&qtthread, 0L, Thread_PlaySound_QuickTime, NULL);
        if (err == 0)
            pthread_detach(qtthread);
        else
            fQTPlaying = FALSE;
    }
}
Ejemplo n.º 13
0
int CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR theCmdLine, int nCmdShow)
{
	HANDLE				myAccel;
	HWND				myWindowFrame;
	MSG					myMsg;
    WNDCLASSEX			myWC;
	char				myFileName[MAX_PATH];
	DWORD				myLength;
	OSErr				myErr = noErr;

	ghInst = hInstance;
	gCmdLine = theCmdLine;
	
	if (hPrevInstance == NULL) {
		LoadString(hInstance, IDS_APPNAME, gAppName, sizeof(gAppName));
		
		// register the frame window class
		myWC.cbSize        = sizeof(WNDCLASSEX);
		myWC.style         = CS_HREDRAW | CS_VREDRAW;
		myWC.lpfnWndProc   = (WNDPROC)QTFrame_FrameWndProc;
		myWC.cbClsExtra    = 0;
		myWC.cbWndExtra    = 0;
		myWC.hInstance     = hInstance;
		myWC.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPICON));
		myWC.hCursor       = LoadCursor(NULL, IDC_ARROW);
		myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		myWC.lpszMenuName  = gAppName;
		myWC.lpszClassName = gAppName;
		myWC.hIconSm       = LoadImage(hInstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, 16, 16, 0);
									 
		if (!RegisterClassEx(&myWC)) {
			if (!RegisterClass((LPWNDCLASS)&myWC.style))
        		return(0);
		}

		// register the movie child window class
		myWC.cbSize        = sizeof(WNDCLASSEX);
		myWC.style         = 0;
		myWC.lpfnWndProc   = (WNDPROC)QTFrame_MovieWndProc;
		myWC.cbClsExtra    = 0;
		myWC.cbWndExtra    = 0;
		myWC.hInstance     = hInstance;
		myWC.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHILDICON));
		// to avoid having QuickTime VR "fight" with the system over the cursor,
		// we set the client area cursor to NULL; this means that for QuickTime
		// movies, we'll need to change the cursor to an arrow manually; see the
		// handling of the WM_MOUSEMOVE message in QTFrame_MovieWndProc
		myWC.hCursor       = NULL;
		myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		myWC.lpszMenuName  = NULL;
		myWC.lpszClassName = gChildName;
		myWC.hIconSm       = LoadImage(hInstance, MAKEINTRESOURCE(IDI_CHILDICON), IMAGE_ICON, 16, 16, 0);
									 
		if (!RegisterClassEx(&myWC)) {
			if (!RegisterClass((LPWNDCLASS)&myWC.style))
        		return(0);
		}
	}

	// load accelerators
	myAccel = LoadAccelerators(hInstance, gAppName);

	// initialize QuickTime Media Layer and QuickTime; alert the user and return 0 if unsuccessful
	myErr = InitializeQTML(0L);
	if (myErr != noErr) {
		MessageBox(NULL, "QuickTime is not installed on this computer. Exiting.", gAppName, MB_OK | MB_APPLMODAL);
		return(0);
	}
	
	myErr = EnterMovies();
	if (myErr != noErr) {
		MessageBox(NULL, "Could not initialize QuickTime. Exiting.", gAppName, MB_OK | MB_APPLMODAL);
		return(0);
	}

	// get the application's resource file, if it exists
	myLength = GetModuleFileName(NULL, myFileName, MAX_PATH);		// NULL means: the current process
	if (myLength != 0) {
		NativePathNameToFSSpec(myFileName, &gAppFSSpec, kFullNativePath);

		gAppResFile = FSpOpenResFile(&gAppFSSpec, fsRdWrPerm);
		if (gAppResFile != kInvalidFileRefNum)
			UseResFile(gAppResFile);
	}
	
	// do any application-specific initialization that must occur before the frame window is created
	QTApp_Init(kInitAppPhase_BeforeCreateFrameWindow);
	
	// create the main frame window
	myWindowFrame = CreateWindow(gAppName, gAppName, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                               		CW_USEDEFAULT, 
                               		CW_USEDEFAULT,
                             		CW_USEDEFAULT, 
                             		CW_USEDEFAULT,
                             		NULL, 
                             		NULL, 
                             		hInstance, 
                             		NULL);
	ghWnd = myWindowFrame;
	
	// make sure we got a frame window
	if (myWindowFrame == NULL)
		return(0);
		
	// show the window
	ShowWindow(myWindowFrame, nCmdShow);
	UpdateWindow(myWindowFrame);
	
	// do any application-specific initialization that must occur after the frame window is created
	QTApp_Init(kInitAppPhase_AfterCreateFrameWindow);
	
	// get and process events until the user quits
    while (GetMessage(&myMsg, NULL, 0, 0)) {	
		if (!TranslateMDISysAccel(ghWndMDIClient, &myMsg)) {
        	if (!TranslateAccelerator(myWindowFrame, myAccel, &myMsg)) {
                TranslateMessage(&myMsg);
                DispatchMessage(&myMsg);
			}
		}
    }

	// close the application's resource file, if it was previously opened
	if (gAppResFile != kInvalidFileRefNum)
		CloseResFile(gAppResFile);

	// terminate the QuickTime Media Layer
	ExitMovies();
	TerminateQTML();

	return(myMsg.wParam);			// returns the value from PostQuitMessage
}
Ejemplo n.º 14
0
void QTFrame_OpenCommandLineMovies (LPSTR theCmdLine)
{
#pragma unused(theCmdLine)
	LPSTR				myCmdLine;
	FSSpec				myFSSpec;
	SHFILEINFO			myFileInfo;
	
	// get the command line for the current process
	myCmdLine = GetCommandLine();

	// parse the command line
	if (*myCmdLine) {
		LPSTR			myTempLine;
		
		// the string preceding any white space is the name of the module (that is, the application)
		myTempLine = strchr(myCmdLine, ' ');
		if (myTempLine) {
			myCmdLine = myTempLine;  				// skip the name of the application
			while (*myCmdLine == ' ')
				myCmdLine++;            			// skip spaces to end of string or to first command

			while (*myCmdLine != '\0') {
				char 	myFileName[MAX_PATH];
				char 	myTempName[MAX_PATH];
				char 	myBuffName[MAX_PATH];
				int 	myIndex;
				
				// read thru the remaining string to find file names
				for (myIndex = 0; *myCmdLine != '\0'; myIndex++, myCmdLine++) {
					// if we encounter a space character, it might be a filename delimiter or a space in the filename;
					// we'll try to open the filename we have so far to see whether it's a valid filename; if not, the
					// space must be part of the filename we're constructing
					if (*myCmdLine == ' ') {
						HANDLE				myFindFile;
						WIN32_FIND_DATA		myFile;
					
						myTempName[myIndex] = '\0';
						strcpy(myBuffName, myTempName);
						
						myFindFile = FindFirstFile(myBuffName, &myFile);
						if (myFindFile != INVALID_HANDLE_VALUE) {
							// we found a file having the specified name; close our file search and
							// break out of our character-gobbling loop (since we've got a valid filename)
							FindClose(myFindFile);
							break;
						}
					}
				
					// if we made it here, *myCmdLine is part of the filename (possibly a space)
					myFileName[myIndex] = myTempName[myIndex] = *myCmdLine;
				}
				
				if (*myCmdLine != '\0')
					myCmdLine++;
				
				// add a terminating NULL character
				myFileName[myIndex] = '\0';

				// make sure the filename picks out a QuickTime movie
				SHGetFileInfo(myFileName, (DWORD)0, &myFileInfo, sizeof(myFileInfo), SHGFI_TYPENAME);
				if (strcmp(myFileInfo.szTypeName, gMovieType) != 0)
					continue;
				
				// make an FSSpec record
				NativePathNameToFSSpec(myFileName, &myFSSpec, 0L);

				// open the file in a movie window
				QTFrame_OpenMovieInWindow(NULL, &myFSSpec);
			}

		} else
			myCmdLine += strlen(myCmdLine);   		// point to NULL
	}
}