Esempio n. 1
0
boolean validhandle (Handle h) {

    if (h == nil)
        return (true);

#ifdef MACVERSION

    if (GetHandleSize (h) < 0) /*negative length never valid*/
        return (false);

    return (MemError () == noErr);
#endif

#ifdef WIN95VERSION
    if (GlobalSize (h) <= 0)
        return (false);

    return (true);
#endif
} /*validhandle*/
Esempio n. 2
0
/*
**	CheckStack checks the size of the search stack (array) to see if there's
**	room to push another LevelRec. If not, CheckStack grows the stack by
**	another kAdditionalLevelRecs elements.
*/
static	OSErr	CheckStack(unsigned short stackDepth,
						   LevelRecHandle searchStack,
						   Size *searchStackSize)
{
	OSErr	result;
	
	if ( (*searchStackSize / sizeof(LevelRec)) == (stackDepth + 1) )
	{
		/* Time to grow stack */
		SetHandleSize((Handle)searchStack, *searchStackSize + (kAdditionalLevelRecs * sizeof(LevelRec)));
		result = MemError();	/* should be noErr */
		*searchStackSize = GetHandleSize((Handle)searchStack);
	}
	else
	{
		result = noErr;
	}
	
	return ( result );
}
Esempio n. 3
0
// RAB BetterTelnet 2.0b5
// handle should be locked and detached
void ParseMacrosFromHandle(NewMacroInfo *macrost, Handle theHandle)
{
	Ptr macroPtr;
	long macroLength;

	macroPtr = *theHandle;
	macroLength = GetHandleSize(theHandle) - 2;
	// format and sanity checks follow
	if ((macroLength < 1) || (*macroPtr != '!') || (*(macroPtr + 1) != '\015')) {
		DisposeHandle(theHandle);
		setupNewMacros(macrost);
		return;
	} // bah
	BlockMoveData(macroPtr + 2, macroPtr, macroLength); // get rid of !CR
	HUnlock(theHandle);
	SetHandleSize(theHandle, macroLength);
	HLock(theHandle);

// now invoke the actual parser
	parseNewMacros2(macrost, theHandle);
}
Esempio n. 4
0
bool VMacResFile::GetResource( const VString& inType, sLONG inID, VBlob& outData) const
{
	outData.Clear();
	bool ok = false;
	Handle data = NULL;
	VError error = _GetResource( inType, inID, &data);
	if (error == VE_OK)
	{
		::LoadResource(data);
		OSErr macError = ::ResError();
		if (testAssert(macError == noErr))
		{
			assert(*data != NULL);
			::HLock(data);
			ok = outData.PutData( *data, GetHandleSize( data)) == VE_OK;
			::HUnlock(data);
			data = NULL;
		}
	}
	return ok;
}
Esempio n. 5
0
static pascal OSErr setmessageverb (const AppleEvent *event, AppleEvent *reply, long refcon) {

	#pragma unused (refcon)

	OSErr ec;
	AEDesc result;
	Str255 s;
	Handle htext;
	long lentext;
	Boolean fl;
	
	ec = AEGetParamDesc (event, keyDirectObject, typeChar, &result);
	
	if (ec != noErr) 
		return (ec);
		
	htext = result.dataHandle;
	
	if (htext == nil)
		return (noErr);
		
	lentext = GetHandleSize (htext);
	
	if (lentext > 255)
		lentext = 255;
		
	s [0] = (unsigned char) lentext;
	
	BlockMove (*htext, &s [1], lentext);
	
	AEDisposeDesc (&result);
	
	setwindowmessage (s);
	
	fl = true;
	
	ec = AEPutParamPtr (reply, keyDirectObject, typeBoolean, (Ptr) &fl, sizeof (Boolean));
	
	return (ec);
	} /*setmessageverb*/
