Beispiel #1
0
static OSStatus infoGSID(ControlRef cRef, DataBrowserItemID item, DataBrowserPropertyID prop, DataBrowserItemDataRef itemData, Boolean setValue)
{
    CFStringRef string = CFSTR("");
    UInt32 index = ((UInt32) item) - 1;

    if (FOUR_CHAR_CODE('name') == prop)
    {
        if ((NULL != g_psTags) && (index >= 0) && (index < g_iNumTags))
        {
            string = g_psTags[2 * index];
        }
    }
    else if (FOUR_CHAR_CODE('data') == prop)
    {
        if ((NULL != g_psTags) && (index >= 0) && (index < g_iNumTags))
        {
            string = g_psTags[(2 * index) + 1];
        }
    }
    else
    {
        return errDataBrowserPropertyNotSupported;
    }

    return SetDataBrowserItemDataText(itemData, string);
}
Beispiel #2
0
void write_setting_i(void *handle, char const *key, int value) {
    int fd = *(int *)handle;
    Handle h;
    int id;
    OSErr error;
    Str255 pkey;

    UseResFile(fd);
    if (ResError() != noErr)
        fatalbox("Failed to open saved session (%d)", ResError());

    /* XXX assume all systems have the same "int" format */
    error = PtrToHand(&value, &h, sizeof(int));
    if (error != noErr)
	fatalbox("Failed to allocate memory (%d)", error);

    /* Put the data in a resource. */
    id = Unique1ID(FOUR_CHAR_CODE('Int '));
    if (ResError() != noErr)
	fatalbox("Failed to get ID for resource %s (%d)", key, ResError());
    c2pstrcpy(pkey, key);
    AddResource(h, FOUR_CHAR_CODE('Int '), id, pkey);
    if (ResError() != noErr)
	fatalbox("Failed to add resource %s (%d)", key, ResError());
}
Beispiel #3
0
void tool_wind_fill_group_combo(void)
{
	int					n,group_idx;
	char				str[256];
	CFStringRef			cf_str;
	HMHelpContentRec	tag;
	
		// old settings
		
	group_idx=GetControl32BitValue(group_combo);
	
		// delete old control and menu
		
	DisposeControl(group_combo);
	
	DeleteMenu(160);
	DisposeMenu(group_menu);
	
		// recreate the menu
		
	CreateNewMenu(group_combo_menu_id,0,&group_menu);
	
	cf_str=CFStringCreateWithCString(kCFAllocatorDefault,"No Group",kCFStringEncodingMacRoman);
	AppendMenuItemTextWithCFString(group_menu,cf_str,0,FOUR_CHAR_CODE('gp01'),NULL);
	CFRelease(cf_str);
	
	AppendMenuItemTextWithCFString(group_menu,NULL,kMenuItemAttrSeparator,0,NULL);
	
	for (n=0;n<map.ngroup;n++) {
		sprintf(str,"%s (%d)",map.groups[n].name,group_count(n));
		cf_str=CFStringCreateWithCString(kCFAllocatorDefault,str,kCFStringEncodingMacRoman);
		AppendMenuItemTextWithCFString(group_menu,cf_str,0,FOUR_CHAR_CODE('gp03'),NULL);
		CFRelease(cf_str);
	}
	
	InsertMenu(group_menu,kInsertHierarchicalMenu);
	
		// recreate the contorl
		
	CreatePopupButtonControl(toolwind,&group_box,NULL,group_combo_menu_id,FALSE,0,0,0,&group_combo);
	Draw1Control(group_combo);
	
		// build the help
	
	tag.version=kMacHelpVersion;
	tag.tagSide=kHMDefaultSide;
	SetRect(&tag.absHotRect,0,0,0,0);
	tag.content[kHMMinimumContentIndex].contentType=kHMCFStringContent;
	tag.content[kHMMinimumContentIndex].u.tagCFString=CFStringCreateWithCString(NULL,"Segment Groups",kCFStringEncodingMacRoman);
	tag.content[kHMMaximumContentIndex].contentType=kHMNoContent;
		
	HMSetControlHelpContent(group_combo,&tag);
	
		// reset the control
		
	SetControl32BitValue(group_combo,group_idx);
}
Beispiel #4
0
bool enablePlayerButtons(bool bPlay, bool bPause, bool bStop, bool bInfo)
{
    ControlRef cPlay, cPause, cStop, cInfo;
    ControlID cID;
    OSStatus iErr;

    /* Get control references.. */
    
    cID.signature = FOUR_CHAR_CODE('play');
    cID.id = 1;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cPlay)))
    {
        fprintf(stderr, "enableButtons() - GetControlByID(play) failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    cID.signature = FOUR_CHAR_CODE('paus');
    cID.id = 2;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cPause)))
    {
        fprintf(stderr, "enableButtons() - GetControlByID(paus) failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    cID.signature = FOUR_CHAR_CODE('stop');
    cID.id = 3;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cStop)))
    {
        fprintf(stderr, "enableButtons() - GetControlByID(stop) failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    cID.signature = FOUR_CHAR_CODE('info');
    cID.id = 4;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cInfo)))
    {
        fprintf(stderr, "enableButtons() - GetControlByID(info) failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    /* And set everything en masse. */

    if (bPlay)  {  EnableControl(cPlay);   }
    else        {  DisableControl(cPlay);  }

    if (bPause)  {  EnableControl(cPause);   }
    else         {  DisableControl(cPause);  }

    if (bStop)  {  EnableControl(cStop);   }
    else        {  DisableControl(cStop);  }

    if (bInfo)  {  EnableControl(cInfo);   }
    else        {  DisableControl(cInfo);  }

    return true;
}
OSErr QTUtils_SetMovieTargetID (Movie theMovie, long theTargetID)
{
	UserData		myUserData = NULL;
	long			myID = 0;
	char 			*myString = NULL;
	Str255	 		myPString;
	char 			*myCString = NULL;
	Handle			myHandle = NULL;
	OSErr			myErr = noErr;

	// make sure we've got a movie
	if (theMovie == NULL)
		return(paramErr);
		
	// get the movie's user data list
	myUserData = GetMovieUserData(theMovie);
	if (myUserData == NULL)
		return(paramErr);

	// remove any existing movie target ID
	while (QTUtils_FindUserDataItemWithPrefix(myUserData, FOUR_CHAR_CODE('plug'), kMovieIDPrefix) != 0)
		RemoveUserData(myUserData, FOUR_CHAR_CODE('plug'), QTUtils_FindUserDataItemWithPrefix(myUserData, FOUR_CHAR_CODE('plug'), kMovieIDPrefix));

	// convert the ID into a string
	NumToString(theTargetID, myPString);
	myCString = QTUtils_ConvertPascalToCString(myPString);
	if (myCString == NULL)
		return(paramErr);
	
	// create the user data item data
	myString = malloc(strlen(kMovieIDPrefix) + strlen(myCString) + 2 + 1);	// 2 + 1 == '\"' + '\"' + '\0'
	if (myString != NULL) {
		myString[0] = '\0';
		strcat(myString, kMovieIDPrefix);
		strcat(myString, "\"");
		strcat(myString, myCString);
		strcat(myString, "\"");

		// add in a new user data item
		PtrToHand(myString, &myHandle, strlen(myString));
		if (myHandle != NULL)
			myErr = AddUserData(myUserData, myHandle, FOUR_CHAR_CODE('plug'));

	} else {
		myErr = memFullErr;
	}
	
	free(myString);
	free(myCString);
	
	if (myHandle != NULL)
		DisposeHandle(myHandle);
	
	return(myErr);
}
void DelegateOnly_CodecRegister(void)
{
	ComponentDescription td;

	ComponentRoutineUPP componentEntryPoint = NewComponentRoutineUPP((ComponentRoutineProcPtr)DelegateOnly_ImageCodecComponentDispatch);

	td.componentType = decompressorComponentType;
	td.componentSubType = FOUR_CHAR_CODE('DelO');		// remember to change the subType and manufacturer
	td.componentManufacturer = FOUR_CHAR_CODE('DTS ');  // for your application - Apple reserves all lowercase types
	td.componentFlags = codecInfoDoes32;
	td.componentFlagsMask = 0;

	RegisterComponent(&td, componentEntryPoint, 0, NULL, NULL, NULL);
}
Beispiel #7
0
bool unloadInfoWin()
{
    DataBrowserCallbacks dbc;
    ControlRef cRef;
    ControlID cID;

    cID.signature = FOUR_CHAR_CODE('tags');
    cID.id = 16;
    if (noErr == GetControlByID(g_refInfoWin, &cID, &cRef))
    {
        dbc.version = kDataBrowserLatestCallbacks;
        if (noErr == InitDataBrowserCallbacks(&dbc))
        {
            SetDataBrowserCallbacks(cRef, &dbc);
        }
    }

    clearInfoWin();

    HideWindow(g_refInfoWin);
    RemoveEventHandler(g_refInfoHdlr);
    DisposeWindow(g_refInfoWin);
    DisposeEventHandlerUPP(g_lpfnInfoProc);
    DisposeDataBrowserItemDataUPP(g_lpfnGSIDProc);

    /* Clean up any previous contents */
    
    return true;
}
Beispiel #8
0
bool setPlayerWinBarMode(bool bIndef)
{
    ControlRef cRef;
    ControlID cID;
    OSStatus iErr;
    Boolean bData;

    cID.signature = FOUR_CHAR_CODE('fpos');
    cID.id = 7;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cRef)))
    {
        fprintf(stderr, "setPlayerWinBarMode() - GetControlByID() failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    bData = bIndef;

    if (noErr != (iErr = SetControlData(cRef, kControlEntireControl, kControlProgressBarIndeterminateTag, sizeof(Boolean), &bData)))
    {
        fprintf(stderr, "setPlayerWinBarMode() - SetControlData() failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    return true;
}
// Component Open Request - Required
pascal ComponentResult DelegateOnly_ImageCodecOpen(DelegateOnly_Globals glob, ComponentInstance self)
{
	ComponentDescription cd = { decompressorComponentType, k422YpCbCr8CodecType, FOUR_CHAR_CODE('app3'), 0, 0 };
	Component c = 0;
	
	ComponentResult rc;
	
	// Allocate memory for our globals, set them up and inform the component manager that we've done so
	glob = (DelegateOnly_Globals)NewPtrClear(sizeof(DelegateOnly_GlobalsRecord));
	if (rc = MemError()) goto bail;
	
	SetComponentInstanceStorage(self, (Handle)glob);
	
	glob->self = self;
	glob->target = self;
	
	if (c = FindNextComponent(c, &cd)) {
		
		rc = OpenAComponent(c, &glob->delegateComponent);
		if (rc) goto bail;

		ComponentSetTarget(glob->delegateComponent, self);
	}

bail:
	return rc;
}
OSErr EI_MakeImageDescription(ImageFramePtr frame, long colorCount, UInt8 *color, ImageDescriptionHandle *descOut)
{
	OSErr err = noErr;
	ImageDescriptionHandle desc = NULL;
	ImageDescriptionPtr idp;
	CTabHandle colors = NULL;

	desc = (ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription));
	if ( (err = MemError()) ) goto bail;

	idp = *desc;
	idp->idSize = sizeof(ImageDescription);					// total size of this image description structure with extra data including color lookup tables and other per sequence data
	idp->cType = FOUR_CHAR_CODE(kEI_Sig);					// type of compressor component that created this compressed image data
	idp->vendor = kAppleManufacturer;						// identifies the developer of the compressor that created the compressed image
	idp->frameCount = 1;									// the number of frames in the image data associated with this description
	idp->depth = frame->frameBitDepth + frame->frameAlpha;	// pixel depth specified for the compressed image
	idp->clutID = -1;										// ID of the color table for the compressed image, -1 if the image does not use a color table 
	idp->hRes = idp->vRes = 72L << 16;									// resolution dpi
	idp->width = EndianU16_BtoN(frame->frameRect.right) - EndianU16_BtoN(frame->frameRect.left);	// image width in pixels
	idp->height = EndianU16_BtoN(frame->frameRect.bottom) - EndianU16_BtoN(frame->frameRect.top);	// image height in pixels
	idp->version = 0;										// the version of the compressed data

	// make up a color table, if there is one
	if (colorCount > 2) {
		int i;

		colors = (CTabHandle)NewHandleClear(sizeof(ColorTable) + colorCount * sizeof(ColorSpec));
		if ( (err = MemError()) ) goto bail;

		(**colors).ctFlags = 0;
		(**colors).ctSeed = GetCTSeed();
		(**colors).ctSize = colorCount - 1;

		for (i=0; i<colorCount; i++) {
			(**colors).ctTable[i].value = i;
			(**colors).ctTable[i].rgb.red   = (color[0] << 8) | color[0];
			(**colors).ctTable[i].rgb.green = (color[1] << 8) | color[1];
			(**colors).ctTable[i].rgb.blue  = (color[2] << 8) | color[2];

			color += 3;
		}
		
		// copy the custom color table into the image description structure
		err = SetImageDescriptionCTable(desc, colors);
		if (err) goto bail;
	}

bail:
	if (colors)
		DisposeCTable(colors);

	if (desc && err) {
		DisposeHandle((Handle)desc);
		desc = NULL;
	}

	*descOut = desc;

	return err;
}
Beispiel #11
0
char *read_setting_s(void *handle, char const *key, char *buffer, int buflen) {
    int fd;
    Handle h;
    size_t len;
    Str255 pkey;

    if (handle == NULL) goto out;
    fd = *(int *)handle;
    UseResFile(fd);
    if (ResError() != noErr) goto out;
    c2pstrcpy(pkey, key);
    h = Get1NamedResource(FOUR_CHAR_CODE('TEXT'), pkey);
    if (h == NULL) goto out;

    len = GetHandleSize(h);
    if (len + 1 > buflen) goto out;
    memcpy(buffer, *h, len);
    buffer[len] = '\0';

    ReleaseResource(h);
    if (ResError() != noErr) goto out;
    return buffer;

  out:
    return NULL;
}
Beispiel #12
0
bool unloadPlayerWin()
{
    ControlRef cRef;
    ControlID cID;
    OSStatus iErr;

    cID.signature = FOUR_CHAR_CODE('volu');
    cID.id = 6;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cRef)))
    {
        /* We don't return false here since this is always called on the way out. */
        fprintf(stderr, "unloadPlayerWin() - GetControlByID() failed, returning %lu!\n", (unsigned long) iErr);
    }
    else
    {
        SetControlAction(cRef, (ControlActionUPP) -1);        
    }
    
    HideWindow(g_refPlayerWin);
    RemoveEventHandler(g_refSeekHdlr);
    RemoveEventHandler(g_refPlayerHdlr);
    DisposeWindow(g_refPlayerWin);
    DisposeEventHandlerUPP(g_lpfnPlayerProc);
    DisposeControlActionUPP(g_lpfnVolumeProc);

    return true;
}
OSErr QTUtils_SetMovieTargetName (Movie theMovie, char *theTargetName)
{
	UserData		myUserData = NULL;
	char 			*myString = NULL;
	Handle			myHandle = NULL;
	OSErr			myErr = noErr;

	// make sure we've got a movie and a name
	if ((theMovie == NULL) || (theTargetName == NULL))
		return(paramErr);
		
	// get the movie's user data list
	myUserData = GetMovieUserData(theMovie);
	if (myUserData == NULL)
		return(paramErr);

	// remove any existing movie target name
	while (QTUtils_FindUserDataItemWithPrefix(myUserData, FOUR_CHAR_CODE('plug'), kMovieNamePrefix) != 0)
		RemoveUserData(myUserData, FOUR_CHAR_CODE('plug'), QTUtils_FindUserDataItemWithPrefix(myUserData, FOUR_CHAR_CODE('plug'), kMovieNamePrefix));

	// create the user data item data
	myString = malloc(strlen(kMovieNamePrefix) + strlen(theTargetName) + 2 + 1);	// 2 + 1 == '\"' + '\"' + '\0'
	if (myString != NULL) {
		myString[0] = '\0';
		strcat(myString, kMovieNamePrefix);
		strcat(myString, "\"");
		strcat(myString, theTargetName);
		strcat(myString, "\"");

		// add in a new user data item
		PtrToHand(myString, &myHandle, strlen(myString));
		if (myHandle != NULL)
			myErr = AddUserData(myUserData, myHandle, FOUR_CHAR_CODE('plug'));
	} else {
		myErr = memFullErr;
	}
	
	free(myString);
	
	if (myHandle != NULL)
		DisposeHandle(myHandle);

	return(myErr);
}
Beispiel #14
0
TLevelWriter3gp::~TLevelWriter3gp()
{
#if 0
if (m_pixmap) 
  UnlockPixels(m_pixmap);
if (m_compressedData)
  DisposeHandle(m_compressedData);
if (m_gworld)
  DisposeGWorld(m_gworld);
#endif

	QDErr err;

	if (m_videoMedia)
		if ((err = EndMediaEdits(m_videoMedia)) != noErr) {
		} // throw TImageException(getFilePath(), "can't end edit media");

	if (m_videoTrack)
		if ((err = InsertMediaIntoTrack(m_videoTrack, 0, 0,
										GetMediaDuration(m_videoMedia), fixed1))) {
		} // throw TImageException(getFilePath(), "can't insert media into track");

	short resId = movieInDataForkResID;
	if (m_movie) {
		FSSpec fspec;
		long myFlags = 0L;
		OSErr myErr = noErr;
		//UCHAR myCancelled = FALSE;

		const char *pStr = toString(m_path.getWideString()).c_str();
		getFSSpecFromPosixPath(pStr, &fspec, true);

		myFlags = createMovieFileDeleteCurFile; // |
												//movieFileSpecValid | movieToFileOnlyExport;

		myErr = ConvertMovieToFile(
			m_movie,				// the movie to convert
			NULL,					// all tracks in the movie
			&fspec,					// the output file
			'3gpp',					// the output file type
			FOUR_CHAR_CODE('TVOD'), // the output file creator
			smSystemScript,			// the script
			&resId,					// no resource ID to be returned
			myFlags,				// export flags
			m_myExporter);			// no specific exp
	}

	DisposeHandle(m_hMovieData);
	DisposeHandle(m_dataRef);
	if (m_hSoundMovieData)
		DisposeHandle(m_hSoundMovieData);

	if (m_refNum)
		CloseMovieFile(m_refNum);
	DisposeMovie(m_movie);
}
void RegisterExampleIPBDecompressor(void)
{
	ComponentDescription td;
	
	td.componentType = decompressorComponentType;
	td.componentSubType = FOUR_CHAR_CODE('EIPB');
	td.componentManufacturer = kAppleManufacturer;
	td.componentFlags = cmpThreadSafe;
	td.componentFlagsMask = 0;

	RegisterComponent(&td,(ComponentRoutineUPP)ExampleIPB_DComponentDispatch, 0, NULL, NULL, NULL);
}
Beispiel #16
0
ComponentResult XMRTPH264Packetizer_PreflightMedia(XMRTPH264PacketizerGlobals globals, OSType inMediaType,
                                                   SampleDescriptionHandle inSampleDescription)
{
  ComponentResult err = noErr;
	
  Handle avccExtension = NULL;
  err = GetImageDescriptionExtension((ImageDescriptionHandle)inSampleDescription,
                                     &avccExtension,
                                     FOUR_CHAR_CODE('avcC'),
                                     1);
  if (err != noErr) {
    printf("GetImageDescriptionExtension failed");
  }
	
  UInt8 *data = (UInt8 *)*avccExtension;
	
  UInt16 *spsLengthData = (UInt16 *)&(data[6]);
  UInt16 spsAtomLength = ntohs(spsLengthData[0]);
	
  UInt32 ppsAtomLengthIndex = 9 + spsAtomLength;
	
  UInt16 *ppsLengthData = (UInt16 *)&(data[ppsAtomLengthIndex]);
  UInt16 ppsAtomLength = ntohs(ppsLengthData[0]);
	
  globals->spsAtomData = malloc(spsAtomLength * sizeof(UInt8));
  globals->ppsAtomData = malloc(ppsAtomLength * sizeof(UInt8));
	
  UInt8 *src = &(data[8]);
  memcpy(globals->spsAtomData, src, spsAtomLength);
  globals->spsAtomLength = spsAtomLength;
	
  src = &(data[ppsAtomLengthIndex + 2]);
  memcpy(globals->ppsAtomData, src, ppsAtomLength);
  globals->ppsAtomLength = ppsAtomLength;
	
  /*printf("SPS: \n");
	for (unsigned i = 0; i < spsAtomLength; i++) {
    printf("%x ", globals->spsAtomData[i]);
  }
  printf("\n");*/
  /*
  printf("PPS: \n");
  for (i = 0; i < ppsAtomLength; i++) {
    printf("%x ", globals->ppsAtomData[i]);
  }
  printf("\n");*/
	
  DisposeHandle(avccExtension);
  return err;
}
Beispiel #17
0
void write_setting_s(void *handle, char const *key, char const *value) {
    int fd = *(int *)handle;
    Handle h;
    int id;
    OSErr error;
    Str255 pkey;

    UseResFile(fd);
    if (ResError() != noErr)
        fatalbox("Failed to open saved session (%d)", ResError());

    error = PtrToHand(value, &h, strlen(value));
    if (error != noErr)
	fatalbox("Failed to allocate memory");
    /* Put the data in a resource. */
    id = Unique1ID(FOUR_CHAR_CODE('TEXT'));
    if (ResError() != noErr)
	fatalbox("Failed to get ID for resource %s (%d)", key, ResError());
    c2pstrcpy(pkey, key);
    AddResource(h, FOUR_CHAR_CODE('TEXT'), id, pkey);
    if (ResError() != noErr)
	fatalbox("Failed to add resource %s (%d)", key, ResError());
}
Beispiel #18
0
static OSStatus playerEvtHandler(EventHandlerCallRef nextHdlr, EventRef thisEvt, void *pvUserData)
{
    ControlRef cRef;
    ControlID cID;
    OSStatus iErr;

    UInt32 iSize, iPos;
    HIPoint pMouse;
    Rect rDims;
    int iPct;
    
    if ( (kEventClassWindow == GetEventClass(thisEvt)) &&
         (kEventWindowClose == GetEventKind(thisEvt)) )
    {
        HideWindow(g_refPlayerWin);
        g_bVisible = false;
        return noErr;
    }
    else if ( (kEventClassControl == GetEventClass(thisEvt)) &&
              (kEventControlClick == GetEventKind(thisEvt)) )
    {
        if (noErr != (iErr = GetEventParameter(thisEvt, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(Point), NULL, &pMouse)))
        {
            fprintf(stderr, "playerEvtHandler() - GetEventParameter(HitTest) failed, returning %lu!\n", (unsigned long) iErr);
        }

        cID.signature = FOUR_CHAR_CODE('fpos');
        cID.id = 7;
        if (noErr == (iErr = GetControlByID(g_refPlayerWin, &cID, &cRef)))
        {
            GetControlBounds(cRef, &rDims);
            iSize = rDims.right - rDims.left;
            iPos = (UInt32) pMouse.x - rDims.left;
            iPct = (int) (100.0 * ((double) iPos) / ((double) iSize));
        }
        else
        {
            fprintf(stderr, "playerEvtHandler() - GetControlByID() failed, returning %lu!\n", (unsigned long) iErr);
        }
        
        attemptSeekTo(iPct);
        
        return CallNextEventHandler(nextHdlr, thisEvt);        
    }
    else
    {
        return CallNextEventHandler(nextHdlr, thisEvt);
    }
}
Beispiel #19
0
bool setPlayerWinVolSlider(int iPosition)
{
    ControlRef cRef;
    ControlID cID;
    OSStatus iErr;

    cID.signature = FOUR_CHAR_CODE('volu');
    cID.id = 6;
    if (noErr != (iErr = GetControlByID(g_refPlayerWin, &cID, &cRef)))
    {
        fprintf(stderr, "setPlayerWinVolSlider() - GetControlByID() failed, returning %lu!\n", (unsigned long) iErr);
        return false;
    }

    SetControl32BitValue(cRef, (UInt32) iPosition);
    return true;
}
void MyQTImage2MovDirectRegister(void)
{   ComponentDescription	theComponentDescription;
    Handle					nameHdl;
#if !TARGET_API_MAC_CARBON
    ComponentRoutineUPP componentEntryPoint = NewComponentRoutineProc(QTImage2MovImportDirect_ComponentDispatch);
#else
    ComponentRoutineUPP componentEntryPoint = NewComponentRoutineUPP((ComponentRoutineProcPtr)QTImage2MovImportDirect_ComponentDispatch);
#endif

    PtrToHand("\pQI2MSource", &nameHdl, 8);
    theComponentDescription.componentType = MovieImportType;
    theComponentDescription.componentSubType = FOUR_CHAR_CODE('VOD ');
    theComponentDescription.componentManufacturer = kAppleManufacturer;
    theComponentDescription.componentFlags = canMovieImportFiles | canMovieImportInPlace | hasMovieImportMIMEList | canMovieImportDataReferences;
    theComponentDescription.componentFlagsMask = 0;

    RegisterComponent(&theComponentDescription, componentEntryPoint, 0, nameHdl, 0, 0);
}
char *QTUtils_GetMovieTargetName (Movie theMovie)
{
	UserData		myUserData = NULL;
	char 			*myString = NULL;
	
	// make sure we've got a movie
	if (theMovie == NULL)
		goto bail;
	
	// get the movie's user data list
	myUserData = GetMovieUserData(theMovie);
	if (myUserData == NULL)
		goto bail;

	// find the "value" of the user data item of type 'plug' that begins with the string "moviename="
	myString = QTUtils_GetUserDataPrefixedValue(myUserData, FOUR_CHAR_CODE('plug'), kMovieNamePrefix);

bail:
	return(myString);
}
Beispiel #22
0
int read_setting_i(void *handle, char const *key, int defvalue) {
    int fd;
    Handle h;
    int value;
    Str255 pkey;

    if (handle == NULL) goto out;
    fd = *(int *)handle;
    UseResFile(fd);
    if (ResError() != noErr) goto out;
    c2pstrcpy(pkey, key);
    h = Get1NamedResource(FOUR_CHAR_CODE('Int '), pkey);
    if (h == NULL) goto out;
    value = *(int *)*h;
    ReleaseResource(h);
    if (ResError() != noErr) goto out;
    return value;

  out:
    return defvalue;
}
pascal ComponentResult VP8_Encoder_GetDITLForSize(VP8EncoderGlobals store,
                                                  Handle *ditl,
                                                  Point *requestedSize)
{
  Handle h = NULL;
  ComponentResult err = noErr;

  switch (requestedSize->h) {
    case kSGSmallestDITLSize:
      GetComponentResource((Component)(store->self), FOUR_CHAR_CODE('DITL'),
                           kVP8_EncoderDITLResID, &h);
      if (NULL != h) *ditl = h;
      else err = resNotFound;
      break;
    default:
      err = badComponentSelector;
      break;
  }

  return err;
}
long QTUtils_GetMovieTargetID (Movie theMovie, Boolean *theMovieHasID)
{
	UserData		myUserData = NULL;
	long			myID = 0;
	char 			*myString = NULL;
	StringPtr 		myPString = NULL;
	Boolean			myMovieHasID = false;
	OSErr			myErr = noErr;
	
	// make sure we've got a movie
	if (theMovie == NULL)
		goto bail;
	
	// get the movie's user data list
	myUserData = GetMovieUserData(theMovie);
	if (myUserData == NULL)
		goto bail;

	// find the "value" of the user data item of type 'plug' that begins with the string "movieid="
	myString = QTUtils_GetUserDataPrefixedValue(myUserData, FOUR_CHAR_CODE('plug'), kMovieIDPrefix);
	
	// convert the string into a number
	if (myString != NULL) {
		myPString = QTUtils_ConvertCToPascalString(myString);
		StringToNum(myPString, &myID);
		myMovieHasID = true;
	}

bail:
	free(myString);
	free(myPString);

	if (theMovieHasID != NULL)
		*theMovieHasID = myMovieHasID;
		
	return(myID);
}
OSErr QTWired_CreateWiredSpritesMovie (void)
{
	short					myResRefNum = 0;
	short					myResID = movieInDataForkResID;
	Movie					myMovie = NULL;
	Track					myTrack;
	Media					myMedia;
	FSSpec					myFile;
	Boolean					myIsSelected = false;
	Boolean					myIsReplacing = false;	
	StringPtr 				myPrompt = QTUtils_ConvertCToPascalString(kWiredSavePrompt);
	StringPtr 				myFileName = QTUtils_ConvertCToPascalString(kWiredSaveFileName);
	QTAtomContainer			mySample = NULL;
	QTAtomContainer			myActions = NULL;
	QTAtomContainer			myBeginButton, myPrevButton, myNextButton, myEndButton;
	QTAtomContainer			myPenguinOne, myPenguinTwo, myPenguinOneOverride;
	QTAtomContainer			myBeginActionButton, myPrevActionButton, myNextActionButton, myEndActionButton;
	QTAtomContainer			myPenguinOneAction, myPenguinTwoAction;
	RGBColor				myKeyColor;
	Point					myLocation;
	short					isVisible, myLayer, myIndex, myID, i, myDelta;
	Boolean					hasActions;
	long					myFlags = createMovieFileDeleteCurFile | createMovieFileDontCreateResFile;
	OSType					myType = FOUR_CHAR_CODE('none');
	UInt32					myFrequency;
	QTAtom					myEventAtom;
	long					myLoopingFlags;
	ModifierTrackGraphicsModeRecord		myGraphicsMode;
	OSErr					myErr = noErr;

	//////////
	//
	// create a new movie file and set its controller type
	//
	//////////

	// ask the user for the name of the new movie file
	QTFrame_PutFile(myPrompt, myFileName, &myFile, &myIsSelected, &myIsReplacing);
	if (!myIsSelected)
		goto bail;

	// create a movie file for the destination movie
	myErr = CreateMovieFile(&myFile, FOUR_CHAR_CODE('TVOD'), smSystemScript, myFlags, &myResRefNum, &myMovie);
	if (myErr != noErr)
		goto bail;
	
	// select the "no controller" movie controller
	myType = EndianU32_NtoB(myType);
	SetUserDataItem(GetMovieUserData(myMovie), &myType, sizeof(myType), kUserDataMovieControllerType, 1);
	
	//////////
	//
	// create the sprite track and media
	//
	//////////
	
	myTrack = NewMovieTrack(myMovie, ((long)kSpriteTrackWidth << 16), ((long)kSpriteTrackHeight << 16), kNoVolume);
	myMedia = NewTrackMedia(myTrack, SpriteMediaType, kSpriteMediaTimeScale, NULL, 0);

	//////////
	//
	// create a key frame sample containing six sprites and all of their shared images
	//
	//////////

	// create a new, empty key frame sample
	myErr = QTNewAtomContainer(&mySample);
	if (myErr != noErr)
		goto bail;

	myKeyColor.red = 0xffff;						// white
	myKeyColor.green = 0xffff;
	myKeyColor.blue = 0xffff;

	// add images to the key frame sample
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToBeginningButtonUp, &myKeyColor, kGoToBeginningButtonUpIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToBeginningButtonDown, &myKeyColor, kGoToBeginningButtonDownIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToEndButtonUp, &myKeyColor, kGoToEndButtonUpIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToEndButtonDown, &myKeyColor, kGoToEndButtonDownIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToPrevButtonUp, &myKeyColor, kGoToPrevButtonUpIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToPrevButtonDown, &myKeyColor, kGoToPrevButtonDownIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToNextButtonUp, &myKeyColor, kGoToNextButtonUpIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kGoToNextButtonDown, &myKeyColor, kGoToNextButtonDownIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kPenguinForward, &myKeyColor, kPenguinForwardIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kPenguinLeft, &myKeyColor, kPenguinLeftIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kPenguinRight, &myKeyColor, kPenguinRightIndex, NULL, NULL);
	SpriteUtils_AddPICTImageToKeyFrameSample(mySample, kPenguinClosed, &myKeyColor, kPenguinClosedIndex, NULL, NULL);

	for (myIndex = kPenguinDownRightCycleStartIndex, myID = kWalkDownRightCycleStart; myIndex <= kPenguinDownRightCycleEndIndex; myIndex++, myID++)
		SpriteUtils_AddPICTImageToKeyFrameSample(mySample, myID, &myKeyColor, myIndex, NULL, NULL);
	
	// assign group IDs to the images
	SpriteUtils_AssignImageGroupIDsToKeyFrame(mySample);
	
	//////////
	//
	// add samples to the sprite track's media
	//
	//////////
	
	BeginMediaEdits(myMedia);

	// go to beginning button with no actions
	myErr = QTNewAtomContainer(&myBeginButton);
	if (myErr != noErr)
		goto bail;
	myLocation.h	= (1 * kSpriteTrackWidth / 8) - (kStartEndButtonWidth / 2);
	myLocation.v	= (4 * kSpriteTrackHeight / 5) - (kStartEndButtonHeight / 2);
	isVisible		= false;
	myLayer			= 1;
	myIndex			= kGoToBeginningButtonUpIndex;
	myErr = SpriteUtils_SetSpriteData(myBeginButton, &myLocation, &isVisible, &myLayer, &myIndex, NULL, NULL, myActions);
	if (myErr != noErr)
		goto bail;

	// go to previous button with no actions
	myErr = QTNewAtomContainer(&myPrevButton);
	if (myErr != noErr)
		goto bail;
	myLocation.h 	= (3 * kSpriteTrackWidth / 8) - (kNextPrevButtonWidth / 2);
	myLocation.v	= (4 * kSpriteTrackHeight / 5) - (kStartEndButtonHeight / 2);
	isVisible		= false;
	myLayer			= 1;
	myIndex			= kGoToPrevButtonUpIndex;
	myErr = SpriteUtils_SetSpriteData(myPrevButton, &myLocation, &isVisible, &myLayer, &myIndex, NULL, NULL, myActions);
	if (myErr != noErr)
		goto bail;

	// go to next button with no actions
	myErr = QTNewAtomContainer(&myNextButton);
	if (myErr != noErr)
		goto bail;
	myLocation.h 	= (5 * kSpriteTrackWidth / 8) - (kNextPrevButtonWidth / 2);
	myLocation.v	= (4 * kSpriteTrackHeight / 5) - (kStartEndButtonHeight / 2);
	isVisible		= false;
	myLayer			= 1;
	myIndex			= kGoToNextButtonUpIndex;
	myErr = SpriteUtils_SetSpriteData(myNextButton, &myLocation, &isVisible, &myLayer, &myIndex, NULL, NULL, myActions);
	if (myErr != noErr)
		goto bail;

	// go to end button with no actions
	myErr = QTNewAtomContainer(&myEndButton);
	if (myErr != noErr)
		goto bail;
	myLocation.h 	= (7 * kSpriteTrackWidth / 8) - (kStartEndButtonWidth / 2);
	myLocation.v	= (4 * kSpriteTrackHeight / 5) - (kStartEndButtonHeight / 2);
	isVisible		= false;
	myLayer			= 1;
	myIndex			= kGoToEndButtonUpIndex;
	myErr = SpriteUtils_SetSpriteData(myEndButton, &myLocation, &isVisible, &myLayer, &myIndex, NULL, NULL, myActions);
	if (myErr != noErr)
		goto bail;

	// first penguin sprite with no actions
	myErr = QTNewAtomContainer(&myPenguinOne);
	if (myErr != noErr)
		goto bail;
	myLocation.h 	= (3 * kSpriteTrackWidth / 8) - (kPenguinWidth / 2);
	myLocation.v 	= (kSpriteTrackHeight / 4) - (kPenguinHeight / 2);
	isVisible		= true;
	myLayer			= 2;
	myIndex			= kPenguinDownRightCycleStartIndex;
	myGraphicsMode.graphicsMode = blend;
	myGraphicsMode.opColor.red = myGraphicsMode.opColor.green = myGraphicsMode.opColor.blue = 0x8FFF;	// grey
	myErr = SpriteUtils_SetSpriteData(myPenguinOne, &myLocation, &isVisible, &myLayer, &myIndex, &myGraphicsMode, NULL, myActions);
	if (myErr != noErr)
		goto bail;
		
	// second penguin sprite with no actions
	myErr = QTNewAtomContainer(&myPenguinTwo);
	if (myErr != noErr)
		goto bail;
	myLocation.h 	= (5 * kSpriteTrackWidth / 8) - (kPenguinWidth / 2);
	myLocation.v 	= (kSpriteTrackHeight / 4) - (kPenguinHeight / 2);
	isVisible		= true;
	myLayer			= 3;
	myIndex			= kPenguinForwardIndex;
	myErr = SpriteUtils_SetSpriteData(myPenguinTwo, &myLocation, &isVisible, &myLayer, &myIndex, NULL, NULL, myActions);
	if (myErr != noErr)
		goto bail;

	//////////
	//
	// add actions to the six sprites
	//
	//////////

	// add go to beginning button
	myErr = QTCopyAtom(myBeginButton, kParentAtomIsContainer, &myBeginActionButton);
	if (myErr != noErr)
		goto bail;

	WiredUtils_AddSpriteSetImageIndexAction(myBeginActionButton, kParentAtomIsContainer, kQTEventMouseClick, 0, NULL, 0, 0, NULL, kGoToBeginningButtonDownIndex, NULL);
	WiredUtils_AddSpriteSetImageIndexAction(myBeginActionButton, kParentAtomIsContainer, kQTEventMouseClickEnd, 0, NULL, 0, 0, NULL, kGoToBeginningButtonUpIndex, NULL);
	WiredUtils_AddMovieGoToBeginningAction(myBeginActionButton, kParentAtomIsContainer, kQTEventMouseClickEndTriggerButton);
	WiredUtils_AddSpriteSetVisibleAction(myBeginActionButton, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, 0, NULL, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myBeginActionButton, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, 0, NULL, false, NULL);
	SpriteUtils_AddSpriteToSample(mySample, myBeginActionButton, kGoToBeginningSpriteID);	
	QTDisposeAtomContainer(myBeginActionButton);

	// add go to prev button
	myErr = QTCopyAtom(myPrevButton, kParentAtomIsContainer, &myPrevActionButton);
	if (myErr != noErr)
		goto bail;

	WiredUtils_AddSpriteSetImageIndexAction(myPrevActionButton, kParentAtomIsContainer, kQTEventMouseClick, 0, NULL, 0, 0, NULL, kGoToPrevButtonDownIndex, NULL);
	WiredUtils_AddSpriteSetImageIndexAction(myPrevActionButton, kParentAtomIsContainer, kQTEventMouseClickEnd, 0, NULL, 0, 0, NULL, kGoToPrevButtonUpIndex, NULL);
	WiredUtils_AddMovieStepBackwardAction(myPrevActionButton, kParentAtomIsContainer, kQTEventMouseClickEndTriggerButton);
	WiredUtils_AddSpriteSetVisibleAction(myPrevActionButton, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, 0, NULL, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPrevActionButton, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, 0, NULL, false, NULL);
	SpriteUtils_AddSpriteToSample(mySample, myPrevActionButton, kGoToPrevSpriteID);
	QTDisposeAtomContainer(myPrevActionButton);

	// add go to next button
	myErr = QTCopyAtom(myNextButton, kParentAtomIsContainer, &myNextActionButton);
	if (myErr != noErr)
		goto bail;

	WiredUtils_AddSpriteSetImageIndexAction(myNextActionButton, kParentAtomIsContainer, kQTEventMouseClick, 0, NULL, 0, 0, NULL, kGoToNextButtonDownIndex, NULL);
	WiredUtils_AddSpriteSetImageIndexAction(myNextActionButton, kParentAtomIsContainer, kQTEventMouseClickEnd, 0, NULL, 0, 0, NULL, kGoToNextButtonUpIndex, NULL);
	WiredUtils_AddMovieStepForwardAction(myNextActionButton, kParentAtomIsContainer, kQTEventMouseClickEndTriggerButton);
	WiredUtils_AddSpriteSetVisibleAction(myNextActionButton, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, 0, NULL, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myNextActionButton, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, 0, NULL, false, NULL);
	SpriteUtils_AddSpriteToSample(mySample, myNextActionButton, kGoToNextSpriteID);
	QTDisposeAtomContainer(myNextActionButton);

	// add go to end button
	myErr = QTCopyAtom(myEndButton, kParentAtomIsContainer, &myEndActionButton);
	if (myErr != noErr)
		goto bail;

	WiredUtils_AddSpriteSetImageIndexAction(myEndActionButton, kParentAtomIsContainer, kQTEventMouseClick, 0, NULL, 0, 0, NULL, kGoToEndButtonDownIndex, NULL);
	WiredUtils_AddSpriteSetImageIndexAction(myEndActionButton, kParentAtomIsContainer, kQTEventMouseClickEnd, 0, NULL, 0, 0, NULL, kGoToEndButtonUpIndex, NULL);
	WiredUtils_AddMovieGoToEndAction(myEndActionButton, kParentAtomIsContainer, kQTEventMouseClickEndTriggerButton);
	WiredUtils_AddSpriteSetVisibleAction(myEndActionButton, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, 0, NULL, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myEndActionButton, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, 0, NULL, false, NULL);
	SpriteUtils_AddSpriteToSample(mySample, myEndActionButton, kGoToEndSpriteID);
	QTDisposeAtomContainer(myEndActionButton);

	// add penguin one
	myErr = QTCopyAtom(myPenguinOne, kParentAtomIsContainer, &myPenguinOneAction);
	if (myErr != noErr)
		goto bail;

	// show the buttons on mouse enter and hide them on mouse exit
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, kTargetSpriteID, (void *)kGoToBeginningSpriteID, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, kTargetSpriteID, (void *)kGoToBeginningSpriteID, false, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, kTargetSpriteID, (void *)kGoToPrevSpriteID, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, kTargetSpriteID, (void *)kGoToPrevSpriteID, false, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, kTargetSpriteID, (void *)kGoToNextSpriteID, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, kTargetSpriteID, (void *)kGoToNextSpriteID, false, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseEnter, 0, NULL, 0, kTargetSpriteID, (void *)kGoToEndSpriteID, true, NULL);
	WiredUtils_AddSpriteSetVisibleAction(myPenguinOneAction, kParentAtomIsContainer, kQTEventMouseExit, 0, NULL, 0, kTargetSpriteID, (void *)kGoToEndSpriteID, false, NULL);
	SpriteUtils_AddSpriteToSample(mySample, myPenguinOneAction, kPenguinOneSpriteID);
	QTWired_AddCursorChangeOnMouseOver(mySample, kPenguinOneSpriteID);
	QTDisposeAtomContainer(myPenguinOneAction);

	// add penguin two
	myErr = QTCopyAtom(myPenguinTwo, kParentAtomIsContainer, &myPenguinTwoAction);
	if (myErr != noErr)
		goto bail;

	// blink when clicked on
	WiredUtils_AddSpriteSetImageIndexAction(myPenguinTwoAction, kParentAtomIsContainer, kQTEventMouseClick, 0, NULL, 0, 0, NULL, kPenguinClosedIndex, NULL);
	WiredUtils_AddSpriteSetImageIndexAction(myPenguinTwoAction, kParentAtomIsContainer, kQTEventMouseClickEnd, 0, NULL, 0, 0, NULL, kPenguinForwardIndex, NULL);

	WiredUtils_AddQTEventAtom(myPenguinTwoAction, kParentAtomIsContainer, kQTEventMouseClickEndTriggerButton, &myEventAtom);

	// toggle the movie rate and both of the birds' graphics modes
	QTWired_AddPenguinTwoConditionalActions(myPenguinTwoAction, myEventAtom);

	QTWired_AddWraparoundMatrixOnIdle(myPenguinTwoAction);

	SpriteUtils_AddSpriteToSample(mySample, myPenguinTwoAction, kPenguinTwoSpriteID);
	QTDisposeAtomContainer(myPenguinTwoAction);
	
	// add an action for when the key frame is loaded, to set the movie's looping mode to palindrome;
	// note that this will actually be triggered every time the key frame is reloaded,
	// so if the operation was expensive we could use a conditional to test if we've already done it
	myLoopingFlags = loopTimeBase | palindromeLoopTimeBase;
	WiredUtils_AddMovieSetLoopingFlagsAction(mySample, kParentAtomIsContainer, kQTEventFrameLoaded, myLoopingFlags);

	// add the key frame sample to the sprite track media
	//
	// to add the sample data in a compressed form, you would use a QuickTime DataCodec to perform the
	// compression; replace the call to the utility AddSpriteSampleToMedia with a call to the utility
	// AddCompressedSpriteSampleToMedia to do this
	
	SpriteUtils_AddSpriteSampleToMedia(myMedia, mySample, kSpriteMediaFrameDuration, true, NULL);	
	//SpriteUtils_AddCompressedSpriteSampleToMedia(myMedia, mySample, kSpriteMediaFrameDuration, true, zlibDataCompressorSubType, NULL);

	//////////
	//
	// add a few override samples to move penguin one and change its image index
	//
	//////////

	// original penguin one location
	myLocation.h 	= (3 * kSpriteTrackWidth / 8) - (kPenguinWidth / 2);
	myLocation.v 	= (kSpriteTrackHeight / 4) - (kPenguinHeight / 2);

	myDelta = (kSpriteTrackHeight / 2) / kNumOverrideSamples;
	myIndex = kPenguinDownRightCycleStartIndex;
	
	for (i = 1; i <= kNumOverrideSamples; i++) {
		QTRemoveChildren(mySample, kParentAtomIsContainer);
		QTNewAtomContainer(&myPenguinOneOverride);

		myLocation.h += myDelta;
		myLocation.v += myDelta;
		myIndex++;
		if (myIndex > kPenguinDownRightCycleEndIndex)
			myIndex = kPenguinDownRightCycleStartIndex;
			
		SpriteUtils_SetSpriteData(myPenguinOneOverride, &myLocation, NULL, NULL, &myIndex, NULL, NULL, NULL);
		SpriteUtils_AddSpriteToSample(mySample, myPenguinOneOverride, kPenguinOneSpriteID);
		SpriteUtils_AddSpriteSampleToMedia(myMedia, mySample, kSpriteMediaFrameDuration, false, NULL);	
		QTDisposeAtomContainer(myPenguinOneOverride);
	}

	EndMediaEdits(myMedia);
	
	// add the media to the track
	InsertMediaIntoTrack(myTrack, 0, 0, GetMediaDuration(myMedia), fixed1);
	
	//////////
	//
	// set the sprite track properties
	//
	//////////
	{
		QTAtomContainer		myTrackProperties;
		RGBColor			myBackgroundColor;
		
		// add a background color to the sprite track
		myBackgroundColor.red = EndianU16_NtoB(0x8000);
		myBackgroundColor.green = EndianU16_NtoB(0);
		myBackgroundColor.blue = EndianU16_NtoB(0xffff);
		
		QTNewAtomContainer(&myTrackProperties);
		QTInsertChild(myTrackProperties, 0, kSpriteTrackPropertyBackgroundColor, 1, 1, sizeof(RGBColor), &myBackgroundColor, NULL);

		// tell the movie controller that this sprite track has actions, Jackson
		hasActions = true;
		QTInsertChild(myTrackProperties, 0, kSpriteTrackPropertyHasActions, 1, 1, sizeof(hasActions), &hasActions, NULL);
	
		// tell the sprite track to generate QTIdleEvents
		myFrequency = EndianU32_NtoB(2);
		QTInsertChild(myTrackProperties, 0, kSpriteTrackPropertyQTIdleEventsFrequency, 1, 1, sizeof(myFrequency), &myFrequency, NULL);
		myErr = SetMediaPropertyAtom(myMedia, myTrackProperties);
		if (myErr != noErr)
			goto bail;

		QTDisposeAtomContainer(myTrackProperties);
	}
	
	//////////
	//
	// finish up
	//
	//////////
	
	// add the movie resource to the movie file
	myErr = AddMovieResource(myMovie, myResRefNum, &myResID, myFile.name);
	
