int CSimplePlayerMFCApp::ExitInstance() 
{
	// Exit QuickTime and terminate QTML
	ExitMovies();
	TerminateQTML();
	return CWinApp::ExitInstance();
}
/*
 *  void PsychQTExitMovies() - Shutdown handler.
 *
 *  This routine is called by Screen('CloseAll') and on clear Screen time to
 *  do final cleanup. It deletes all Quicktime textures and releases all Quicktime
 *  movie objects.
 *
 */
void PsychQTExitMovies(void)
{
    PsychWindowRecordType	**windowRecordArray;
    int				i, numWindows; 
    
    // Release all Quicktime related OpenGL textures:
    PsychCreateVolatileWindowRecordPointerList(&numWindows, &windowRecordArray);
    for(i=0; i<numWindows; i++) {
        // Delete all Quicktime textures:
        if ((windowRecordArray[i]->windowType == kPsychTexture) && (windowRecordArray[i]->targetSpecific.QuickTimeGLTexture !=NULL)) { 
            PsychCloseWindow(windowRecordArray[i]);
        }
    }
    PsychDestroyVolatileWindowRecordPointerList(windowRecordArray);
    
    // Release all movies:
    PsychQTDeleteAllMovies();
    
    // Shutdown Quicktime toolbox: We skip this, because according to Apple its not necessary,
    // and for some reason it reliably hangs Matlab, so one has to force-quit it :-(
    // Don't do this: ExitMovies();

#if PSYCH_SYSTEM == PSYCH_WINDOWS
    // Shutdown Quicktime core system:
    ExitMovies();
    
    // Shutdown Quicktime for Windows compatibility layer:
    TerminateQTML();
#endif
    
    return;
}
Beispiel #3
0
/*****************************************************************************
 * Close:
 *****************************************************************************/