Esempio n. 6
0
int read_setting_filename(void *handle, const char *key, Filename *result)
{
    int fd;
    AliasHandle h;
    Boolean changed;
    OSErr err;
    Str255 pkey;

    if (handle == NULL) goto out;
    fd = *(int *)handle;
    UseResFile(fd);
    if (ResError() != noErr) goto out;
    c2pstrcpy(pkey, key);
    h = (AliasHandle)Get1NamedResource(rAliasType, pkey);
    if (h == NULL) goto out;
    if ((*h)->userType == 'pTTY' && (*h)->aliasSize == sizeof(**h))
	memset(result, 0, sizeof(*result));
    else {
	err = ResolveAlias(NULL, h, &result->fss, &changed);
	if (err != noErr && err != fnfErr) goto out;
	if ((*h)->userType == 'pTTY') {
	    long dirid;
	    StrFileName fname;

	    /* Tail of record is pascal string contaning leafname */
	    if (FSpGetDirID(&result->fss, &dirid, FALSE) != noErr) goto out;
	    memcpy(fname, (char *)*h + (*h)->aliasSize,
		   GetHandleSize((Handle)h) - (*h)->aliasSize);
	    err = FSMakeFSSpec(result->fss.vRefNum, dirid, fname,
			       &result->fss);
	    if (err != noErr && err != fnfErr) goto out;
	}
    }
    ReleaseResource((Handle)h);
    if (ResError() != noErr) goto out;
    return 1;

  out:
    return 0;
}
static PoolHandlePtr NewPoolListSlot()
{   // Find or make an empty slot in the list.
    // WARNING: returns a pointer to data in an unlocked handle.
    PoolHandlePtr p, q;
    long count;
    const int kInitialSlots = 4;
    const int kIncreaseBySlots = 4;

    // Initialize the pool list if necessary
    if ( poolList == 0 ) {
        poolList = (PoolListHandle)NewHandleClear(kInitialSlots*sizeof(Handle));
        assert( poolList != 0 );
    }

    // Find an empty slot in the poolList (if there is one)
    count = GetHandleSize( (Handle)poolList )/sizeof(PoolHandle);

    p = *poolList;
    q = p + count;

    while (p<q) {
        if ( *p == 0 )
            return p;
        p++;
    }

    // Couldn't find and empty slot. Make some.
    SetHandleSize( (Handle)poolList, sizeof(PoolHandle) * ( count + kIncreaseBySlots) );
    assert( MemError() == noErr );

    // Note: poolList might have moved, so we *must* rebuild p and q.
    p = *poolList + count;
    q = p + kIncreaseBySlots;

    while ( p<q ) {
        *(p++) = 0;
    }

    return *poolList + count;
}
ODSize
RealShape::Purge( ODSize )
{
   if( fQDRegion ) {

#if defined(_PLATFORM_OS2_) || defined(_PLATFORM_WIN32_) || defined(_PLATFORM_UNIX_)

      ODSize size = 0;
      fQDRegion.DisposeRgn();

#else

      ODSize size = GetHandleSize( (Handle)fQDRegion );
      DisposeRgn( fQDRegion );

#endif // IBM Platforms

      fQDRegion = kODNULL;
      return size;
   } else
      return 0;
}
Esempio n. 9
0
void parseNewMacros2(NewMacroInfo *macrost, Handle macroHandle)
{
	Ptr macroPtr, pos;
	long macroLength, len;
	short i, flag;

	macroLength = GetHandleSize(macroHandle);
	macroPtr = *macroHandle;

	len = macroLength;
	pos = macroPtr;
	i = 1; // first index is obviously always zero, so we use it as length (see below)
	flag = 0;

	while (len) {
		if (*pos == 13) *pos = 0; // for strlen
		pos++;
		len--;
	}

	len = macroLength;
	pos = macroPtr;
	
	while ((i < NUM_MACROS) && (len > 1)) { // if len = 1, this is the last char;
											// then the index points out of the handle!
		if (*pos == 0) {
			macrost->index[i] = (pos - macroPtr + 1);
			i++;
		}
		pos++;
		len--;
	}

	macrost->handle = macroHandle;
	macrost->index[0] = macroLength; // first index is length of whole shebang
	HUnlock(macroHandle);
	fixMacros(macrost); // make sure there's an entry for each macro
}
OSErr SpriteUtils_AddPICTImageToKeyFrameSample (QTAtomContainer theKeySample, short thePictID, RGBColor *theKeyColor, QTAtomID theID, FixedPoint *theRegistrationPoint, StringPtr theImageName)
{
	PicHandle				myPicture = NULL;
	Handle					myCompressedPicture = NULL;
	ImageDescriptionHandle	myImageDesc = NULL;
	OSErr					myErr = noErr;
	
	// get picture from resource
	myPicture = (PicHandle)GetPicture(thePictID);
	if (myPicture == NULL)
		myErr = resNotFound;

	if (myErr != noErr)
		goto bail;
	
	DetachResource((Handle)myPicture);
	
	// convert it to image data compressed by the animation compressor
	myErr = ICUtils_RecompressPictureWithTransparency(myPicture, theKeyColor, NULL, &myImageDesc, &myCompressedPicture);
	if (myErr != noErr)
		goto bail;

	// add it to the key sample
	HLock(myCompressedPicture);
	myErr = SpriteUtils_AddCompressedImageToKeyFrameSample(theKeySample, myImageDesc, GetHandleSize(myCompressedPicture), *myCompressedPicture, theID, theRegistrationPoint, theImageName);
	
bail:
	if (myPicture != NULL)
		KillPicture(myPicture);
		
	if (myCompressedPicture != NULL)
		DisposeHandle(myCompressedPicture);
		
	if (myImageDesc != NULL)
		DisposeHandle((Handle)myImageDesc);
		
	return(myErr);
}
Esempio n. 11
0
static short indexNthWord (Handle htext, short n, short *wordcount) {
	
	short i;
	short ctchars;
	Boolean inwhite = true;
	Boolean thischarwhite;
	
	*wordcount = 0;
	
	ctchars = GetHandleSize (htext);
	
	if (ctchars == 0)
		return (0);
	
	for (i = 0; i < ctchars; i++) {
		
		thischarwhite = iswhite ((*htext) [i]);
		
		if (inwhite) {
			
			if (!thischarwhite) {
				
				(*wordcount)++;
				
				if (*wordcount >= n)
					return (i + 1); /*returned value is 1-based*/
					
				inwhite = false;
				}
			}
		else {
			if (thischarwhite)
				inwhite = true;
			}
		} /*indexNthWord*/
		
	return (0); /*aren't that many words*/
	} /*indexNthWord*/