bail:
	free(myPrompt);
	free(myFileName);

	if (mySample != NULL)
		QTDisposeAtomContainer(mySample);

	if (myBeginButton != NULL)
		QTDisposeAtomContainer(myBeginButton);	
			
	if (myPrevButton != NULL)
		QTDisposeAtomContainer(myPrevButton);
				
	if (myNextButton != NULL)
		QTDisposeAtomContainer(myNextButton);
				
	if (myEndButton != NULL)
		QTDisposeAtomContainer(myEndButton);		
		
	if (myResRefNum != 0)
		CloseMovieFile(myResRefNum);

	if (myMovie != NULL)
		DisposeMovie(myMovie);
		
	return(myErr);
}
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;
}
Beispiel #27
0
int qCreateEncoderAPI(QEncoder **eptr, char* encoderArgs, int semaIndex, int width, int height)
{
    QEncoder* encoder;
    OSStatus err;
    QVideoArgs* args = (QVideoArgs*)encoderArgs;

    //XXXX: we should be able to configure this
    SInt32 averageDataRate = 100000;

    ICMEncodedFrameOutputRecord encodedFrameOutputRecord = {0};
    ICMCompressionSessionOptionsRef sessionOptions = NULL;

    CFMutableDictionaryRef pixelBufferAttributes = NULL;
    CFNumberRef number = NULL;
    OSType pixelFormat = Q_PIXEL_FORMAT;

    fprintf(QSTDERR, "\nqCreateEncoderQT(): ABOUT TO TRY TO CREATE ENCODER");
    fprintf(QSTDERR, "\n\t time-scale: %d", args->timeScale);
    fprintf(QSTDERR, "\n\t big-endian: %d", (args->isBigEndian)[0]);
    fprintf(QSTDERR, "\n\t codec-type: %c%c%c%c",
            ((unsigned char*)&(args->codecType))[3],
            ((unsigned char*)&(args->codecType))[2],
            ((unsigned char*)&(args->codecType))[1],
            ((unsigned char*)&(args->codecType))[0]);

    encoder = (QEncoder*)malloc(sizeof(QEncoder));
    if (encoder == NULL) {
        fprintf(QSTDERR, "\nqCreateDecoderQT: failed to malloc encoder struct");
        return -2;
    }

    encoder->semaIndex = semaIndex;
    encoder->timeScale = args->timeScale;
    encoder->codecType = *((CodecType*)(args->codecType));
    encoder->width = width;
    encoder->height = height;

    err = ICMCompressionSessionOptionsCreate( NULL, &sessionOptions );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not create session options");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        free(encoder);
        return -5;
    }

    // Create and configure the compressor component.
    OSType codecManufacturer = 'appl';
    ComponentDescription componentDescription;
    componentDescription.componentType = FOUR_CHAR_CODE('imco');
    componentDescription.componentSubType = encoder->codecType;
    componentDescription.componentManufacturer = codecManufacturer;
    componentDescription.componentFlags = 0;
    componentDescription.componentFlagsMask = 0;

    Component compressorComponent = FindNextComponent(0, &componentDescription);
    if(compressorComponent == NULL) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not find a matching compressor");
        ICMCompressionSessionOptionsRelease(sessionOptions);
        free(encoder);
        return -5;
    }
    err = OpenAComponent(compressorComponent, &(encoder->compressor));
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): failed to open compressor component");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        free(encoder);
        return -5;
    }
    // If we want to use H.264, we need to muck around a bit.
    // XXXX: "clean up" this code.
    if(encoder->codecType == FOUR_CHAR_CODE('avc1'))
    {
        // Profile is currently fixed to Baseline
        // The level is adjusted by the use of the
        // bitrate, but the SPS returned reveals
        // level 1.1 in case of QCIF and level 1.3
        // in case of CIF

        Handle h264Settings = NewHandleClear(0);

        err = ImageCodecGetSettings(encoder->compressor, h264Settings);
        if(err != noErr) {
            fprintf(QSTDERR, "\nqCreateEncoderQT(): failed to get codec settings");
            fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
            ICMCompressionSessionOptionsRelease(sessionOptions);
            CloseComponent(encoder->compressor);
            free(encoder);
            return -5;
        }

        // For some reason, the QTAtomContainer functions will crash if used on the atom
        // container returned by ImageCodecGetSettings.
        // Therefore, we have to parse the atoms self to set the correct settings.
        unsigned i;
        unsigned settingsSize = GetHandleSize(h264Settings) / 4;
        UInt32 *data = (UInt32 *)*h264Settings;
        for(i = 0; i < settingsSize; i++)
        {
            // Forcing Baseline profile
#if defined(__BIG_ENDIAN__)
            if(data[i] == FOUR_CHAR_CODE('sprf'))
            {
                i+=4;
                data[i] = 1;
            }
#else
            if(data[i] == FOUR_CHAR_CODE('frps'))
            {
                i+=4;
                // data[i] = CFSwapInt32(1);
                data[i] = 16777216;  // avoid CFSwapInt32;
            }
#endif

            // if video sent is CIF size, we set this flag to one to have the picture
            // encoded in 5 slices instead of two.
            // If QCIF is sent, this flag remains zero to send two slices instead of
            // one.
#if defined(__BIG_ENDIAN__)
            else if(/*videoSize == XMVideoSize_CIF &&*/ data[i] == FOUR_CHAR_CODE('susg'))
            {
                i+=4;
                data[i] = 1;
            }
#else
            else if(/*videoSize == XMVideoSize_CIF &&*/ data[i] == FOUR_CHAR_CODE('gsus'))
            {
                i+=4;
                // data[i] = CFSwapInt32(1);
                data[i] = 16777216;  // avoid CFSwapInt32;
            }
#endif
        }
        err = ImageCodecSetSettings(encoder->compressor, h264Settings);
        if(err != noErr) {
            fprintf(QSTDERR, "\nqCreateEncoderQT(): failed to set codec settings");
            fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
            ICMCompressionSessionOptionsRelease(sessionOptions);
            CloseComponent(encoder->compressor);
            free(encoder);
            return -5;
        }
    }
    err = ICMCompressionSessionOptionsSetProperty(sessionOptions,
            kQTPropertyClass_ICMCompressionSessionOptions,
            kICMCompressionSessionOptionsPropertyID_CompressorComponent,
            sizeof(encoder->compressor),
            &(encoder->compressor));


    // XXXX: allow (some of) the following options to be set from the 'encoderArgs'

    // We must set this flag to enable P or B frames.
    err = ICMCompressionSessionOptionsSetAllowTemporalCompression( sessionOptions, true );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not enable temporal compression");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    // We must set this flag to enable B frames.