static void Close( vlc_object_t *p_this )
{
    decoder_t     *p_dec = (decoder_t*)p_this;
    decoder_sys_t *p_sys = p_dec->p_sys;
    vlc_value_t   lockval;

    /* get lock, avoid segfault */
    var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
    vlc_mutex_lock( lockval.p_address );
#ifdef SYS_DARWIN
    /* on OS X QT is not threadsafe */
    vlc_mutex_lock( &p_dec->p_vlc->quicktime_lock );
#endif

    if( p_dec->fmt_out.i_cat == AUDIO_ES )
    {
        int i_error;
        unsigned long ConvertedFrames=0;
        unsigned long ConvertedBytes=0;

        i_error = p_sys->SoundConverterEndConversion( p_sys->myConverter, NULL,
                                                      &ConvertedFrames,
                                                      &ConvertedBytes );
        msg_Dbg( p_dec, "SoundConverterEndConversion => %d", i_error );

        i_error = p_sys->SoundConverterClose( p_sys->myConverter );
        msg_Dbg( p_dec, "SoundConverterClose => %d", i_error );

        free( p_sys->p_buffer );
    }
    else if( p_dec->fmt_out.i_cat == VIDEO_ES )
    {
        free( p_sys->plane );
    }

#ifndef SYS_DARWIN
    FreeLibrary( p_sys->qtml );
    msg_Dbg( p_dec, "FreeLibrary ok." );
#endif

#ifdef SYS_DARWIN
    ExitMovies();
#endif

#if 0
    /* Segfault */
#ifdef LOADER
    Restore_LDT_Keeper( p_sys->ldt_fs );
    msg_Dbg( p_dec, "Restore_LDT_Keeper" );
#endif
#endif

#ifdef SYS_DARWIN
    vlc_mutex_unlock( &p_dec->p_vlc->quicktime_lock );
#endif
    vlc_mutex_unlock( lockval.p_address );

    free( p_sys );
}
MacOpMultimediaPlayer::~MacOpMultimediaPlayer()
{
	ExitMovies();
	if(movie)
	{
		DisposeMovie(movie);
	}
}
Beispiel #5
0
static void QT_Destroy(QTSplitter *This)
{
    IPin *connected = NULL;
    ULONG pinref;

    TRACE("Destroying\n");

    EnterCriticalSection(&This->csReceive);
    /* Don't need to clean up output pins, disconnecting input pin will do that */
    IPin_ConnectedTo(&This->pInputPin.pin.IPin_iface, &connected);
    if (connected)
    {
        IPin_Disconnect(connected);
        IPin_Release(connected);
    }
    pinref = IPin_Release(&This->pInputPin.pin.IPin_iface);
    if (pinref)
    {
        ERR("pinref should be null, is %u, destroying anyway\n", pinref);
        assert((LONG)pinref > 0);

        while (pinref)
            pinref = IPin_Release(&This->pInputPin.pin.IPin_iface);
    }

    if (This->pQTMovie)
    {
        DisposeMovie(This->pQTMovie);
        This->pQTMovie = NULL;
    }
    if (This->vContext)
        QTVisualContextRelease(This->vContext);
    if (This->aSession)
        MovieAudioExtractionEnd(This->aSession);

    ExitMovies();
    LeaveCriticalSection(&This->csReceive);

    if (This->loaderThread)
    {
        WaitForSingleObject(This->loaderThread, INFINITE);
        CloseHandle(This->loaderThread);
    }
    if (This->splitterThread)
    {
        SetEvent(This->runEvent);
        WaitForSingleObject(This->splitterThread, INFINITE);
        CloseHandle(This->splitterThread);
    }

    CloseHandle(This->runEvent);

    This->csReceive.DebugInfo->Spare[0] = 0;
    DeleteCriticalSection(&This->csReceive);

    CoTaskMemFree(This);
}
//----------------------------------------
void closeQuicktime(){
	if (bQuicktimeInitialized == true){
		ExitMovies();
		#ifdef TARGET_WIN32
			TerminateQTML();
		#endif
		bQuicktimeInitialized = false;
	}
}
// -----------------------------------------------------------------------------------------
// platformWindup()
// -----------------------------------------------------------------------------------------
// performs any platform-specific deinitialisation when the program terminates
// used to shut down QuickTime
// -----------------------------------------------------------------------------------------
void platformWindup(void)
{
#ifdef QuickTimeInstalled
	ExitMovies();
#ifdef _WIN32
	TerminateQTML();
#endif
#endif // QuickTimeInstalled
} 
Beispiel #8
0
void wxExitQT()
{
    //Note that ExitMovies() is not necessary, but
    //the docs are fuzzy on whether or not TerminateQTML is
    ExitMovies();

#ifndef __WXMAC__
    TerminateQTML();
#endif
}
////////////////////////////////////////////////////////////////////////////////
// (static) super-uninitialization - called once at application closedown
bool LLMediaImplQuickTime::closedown()
{
	ExitMovies();

#ifdef WIN32
	TerminateQTML();
#endif

	return true;
}
void MIDI_Cleanup (void)
{
	if (bMidiInited)
	{
		MIDI_Stop();
		Con_Printf("%s: closing QuickTime.\n", __thisfunc__);
		ExitMovies ();
		bMidiInited = false;
	}
}
Beispiel #11
0
   ~QTImportPlugin()
   {
      if (mInitialized) {
         ExitMovies();
#if defined(__WXMSW__)
         TerminateQTML();
#endif
      }

      mInitialized = false;
   }
Beispiel #12
0
int FAR PASCAL _export WEP(int nParameter)
  {
// Cut the connections to QuickTime for Windows

   I_UNUSED(nParameter);

   if (QTInstall)
   {
     ExitMovies ();
     QTTerminate ();
     QTInstall = FALSE;
   }
   return 1;
  }
Beispiel #13
0
/*****************************************************************************
 * Close:
 *****************************************************************************/