Esempio n. 12
0
void CRectTracker::DrawTrackerRect(
	LPCRECT lpRect, CWnd* pWndClipTo, CDC* pDC, CWnd* pWnd)
{
	// first, normalize the rectangle for drawing
	CRect rect = *lpRect;
	rect.NormalizeRect();

	// convert to client coordinates
	if (pWndClipTo != NULL)
	{
		pWnd->ClientToScreen(&rect);
		pWndClipTo->ScreenToClient(&rect);
	}

	CSize size(0, 0);
	if (!m_bFinalErase)
	{
		// otherwise, size depends on the style
		if (m_nStyle & hatchedBorder)
		{
			size.cx = size.cy = max(1, GetHandleSize(rect)-1);
			rect.InflateRect(size);
		}
		else
		{
			size.cx = CX_BORDER;
			size.cy = CY_BORDER;
		}
	}

	// and draw it
	if (m_bFinalErase || !m_bErase)
		pDC->DrawDragRect(rect, size, m_rectLast, m_sizeLast);

	// remember last rectangles
	m_rectLast = rect;
	m_sizeLast = size;
}
static long QTUtils_FindUserDataItemWithPrefix (UserData theUserData, OSType theType, char *thePrefix)
{
	Handle			myData = NULL;
	long			myCount = 0;
	long			myIndex = 0;
	long			myItemIndex = 0;
	OSErr			myErr = noErr;
	
	// make sure we've got some valid user data
	if (theUserData == NULL)
		goto bail;
	
	// allocate a handle for GetUserData
	myData = NewHandle(0);
	if (myData == NULL)
		goto bail;

	myCount = CountUserDataType(theUserData, theType);
	for (myIndex = 1; myIndex <= myCount; myIndex++) {
		myErr = GetUserData(theUserData, myData, theType, myIndex);
		if (myErr == noErr) {
			if (GetHandleSize(myData) < strlen(thePrefix))
				continue;

			// see if the user data begins with the specified prefix (IdenticalText is case-insensitive)
			if (IdenticalText(*myData, thePrefix, strlen(thePrefix), strlen(thePrefix), NULL) == 0) {
				myItemIndex = myIndex;
				goto bail;
			}
		}
	}

bail:
	if (myData != NULL)
		DisposeHandle(myData);
		
	return(myItemIndex);
}
Esempio n. 14
0
/*e*/
TClut &TClut::operator=(const TClut &copyMe)
{
	if (copyMe.ctab)
	{
		Size			size=GetHandleSize((Handle)copyMe.ctab);
		if (ctab)
			BetterSetHandleSize((Handle)ctab,size,0);
		else
		{
			ctab=(CTabHandle)NewHandle(size);
			ThrowIfMemFull_(ctab);
		}
		BlockMove(*copyMe.ctab,*ctab,size);
	}
	else
	{
		if (ctab)
			DisposeHandle((Handle)ctab);
		ctab=0L;
	}

	return *this;
}
Esempio n. 15
0
void wxMetafile::SetHMETAFILE(WXHMETAFILE mf)
{
    UnRef() ;

    m_refData = new wxMetafileRefData;

    M_METAFILEDATA->m_metafile = (PicHandle) mf;
#if wxMAC_USE_CORE_GRAPHICS
    size_t sz = GetHandleSize( (Handle) M_METAFILEDATA->m_metafile ) ;
    wxMemoryBuffer* membuf = new wxMemoryBuffer( sz ) ;
    void * data = membuf->GetWriteBuf(sz) ;
    memcpy( data , *M_METAFILEDATA->m_metafile , sz ) ;
    membuf->UngetWriteBuf(sz) ;
    CGDataProviderRef provider = CGDataProviderCreateWithData( membuf , data , sz ,
        wxMacMemoryBufferReleaseProc ) ;
    M_METAFILEDATA->m_qdPictRef = NULL ;
    if ( provider != NULL )
    {
        M_METAFILEDATA->m_qdPictRef = QDPictCreateWithProvider( provider ) ;
        CGDataProviderRelease( provider ) ;
    }
#endif
}
Esempio n. 16
0
  /* Create a new FT_Face from an SFNT resource, specified by res ID. */
  static
  FT_Error  FT_New_Face_From_SFNT( FT_Library  library,
                                   short       sfnt_id,
                                   FT_Long     face_index,
                                   FT_Face*    aface )
  {
    Handle     sfnt = NULL;
    FT_Byte*   sfnt_data;
    size_t     sfnt_size;
    FT_Stream  stream = NULL;
    FT_Error   error = 0;
    FT_Memory  memory = library->memory;


    sfnt = GetResource( 'sfnt', sfnt_id );
    if ( ResError() )
      return FT_Err_Invalid_Handle;

    sfnt_size = (FT_ULong)GetHandleSize( sfnt );
    if ( ALLOC( sfnt_data, (FT_Long)sfnt_size ) )
    {
      ReleaseResource( sfnt );
      return error;
    }

    HLock( sfnt );
    memcpy( sfnt_data, *sfnt, sfnt_size );
    HUnlock( sfnt );
    ReleaseResource( sfnt );

    return open_face_from_buffer( library,
                                  sfnt_data,
                                  sfnt_size,
                                  face_index,
                                  "truetype",
                                  aface );
  }