// XXXX:	err = ICMCompressionSessionOptionsSetAllowFrameReordering( sessionOptions, true );
    err = ICMCompressionSessionOptionsSetAllowFrameReordering( sessionOptions, false );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not enable frame reordering");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    // Set the maximum key frame interval, also known as the key frame rate.
    // XXXX: even 5 frames might be a bit long for videoconferencing
    err = ICMCompressionSessionOptionsSetMaxKeyFrameInterval( sessionOptions, 3 );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not set maximum keyframe interval");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    // This allows the compressor more flexibility (ie, dropping and coalescing frames).
    // XXXX: does this mean that playback has to be more careful about when to actually display decoded frames?
// XXXX:	err = ICMCompressionSessionOptionsSetAllowFrameTimeChanges( sessionOptions, true );
    err = ICMCompressionSessionOptionsSetAllowFrameTimeChanges( sessionOptions, false );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not set enable frame time changes");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    // XXXX: CaptureAndCompressIPBMovie set this to true
    err = ICMCompressionSessionOptionsSetDurationsNeeded( sessionOptions, false );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not set whether frame durations are needed");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    // Set the average data rate.
    // XXXX: another good one to parameterize
    // XXXX: can we change this one at runtime?
    err = ICMCompressionSessionOptionsSetProperty(	sessionOptions,
            kQTPropertyClass_ICMCompressionSessionOptions,
            kICMCompressionSessionOptionsPropertyID_AverageDataRate,
            sizeof( averageDataRate ),
            &averageDataRate );
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not set average data rate");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    encodedFrameOutputRecord.encodedFrameOutputCallback = (void*)qQuickTimeEncoderCallback;
    encodedFrameOutputRecord.encodedFrameOutputRefCon = encoder;
    encodedFrameOutputRecord.frameDataAllocator = NULL;

    // Specify attributes for the compression-session's pixel-buffer pool.
    pixelBufferAttributes = CFDictionaryCreateMutable( NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );
    number = CFNumberCreate( NULL, kCFNumberIntType, &width );
    CFDictionaryAddValue( pixelBufferAttributes, kCVPixelBufferWidthKey, number );
    CFRelease( number );
    number = CFNumberCreate( NULL, kCFNumberIntType, &height );
    CFDictionaryAddValue( pixelBufferAttributes, kCVPixelBufferHeightKey, number );
    CFRelease( number );
    number = CFNumberCreate( NULL, kCFNumberSInt32Type, &pixelFormat );
    CFDictionaryAddValue( pixelBufferAttributes, kCVPixelBufferPixelFormatTypeKey, number );
    CFRelease( number );

    err = ICMCompressionSessionCreate(	NULL,
                                        width,
                                        height,
                                        args->codecType,
                                        args->timeScale,
                                        sessionOptions,
                                        pixelBufferAttributes,
                                        &encodedFrameOutputRecord,
                                        &(encoder->session));
    CFRelease(pixelBufferAttributes);
    if(err != noErr) {
        fprintf(QSTDERR, "\nqCreateEncoderQT(): could not create compression session");
        fprintf(QSTDERR, "\n\tQUICKTIME ERROR CODE: %d", err);
        ICMCompressionSessionOptionsRelease(sessionOptions);
        CloseComponent(encoder->compressor);
        free(encoder);
        return -5;
    }

    ICMCompressionSessionOptionsRelease(sessionOptions);

    *eptr = encoder;
    return 0;
}
int convertToMP4PathThrough(CFStringRef inFile, CFStringRef outFile)
{
	OSStatus error;
	MovieExportComponent movieExporter = NULL;
	Handle inDataRef=0, outDataRef=0;
	OSType inDataRefType, outDataRefType;
	short inResID = 0;
	Movie theMovie=0;
	int ret = -1;

	error = OpenADefaultComponent(MovieExportType, kQTFileTypeMP4, &movieExporter);
	if(error) {
		fprintf(stderr,"OpenADefaultComponent error: cannot find the QuickTime conponent\n");
		goto last;
	}
	error = QTNewDataReferenceFromFullPathCFString(inFile, kQTNativeDefaultPathStyle, 0, &inDataRef, &inDataRefType);
	if(error) {
		fprintf(stderr,"QTNewDataReferenceFromFullPathCFString error: input file path is invalid\n");
		goto last;
	}
	error = QTNewDataReferenceFromFullPathCFString(outFile, kQTNativeDefaultPathStyle, 0, &outDataRef, &outDataRefType);
	if(error) {
		fprintf(stderr,"QTNewDataReferenceFromFullPathCFString error: output file path is invalid\n");
		goto last;
	}
	error = NewMovieFromDataRef(&theMovie, newMovieActive, &inResID, inDataRef, inDataRefType);
	if(error) {
		fprintf(stderr,"NewMovieFromDataRef error: cannot open the input file\n");
		goto last;
	}

	Track theTrack = getSoundTrack(theMovie);
	Media theMedia = GetTrackMedia(theTrack);
	DeleteTrackSegment(theTrack, 0, GetTrackDuration(theTrack));
	SetMovieTimeScale(theMovie, GetMediaTimeScale(theMedia));
	InsertMediaIntoTrack(theTrack, 0, 0, GetMediaDuration(theMedia), fixed1);

	Boolean useHighResolutionAudio = true;
	QTSetComponentProperty(
		movieExporter,
		kQTPropertyClass_MovieExporter,
		kQTMovieExporterPropertyID_EnableHighResolutionAudioFeatures,
		sizeof(Boolean),
		&useHighResolutionAudio
	);

	UInt32 ftyp = 'mp42';
	QTSetComponentProperty(
		movieExporter,
		kQTPropertyClass_MovieExporter,
		'ftyp',
		4,
		&ftyp
	);

	QTAtomContainer ac;
	MovieExportGetSettingsAsAtomContainer(movieExporter, &ac);
	QTAtom ensoAtom = QTFindChildByID(ac, kParentAtomIsContainer, kQTSettingsMovieExportEnableSound, 1, NULL);
	if(ensoAtom) {
		long size, *data;
		QTGetAtomDataPtr(ac,ensoAtom,&size,(Ptr *)&data);
		data[0] = EndianS32_NtoB('past');
		QTSetAtomData(ac, ensoAtom, size, data);
		MovieExportSetSettingsFromAtomContainer(movieExporter, ac);
	}
	DisposeHandle(ac);
	
	/*Boolean cancelled;
	error = MovieExportDoUserDialog(movieExporter, theMovie, NULL, 0, GetMovieDuration(theMovie), &cancelled);
	if(cancelled) goto last;
	if(error) {
		printf("MovieExportDoUserDialog error\n");
		goto last;
	}*/
	
	error = ConvertMovieToDataRef(theMovie, 0, outDataRef, outDataRefType, kQTFileTypeMP4, FOUR_CHAR_CODE('TVOD'), createMovieFileDeleteCurFile|createMovieFileDontCreateResFile, movieExporter);
	if(error) {
        fprintf(stderr,"ConvertMovieToDataRef error: cannot translate .mov into .m4a (%d)\n",error);
		goto last;
	}

	ret = 0;
	
last:
	if(movieExporter) CloseComponent(movieExporter);
	if(theMovie) DisposeMovie(theMovie);
	if(inDataRef) DisposeHandle(inDataRef);
	if(outDataRef) DisposeHandle(outDataRef);

	return ret;
}
Beispiel #29
0
namespace OS {