static void Close( vlc_object_t *p_this )
{
    decoder_t     *p_dec = (decoder_t*)p_this;
    decoder_sys_t *p_sys = p_dec->p_sys;

    /* get lock, avoid segfault */
    vlc_mutex_lock( &qt_mutex );

    if( p_dec->fmt_out.i_cat == AUDIO_ES )
    {
        int i_error;
        unsigned long ConvertedFrames=0;
        unsigned long ConvertedBytes=0;

        i_error = p_sys->SoundConverterEndConversion( p_sys->myConverter, NULL,
                                                      &ConvertedFrames,
                                                      &ConvertedBytes );
        msg_Dbg( p_dec, "SoundConverterEndConversion => %d", i_error );

        i_error = p_sys->SoundConverterClose( p_sys->myConverter );
        msg_Dbg( p_dec, "SoundConverterClose => %d", i_error );

        free( p_sys->p_buffer );
    }
    else if( p_dec->fmt_out.i_cat == VIDEO_ES )
    {
        free( p_sys->plane );
    }

#ifndef __APPLE__
    FreeLibrary( p_sys->qtml );
    FreeLibrary( p_sys->qts );
    msg_Dbg( p_dec, "FreeLibrary ok." );
#else
    ExitMovies();
#endif

#if 0
    /* Segfault */
#ifdef LOADER
    Restore_LDT_Keeper( p_sys->ldt_fs );
    msg_Dbg( p_dec, "Restore_LDT_Keeper" );
#endif
#endif

    vlc_mutex_unlock( &qt_mutex );

    free( p_sys );
}
Beispiel #14
0
// uninit driver
static void uninit(sh_video_t *sh){
    if(OutBufferGWorld) {
        DisposeGWorld(OutBufferGWorld);
        OutBufferGWorld = NULL;
    }
    if(framedescHandle) {
        DisposeHandle((Handle)framedescHandle);
        framedescHandle = NULL;
    }
    if(imageSeq) {
        CDSequenceEnd(imageSeq);
        imageSeq = 0;
    }
    ExitMovies();
}
Beispiel #15
0
    virtual ~wxQTTimer()
    {
        if(m_pbPlaying)
            *m_pbPlaying = false;

        StopMovie(m_movie);
        DisposeMovie(m_movie);
        Stop();

        //Note that ExitMovies() is not necessary, but
        //the docs are fuzzy on whether or not TerminateQTML is
        ExitMovies();

#ifndef __WXMAC__
        TerminateQTML();
#endif
    }
/*
	WinMain
*/
int CALLBACK WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    MSG    msg;
    HANDLE hAccel;

	// Store our module handle
    ghModule = GetModuleHandle(NULL);

	// Initialize QuickTime Media Layer
	InitializeQTML(0);

	// Initialize QuickTime
	EnterMovies();

	// Initialize the app
    if (!InitializeApp()) 
    {
        MessageBox(ghwndMain, "MDI: InitializeApp failure!", "Error", MB_OK);
        return 0;
    }

	// Load our accelerator keys
    if (!(hAccel = LoadAccelerators (ghModule, MAKEINTRESOURCE(ACCEL_ID))))
        MessageBox(ghwndMain, "MDI: Load Accel failure!", "Error", MB_OK);

	// Parse the command line for drag and drop
	ParseCmdLinePriv(NULL);

	// Loop for messages
    while (GetMessage(&msg, NULL, 0, 0)) {
        if (!TranslateAccelerator( ghwndMain, hAccel, &msg) &&
            !TranslateMDISysAccel(  ghwndClient, &msg)          ) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

	// Deinitialize QuickTime
	ExitMovies();

	// Deinitialize QTML
	TerminateQTML();

    return TRUE;
}
Beispiel #17
0
/**
 * Stops the MIDI player.
 *
 * Stops playing and frees any used resources before returning. As it
 * deinitilizes QuickTime, the #_quicktime_started flag is set to @c false.
 */