Esempio n. 17
0
/* create icns(icon for MacOS X) with IPIcon */
OSErr MakeXIconWithIPIcon(const FSSpec *theFile,const IPIconRec *ipIcon)
{
	OSErr	err;
	FInfo	fndrInfo;
	short	refNum;
	IconFamilyHandle	iconFamily;
	long	count;
	
	if (!isIconServicesAvailable) return -1;
	
	/* convert IPIcon to icns */
	err=IPIconToIconFamily(ipIcon,&iconFamily);
	if (err!=noErr) return err;
	
	/* create a file */
	err=FSpGetFInfo(theFile,&fndrInfo);
	if (err==fnfErr)
		err=FSpCreate(theFile,kIconPartyCreator,kXIconFileType,smSystemScript);
	if (err!=noErr) return err;
	
	/* open the file */
	err=FSpOpenDF(theFile,fsWrPerm,&refNum);
	if (err!=noErr) return err;
	
	/* save icns */
	HLock((Handle)iconFamily);
	count=GetHandleSize((Handle)iconFamily);
	err=FSWrite(refNum,&count,*iconFamily);
	err=SetEOF(refNum,count);
	HUnlock((Handle)iconFamily);
	DisposeHandle((Handle)iconFamily);
	
	/* close the file */
	err=FSClose(refNum);
	
	return noErr;
}
static PoolHandlePtr FindPoolListSlot(void *ptr)
{   // Find the slot used by a pointer.
    // WARNING: returns a pointer to data in an unlocked handle.
    PoolHandlePtr p, q;
    long count;

    assert( poolList != 0 && *poolList != 0 );

    // find the slot in the pool list that refers to ptr
    p = *poolList;
    count = GetHandleSize( (Handle)poolList )/sizeof(PoolHandle);

    q = p + count;

    while (p<q) {
        if ( **p == ptr )
            return p;
        p++;
    }

    // Not found.
    return 0;

}
NS_IMETHODIMP
nsMacShellService::OnStateChange(nsIWebProgress* aWebProgress,
                                 nsIRequest* aRequest,
                                 uint32_t aStateFlags,
                                 nsresult aStatus)
{
  if (aStateFlags & STATE_STOP) {
    nsCOMPtr<nsIObserverService> os(do_GetService("@mozilla.org/observer-service;1"));
    if (os)
      os->NotifyObservers(nullptr, "shell:desktop-background-changed", nullptr);

    bool exists = false;
    mBackgroundFile->Exists(&exists);
    if (!exists)
      return NS_OK;

    nsAutoCString nativePath;
    mBackgroundFile->GetNativePath(nativePath);

    AEDesc tAEDesc = { typeNull, nil };
    OSErr err = noErr;
    AliasHandle aliasHandle = nil;
    FSRef pictureRef;
    OSStatus status;

    // Convert the path into a FSRef
    status = ::FSPathMakeRef((const UInt8*)nativePath.get(), &pictureRef,
                             nullptr);
    if (status == noErr) {
      err = ::FSNewAlias(nil, &pictureRef, &aliasHandle);
      if (err == noErr && aliasHandle == nil)
        err = paramErr;

      if (err == noErr) {
        // We need the descriptor (based on the picture file reference)
        // for the 'Set Desktop Picture' apple event.
        char handleState = ::HGetState((Handle)aliasHandle);
        ::HLock((Handle)aliasHandle);
        err = ::AECreateDesc(typeAlias, *aliasHandle,
                             GetHandleSize((Handle)aliasHandle), &tAEDesc);
        // unlock the alias handler
        ::HSetState((Handle)aliasHandle, handleState);
        ::DisposeHandle((Handle)aliasHandle);
      }
      if (err == noErr) {
        AppleEvent tAppleEvent;
        OSType sig = 'MACS';
        AEBuildError tAEBuildError;
        // Create a 'Set Desktop Pictue' Apple Event
        err = ::AEBuildAppleEvent(kAECoreSuite, kAESetData, typeApplSignature,
                                  &sig, sizeof(OSType), kAutoGenerateReturnID,
                                  kAnyTransactionID, &tAppleEvent, &tAEBuildError,
                                  "'----':'obj '{want:type (prop),form:prop" \
                                  ",seld:type('dpic'),from:'null'()},data:(@)",
                                  &tAEDesc);
        if (err == noErr) {
          AppleEvent reply = { typeNull, nil };
          // Sent the event we built, the reply event isn't necessary
          err = ::AESend(&tAppleEvent, &reply, kAENoReply, kAENormalPriority,
                         kNoTimeOut, nil, nil);
          ::AEDisposeDesc(&tAppleEvent);
        }
      }
    }
  }

  return NS_OK;
}
Esempio n. 20
0
boolean ploticonfromodb (const Rect *r, short align, short transform, bigstring bsadricon) {
#if defined (MACVERSION)
	//bigstring bsadricon = "\psystem.verbs.builtins.Frontier.tools.data.nodeTypes.link.icon.mac";
	

	IconRef iconRef;
	IconFamilyHandle iconHand;
	SInt32 theSize;
	OSStatus theErr;
	Handle hicon;
	bigstring bsadriconpart;
	
	theErr = noErr;
	theSize = sizeof(OSType) + sizeof(OSType);
	
	newhandle(theSize, (Handle*) &iconHand);

	//iconHand = (IconFamilyHandle) getnewhandle(theSize, false);
	
	if (iconHand == NULL) theErr = memFullErr;
	
	if (theErr == noErr) {
		(*iconHand)->resourceType = EndianU32_NtoB(kIconFamilyType);
		(*iconHand)->resourceSize = EndianU32_NtoB(theSize);
	}
	
	if (theErr == noErr) {
		setemptystring(bsadriconpart);
		copystring(bsadricon, bsadriconpart);
		pushstring(BIGSTRING("\x05" ".ics4"), bsadriconpart);
		theErr = loadicondatafromodb(bsadriconpart, BIGSTRING("\x04" "ics4"), &hicon);
		
		if (theErr == noErr) {
			theErr = SetIconFamilyData(iconHand, kSmall4BitData, hicon);
			disposehandle(hicon);
		}
	}
	
	if (theErr == noErr) {
		setemptystring(bsadriconpart);
		copystring(bsadricon, bsadriconpart);
		pushstring(BIGSTRING("\x05" ".ics8"), bsadriconpart);
		theErr = loadicondatafromodb(bsadriconpart, BIGSTRING("\x04" "ics8"), &hicon);
		
		if (theErr == noErr) {
			theErr = SetIconFamilyData(iconHand, kSmall8BitData, hicon);
			disposehandle(hicon);
		}
	}
	
	if (theErr == noErr) {
		setemptystring(bsadriconpart);
		copystring(bsadricon, bsadriconpart);
		pushstring(BIGSTRING("\x09" ".icspound"), bsadriconpart);
		theErr = loadicondatafromodb(bsadriconpart, BIGSTRING("\x08" "icspound"), &hicon);
		
		if (theErr == noErr) {
			theErr = SetIconFamilyData(iconHand, kSmall1BitMask, hicon);
			disposehandle(hicon);
		}
	}
	
	if (theErr == noErr) {
		theErr = GetIconRefFromIconFamilyPtr(*iconHand, GetHandleSize((Handle) iconHand), &iconRef);
	}
	
	if (theErr == noErr) {
		theErr = PlotIconRef(r, align, transform, kIconServicesNormalUsageFlag, iconRef);
	}
	
	setemptystring(bsadriconpart);
	ReleaseIconRef(iconRef);
	disposehandle((Handle) iconHand);
	
	return theErr == noErr;
#else if defined (WIN95VERSION)
	return FALSE;
#endif
}
Esempio n. 21
0
CFDictionaryRef createDockDescriptionForURL(CFURLRef url) {
	if (!url) {
		NSLog(CFSTR("%@"), CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: Cannot copy Dock description for a NULL URL"));
		return NULL;
	}

	//return NULL for non-file: URLs.
	CFStringRef scheme = CFURLCopyScheme(url);
	Boolean isFileURL = (CFStringCompare(scheme, CFSTR("file"), kCFCompareCaseInsensitive) == kCFCompareEqualTo);
	CFRelease(scheme);
	if (!isFileURL)
		return NULL;

	CFDictionaryRef dict = NULL;
	CFStringRef path     = NULL;
	CFDataRef aliasData  = NULL;

	FSRef    fsref;
	if (CFURLGetFSRef(url, &fsref)) {
		AliasHandle alias = NULL;
		OSStatus    err   = FSNewAlias(/*fromFile*/ NULL, &fsref, &alias);
		if (err != noErr) {
			NSLog(CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: FSNewAlias for %@ returned %li"), url, (long)err);
		} else {
			HLock((Handle)alias);

			err = FSCopyAliasInfo(alias, /*targetName*/ NULL, /*volumeName*/ NULL, (CFStringRef *)&path, /*whichInfo*/ NULL, /*info*/ NULL);
			if (err != noErr) {
				NSLog(CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: FSCopyAliasInfo for %@ returned %li"), url, (long)err);
			}

			aliasData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)*alias, GetHandleSize((Handle)alias));

			HUnlock((Handle)alias);
			DisposeHandle((Handle)alias);
		}
	}

	if (!path) {
		path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
	}

	if (path || aliasData) {
		CFMutableDictionaryRef temp = CFDictionaryCreateMutable(kCFAllocatorDefault, /*capacity*/ 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

		if (path) {
			CFDictionarySetValue(temp, _CFURLStringKey, path);
			CFRelease(path);

			int pathStyle = kCFURLPOSIXPathStyle;
			CFNumberRef pathStyleNum = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pathStyle);
			CFDictionarySetValue(temp, _CFURLStringTypeKey, pathStyleNum);
			CFRelease(pathStyleNum);
		}

		if (aliasData) {
			CFDictionarySetValue(temp, _CFURLAliasDataKey, aliasData);
			CFRelease(aliasData);
		}

		dict = temp;
	}

	return dict;
}
Esempio n. 22
0
void saveMacros(NewMacroInfo *macrost, FSSpec *theFile)
{
	SFReply		whereReply;
	short 		refNum,exist;
	FSSpec		macroFile;
	long		junk, len, len2;
	short 		i;
	Point		where;
	OSErr		err;
	Str255		tempString,tempString2;
	Handle		macroHandle;
	Ptr			pos;

	if (!macrost->handle) return; // sanity check

	where.h = 100; where.v = 100;

	GetIndString(tempString,MISC_STRINGS,SAVE_MACROS_STRING);
	GetIndString(tempString2,MISC_STRINGS,DEFAULT_MACRO_SET_NAME);

	if (theFile == 0) {
		SFPutFile( where, tempString, tempString2, 0L, &whereReply);

		if (!whereReply.good)
			return;

		BlockMoveData(&whereReply.fName, macroFile.name, (*whereReply.fName)+1); 
		GetWDInfo(whereReply.vRefNum, &macroFile.vRefNum, &macroFile.parID, &junk);
	}
	else
		macroFile = *theFile;

	if ((err = HCreate(macroFile.vRefNum, macroFile.parID, 
			macroFile.name, kNCSACreatorSignature, 'TEXT')) == dupFNErr)
		exist = 1;
	
	err = HOpenDF(macroFile.vRefNum, macroFile.parID, macroFile.name, fsWrPerm, &refNum);

	if (exist) 
		SetEOF(refNum, 0L);

// the new code - RAB BetterTelnet 2.0b5
	macroHandle = macrost->handle;
	HandToHand(&macroHandle);
	HLock(macroHandle);
	pos = *macroHandle;
	len = len2 = GetHandleSize(macroHandle);
	while (len) {
		if (*pos == 0) *pos = 13;
		pos++;
		len--;
	}

	pos = *macroHandle;
	junk = 2;
	FSWrite(refNum, &junk, "!\015");
	FSWrite(refNum, &len2, pos);
	DisposeHandle(macroHandle); // it's a copy anyway, get rid of it!

	FSClose(refNum);
}
Esempio n. 23
0
short	sendmacro(struct WindRec *tw, short n)				/* send macro number n */
// RAB BetterTelnet 2.0b5 - changed to support new macro system
{
	char			temp[20];
	unsigned char	*s, *first, *p;
	unsigned char	myipnum[4];
	Handle			mh, ph;
	short			i, num, pos, escape, length;
	char			*plabel;
	Str255			password;
	unsigned long	startTicks;
	
	// Invalid number
	if (n < 0 || n >= NUM_MACROS) {
		return -1;
	}

	// first we actually have to GET the macro (2.0b5)
	// we use getmacrointohandle for this
	i = -1;
	if (tw->sessmacros.handle)
		i = getmacrointohandle(&tw->sessmacros, n, &mh);
	if (i == -1)
		i = getmacrointohandle(&TelInfo->newMacros, n, &mh);
	if (i == -1)
		return 0;

// Empty macro, so do nothing
//	if (gMacros[n] == nil) {
//		return 0;
//		}

//	HLock(gMacros[n]);
//	mp = (unsigned char *)*gMacros[n];

	s = (unsigned char *)*mh;

	ph = myNewHandle(GetHandleSize(mh) + 256);
	if (!ph) return 0; // ouch
	HLock(ph);
	first = p = (unsigned char *)*ph;

	netgetip(myipnum);

// totally revised - we parse as we go (RAB BetterTelnet 2.0b5)
// this has the pleasant side effect of getting rid of the use of 254 and 255 as special
// characters, so we can use them in macros now - you can now send telnet options from a macro!
	num = 0;
	pos = 0;
	escape = 0;

	while ( *s) {
		if (escape == 1 && (((*s < '0' || *s > '9') && pos) || pos >= 3)) {
												  // do this ONCE -
												  // it's a kludge to do this in each case
			*p++=num;
			pos = 0;
			escape = 0;
			// now the rest of the code will take care of whatever char this was
		}
		if (escape == 1) {
			escape = 0;
			switch (*s) {
				case 'i':
					SendStringAsIfTyped(tw, (char *)first, p-first);
					sprintf(temp,"%d.%d.%d.%d", myipnum[0], myipnum[1], myipnum[2], myipnum[3]);
					SendStringAsIfTyped(tw, temp, strlen(temp));
					first = p = (unsigned char *)*ph;
					break;
				case '#':
					SendStringAsIfTyped(tw, (char *)first, p-first);
					sprintf(temp,"%d", VSgetlines(tw->vs));
					SendStringAsIfTyped(tw, temp, strlen(temp));
					first = p = (unsigned char *)*ph;
					break;
				case 'n':
					*p++='\012';
					break;
				case 'r':
					*p++='\015';
					break;
				case 't':
					*p++='\t';
					break;
				case '"':
					*p++='\"';
					break;
				case '\\':
					*p++='\\';
					break;
				case 'k':
					escape = 2;
					break;
				case 'w':
					// switch to window num
					if ( s[1] >= '1' && s[1] <= '9') {
						HandleMenuCommand( (connMenu << 16 | FIRST_CNXN_ITEM) + s[1] - '1', 0 );
						++s;
					}
					break;
				default:
					if (*s <='9' && *s >='0' && pos <3) {
						num= num*8+( *s -'0');
						pos++;
						escape=1;
						}
					else {
//						if (pos ==0 && num==0) {
							*p++='\\';
							*p++=*s;
//							}
//						else {
//							*p++=num;
//							pos= 0;
//							s--;			/* back up the buffer. */
//							}
						}
					break;
				}
		} else if (escape == 2) {
			if (*s == '{') {
				escape = 3;
				plabel = NULL;
			} else {
				escape = 0;
			}
		} else if (escape == 3) {
			if (*s != '}') {
				if ( plabel == NULL )
					plabel = s;
			} else {
				*s = 0;
				if (plabel && SSH2PasswordDialog(plabel, password, NULL)) {
					SendStringAsIfTyped(tw, (char *)first, p-first);
					// better wait for echo off...
					startTicks = TickCount();
					while (TickCount() - startTicks < 30) {
						ssh2_sched();
						DoNetEvents();
					}
					first = p = (unsigned char *)*ph;
					SendStringAsIfTyped(tw, (char *)password + 1, password[0]);
				} else {
					// malformed macro, or pasword cancel
					first = p = (unsigned char *)*ph;
					break;
				}
				escape = 0;
			}
		} else {
			if (*s=='\\') {
				num=0;
				pos=0;
				escape=1;
				}
			else
				*p++=*s;
			}
		s++;
		}

	if (pos >0) *p++=num;

	SendStringAsIfTyped(tw, (char *)first, p-first);

	DisposeHandle(mh);
	DisposeHandle(ph);
	return 0;
}
Esempio n. 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;
  }