	enum
	{
		gestaltUndefSelectorErr = -5551,
		gestaltUnknownErr = -5550,
		gestaltDupSelectorErr = -5552,
		gestaltLocationErr = -5553,
	};


	enum {
		gestaltOSAttr                 = FOUR_CHAR_CODE('os  '), /* o/s attributes */
		gestaltSysZoneGrowable        = 0,    /* system heap is growable */
		gestaltLaunchCanReturn        = 1,    /* can return from launch */
		gestaltLaunchFullFileSpec     = 2,    /* can launch from full file spec */
		gestaltLaunchControl          = 3,    /* launch control support available */
		gestaltTempMemSupport         = 4,    /* temp memory support */
		gestaltRealTempMemory         = 5,    /* temp memory handles are real */
		gestaltTempMemTracked         = 6,    /* temporary memory handles are tracked */
		gestaltIPCSupport             = 7,    /* IPC support is present */
		gestaltSysDebuggerSupport     = 8,    /* system debugger support is present */
		gestaltNativeProcessMgrBit    = 19    /* the process manager itself is native */
	};


	template<unsigned...>
	struct make_bitmask;

	template<>
	struct make_bitmask<> : public std::integral_constant<uint32_t, 0>
	{};

	template<unsigned First, unsigned... Rest>
	struct make_bitmask<First, Rest...> : 
	public std::integral_constant<uint32_t, (1 << First) | make_bitmask<Rest...>::value > 
	{};