void MusicDriver_QtMidi::Stop()
{
	if (!_quicktime_started) return;

	DEBUG(driver, 2, "qtmidi: stopping driver...");
	switch (_quicktime_state) {
		case QT_STATE_IDLE:
			DEBUG(driver, 3, "qtmidi: stopping not needed, already idle");
			/* Do nothing. */
			break;

		case QT_STATE_PLAY:
			StopSong();
			FALLTHROUGH;

		case QT_STATE_STOP:
			DisposeMovie(_quicktime_movie);
	}

	ExitMovies();
	_quicktime_started = false;
}
Beispiel #18
0
void quicktime_exit() {
    ExitMovies();
    #ifdef WIN32
    TerminateQTML();
    #endif
}
Beispiel #19
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
}
//---------------------------------------
void ofQuicktimeSoundPlayer::closeQuicktime(){
	ExitMovies();		
	// TODO: a problem for video players?
}
Beispiel #21
0
void QTCode_QTCleanUp()
{
		/* Clean up */
	ExitMovies();
	TerminateQTML();
}
Beispiel #22
0
// uninit driver
static void uninit(sh_video_t *sh){
#ifdef CONFIG_QUICKTIME
    ExitMovies();
#endif
}
Beispiel #23
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;
}
Beispiel #24
0
int main( int argc, char **argv ) {

    Movie movie;
    Track track;
    Media media;
    short refNum;
    short resID = 0;
    Boolean wasChanged;
    OSErr err = noErr;
    FSSpec fsspec;
    AudioFormatAtomPtr outAudioAtom;
    CmpSoundHeader outSoundInfo;
    SoundComponentData theInputFormat,
                       theOutputFormat;
    SoundConverter mySoundConverter = NULL;
//    SCFillBufferData scFillBufferData = { NULL };
    Ptr pDecomBuffer0 = NULL,
        pDecomBuffer1 = NULL;
    long kMaxOutputBuffer = 64 * 1024;
    long noFrames = 0,
                  niFrames = 0,
                  noBytes = 0,
                  noSamples = 0;
#define MAX_BUFFER_SIZE 256 * 1024 * 1024


    /** Initialise MovieToolbox */
    EnterMovies();

    /** Open the movie file from the first argument */
    printf( "opening audio file: '%s'\n", argv[1] );
    path2fss( &fsspec, argv[1] );
    err = OpenMovieFile( &fsspec, &refNum, fsRdPerm );
    if ( err != noErr ) {
        printf( "failed to open audio: %d\n", GetMoviesError() );
        exit( -1 );
      }

    /** Instantiate the movie */
    err = NewMovieFromFile( &movie, refNum, &resID, NULL,
                            newMovieActive, &wasChanged );
    if ( err ) {
        printf( "failed to instantiate movie\n" );
        exit( -1 );
      }

    CloseMovieFile( refNum );
    refNum = 0;

    /** Get the first sound track */
    track = GetMovieIndTrackType( movie, 1, SoundMediaType,
                                  movieTrackMediaType );
    if ( track == NULL ) {
        printf( "failed to get sound track\n" );
        exit( -1 );
      }

    /** Get the sound track media */
    media = GetTrackMedia( track );
    if ( media == NULL ) {
        printf( "failed to get media from audio track\n" );
        exit( -1 );
      }

    Size size;
    Handle extension;
    SoundDescriptionHandle sourceSoundDescription;

    sourceSoundDescription = (SoundDescriptionHandle)NewHandle(0);

    /** Get the description of the sample data */
    GetMediaSampleDescription( media, 1,
                               (SampleDescriptionHandle)sourceSoundDescription );
    err = GetMoviesError();
    if ( err ) {
        printf( "failed to get description of sample data\n" );
        exit( -1 );
      }

    extension = NewHandle( 0 );

    // get the "magic" decompression atom
    // This extension to the SoundDescription information stores
    // data specific to a given audio decompressor. Some audio
    // decompression algorithms require a set of out-of-stream
    // values to configure the decompressor.
    err = 
        GetSoundDescriptionExtension( (SoundDescriptionHandle)sourceSoundDescription,
                                      &extension, siDecompressionParams );
    if ( noErr == err ) {
        size = GetHandleSize( extension );
        printf( "transferring data to audio buffer: %d bytes\n", size );
        HLock( extension );
        outAudioAtom = (AudioFormatAtom*)NewPtr( size );
        err = MemError();
        // copy the atom data to our buffer...
        BlockMoveData( *extension, outAudioAtom, size );
        HUnlock( extension );
      } else {
        // if it doesn't have an atom, that's ok
        outAudioAtom = NULL;
        err = noErr;
      }

    /** Setup our sound header */
    outSoundInfo.format = (*sourceSoundDescription)->dataFormat;
    outSoundInfo.numChannels = (*sourceSoundDescription)->numChannels;
    outSoundInfo.sampleSize = (*sourceSoundDescription)->sampleSize;
    outSoundInfo.sampleRate = (*sourceSoundDescription)->sampleRate;
    outSoundInfo.compressionID = (*sourceSoundDescription)->compressionID;

    float db = ((float)outSoundInfo.sampleRate)/(1<<16);

    printf( "sample: %d\tchannels: %d\tsample size: %d\tsample rate: %f\tcompressionID: %d\n",
            outSoundInfo.format, outSoundInfo.numChannels, outSoundInfo.sampleSize,
            db, outSoundInfo.compressionID );

    DisposeHandle( extension );
    DisposeHandle( (Handle)sourceSoundDescription );

    /** 
     * Now that we've figured out what the audio file is, allocate buffers
     * and so on for conversion and playback
     */

    printf( "initialising input/output conversion buffers\n" );

    /** setup input/output format for sound converter */
    theInputFormat.flags = 0;
    theInputFormat.format = outSoundInfo.format;
    theInputFormat.numChannels = outSoundInfo.numChannels;
    theInputFormat.sampleSize = outSoundInfo.sampleSize;
    theInputFormat.sampleRate = outSoundInfo. sampleRate;
    theInputFormat.sampleCount = 0;
    theInputFormat.buffer = NULL;
    theInputFormat.reserved = 0;

    theOutputFormat.flags = 0;
    theOutputFormat.format = kSoundNotCompressed;
    theOutputFormat.numChannels = theInputFormat.numChannels;
    theOutputFormat.sampleSize = theInputFormat.sampleSize;
    theOutputFormat.sampleRate = theInputFormat.sampleRate;
    theOutputFormat.sampleCount = 0;
    theOutputFormat.buffer = NULL;
    theOutputFormat.reserved = 0;

    // variableCompression means we're going to use the commonFrameSize field and the kExtendedSoundCommonFrameSizeValid flag
//    scFillBufferData.isSourceVBR = (outSoundInfo.compressionID == variableCompression );

    err = SoundConverterOpen( &theInputFormat, &theOutputFormat, 
                              &mySoundConverter );
    if ( err != noErr ) {
        printf( "failed to open sound converter\n" );
        exit( -1 );
      } else {
        printf( "opened sound converter ok\n" );
      }

    // this isn't crucial or even required for decompression only, but it does tell
    // the sound converter that we're cool with VBR audio
    Ptr tptr = NewPtr( 1 );
    tptr[0] = 1;
    SoundConverterSetInfo( mySoundConverter, siClientAcceptsVBR, tptr );
    free( tptr );

    /**
     * Set up the sound converters decompresson 'environment' by passing
     * in the 'magic' decompression atom
     */
    err = 
        SoundConverterSetInfo( mySoundConverter, siDecompressionParams,
                               outAudioAtom );
    if ( err != noErr ) {
        printf( "failed to set sound converter info\n" );
        exit( -1 );
      } else {
        printf( "set sound converter info ok\n" );
      }

    if ( outAudioAtom ) {
        DisposePtr( (Ptr)outAudioAtom );
      }

    if ( siUnknownInfoType == err ) {
        // clear this error, the decompressor didn't
        // need the decompression atom and that's OK
        err = noErr;
      } else {
//        BailErr(err);
      }

    /** 
     * The input buffer has to be large enough so GetMediaSample isn't
     * going to fail, your mileage may vary
     */
    Handle inputBuffer = NewHandle( MAX_BUFFER_SIZE );
//    HLock( inputBuffer );

    /** Start the sound conversion */
    err = SoundConverterBeginConversion(mySoundConverter);
//    BailErr(err);

    /** Extract compressed audio from media track */
    TimeValue tperSample = 0;
    err = 
        GetMediaSample( media, inputBuffer, 0, 
                        &noBytes, 0, NULL, &tperSample, NULL, NULL, 0, &noSamples, NULL );
    if ( err != noErr ) {
        printf( "failed to fetch media sample data: %d\n", GetMoviesError() );
        exit( -1 );
      } else {
        printf( "media sample: %d (%d) bytes / %ld samples / %d per sample\n", 
                noBytes, GetHandleSize( inputBuffer ), noSamples, tperSample );
      }

    unsigned long niBytes = 0;
    SoundConverterGetBufferSizes( mySoundConverter, noBytes * noSamples,
                                  &niFrames, &niBytes, &noBytes );

    printf( "buffer sizes: frames: %d\tibytes: %d\tobytes: %d\n",
            niFrames, niBytes, noBytes );

    /** Convert into uncompressed audio */
    Ptr outputBuffer = NewPtr( noBytes * 1.2 );
    SoundConverterConvertBuffer( mySoundConverter, inputBuffer, noSamples /* niFrames */, 
                                 outputBuffer, &noFrames, &noBytes );

    printf( "converted: %d frames / %d bytes\n", noFrames, noBytes );

    /** Shutdown the sound converter */
    err = SoundConverterEndConversion( mySoundConverter, outputBuffer, &noFrames, &noBytes );

    printf( "converted final: %d frames / %d bytes\n", noFrames, noBytes );

//    HUnlock( inputBuffer );

    /** We now should have decompressed audio for the input file */
    /** 
     * So, generate visuals using a sliding sample grid at the
     * given framerate
     */

    /** Create a new movie clip with audio and video tracks */

    /** PROJECTM CRAP HERE -- stuff frames into QuickTime */

    /** Close movie file */

    /** Shutdown MovieToolbox */
    ExitMovies();

    return 0;
  }