Esempio n. 25
0
OSErr PAS_flattenResource(ResType type, short *ids, long count, short source, short dest)
{
	long 			idIndex;
	
	
	Handle			resToCopy;
	long			handleLength;
	
	PASResource		pasResource;
	long			pasResLen;
	
	OSErr			err;
	
	for (idIndex=0; idIndex < count; idIndex++)
	{
		if( (type == 'SIZE') && ( ids[idIndex] == 1 || ids[idIndex] == 0  ) )
		{
			/* 	
				We do not want to encode/flatten SIZE 0 or 1 because this
				is the resource that the user can modify.  Most applications
				will not be affected if we remove these resources
			*/
		}
		else
		{	
			resToCopy=Get1Resource(type,ids[idIndex]);
					
			if(!resToCopy)	
			{
				return resNotFound;
			}	
				
			memset(&pasResource, 0, sizeof(PASResource));	
				
			GetResInfo(	resToCopy, 	
						&pasResource.attrID, 
						&pasResource.attrType, 
						pasResource.attrName);	
			
			pasResource.attr = GetResAttrs(resToCopy);
			
			DetachResource(resToCopy);	
			HLock(resToCopy);
			
			pasResource.length 	= GetHandleSize(resToCopy);
			handleLength 		= pasResource.length;
			
			pasResLen			=	sizeof(PASResource);
			
			err = FSWrite(dest, &pasResLen, &pasResource);
			
			if(err != noErr) 
			{
				return err;
			}
			
			err = FSWrite(dest, &handleLength, &(**resToCopy));

			if(err != noErr) 
			{
				return err;
			}
			
			HUnlock(resToCopy);
			DisposeHandle(resToCopy);		
		}
	}
	
	
	return noErr;
}
Esempio n. 26
0
 void QuicktimeImportExport::writeToStream(std::ostream& outStream, osg::Image* image, const std::string& fileTypeHint) 
 {

    std::string ext = osgDB::getFileExtension(fileTypeHint);
    //Build map  of extension <-> osFileTypes
    static std::map<std::string, OSType> extmap;
    if (extmap.size() == 0) {
        extmap["jpg"]  = kQTFileTypeJPEG;
        extmap["jpeg"] = kQTFileTypeJPEG;
        extmap["bmp"]  = kQTFileTypeBMP;
        extmap["tif"]  = kQTFileTypeTIFF;
        extmap["tiff"] = kQTFileTypeTIFF;
        extmap["png"]  = kQTFileTypePNG;
        extmap["gif"]  = kQTFileTypeGIF;
        extmap["psd"]  = kQTFileTypePhotoShop;
        extmap["sgi"]  = kQTFileTypeSGIImage;
        extmap["rgb"]  = kQTFileTypeSGIImage;
        extmap["rgba"] = kQTFileTypeSGIImage;
    }

    
    std::map<std::string, OSType>::iterator cur = extmap.find(ext);
    
    // can not handle this type of file, perhaps a movie?
    if (cur == extmap.end())
        return;
    
    unsigned int numBytes = image->computeNumComponents(image->getPixelFormat());
    unsigned char* pixels = prepareBufferForQuicktime(
        image->data(),
        image->getPixelFormat(), 
        numBytes,
        image->s(),
        image->t()
    );
    
        
    OSType desiredType = cur->second;
    GraphicsExportComponent geComp = NULL;
    GWorldPtr gw = 0;
    Handle dataHandle;
    dataHandle = NewHandle(0);

    try {
        OSErr err = OpenADefaultComponent(GraphicsExporterComponentType, desiredType, &geComp);
        Rect bounds = {0,0, image->t(), image->s()};
        
        err = QTNewGWorldFromPtr(&gw, k32ARGBPixelFormat, &bounds, 0,0,0, pixels, image->s()*4);
        if (err != noErr) {
            throw QTImportExportException(err,  "could not create gworld for type " + ext);
        }
        
        err = GraphicsExportSetInputGWorld(geComp, gw);
        if (err != noErr) {
            throw QTImportExportException(err, "could not set input gworld for type " + ext);
        }
        
        err = GraphicsExportSetOutputHandle( geComp, dataHandle);
        if (err != noErr) {
            throw QTImportExportException(err, "could not set output file for type " + ext);
        } 
        
        // Set the compression quality (needed for JPEG, not necessarily for other formats)
        if (desiredType == kQTFileTypeJPEG) {
            err = GraphicsExportSetCompressionQuality(geComp, codecLosslessQuality);
            if (err != noErr) {
                throw QTImportExportException(err, "could not set compression for type " + ext);
            }
        }
        
        if(4 == numBytes)
        {
            err = GraphicsExportSetDepth( geComp, k32ARGBPixelFormat );    // depth
        }
        // else k24RGBPixelFormat???
        
        // do the export
        err = GraphicsExportDoExport(geComp, NULL);
        if (err != noErr) {
            throw QTImportExportException(err, "could not do the export for type " + ext);
        } 
        
        if (geComp != NULL)
            CloseComponent(geComp);
            
        if (gw) DisposeGWorld (gw);
        if (pixels) free(pixels);
        
        outStream.write(*dataHandle, GetHandleSize(dataHandle));
        DisposeHandle(dataHandle);
    }
    
    
    catch (QTImportExportException& e) 
    {
        setError(e.what());
        
        if (geComp != NULL) CloseComponent(geComp);      
        if (gw != NULL) DisposeGWorld (gw);
        if (pixels) free(pixels);
        
        DisposeHandle(dataHandle);

    }

}
Esempio n. 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;
}
size_t				CResource::GetSize()
{
	return GetHandleSize(mHandle);
}
Esempio n. 29
0
File: ftmac.c Progetto: 32767/libgdx
  /* Read Type 1 data from the POST resources inside the LWFN file,
     return a PFB buffer.  This is somewhat convoluted because the FT2
     PFB parser wants the ASCII header as one chunk, and the LWFN
     chunks are often not organized that way, so we glue chunks
     of the same type together. */
  static FT_Error
  read_lwfn( FT_Memory      memory,
             ResFileRefNum  res,
             FT_Byte**      pfb_data,
             FT_ULong*      size )
  {
    FT_Error       error = FT_Err_Ok;
    ResID          res_id;
    unsigned char  *buffer, *p, *size_p = NULL;
    FT_ULong       total_size = 0;
    FT_ULong       old_total_size = 0;
    FT_ULong       post_size, pfb_chunk_size;
    Handle         post_data;
    char           code, last_code;


    UseResFile( res );

    /* First pass: load all POST resources, and determine the size of */
    /* the output buffer.                                             */
    res_id    = 501;
    last_code = -1;

    for (;;)
    {
      post_data = Get1Resource( TTAG_POST, res_id++ );
      if ( post_data == NULL )
        break;  /* we are done */

      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( code == 5 )
          total_size += 2; /* just the end code */
        else
          total_size += 6; /* code + 4 bytes chunk length */
      }

      total_size += GetHandleSize( post_data ) - 2;
      last_code = code;

      /* detect integer overflows */
      if ( total_size < old_total_size )
      {
        error = FT_Err_Array_Too_Large;
        goto Error;
      }

      old_total_size = total_size;
    }

    if ( FT_ALLOC( buffer, (FT_Long)total_size ) )
      goto Error;

    /* Second pass: append all POST data to the buffer, add PFB fields. */
    /* Glue all consecutive chunks of the same type together.           */
    p              = buffer;
    res_id         = 501;
    last_code      = -1;
    pfb_chunk_size = 0;

    for (;;)
    {
      post_data = Get1Resource( TTAG_POST, res_id++ );
      if ( post_data == NULL )
        break;  /* we are done */

      post_size = (FT_ULong)GetHandleSize( post_data ) - 2;
      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( last_code != -1 )
        {
          /* we are done adding a chunk, fill in the size field */
          if ( size_p != NULL )
          {
            *size_p++ = (FT_Byte)(   pfb_chunk_size         & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 8  ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 16 ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 24 ) & 0xFF );
          }
          pfb_chunk_size = 0;
        }

        *p++ = 0x80;
        if ( code == 5 )
          *p++ = 0x03;  /* the end */
        else if ( code == 2 )
          *p++ = 0x02;  /* binary segment */
        else
          *p++ = 0x01;  /* ASCII segment */

        if ( code != 5 )
        {
          size_p = p;   /* save for later */
          p += 4;       /* make space for size field */
        }
      }

      ft_memcpy( p, *post_data + 2, post_size );
      pfb_chunk_size += post_size;
      p += post_size;
      last_code = code;
    }
