MovieGWorlds.c

/*
    File:       MovieGWorlds.c
 
    Contains:   Code showing how to use movie gworlds
 
    Written by: Apple Developer Technical Support
 
    Copyright:  Copyright © 2003 by Apple Computer, Inc., All Rights Reserved.
 
    Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
                ("Apple") in consideration of your agreement to the following terms, and your
                use, installation, modification or redistribution of this Apple software
                constitutes acceptance of these terms.  If you do not agree with these terms,
                please do not use, install, modify or redistribute this Apple software.
 
                In consideration of your agreement to abide by the following terms, and subject
                to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs
                copyrights in this original Apple software (the "Apple Software"), to use,
                reproduce, modify and redistribute the Apple Software, with or without
                modifications, in source and/or binary forms; provided that if you redistribute
                the Apple Software in its entirety and without modifications, you must retain
                this notice and the following text and disclaimers in all such redistributions of
                the Apple Software.  Neither the name, trademarks, service marks or logos of
                Apple Computer, Inc. may be used to endorse or promote products derived from the
                Apple Software without specific prior written permission from Apple.  Except as
                expressly stated in this notice, no other rights or licenses, express or implied,
                are granted by Apple herein, including but not limited to any patent rights that
                may be infringed by your derivative works or by other works in which the Apple
                Software may be incorporated.
 
                The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
                WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
                WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
                COMBINATION WITH YOUR PRODUCTS.
 
                IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
                CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
                GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
                OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
                (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
                ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
    Change History (most recent first):
                3/18/2003   srk             Carbonized
                8/17/1999   Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
                
 
*/
#include "MovieGWorlds.h"
#include <Fonts.h>
 