Beispiel #25
0
// uninit driver
static void uninit(sh_video_t *sh){
#ifdef MACOSX
  ExitMovies();
#endif
}
Beispiel #26
0
void MolDisplayWin::WriteQTMovie(wxString & filepath) {
	//Create a QuickTime movie using the standard animation codecs with normal quality, and 
	//temporal compression. The final file is flattened for cross platform compatability
	
	QTExport * QTOptions = new QTExport(this);
	//setup controls for the current data
	if (MainData->GetNumFrames() > 1) { //default to frame animation
		QTOptions->SetMovieChoice(0);
	} else {
		QTOptions->EnableFrameMovie(false);
	}
	if (MainData->cFrame->GetNumberNormalModes() <= 0) {
		QTOptions->EnableModeMovie(false);
	}
	
	if (QTOptions->ShowModal() != wxID_OK) {
		//user cancelled the operation
		QTOptions->Destroy();
		return;
	}
	//retrieve the value of each option
	int MovieType = QTOptions->GetMovieChoice();
	bool IncludeEPlot = QTOptions->AddEnergyPlot();
	int compressorChoice = QTOptions->GetCompressorChoice();
	int keyFrameRate = QTOptions->GetKeyFrameRate();
	if (keyFrameRate < 0) keyFrameRate = 0;
	
	QTOptions->Destroy();
	
	CodecType mCodec;
	switch (compressorChoice) {
		case 0:
			mCodec = kCinepakCodecType;
			break;
		case 1:
			mCodec = kGraphicsCodecType;
			break;
		case 2:
			mCodec = kAnimationCodecType;
			break;
		case 3:
		default:
			mCodec = kMPEG4VisualCodecType;
	}

	OSStatus s;
	OSErr myErr = myErr;
	FSSpec targetSpec;
	//ugh I need to get an FSSpec to hand to quicktime, but these calls only seem to work if
	//the file already exists...
	const char * t = filepath.mb_str(wxConvUTF8);
	FILE * temp = fopen(t, "wb");
	fclose(temp);

#ifdef __WXOSX_COCOA__
	//This function is not found in the wxCocoa implementation, it is probably possible to work around it
	//Otherwise the code appears to link and run currently. However, it is probably better to redue the
	//code to use the Cocoa qtKit framework rather than the old Carbon QT library.
	
	//This path is not tested as the current Cocoa code does not properly support the extended save dialog.
	//	void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
	{
		OSStatus err = noErr;
		FSRef fsRef;
		wxMacPathToFSRef( filepath , &fsRef );
		err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, &targetSpec, NULL);
		verify_noerr( err );
	}