Esempio n. 30
0
File: ftmac.c Progetto: 32767/libgdx
  /* Create a new FT_Face from an SFNT resource, specified by res ID. */
  static FT_Error
  FT_New_Face_From_SFNT( FT_Library  library,
                         ResID       sfnt_id,
                         FT_Long     face_index,
                         FT_Face*    aface )
  {
    Handle     sfnt = NULL;
    FT_Byte*   sfnt_data;
    size_t     sfnt_size;
    FT_Error   error  = FT_Err_Ok;
    FT_Memory  memory = library->memory;
    int        is_cff, is_sfnt_ps;


    sfnt = GetResource( TTAG_sfnt, sfnt_id );
    if ( sfnt == NULL )
      return FT_Err_Invalid_Handle;

    sfnt_size = (FT_ULong)GetHandleSize( sfnt );
    if ( FT_ALLOC( sfnt_data, (FT_Long)sfnt_size ) )
    {
      ReleaseResource( sfnt );
      return error;
    }

    ft_memcpy( sfnt_data, *sfnt, sfnt_size );
    ReleaseResource( sfnt );

    is_cff     = sfnt_size > 4 && !ft_memcmp( sfnt_data, "OTTO", 4 );
    is_sfnt_ps = sfnt_size > 4 && !ft_memcmp( sfnt_data, "typ1", 4 );

    if ( is_sfnt_ps )
    {
      FT_Stream  stream;


      if ( FT_NEW( stream ) )
        goto Try_OpenType;

      FT_Stream_OpenMemory( stream, sfnt_data, sfnt_size );
      if ( !open_face_PS_from_sfnt_stream( library,
                                           stream,
                                           face_index,
                                           0, NULL,
                                           aface ) )
      {
        FT_Stream_Close( stream );
        FT_FREE( stream );
        FT_FREE( sfnt_data );
        goto Exit;
      }

      FT_FREE( stream );
    }
  Try_OpenType:
    error = open_face_from_buffer( library,
                                   sfnt_data,
                                   sfnt_size,
                                   face_index,
                                   is_cff ? "cff" : "truetype",
                                   aface );
  Exit:
    return error;
  }