	std::map<uint32_t, uint32_t> GestaltMap = {
		{'alis', 1}, // Alias Manager
		{'tmgr', 2}, // Time Manager (2 = revised, 3 = extended.)
		{
			// enable temp memory for codewarrior
			gestaltOSAttr, 
			make_bitmask<gestaltTempMemSupport, gestaltRealTempMemory, gestaltTempMemTracked>::value
		},
	};

	uint16_t Gestalt(uint16_t trap)
	{
		// FUNCTION Gestalt (selector: OSType; VAR response: LongInt): OSErr;

		/*
		 * on entry:
		 * D0 Selector code
		 *
		 * on exit:
		 * A0 Response
		 * D0 Result code
		 *
		 */

		uint32_t selector = cpuGetDReg(0);
		uint32_t response;

		Log("%04x Gestalt('%s')\n", trap, ToolBox::TypeToString(selector).c_str());

		auto iter = GestaltMap.find(selector);

		if (iter == GestaltMap.end()) return gestaltUndefSelectorErr;
		response = iter->second;
		cpuSetAReg(0, response);

		return 0;
	}


	uint16_t SysEnvirons(uint16_t trap)
	{
		//  FUNCTION SysEnvirons (versionRequested: Integer;
		//                        VAR theWorld: SysEnvRec): OSErr;

		/*
		 * on entry:
		 * D0 Version requested
		 * A0 SysEnvRec pointer
		 *
		 * on exit:
		 * D0 Result code
		 *
		 */

		enum {
			/* SysEnvRec */
			_environsVersion = 0,
			_machineType = 2,
			_systemVersion = 4,
			_processor = 6,
			_hasFPU = 8,
			_hasColorQD = 9,
			_keyBoardType = 10,
			_atDrvrVersNum = 12,
			_sysVRefNum = 14,
		};

		uint16_t versionRequested = cpuGetDReg(0);
		uint32_t theWorld = cpuGetAReg(0);

		Log("%04x SysEnvirons(%04x, %08x)\n", trap, versionRequested, theWorld);

		memoryWriteWord(2, theWorld + _environsVersion);

		// negative version.
		if (versionRequested >= 0x8000)
			return MacOS::envBadVers;

		if (versionRequested > 2)
			return MacOS::envVersTooBig;

		memoryWriteWord(0, theWorld + _machineType); // 0 = unknown model newer than the IIci (v1) or IIfx (v2)
		memoryWriteWord(1 + cpuGetModelMajor(), theWorld + _processor);
		memoryWriteWord(0x0700, theWorld + _systemVersion); // system 7
		memoryWriteWord(0, theWorld + _hasFPU);
		memoryWriteWord(0, theWorld + _hasColorQD);
		memoryWriteWord(5, theWorld + _keyBoardType); // standard adb I guess
		memoryWriteWord(0, theWorld + _atDrvrVersNum); // no appletalk
		memoryWriteWord(-1, theWorld + _sysVRefNum); // System folder #

		return 0;
	}

}
OSErr QTTarg_MakeDualVRControllerMovie (void)
{
	Movie					myMovie = NULL;
	Track					myTrack = NULL;
	Media					myMedia = NULL;
	RGBColor				myKeyColor;
	Fixed					myWidth, myHeight;
	FSSpec					myFile;
	Boolean					myIsSelected = false;
	Boolean					myIsReplacing = false;	
	StringPtr 				myPrompt = QTUtils_ConvertCToPascalString(kSpriteSavePrompt);
	StringPtr 				myFileName = QTUtils_ConvertCToPascalString(kSpriteSaveMovieFileName);
	long					myFlags = createMovieFileDeleteCurFile | createMovieFileDontCreateResFile;
	short					myResRefNum = 0;
	short					myResID = movieInDataForkResID;
	OSType					myType = FOUR_CHAR_CODE('none');
	OSErr					myErr = noErr;

	//////////
	//
	// create a new movie file
	//
	//////////

	// prompt the user for the destination file name
	QTFrame_PutFile(myPrompt, myFileName, &myFile, &myIsSelected, &myIsReplacing);
	myErr = myIsSelected ? noErr : userCanceledErr;
	if (!myIsSelected)
		goto bail;

	// create a movie file for the destination movie
	myErr = CreateMovieFile(&myFile, FOUR_CHAR_CODE('TVOD'), smSystemScript, myFlags, &myResRefNum, &myMovie);
	if (myErr != noErr)
		goto bail;
	
	// select the "no-interface" movie controller
	myType = EndianU32_NtoB(myType);
	SetUserDataItem(GetMovieUserData(myMovie), &myType, sizeof(myType), kUserDataMovieControllerType, 1);

	//////////
	//
	// get some information about the target movie
	//
	//////////

	myWidth = Long2Fix(kVRControlMovieWidth);
	myHeight = Long2Fix(kVRControlMovieHeight);
	
	//////////
	//
	// create a new sprite track in the target movie
	//
	//////////
	
	myTrack = NewMovieTrack(myMovie, myWidth, myHeight, kNoVolume);
	myMedia = NewTrackMedia(myTrack, SpriteMediaType, kVRControlMovieDuration, NULL, 0);

	myErr = BeginMediaEdits(myMedia);
	if (myErr != noErr)
		goto bail;
	
	//////////
	//
	// add sprite images and sprites to the sprite track; add actions to the sprites
	//
	//////////
	
	QTTarg_AddVRControllerButtonSamplesToMedia(myMedia, kVRControlMovieWidth, kVRControlMovieHeight, kVRControlMovieDuration);
	
	//////////
	//
	// insert media into track
	//
	//////////
	
	myErr = EndMediaEdits(myMedia);
	if (myErr != noErr)
		goto bail;
	
	// add the media to the track
	InsertMediaIntoTrack(myTrack, 0, 0, GetMediaDuration(myMedia), fixed1);
		
	//////////
	//
	// set the sprite track properties
	//
	//////////
	
	QTTarg_SetTrackProperties(myMedia, 0);								// idle as fast as possible
	
	myKeyColor.red = myKeyColor.green = myKeyColor.blue = 0xffff;		// white
	MediaSetGraphicsMode(GetMediaHandler(myMedia), transparent, &myKeyColor);
	
	//////////
	//
	// add the movie resource to the movie file
	//
	//////////
	
	myErr = AddMovieResource(myMovie, myResRefNum, &myResID, myFile.name);
		
bail:
	if (myResRefNum != 0)
		CloseMovieFile(myResRefNum);

	if (myMovie != NULL)
		DisposeMovie(myMovie);
		
	free(myPrompt);
	free(myFileName);

	return(myErr);
}