#else
	wxMacFilename2FSSpec(filepath, &targetSpec);
#endif
	
	Movie	theMovie = NULL;
		
	FSSpec tempSpec = targetSpec;
	strcpy((char *) &(tempSpec.name[1]), "MacMolPlt8933tempMovie");
	tempSpec.name[0] = 22;

	BeginOperation();
	ProgressInd->ChangeText("Creating movie...");
		
	myErr = EnterMovies();	//initialize the quicktime manager
	if (myErr != noErr) {
		FinishOperation();
		MessageAlert("Error initializing QuickTime!");
		return;
	}
		//Create the movie file and initialize file data
		//Use Quicktime creator code 'TVOD' instead of simpletext 'ttxt'
	short	resRefNum = 0;
	short	resId = 0;
	myErr = CreateMovieFile(&tempSpec, 'TVOD', smCurrentScript, createMovieFileDeleteCurFile,
							&resRefNum, &theMovie);
	if (myErr != noErr) {
		MessageAlert("Error creating movie file!");
	} else {
		bool KillEPlot = false;
		int width, height, savedEPlotWidth, savedEPlotHeight;
		glCanvas->GetClientSize(&width, &height);
		Rect lDisplayRect={0,0,0,0};
		lDisplayRect.right = width;
		lDisplayRect.bottom = height;
		Rect		gRect = lDisplayRect;

		Rect EPlotRect = lDisplayRect;
		//If we are including an energy plot add space for it here
		if (IncludeEPlot && (MovieType == 0)) {
			EPlotRect.left = EPlotRect.right;
			EPlotRect.right = EPlotRect.left + height;
			if (!energyPlotWindow) {
				energyPlotWindow = new EnergyPlotDialog(this);
				KillEPlot = true;
			} else {
				energyPlotWindow->GetSize(&savedEPlotWidth, &savedEPlotHeight);
			}
			gRect.right += height;
			width += height;
			energyPlotWindow->Show(false);
			energyPlotWindow->SetSize(height, height);
			energyPlotWindow->Update();	//This is needed to initialise the window if we just created it
		}

		LocalToGlobal ((Point *) &(gRect.top));
		LocalToGlobal ((Point *) &(gRect.bottom));
		WindowRef TempWindow;
		s = CreateNewWindow(kDocumentWindowClass, kWindowNoAttributes, &gRect, &TempWindow);
		if (s == noErr) {
													//Create the video track
			Track theTrack = NewMovieTrack (theMovie, FixRatio(width,1),
											FixRatio(height,1), kNoVolume);
			if ((noErr == GetMoviesError())&&theTrack) {
				Media theMedia = NewTrackMedia (theTrack, VideoMediaType,
												60, // Video Time Scale
												NULL, 0);
				if ((noErr == GetMoviesError())&&theMedia) {
					myErr = BeginMediaEdits (theMedia);
					if (myErr == noErr) {
						//create the actual movie frames
						GWorldPtr	lgWorld=NULL;
						
						if (! NewGWorld (&lgWorld, 0, &gRect, (CTabHandle) NULL, (GDHandle) NULL,
										 (GWorldFlags) (pixPurge + useTempMem))) {
							long MaxCompressedSize;
							ImageSequence seqID;
							ImageDescriptionHandle imageDesc = (ImageDescriptionHandle)NewHandle(4);
							PixMapHandle myPixMap = GetPortPixMap(lgWorld);
							LockPixels (myPixMap);
							myErr = CompressSequenceBegin(&seqID, myPixMap, NULL, &gRect, &gRect, 0,
														  mCodec, bestCompressionCodec, codecNormalQuality, codecNormalQuality, keyFrameRate, NULL,
														  codecFlagUpdatePreviousComp, imageDesc);
							GetMaxCompressionSize (myPixMap, &gRect,
												   0, codecNormalQuality, mCodec, (CompressorComponent) anyCodec, &MaxCompressedSize);
							Handle Buffer = TempNewHandle(MaxCompressedSize, &myErr);
							if (!Buffer)
								Buffer = NewHandle(MaxCompressedSize);
							if (Buffer) {
								qtData myqtData = {theMedia, imageDesc, seqID, lDisplayRect, gRect};
								if (MovieType == 0) {
									CreateFrameMovie(lgWorld, Buffer, myqtData, IncludeEPlot);
								} else {
									CreateModeMovie(lgWorld, Buffer, myqtData);
								}
								DisposeHandle(Buffer);
							}
							myErr = CDSequenceEnd(seqID);
							if (lgWorld != NULL) DisposeGWorld (lgWorld);
							if (imageDesc) DisposeHandle((Handle) imageDesc);
						}
						
						myErr = EndMediaEdits (theMedia);
					}
					myErr = InsertMediaIntoTrack (theTrack, 0,/* track start time */
						0,        /* media start time */
						GetMediaDuration (theMedia),
						FixRatio(1,1));
				}
				myErr = AddMovieResource (theMovie, resRefNum, &resId, NULL);
			}
			if (resRefNum) {
						//Create the actual file as a flat data fork so it can be placed on the www
				ProgressInd->ChangeText("Flattening movieÉ");
				FlattenMovie(theMovie, flattenAddMovieToDataFork, &targetSpec, 'TVOD', smCurrentScript, 
							 createMovieFileDeleteCurFile, &resId, NULL);
				CloseMovieFile (resRefNum);
			}
			DisposeWindow(TempWindow);
		}
		DisposeMovie (theMovie);
		DeleteMovieFile (&tempSpec);	//delete the temp file after disposing of the movie

		if (energyPlotWindow) {
			if (KillEPlot) {
				delete energyPlotWindow;
				energyPlotWindow = NULL;
			} else {
				energyPlotWindow->SetSize(savedEPlotWidth, savedEPlotHeight);
				energyPlotWindow->FrameChanged();
				energyPlotWindow->Show(true);
			}
		}
	}
	ExitMovies();	//Close out quicktime as we are done with it for now
	FinishOperation();
}
Beispiel #27
0
QuickPlayer::~QuickPlayer()
{
  /* destructor code */
	ExitMovies();
}
Beispiel #28
0
void ExitQuicktime()
{
   ExitMovies();
}