// GLOBALS
Movie                   gMovie = NULL;
WindowRef               gWindow = NULL;
TimeValue               gCurrentTime = 0L;
TimeValue               gNextTime = 0L;
long                    gSampleCount = 0L;
long                    gDrawingTime = 0L;
 
 
// ______________________________________________________________________
//¥ MAIN -- Starting Point.
int main(void) {
    EventRecord     anEvent;
    OSErr       anErr = noErr;
    OSType      mediaType = VideoMediaType;
    
    //¥ Initialize the Mac environment.
    InitMacEnvironment(6);
    InitializeQTEnvironment();
    if( InitializeMovie() != noErr) ExitToShell();
 
    //¥  Get information about the first video sample (frame).
    anErr =  QTUGetStartPointOfFirstVideoSample(gMovie,&gCurrentTime); DebugAssert(anErr == noErr);
    if(gCurrentTime  == -1) ExitToShell();  // no frames at all
    gSampleCount++;
    
    //¥ Set to Window GWorld, scroll to the first video sample.
    SetGWorld(GetWindowPort(gWindow), NULL);
    
    gDrawingTime = TickCount();
    anErr = QTUScrollToNextVideoSample(gMovie, gCurrentTime, gCurrentTime ); DebugAssert(anErr == noErr); // draw first frame
    gDrawingTime = TickCount() - gDrawingTime;
    
    //¥ Draw information on the screen.
    DrawInformation();
    DrawUsageInformation();
    
    //¥ Event loop.
    for(;;) {
        WaitNextEvent(everyEvent, &anEvent, 1, NULL);
 
        if(anEvent.what == mouseDown)
            break;
        
        if(anEvent.what == keyDown) {               // Get next sample, stop if the time value for next sample is -1 (no more samples)
            GetMovieNextInterestingTime(gMovie, nextTimeMediaSample, 1, &mediaType, gCurrentTime, 0, &gNextTime, NULL);
            if(gNextTime == -1) break;
            
            gSampleCount++;
            SetGWorld(GetWindowPort(gWindow), NULL);
            
            gDrawingTime = TickCount();
            anErr = QTUScrollToNextVideoSample(gMovie, gCurrentTime, gNextTime); DebugAssert(anErr == noErr);
            gDrawingTime = TickCount() - gDrawingTime;
 
            gCurrentTime = gNextTime;
            DrawInformation();
        }
    }
    
    return 0;
}
 
 
// ______________________________________________________________________
//¥ InitMacEnvironment -- Initialize the Mac Toolbox.
void InitMacEnvironment(long nMasters) {
    long i;
 
    for(i = 0; i <nMasters; i++)
        MoreMasters();
    
    FlushEvents(everyEvent, 0);
    InitCursor();
}
 
 
// ______________________________________________________________________
//¥ InitializeQTEnvironment -- Initialize the QuickTime movie toolbox parts.
void InitializeQTEnvironment(void) {
    OSErr anErr = noErr;
    
    if( !QTUIsQuickTimeInstalled() ) {
        DebugStr("\pThe QuickTime extension is not present in this system");
        ExitToShell();
    }
 
    if( (QTUGetQTVersion() >> 16 ) < 0x200 ) {
        DebugStr("\pWe need QT 2.0 or higher due to APIs used in this sample, consult the sources (exit).");
        ExitToShell();
    }
 
#if powerc  
    if( !QTUIsQuickTimeCFMInstalled() ) {
        DebugStr("\pThe QuickTime PowerPlug extension is not available (exit)");
        ExitToShell();  
    }                           
#endif 
    
    anErr = EnterMovies(); DebugAssert(anErr == noErr);
    if(anErr != noErr) {
        DebugStr("\pProblems with Entermovies, returning errors (exit)");
        ExitToShell();
    }
}
 
 
// ______________________________________________________________________
//¥ InitializeMovie -- Initialize the needed movie parts for the offscreen handling.
OSErr InitializeMovie(void) {
    OSErr       anErr = noErr;
    Rect        windowBounds = { kWindowYStart, kWindowXStart, kWindowHeigth, kWindowLength};
    Rect        movieRect = {0, 0, 0, 0};
    
    //¥ Create the window we will use.
    anErr = CreateNewWindow( kDocumentWindowClass, 
                            kWindowCloseBoxAttribute, 
                            &windowBounds, 
                            &gWindow ); DebugAssert(anErr == noErr);
    ShowWindow(gWindow);
 
    // set the port to the new window
    SetPortWindowPort(gWindow);
    
    //¥ Get the movie.
    anErr = QTUSimpleGetMovie(&gMovie); DebugAssert(anErr == noErr);
    if(anErr)  goto Closure;
    
    //¥ Adjust the  movie box values.
    GetMovieBox(gMovie, &movieRect); 
    OffsetRect(&movieRect, -movieRect.left, -movieRect.top);
    SetMovieBox(gMovie, &movieRect); 
    AlignWindow(gWindow, false,  &movieRect, NULL);
 
    //¥ Specify the movie GWorld.
    SetMovieGWorld(gMovie, GetWindowPort(gWindow), NULL);
    anErr = GetMoviesError(); DebugAssert(anErr == noErr);
 
Closure:    
    return anErr;
}
 
 
// ______________________________________________________________________
//¥ QTUScrollToNextVideoSample -- Scroll offscreen from one video sample to the next.
pascal OSErr ScrollToNextVideoSample(Movie theMovie, TimeValue fromTimePoint, TimeValue toTimePoint) {
    OSErr           anErr = noErr;
    GWorldPtr       frameGWorld1 = NULL;
    GWorldPtr       frameGWorld2 = NULL;
    PixMapHandle    pixMap1 = NULL;
    PixMapHandle    pixMap2 = NULL;
    CGrafPtr        aSavedPort, moviePort;
    GDHandle        aSavedGDevice, movieGDevice;
    CTabHandle      colorTable;
    short           screenDepth = 0;
    short           screenSize = 0;
    Rect            movieRect, sourceRect, destinationRect;
    RgnHandle       scrollRegion = NULL;
    RgnHandle       clipRegion = NULL;
    short           nSteps;
        
    DebugAssert(theMovie != NULL); if(theMovie == NULL) goto Closure;
    
    //¥ Store away current portrect and Gdevice, get pixel sizes and color table for GWorld creation purposes.
    GetGWorld(&aSavedPort, &aSavedGDevice);
    
    GetMovieGWorld(theMovie, &moviePort, &movieGDevice);
    screenDepth = GetPixDepth((**aSavedGDevice).gdPMap);
    colorTable = (**(**aSavedGDevice).gdPMap).pmTable;
    
    //¥ Adjust the movie box.
     GetMovieBox(theMovie, &movieRect);  // If you want to offset by 10,10: OffsetRect(&movieRect, 10 -movieRect.left, 10 - movieRect.top);
     SetMovieBox(theMovie, &movieRect);
    
    //¥ Create two GWorlds for dual screen writing and possible scrolling transition effects. Lock down pixmaps.
    anErr = NewGWorld(&frameGWorld1, screenDepth, &movieRect, colorTable, NULL, 0); DebugAssert(anErr == noErr);
    if(anErr != noErr) goto Closure;
    anErr = NewGWorld(&frameGWorld2, screenDepth, &movieRect, colorTable, NULL, 0); DebugAssert(anErr == noErr);
    if(anErr != noErr) goto Closure;
    
    pixMap1 = GetGWorldPixMap(frameGWorld1);  if(!LockPixels(pixMap1)) goto Closure;
    pixMap2 = GetGWorldPixMap(frameGWorld2);  if(!LockPixels(pixMap2)) goto Closure;
    
    //¥ Draw first video sample (frame) to GWorld number 1.
    SetMovieGWorld(theMovie, frameGWorld1, GetGWorldDevice(frameGWorld1));
    SetMovieTimeValue(theMovie, fromTimePoint);
    UpdateMovie(theMovie); MoviesTask(theMovie, 0);
    
    //¥ Draw second video sample (frame) to GWorld number 2.
    SetMovieGWorld(theMovie, frameGWorld2, GetGWorldDevice(frameGWorld2));
    SetMovieTimeValue(theMovie, toTimePoint); 
    UpdateMovie(theMovie); MoviesTask(theMovie, 0);
    
    //¥ Create scroll region and store away the current clip region.
    scrollRegion = NewRgn(); DebugAssert(scrollRegion != NULL);
    if(scrollRegion == NULL) goto Closure;
    
    clipRegion = NewRgn(); DebugAssert(clipRegion != NULL);
    if(clipRegion == NULL) goto Closure;
    GetClip(clipRegion); ClipRect(&movieRect);
    
    //¥ Create the scroll effect.
    screenSize = movieRect.right - movieRect.left;
    
    for(nSteps = 10; nSteps <= screenSize; nSteps += 10)  {
        SetGWorld( frameGWorld1, NULL);
        
        ScrollRect(&movieRect, -10, 0, scrollRegion);
        SetRect(&sourceRect, movieRect.left, movieRect.top, 
                movieRect.left + nSteps, movieRect.bottom);
        SetRect(&destinationRect, movieRect.right - nSteps,
                movieRect.top, movieRect.right, movieRect.bottom);
        
        CopyBits( (BitMap *) *pixMap2, (BitMap *) *pixMap1, &sourceRect, &destinationRect,
                    srcCopy, NULL );                // blit from frameGWorld2 to frameGWorld1
        DebugAssert(QDError() == noErr);
        
        SetGWorld(aSavedPort, aSavedGDevice);
        CopyBits( (BitMap *) *pixMap1, (BitMap *) GetPortBitMapForCopyBits(aSavedPort), &movieRect, &movieRect, srcCopy, NULL );    // blit from frameGWorld1 to screen pixmap
        DebugAssert(QDError() == noErr);
    }
 
    //¥ Unlock pixels, restore the original clip region.    
    UnlockPixels(pixMap1); UnlockPixels(pixMap2);
    SetClip(clipRegion);
    
    //¥ Closure. Clean up if we have handles.
Closure:    
    if(frameGWorld1 != NULL)        DisposeGWorld(frameGWorld1);
    if(frameGWorld2 != NULL)        DisposeGWorld(frameGWorld2);
    if(scrollRegion != NULL)            DisposeRgn(scrollRegion);
    if(clipRegion != NULL)          DisposeRgn(clipRegion);
 
    SetMovieGWorld(theMovie, moviePort, movieGDevice);
    SetGWorld(aSavedPort, aSavedGDevice);   
 
    return anErr;
}
 
 
// ______________________________________________________________________
//¥ DrawInformation -- Provide information about what video sample is currently drawn.
void DrawInformation(void) {
    Str255  theString;
    Rect    eraseArea = {kDrawValuesY-20, kDrawValuesX -20, kDrawValuesY+50, kDrawValuesX+50};
    
    EraseRect(&eraseArea); 
 
    //¥ Display what frame (sample) we are drawing.
    MoveTo(kDrawTextX, kDrawTextY); 
    TextFace(bold); TextSize(9);
    DrawString("\pFrame drawn (number):");
    MoveTo(kDrawValuesX, kDrawValuesY);
    NumToString(gSampleCount, theString); 
    DrawString(theString);
    
    //¥ Display how long it took to call the QTUScrollToNextVideoSample function.
    MoveTo(kDrawTextX, 100);
    TextFace(bold); TextSize(9);
    DrawString("\pOperation took (ticks): ");
    MoveTo(kDrawValuesX, 100);
    NumToString(gDrawingTime, theString);
    DrawString(theString);
}
 
// ______________________________________________________________________
//¥ DrawUsageInformation -- Draw instructions how to use this simple program.
void DrawUsageInformation(void) {
    TextFace(normal); TextSize(9);
    MoveTo(kDrawTextX, 200); DrawString("\pHit a key to switch to next video sample (frame).");
    MoveTo(kDrawTextX, 220); DrawString("\pClick on the mouse to terminate program.");
}