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;
}
Example #2
0
bool MacPrinterCanvas::setup(bool s){
#if carbon
	return false;
#else
	GetPort(&oldPort);
	PrOpen();
  if (!prRecHdl) {
	prRecHdl = THPrint(NewHandleClear(sizeof(TPrint)));
	if (PrError()  != noErr) {
		return false;
	}
	PrintDefault(prRecHdl);
	if (PrError()  != noErr) {
		return false;
	}
  }else{
	PrValidate(prRecHdl);
  }
    if (s) {
		PrStlDialog(prRecHdl);
	}
	PrClose();
	if (PrError()  != noErr) {
		return false;
	}
	//debugfile("MacPrinterCanvas::setup  width=%d height=%d\n", pwidth(), pheight());
	SetPort(oldPort);
	return true;
#endif
}
Example #3
0
bool MacPrinterCanvas::start() {
#if carbon
	return false;
#else
//debugfile("MacPrinter::init\n");
	GetPort(&oldPort);
	PrOpen();
  if (!prRecHdl) {
	prRecHdl = THPrint(NewHandleClear(sizeof(TPrint)));
	if (PrError()  != noErr) {
		return false;
	}
	PrintDefault(prRecHdl);
	if (PrError()  != noErr) {
		return false;
	}
	PrStlDialog(prRecHdl);
  }else{
	PrValidate(prRecHdl);
  }
	gPrinterPort = PrOpenDoc(prRecHdl, nil, nil);
	if (PrError()  != noErr) {
		return false;
	}
	PrOpenPage(gPrinterPort, nil);
	if (PrError()  != noErr) {
		return false;
	}
	damage_all();
	beginPaint();
	return true;
#endif
}
char * ReadDataFile (long * pBufferSize, FSSpec * pfsspecData)
{
	NavReplyRecord replyNav;
	NavTypeListHandle hTypeList = (NavTypeListHandle) NewHandleClear (sizeof (NavTypeList) + sizeof (OSType) * 1);
	AEKeyword theKeyword;
	DescType actualType;
	Size actualSize;
	OSStatus err = noErr;
    short fileRef;
    char * pFileBuffer;

	HLock ((Handle) hTypeList);
	(**hTypeList).osTypeCount = 2;
	(**hTypeList).osType[0] = 'TEXT';
	(**hTypeList).osType[1] = '????';

    // select sprite file
	err = NavChooseFile (NULL, &replyNav, NULL, NULL, NULL, NULL, hTypeList, NULL); 
	if ((err == noErr) && (replyNav.validRecord))
		err = AEGetNthPtr (&(replyNav.selection), 1, typeFSS, &theKeyword, &actualType,
						   pfsspecData, sizeof (FSSpec), &actualSize);
	NavDisposeReply (&replyNav);
	if (err != noErr)
		return false;
    FSpOpenDF(pfsspecData, fsRdPerm, &fileRef);
    GetEOF(fileRef, pBufferSize);
    pFileBuffer = (char *) NewPtrClear (*pBufferSize);
    FSRead (fileRef, pBufferSize, pFileBuffer);
    FSClose (fileRef);
	return pFileBuffer;
}
Example #5
0
// Component Open Request - Required
pascal ComponentResult TextSubCodecOpen(TextSubGlobals glob, ComponentInstance self)
{
	ComponentResult err;

	// Allocate memory for our globals, set them up and inform the component manager that we've done so
	glob = (TextSubGlobals)NewPtrClear(sizeof(TextSubGlobalsRecord));
	if (err = MemError()) goto bail;

	SetComponentInstanceStorage(self, (Handle)glob);

	glob->self = self;
	glob->target = self;
	glob->wantedDestinationPixelTypeH = (OSType **)NewHandleClear((kNumPixelFormatsSupportedTextSub+1) * sizeof(OSType));
	if (err = MemError()) goto bail;
	glob->drawBandUPP = NULL;
	glob->ssa = NULL;
	glob->colorSpace = NULL;
	glob->translateSRT = true;
	
	// Open and target an instance of the base decompressor as we delegate
	// most of our calls to the base decompressor instance
	err = OpenADefaultComponent(decompressorComponentType, kBaseCodecType, &glob->delegateComponent);
	if (err) goto bail;

	ComponentSetTarget(glob->delegateComponent, self);

bail:
	return err;
}
OSErr SpriteUtils_AddSpriteSampleToMedia (Media theMedia, QTAtomContainer theSample, TimeValue theDuration, Boolean isKeyFrame, TimeValue *theSampleTime)
{
	SampleDescriptionHandle 	mySampleDesc = NULL;
	OSErr						myErr = noErr;
	
	mySampleDesc = (SampleDescriptionHandle)NewHandleClear(sizeof(SpriteDescription));
	if (mySampleDesc == NULL) {
		myErr = MemError();
		goto bail;
	}
	
	myErr = AddMediaSample(theMedia,
							(Handle)theSample,
							0,
							GetHandleSize(theSample),
							theDuration,
							mySampleDesc,
							1,
							(short)(isKeyFrame ? 0 : mediaSampleNotSync),
							theSampleTime);
							
bail:
	if (mySampleDesc != NULL)
		DisposeHandle((Handle) mySampleDesc);
	return(myErr);
}
Example #7
0
ComponentResult create_placeholder_track(Movie movie, Track *placeholderTrack, TimeValue duration, Handle dataRef, OSType dataRefType) {
    SampleDescriptionHandle sdH = NULL;
    Media placeholderMedia;
    TimeScale movieTimeScale;
    ComponentResult result = noErr;

    movieTimeScale = GetMovieTimeScale(movie);

    sdH = (SampleDescriptionHandle)NewHandleClear(sizeof(SampleDescription));
    (*sdH)->descSize = sizeof(SampleDescription);

    *placeholderTrack = NewMovieTrack(movie, 0, 0, kNoVolume);
    placeholderMedia = NewTrackMedia(*placeholderTrack, BaseMediaType, movieTimeScale, dataRef, dataRefType);

    result = AddMediaSampleReference(placeholderMedia, 0, 1, duration, sdH, 1, 0, NULL);
    if(result != noErr)
        goto bail;

    result = InsertMediaIntoTrack(*placeholderTrack, -1, 0, duration, fixed1);

bail:
    if (sdH)
        DisposeHandle((Handle) sdH);
    return(result);
}
CTabHandle build_macintosh_color_table(
	color_table *table)
{
	CTabHandle clut;
	int i,n;
	rgb_color *src;
	ColorSpec *dst;

	n=table->color_count;
	if (n<0) {
		n=0;
	} else if (n>256) {
		n=256;
	}
	clut=(CTabHandle)NewHandleClear(offsetof(ColorTable,ctTable)+n*sizeof (ColorSpec));
	if (clut) {
		(*clut)->ctSeed=GetCTSeed();
		(*clut)->ctSize=n-1;

		src=table->colors;
		dst=(*clut)->ctTable;
		for (i=0; i<n; i++) {
			dst->value=i;
			dst->rgb.red=src->red;
			dst->rgb.green=src->green;
			dst->rgb.blue=src->blue;
			src++;
			dst++;
		}
	}
	return clut;
}
Example #9
0
static OSErr QT_AddUserDataTextToMovie (Movie theMovie, char *theText, OSType theType)
{
	UserData					myUserData = NULL;
	Handle						myHandle = NULL;
	long						myLength = strlen(theText);
	OSErr						myErr = noErr;

	// get the movie's user data list
	myUserData = GetMovieUserData(theMovie);
	if (myUserData == NULL)
		return(paramErr);
	
	// copy the specified text into a new handle
	myHandle = NewHandleClear(myLength);
	if (myHandle == NULL)
		return(MemError());

	BlockMoveData(theText, *myHandle, myLength);

	// add the data to the movie's user data
	myErr = AddUserDataText(myUserData, myHandle, theType, 1, (short)GetScriptManagerVariable(smRegionCode));

	// clean up
	DisposeHandle(myHandle);
	return(myErr);
}
Example #10
0
TLevelReader3gp::TLevelReader3gp(const TFilePath &path)
	: TLevelReader(path), m_IOError(QTNoError), m_track(0), m_movie(0), m_depth(0)
//                ,m_timeScale(0)
{

	FSSpec fspec;
	QDErr err;
	Boolean dataRefWasChanged;
	if (QuickTimeStuff::instance()->getStatus() != noErr) {
		m_IOError = QTNotInstalled;
		return;
	}

	const char *pStr = toString(m_path.getWideString()).c_str();
	FSMakeFSSpec(0, 0, (const unsigned char *)pStr, &fspec);
	getFSSpecFromPosixPath(pStr, &fspec, false);
	pStr = 0;

	if ((err = OpenMovieFile(&fspec, &m_refNum, fsRdPerm))) {
		m_IOError = QTUnableToOpenFile;
		return;
	}

	m_resId = 0;
	Str255 name;
	err = NewMovieFromFile(&m_movie, m_refNum, &m_resId,
						   name, fsRdPerm, &dataRefWasChanged);

	int numTracks = GetMovieTrackCount(m_movie);
	assert(numTracks == 1 || numTracks == 2);

	m_track = GetMovieIndTrackType(m_movie, 1, VideoMediaType, movieTrackMediaType);

	//m_track=GetMovieTrack(m_movie,numTracks);

	ImageDescriptionHandle imageH;
	imageH = (ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription));
	TINT32 index = 1;
	Media theMedia = GetTrackMedia(m_track);

	GetMediaSampleDescription(theMedia, index, (SampleDescriptionHandle)imageH);
	ImageDescriptionPtr imagePtr = *imageH;
	m_lx = imagePtr->width;
	m_ly = imagePtr->height;
	m_depth = imagePtr->depth;
	m_info = new TImageInfo();
	m_info->m_lx = m_lx;
	m_info->m_ly = m_ly;
	Tiio::MovWriterProperties *prop = new Tiio::MovWriterProperties();
	m_info->m_properties = prop;

	DisposeHandle((Handle)imageH);

	m_info->m_frameRate = GetMediaTimeScale(theMedia);
}
Example #11
0
OSErr QTDR_CreateTrackInRAM (Movie theMovie)
{
	Track					myTrack = NULL;
	Media					myMedia = NULL;
	Handle					myDataRef = NULL;
	unsigned long			myAtomHeader[2];
	OSErr					myErr = noErr;

	if (theMovie == NULL)
		return(paramErr);
	
	myDataRef = NewHandleClear(sizeof(Handle) + sizeof(char));
	if (myDataRef == NULL)
		return(MemError());
	
	myAtomHeader[0] = EndianU32_NtoB(sizeof(myAtomHeader));
	myAtomHeader[1] = EndianU32_NtoB(kDataRefExtensionInitializationData);

	myErr = PtrAndHand(myAtomHeader, myDataRef, sizeof(myAtomHeader));
	if (myErr != noErr)
		goto bail;
		
	// create the movie track and media
	myTrack = NewMovieTrack(theMovie, FixRatio(kVideoTrackWidth, 1), FixRatio(kVideoTrackHeight, 1), kNoVolume);
	myErr = GetMoviesError();
	if (myErr != noErr)
		goto bail;
		
	myMedia = NewTrackMedia(myTrack, VideoMediaType, kVideoTimeScale, myDataRef, HandleDataHandlerSubType);
	myErr = GetMoviesError();
	if (myErr != noErr)
		goto bail;

	// create the media samples
	myErr = BeginMediaEdits(myMedia);
	if (myErr != noErr)
		goto bail;

	myErr = QTDR_AddVideoSamplesToMedia(myMedia, kVideoTrackWidth, kVideoTrackHeight);
	if (myErr != noErr)
		goto bail;

	myErr = EndMediaEdits(myMedia);
	if (myErr != noErr)
		goto bail;
	
	// add the media to the track
	myErr = InsertMediaIntoTrack(myTrack, 0, 0, GetMediaDuration(myMedia), fixed1);
	
bail:
	if (myDataRef != NULL)
		DisposeHandle(myDataRef);

	return(myErr);
}
Handle QTDR_MakePointerDataRef (void *thePtr, Size theLength)
{
    PointerDataRef		myDataRef = NULL;
    
    myDataRef = (PointerDataRef)NewHandleClear(sizeof(PointerDataRefRecord));
    if (myDataRef != NULL) {
        (**myDataRef).data = thePtr;
        (**myDataRef).dataLength = theLength;
    }
    
    return((Handle)myDataRef);
}
Example #13
0
void dump_colors(
	struct rgb_color_value *colors, 
	short color_count)
{
	CTabHandle new_table;
	Handle old_bad_clut;
	struct rgb_color_value *color;
	short loop;
	FSSpec file;
	short refnum;
	
	file.vRefNum= -1;
	file.parID= 2;
	strcpy((char *)file.name, (const char *)"\pMarathon2 Clut\0");

	FSpCreateResFile(&file, 'RSED', 'rsrc', smSystemScript);
	refnum= FSpOpenResFile(&file, fsWrPerm);
	if(refnum>=0)
	{
		new_table= (CTabHandle) NewHandleClear(sizeof(ColorTable)+color_count*sizeof(ColorSpec));
		HLock((Handle) new_table);
		(*new_table)->ctSeed= GetCTSeed();
		(*new_table)->ctFlags= 0;
		(*new_table)->ctSize= color_count-1;
		
		/* Slam the colors.. */
		color= colors;
		for(loop=0; loop<=color_count; ++loop)
		{
			(*new_table)->ctTable[loop].rgb.red= color->red;
			(*new_table)->ctTable[loop].rgb.green= color->green;
			(*new_table)->ctTable[loop].rgb.blue= color->blue;
			(*new_table)->ctTable[loop].value= loop;
			color++;
		}
		HUnlock((Handle) new_table);
	
		old_bad_clut= GetResource('clut', 5454);
		if (old_bad_clut)
		{
			RmveResource((Handle) old_bad_clut);
			DisposeHandle((Handle) old_bad_clut);
			UpdateResFile(CurResFile());
		}
		
		AddResource((Handle) new_table, 'clut', 5454, "\pMarathon2 Color Table");
		if(ResError()) dprintf("Err adding it: %d", ResError());
		WriteResource((Handle) new_table);
		ReleaseResource((Handle) new_table);
		
		CloseResFile(refnum);
	}
// ImageCodecPreflight
// 		The base image decompressor gets additional information about the capabilities of your image
// decompressor component by calling ImageCodecPreflight. The base image decompressor uses this
// information when responding to a call to the ImageCodecPredecompress function,
// which the ICM makes before decompressing an image. You are required only to provide values for
// the wantedDestinationPixelSize and wantedDestinationPixelTypes fields and can also modify other
// fields if necessary.
pascal ComponentResult ExampleIPB_DPreflight(ExampleIPBDecompressorGlobals glob, CodecDecompressParams *p)
{
	OSStatus err = noErr;
	CodecCapabilities *capabilities = p->capabilities;
	int widthRoundedUp, heightRoundedUp;
	int frameIndex;

	// Specify the minimum image band height supported by the component
	// bandInc specifies a common factor of supported image band heights - 
	// if your component supports only image bands that are an even
    // multiple of some number of pixels high report this common factor in bandInc
	capabilities->bandMin = (**p->imageDescription).height;
	capabilities->bandInc = capabilities->bandMin;

	// Indicate the pixel depth the component can use with the specified image
	capabilities->wantedPixelSize = 0; // set this to zero when using wantedDestinationPixelTypes
	if( NULL == glob->wantedDestinationPixelTypes ) {
		glob->wantedDestinationPixelTypes = NewHandleClear( 2 * sizeof(OSType) );
		if( NULL == glob->wantedDestinationPixelTypes )
			return memFullErr;
	}
	p->wantedDestinationPixelTypes = (OSType **)glob->wantedDestinationPixelTypes;
	(*p->wantedDestinationPixelTypes)[0] = k422YpCbCr8PixelFormat; // also known as '2vuy'
	(*p->wantedDestinationPixelTypes)[1] = 0;

	// Specify the number of pixels the image must be extended in width and height if
	// the component cannot accommodate the image at its given width and height.
	// This codec must have output buffers that are rounded up to multiples of 16x16.
	glob->width = (**p->imageDescription).width;
	glob->height = (**p->imageDescription).height;
	widthRoundedUp = glob->width;
	heightRoundedUp = glob->height;
	if( 0 != ( widthRoundedUp & 15 ) )
		widthRoundedUp = ( widthRoundedUp + 15 ) & ~15;
	if( 0 != ( heightRoundedUp & 15 ) )
		heightRoundedUp = ( heightRoundedUp + 15 ) & ~15;
	capabilities->extendWidth = widthRoundedUp - glob->width;
	capabilities->extendHeight = heightRoundedUp - glob->height;

	// Allocate our buffers.
	for( frameIndex = 0; frameIndex < kMaxStoredFrames; frameIndex++ ) {
		err = callocInternalPixelBuffer( widthRoundedUp, heightRoundedUp, &glob->storedFrameArray[frameIndex] );
		if( err )
			goto bail;
	}
	callocInternalPixelBuffer( widthRoundedUp, heightRoundedUp, &glob->immediateFrame );
	if( err )
		goto bail;

bail:
	return err;
}
void QTApp_SetupWindowObject (WindowObject theWindowObject)
{
	ApplicationDataHdl		myAppData = NULL;
	
	if (theWindowObject != NULL) {
	
		// allocate an application-specific data record
		myAppData = (ApplicationDataHdl)NewHandleClear(sizeof(ApplicationDataRecord));
		(**theWindowObject).fAppData = (Handle)myAppData;		
		if (myAppData != NULL)
			(**myAppData).fCurrentSize = IDM_NORMAL_SIZE;	
	}
}
Example #16
0
Handle QTDR_MakeHandleDataRef (Handle theHandle)
{
	Handle			myDataRef = NULL;

	myDataRef = NewHandleClear(sizeof(Handle));
	if (myDataRef != NULL)
		BlockMove(&theHandle, *myDataRef, sizeof(Handle));

	// the following single line can replace the preceding three lines
//	PtrToHand(&theHandle, &myDataRef, sizeof(Handle));

	return(myDataRef);
}
Example #17
0
boolean menewmenubar (hdloutlinerecord houtline, hdlmenubarstack *hstack) {
	
	/*
	create a new, empty menubar data structure, linked into menubarlist.

	4.1b2 dmb: xxx - create stack in the (client) application zone
	*/
	
	register hdlmenubarstack hs;
	
	#if 0
	
		THz savezone = GetZone ();
		
		SetZone (ApplicationZone ());
		
		*hstack = (hdlmenubarstack) NewHandleClear (sizeof (tymenubarstack));
		
		SetZone (savezone);
		
		hs = *hstack; /*move into register*/
		
		if (hs == nil) {
		
			memoryerror ();
			
			return (false);
			}
		
	#else
		
		if (!newclearhandle (sizeof (tymenubarstack), (Handle *) hstack))
			return (false);
	
		hs = *hstack; /*move into register*/
		
	#endif
	
	(**hs).menubaroutline = houtline;
	
	(**hs).ixdeletedmenu = -1; /*no halfway deleted menu*/
	
	/*
	if (pushmenubarlist (hs)) /%add it to the end of our list%/
		
		(**hs).flactive = (**menubarlist).flactive;
	*/
	
	return (true);
	} /*menewmenubar*/
Example #18
0
static void MacQTOpenVideoComponent(ComponentInstance *rci)
{	
	OSStatus			err;
	ComponentInstance	ci;
	
	ci = OpenDefaultComponent(StandardCompressionType, StandardCompressionSubType);
	CheckError((ci == nil), 01);
	
	CFDataRef	data;

	data = (CFDataRef) CFPreferencesCopyAppValue(CFSTR("QTVideoSetting"), kCFPreferencesCurrentApplication);
	if (data)
	{
		CFIndex	len;
		Handle	hdl;
		
		len = CFDataGetLength(data);
		hdl = NewHandleClear((Size) len);
		if (MemError() == noErr)
		{	
			HLock(hdl);
			CFDataGetBytes(data, CFRangeMake(0, len), (unsigned char *) *hdl);
			err = SCSetInfo(ci, scSettingsStateType, &hdl);
		
			DisposeHandle(hdl);
		}

		CFRelease(data);
	}
	else
	{
		SCSpatialSettings	ss;
		SCTemporalSettings	ts;
		
		ss.codecType       = kAnimationCodecType;
		ss.codec           = 0;
		ss.depth           = 16;
		ss.spatialQuality  = codecMaxQuality;
		err = SCSetInfo(ci, scSpatialSettingsType, &ss);
		
		ts.frameRate       = FixRatio(Memory.ROMFramesPerSecond, 1);
		ts.keyFrameRate    = Memory.ROMFramesPerSecond;
		ts.temporalQuality = codecMaxQuality;
		err = SCSetInfo(ci, scTemporalSettingsType, &ts);
	}

	*rci = ci;
}
OSErr CompressRLE(Ptr baseAddr, long rowBytes, int depth, int width, int height, Ptr compressBuffer, Size *compressBufferSizePtr)
{
	Handle hdl;
	Ptr    tempPtr;
	int  i;
	Size   widthByteSize = (depth * (long)width + 7) >> 3;
	OSErr  err;

	// Make a temp buffer for the source
	hdl = NewHandleClear(height * widthByteSize);
	err = MemError();
	if (err) goto bail;
	
	HLock(hdl);
	
	tempPtr = *hdl;
	
	// Get rid of row bytes padding
	for (i = 0; i < height; i++) {
		BlockMoveData(baseAddr, tempPtr, widthByteSize);
		
		tempPtr += widthByteSize;
		baseAddr += rowBytes;
	}

	// Compress
	switch (depth) {
	case 1:
		CompressRLE8((UInt8 *)*hdl, height * widthByteSize, compressBuffer, compressBufferSizePtr);
		break;
	case 8:
		CompressRLE8((UInt8 *)*hdl, height * widthByteSize, compressBuffer, compressBufferSizePtr);
		break;
	case 16:
		CompressRLE16((UInt16 *)*hdl, height * (widthByteSize >> 1), compressBuffer, compressBufferSizePtr);
		break;
	case 32:
		CompressRLE32((UInt32 *)*hdl, height * (widthByteSize >> 2), compressBuffer, compressBufferSizePtr);
		break;
	}
	
bail:
	if (hdl)
		DisposeHandle(hdl);

	return err;
}
Example #20
0
pascal short
AdvertiseService(unsigned short serviceType, char *serviceName,
                 unsigned short serviceSocket, unsigned long *adv_handle)
{
    T_AdvertisingStruct *ASp;
    Handle				h;
    SAPpb				pb;
    short				status;
    unsigned int		i;
    char				*tmp;

    *adv_handle = 0L;

    if ((h = NewHandleClear(sizeof(T_AdvertisingStruct))) == (Handle)0) {
        return (SAP_NO_MEM);
    }
    MoveHHi(h);
    HLock(h);

    ASp = (T_AdvertisingStruct *)*h;
    ASp->signature = ADVERTISING_SIGNATURE;
    ASp->ASServerIDpacket.SAPPacketType = IntSwap( PERIODIC_ID_PACKET );
    ASp->ASServerIDpacket.serverType = IntSwap( serviceType );
    /*
     * Make sure the serviceName isn't longer than 47 characters.
     */
    for(i=0, tmp=serviceName; i<sizeof(ASp->ASServerIDpacket.serverName); i++, tmp++) {
        if (*tmp == 0) {
            break;
        }
    }
    if (i >= sizeof(ASp->ASServerIDpacket.serverName)) {
        serviceName[sizeof(ASp->ASServerIDpacket.serverName)-1] = 0;
    }
    strncpy((char *)ASp->ASServerIDpacket.serverName, serviceName, sizeof(ASp->ASServerIDpacket.serverName));
    ASp->ASServerIDpacket.serverSocket = serviceSocket;
    ASp->ASServerIDpacket.interveningNetworks = IntSwap( 1 );
    pb.csCode = ADVERTISESERVICE;
    pb.csParams.adv_service.h = h;
    status = call_sap(&pb);
    if (status) {
        DisposeHandle(h);
        return (status);
    }
    *adv_handle = (unsigned long)h;
    return (SAP_SUCCESSFUL);
}
Example #21
0
Handle QTDR_MakeURLDataRef (char *theURL)
{
	Handle			myDataRef = NULL;
	Size			mySize = 0;

	// get the size of the URL, plus the terminating null byte
	mySize = (Size)strlen(theURL) + 1;
	if (mySize == 1)
		goto bail;
	
	// allocate a new handle and copy the URL into the handle
	myDataRef = NewHandleClear(mySize);
    if (myDataRef != NULL)
		BlockMove(theURL, *myDataRef, mySize);

bail:
	return(myDataRef);
}
RTPMPComponentVideo_Open(
	RTPMPComponentVideoInstanceData **	inGlobals,
	ComponentInstance					self )
{
	ComponentResult		theResult = noErr;
	RTPMediaPacketizer	theBase;
	
	
	inGlobals =
		REINTERPRET_CAST( RTPMPComponentVideoInstanceData ** )(
			NewHandleClear( sizeof( **inGlobals ) ) );
	
	if( inGlobals )
	{
		( **inGlobals ).itself = self;
		( **inGlobals ).itsFinalDerivation = self;
		( **inGlobals ).itsInitialized = false;
		
		SetComponentInstanceStorage( self, REINTERPRET_CAST( Handle )( inGlobals ) );
		
		theResult =
			OpenADefaultComponent(
				kRTPMediaPacketizerType, kRTPBaseMediaPacketizerType, &theBase );
		
		if( theResult == noErr )
		{
			( **inGlobals ).itsBase = theBase;
			theResult = CallComponentTarget( ( **inGlobals ).itsBase, self );
		}
	}
	
	else
	{
		theResult = MemError();
		
		if( theResult == noErr )
			theResult = memFullErr;
	}
	
	return( theResult );
}
Example #23
0
void wxMacClassicPrintData::ValidateOrCreate()
{
    if ( m_macPrintSettings == NULL )
    {
        m_macPrintSettings = (THPrint) NewHandleClear( sizeof( TPrint ) );
        (**m_macPrintSettings).iPrVersion = 0;                    // something invalid

        (**m_macPrintSettings).prInfo.iHRes = 72;
        (**m_macPrintSettings).prInfo.iVRes = 72;
        Rect r1 = { 0, 0, 8*72 - 2 * 18, 11*72 - 2 * 36 };
        (**m_macPrintSettings).prInfo.rPage = r1;// must have its top left & (0,0)

        Rect r2 = { -18, -36, 8*72 - 18, 11*72 - 36  };
        (**m_macPrintSettings).rPaper = r2;
        (**m_macPrintSettings).prStl.iPageV = 11 * 120 ;                // 11 inches in 120th of an inch
        (**m_macPrintSettings).prStl.iPageH = 8 * 120 ;                // 8 inches in 120th of an inch
    }
    else
    {
    }
}
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;
}
Example #25
0
void	AUControlGroup::AddAUInfo (		AUCarbonViewBase *			auView,
										const Point &				inLocation,
										const SInt16 				inRightOffset,
										const SInt16				inTotalWidth)
{
#if !__LP64__
   // get component info
	ComponentDescription desc;
    Handle h1 = NewHandleClear(4);
	OSStatus err = GetComponentInfo ((Component)auView->GetEditAudioUnit(), &desc, h1, 0, 0);

    if (err == noErr) {
        // Get the manufacturer's name... look for the ':' character convention
        HLock(h1);
        char* ptr1 = *h1;
        int len = *ptr1++;
        char* displayStr = 0;

        for (int i = 0; i < len; ++i) {
            if (ptr1[i] == ':') { // found the name
                ptr1[i++] = 0;
                displayStr = ptr1;
                break;
            }
        }

        // localize as necessary:
        if (!sLocalized) {
            CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(kLocalizedStringBundle_AUView);
            if (mainBundle) {
                kStringManufacturer = CFCopyLocalizedStringFromTableInBundle(
                                            kAUViewLocalizedStringKey_Manufacturer, kLocalizedStringTable_AUView,
                                            mainBundle, CFSTR("Manufacturer title string"));
                sLocalized = true;
            }
        }

        // display strings
        ControlRef newControl;
        Rect r;
        r.top = SInt16(inLocation.v);		r.bottom = SInt16(inLocation.v) + 16;
        ControlFontStyleRec fontStyle;
        fontStyle.flags = kControlUseFontMask | kControlUseJustMask;
        fontStyle.font = kControlFontSmallBoldSystemFont;

        // display manufacturer string
        if (displayStr) {
            CFMutableStringRef mfrstring = CFStringCreateMutable(NULL, 0);
            CFStringAppend(mfrstring, kStringManufacturer);		// "Manufacturer"
            CFStringAppend(mfrstring, kAUViewUnlocalizedString_TitleSeparator);
                                                                // "Manufacturer: "
            CFStringRef mfrname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
            if (mfrname) {
                CFStringAppend(mfrstring, mfrname);	// "Manufacturer: MFRName"
                CFRelease (mfrname);
            }

            r.left = inLocation.h + inRightOffset;
			r.right = inLocation.h + inTotalWidth - 28;
			fontStyle.just = teFlushRight;

            verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, mfrstring, &fontStyle, &newControl));
            verify_noerr(auView->EmbedControl(newControl));
            CFRelease (mfrstring);

            //move displayStr ptr past the manu, to the name
            // we move the characters down an index, because the handle doesn't have any room
            // at the end for the \0
			int i = strlen(displayStr), j = 0;
			while (displayStr[++i] == ' ' && i < len)
				;
			while (i < len)
				displayStr[j++] = displayStr[i++];
			displayStr[j] = 0;
        } else {
			displayStr = ptr1;
			int i = 0, j = 0;
			do {
				displayStr[j] = displayStr[i];
				++j; ++i;
			} while (i < len);

			displayStr[j] = 0;
        }

        // display AudioUnit string
        r.left = inLocation.h;	r.right = r.left + inRightOffset;
        fontStyle.just = 0;

        CFMutableStringRef cfstr = CFStringCreateMutable(NULL, 0);
        CFStringAppend(cfstr, kAUViewLocalizedStringKey_AudioUnit);		// "Audio Unit"
        CFStringAppend(cfstr, kAUViewUnlocalizedString_TitleSeparator);
                                                        // "Audio Unit: "

		CFStringRef auname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
		CFStringAppend(cfstr, auname);				// "Audio Unit: AUName"
		CFRelease (auname);

        verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, cfstr, &fontStyle, &newControl));

		// size text control correctly
		Boolean bValue = false;
		SetControlData(newControl, kControlEntireControl, 'stim' /* kControlStaticTextIsMultilineTag */, sizeof(Boolean), &bValue);
		SInt16 baseLineOffset;
		Rect bestRect;
		err = GetBestControlRect(newControl, &bestRect, &baseLineOffset);
		if (err == noErr)
		{
			int width = (bestRect.right - bestRect.left) + 1;
			int height = (bestRect.bottom - bestRect.top) + 1;
			SizeControl (newControl, width, height);
		}

        verify_noerr(auView->EmbedControl(newControl));
        CFRelease (cfstr);
    }

	DisposeHandle (h1);
#endif
}
OSErr makeMovieFromVideoFramesFile(char *inDestMovieFile)
{
    Handle					dataRef = NULL;
    OSType					dataRefType;
    ImageDescriptionHandle	videoDescH = NULL;
	OSErr					err;

#if TARGET_OS_WIN32
	err = InitializeQTML(0);
	if ((err = GetMoviesError()) != noErr) goto bail;
#endif
	err = EnterMovies();
	if ((err = GetMoviesError()) != noErr) goto bail;

	// create a data reference from the full path to the video frames file
	makeDataRefFromFullPath(inDestMovieFile, &dataRef, &dataRefType);
	if (dataRef == NULL) goto bail;

    Movie m = NewMovie(0);
	if ((err = GetMoviesError()) != noErr) goto bail;

	// create the video track for the movie
    Track videoT = NewMovieTrack( m, Long2Fix(kFrameWidth), Long2Fix(kFrameHeight), kNoVolume);
	if ((err = GetMoviesError()) != noErr) goto bail;
	
	// create the video track media
    Media videoM = NewTrackMedia( videoT, VideoMediaType, kMediaTimeScale, dataRef, dataRefType);
	if ((err = GetMoviesError()) != noErr) goto bail;
	
	videoDescH = (ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription));
	if (videoDescH == NULL) goto bail;
	
	// create the ImageDescription that will describe our video track media samples
    videoDescH[0]->idSize = sizeof(ImageDescription);
    videoDescH[0]->cType = kCodecType; // the codec type for your data 
    videoDescH[0]->temporalQuality = codecNormalQuality;
    videoDescH[0]->spatialQuality = codecNormalQuality;
    videoDescH[0]->width = kFrameWidth;
    videoDescH[0]->height = kFrameHeight;
    videoDescH[0]->hRes = 72L << 16;
    videoDescH[0]->vRes = 72L << 16;
    videoDescH[0]->depth = 32;
    videoDescH[0]->clutID = -1;

    SampleReference64Record videoRef;
    videoRef.dataOffset.hi = 0; videoRef.dataOffset.lo = 0;
    videoRef.dataSize = (kFrameWidth*kFrameHeight*4) * kNumberOfSamples; 
    videoRef.durationPerSample = kDurationPerSample;
    videoRef.numberOfSamples = kNumberOfSamples;
    videoRef.sampleFlags = 0;

	// now add all of our media samples to the movie data file.
    err = AddMediaSampleReferences64(videoM, (SampleDescriptionHandle)videoDescH,
                            1, &videoRef, 0);
	if (err != noErr) goto bail;

    TimeValue mediaDuration = kNumberOfSamples * kDurationPerSample;
	// inserts a reference to our media samples into the track.
    err = InsertMediaIntoTrack(videoT, 0, 0, mediaDuration, 
				fixed1);	// media's rate (1.0 = media's natural playback rate).
	if (err != noErr) goto bail;

    DataHandler outDataHandler;
	// opens a data handler for our movie storage (the video frames file)
    err = OpenMovieStorage (dataRef, dataRefType, kDataHCanWrite, &outDataHandler );
	if (err != noErr) goto bail;
	
	// add a movie to our movie storage container
    err = AddMovieToStorage (m, outDataHandler );
	if (err != noErr) goto bail;

    err = CloseMovieStorage (outDataHandler);
	outDataHandler = NULL;
	
bail:
	if (videoDescH)
	{
		DisposeHandle((Handle)videoDescH);
	}
	
	return err;
}
Example #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;
}
Example #28
0
/*****************************************************************************
 * OpenVideo:
 *****************************************************************************/
static int OpenVideo( decoder_t *p_dec )
{
#ifndef WIN32
    decoder_sys_t *p_sys = malloc( sizeof( decoder_sys_t ) );
    if( !p_sys )
        return VLC_ENOMEM;

    long                                i_result;
    ComponentDescription                desc;
    Component                           prev;
    ComponentResult                     cres;
    ImageSubCodecDecompressCapabilities icap;   /* for ImageCodecInitialize() */
    CodecInfo                           cinfo;  /* for ImageCodecGetCodecInfo() */
    ImageDescription                    *id;

    char                fcc[4];
    int     i_vide = p_dec->fmt_in.i_extra;
    uint8_t *p_vide = p_dec->fmt_in.p_extra;

    p_dec->p_sys = p_sys;
    p_dec->pf_decode_video = DecodeVideo;
    p_sys->i_late = 0;

    if( i_vide <= 0 )
    {
        msg_Err( p_dec, "missing extra info" );
        free( p_sys );
        return VLC_EGENERIC;
    }

    if( p_dec->fmt_in.i_original_fourcc )
        memcpy( fcc, &p_dec->fmt_in.i_original_fourcc, 4 );
    else
        memcpy( fcc, &p_dec->fmt_in.i_codec, 4 );

    msg_Dbg( p_dec, "quicktime_video %4.4s %dx%d",
             fcc, p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height );

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

#ifdef __APPLE__
    EnterMovies();
#endif

    if( QTVideoInit( p_dec ) )
    {
        msg_Err( p_dec, "cannot initialize QT");
        goto exit_error;
    }

#ifndef __APPLE__
    if( ( i_result = p_sys->InitializeQTML( 6 + 16 ) ) )
    {
        msg_Dbg( p_dec, "error on InitializeQTML = %d", (int)i_result );
        goto exit_error;
    }
#endif

    /* init ComponentDescription */
    memset( &desc, 0, sizeof( ComponentDescription ) );
    desc.componentType      = FCC( 'i', 'm', 'd', 'c' );
    desc.componentSubType   = FCC( fcc[0], fcc[1], fcc[2], fcc[3] );
    desc.componentManufacturer = 0;
    desc.componentFlags        = 0;
    desc.componentFlagsMask    = 0;

    if( !( prev = p_sys->FindNextComponent( NULL, &desc ) ) )
    {
        msg_Err( p_dec, "cannot find requested component" );
        goto exit_error;
    }
    msg_Dbg( p_dec, "component id=0x%p", prev );

    p_sys->ci =  p_sys->OpenComponent( prev );
    msg_Dbg( p_dec, "component instance p=0x%p", p_sys->ci );

    memset( &icap, 0, sizeof( ImageSubCodecDecompressCapabilities ) );
    cres =  p_sys->ImageCodecInitialize( p_sys->ci, &icap );
    msg_Dbg( p_dec, "ImageCodecInitialize->0x%X size=%d (%d)",
             (int)cres, (int)icap.recordSize, (int)icap.decompressRecordSize);

    memset( &cinfo, 0, sizeof( CodecInfo ) );
    cres =  p_sys->ImageCodecGetCodecInfo( p_sys->ci, &cinfo );
    msg_Dbg( p_dec,
             "Flags: compr: 0x%x decomp: 0x%x format: 0x%x",
             (unsigned int)cinfo.compressFlags,
             (unsigned int)cinfo.decompressFlags,
             (unsigned int)cinfo.formatFlags );
    msg_Dbg( p_dec, "quicktime_video: Codec name: %.*s",
             ((unsigned char*)&cinfo.typeName)[0],
             ((unsigned char*)&cinfo.typeName)+1 );

    /* make a yuy2 gworld */
    p_sys->OutBufferRect.top    = 0;
    p_sys->OutBufferRect.left   = 0;
    p_sys->OutBufferRect.right  = p_dec->fmt_in.video.i_width;
    p_sys->OutBufferRect.bottom = p_dec->fmt_in.video.i_height;


    /* codec data FIXME use codec not SVQ3 */
    msg_Dbg( p_dec, "vide = %d", i_vide  );
    id = malloc( sizeof( ImageDescription ) + ( i_vide - 70 ) );
    if( !id )
        goto exit_error;
    id->idSize          = sizeof( ImageDescription ) + ( i_vide - 70 );
    id->cType           = FCC( fcc[0], fcc[1], fcc[2], fcc[3] );
    id->version         = GetWBE ( p_vide +  0 );
    id->revisionLevel   = GetWBE ( p_vide +  2 );
    id->vendor          = GetDWBE( p_vide +  4 );
    id->temporalQuality = GetDWBE( p_vide +  8 );
    id->spatialQuality  = GetDWBE( p_vide + 12 );
    id->width           = GetWBE ( p_vide + 16 );
    id->height          = GetWBE ( p_vide + 18 );
    id->hRes            = GetDWBE( p_vide + 20 );
    id->vRes            = GetDWBE( p_vide + 24 );
    id->dataSize        = GetDWBE( p_vide + 28 );
    id->frameCount      = GetWBE ( p_vide + 32 );
    memcpy( &id->name, p_vide + 34, 32 );
    id->depth           = GetWBE ( p_vide + 66 );
    id->clutID          = GetWBE ( p_vide + 68 );
    if( i_vide > 70 )
    {
        memcpy( ((char*)&id->clutID) + 2, p_vide + 70, i_vide - 70 );
    }

    msg_Dbg( p_dec, "idSize=%d ver=%d rev=%d vendor=%d tempQ=%d "
             "spaQ=%d w=%d h=%d dpi=%d%d dataSize=%d depth=%d frameCount=%d clutID=%d",
             (int)id->idSize, id->version, id->revisionLevel, (int)id->vendor,
             (int)id->temporalQuality, (int)id->spatialQuality,
             (int)id->width, (int)id->height,
             (int)id->hRes, (int)id->vRes,
             (int)id->dataSize,
             id->depth,
             id->frameCount,
             id->clutID );

    p_sys->framedescHandle = (ImageDescriptionHandle) NewHandleClear( id->idSize );
    memcpy( *p_sys->framedescHandle, id, id->idSize );

    if( p_dec->fmt_in.video.i_width != 0 && p_dec->fmt_in.video.i_height != 0) 
        p_sys->plane = malloc( p_dec->fmt_in.video.i_width * p_dec->fmt_in.video.i_height * 3 );
    if( !p_sys->plane )
        goto exit_error;

    i_result = p_sys->QTNewGWorldFromPtr( &p_sys->OutBufferGWorld,
                                          /*pixel format of new GWorld==YUY2 */
                                          kYUVSPixelFormat,
                                          /* we should benchmark if yvu9 is
                                           * faster for svq3, too */
                                          &p_sys->OutBufferRect,
                                          0, 0, 0,
                                          p_sys->plane,
                                          p_dec->fmt_in.video.i_width * 2 );

    msg_Dbg( p_dec, "NewGWorldFromPtr returned:%ld",
             65536 - ( i_result&0xffff ) );

    memset( &p_sys->decpar, 0, sizeof( CodecDecompressParams ) );
    p_sys->decpar.imageDescription = p_sys->framedescHandle;
    p_sys->decpar.startLine        = 0;
    p_sys->decpar.stopLine         = ( **p_sys->framedescHandle ).height;
    p_sys->decpar.frameNumber      = 1;
    p_sys->decpar.matrixFlags      = 0;
    p_sys->decpar.matrixType       = 0;
    p_sys->decpar.matrix           = 0;
    p_sys->decpar.capabilities     = &p_sys->codeccap;
    p_sys->decpar.accuracy         = codecNormalQuality;
    p_sys->decpar.srcRect          = p_sys->OutBufferRect;
    p_sys->decpar.transferMode     = srcCopy;
    p_sys->decpar.dstPixMap        = **p_sys->GetGWorldPixMap( p_sys->OutBufferGWorld );/*destPixmap;  */

    cres =  p_sys->ImageCodecPreDecompress( p_sys->ci, &p_sys->decpar );
    msg_Dbg( p_dec, "quicktime_video: ImageCodecPreDecompress cres=0x%X",
             (int)cres );

    es_format_Init( &p_dec->fmt_out, VIDEO_ES, VLC_CODEC_YUYV);
    p_dec->fmt_out.video.i_width = p_dec->fmt_in.video.i_width;
    p_dec->fmt_out.video.i_height= p_dec->fmt_in.video.i_height;
    p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR * p_dec->fmt_in.video.i_width / p_dec->fmt_in.video.i_height;

    vlc_mutex_unlock( &qt_mutex );
    return VLC_SUCCESS;

exit_error:
#ifdef LOADER
    Restore_LDT_Keeper( p_sys->ldt_fs );
#endif
    vlc_mutex_unlock( &qt_mutex );

#else
    VLC_UNUSED( p_dec );
#endif /* !WIN32 */

    return VLC_EGENERIC;
}
Example #29
0
bool wxSound::DoPlay(unsigned flags) const
{
    Stop();

    Movie movie;

    switch(m_type)
    {
    case wxSound_MEMORY:
        {
            if (!wxInitQT())
                return false;
            Handle myHandle, dataRef = nil;
            MovieImportComponent miComponent;
            Track targetTrack = nil;
            TimeValue addedDuration = 0;
            long outFlags = 0;
            OSErr err;
            ComponentResult result;

            myHandle = NewHandleClear((Size)m_waveLength);

            BlockMove(m_hSnd, *myHandle, m_waveLength);

            err = PtrToHand(&myHandle, &dataRef, sizeof(Handle));

            if (memcmp(&m_hSnd[8], "WAVE", 4) == 0)
                miComponent = OpenDefaultComponent(MovieImportType, kQTFileTypeWave);
            else if (memcmp(&m_hSnd[8], "AIFF", 4) == 0)
                miComponent = OpenDefaultComponent(MovieImportType, kQTFileTypeAIFF);
            else if (memcmp(&m_hSnd[8], "AIFC", 4) == 0)
                miComponent = OpenDefaultComponent(MovieImportType, kQTFileTypeAIFC);
            else
            {
                wxLogSysError(wxT("wxSound - Location in memory does not contain valid data"));
                return false;
            }

            movie = NewMovie(0);

            result = MovieImportDataRef(miComponent,                dataRef,
                                        HandleDataHandlerSubType,   movie,
                                        nil,                        &targetTrack,
                                        nil,                        &addedDuration,
                                        movieImportCreateTrack,     &outFlags);

            if (result != noErr)
            {
                wxLogSysError(wxString::Format(wxT("Couldn't import movie data\nError:%i"), (int)result));
            }

            SetMovieVolume(movie, kFullVolume);
            GoToBeginningOfMovie(movie);

            DisposeHandle(myHandle);
        }
        break;
    case wxSound_RESOURCE:
        {
            SoundComponentData data;
            unsigned long numframes, offset;

            ParseSndHeader((SndListHandle)m_hSnd, &data, &numframes, &offset);
            //m_waveLength = numFrames * data.numChannels;

            SndChannelPtr pSndChannel;
            SndNewChannel(&pSndChannel, sampledSynth,
                initNoInterp
                + (data.numChannels == 1 ? initMono : initStereo), NULL);

            if(SndPlay(pSndChannel, (SndListHandle) m_hSnd, flags & wxSOUND_ASYNC ? 1 : 0) != noErr)
                return false;

            if (flags & wxSOUND_ASYNC)
            {
                lastSoundTimer = ((wxSMTimer*&)m_pTimer)
                    = new wxSMTimer(pSndChannel, m_hSnd, flags & wxSOUND_LOOP ? 1 : 0,
                                    &lastSoundIsPlaying);
                lastSoundIsPlaying = true;

                ((wxTimer*)m_pTimer)->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS);
            }
            else
                SndDisposeChannel(pSndChannel, TRUE);

            return true;
        }
        break;
    case wxSound_FILE:
        {
            if (!wxInitQT())
                return false;

            OSErr err = noErr ;

            Handle dataRef = NULL;
            OSType dataRefType;

            err = QTNewDataReferenceFromFullPathCFString(wxMacCFStringHolder(m_sndname,wxLocale::GetSystemEncoding()),
                (UInt32)kQTNativeDefaultPathStyle, 0, &dataRef, &dataRefType);

            wxASSERT(err == noErr);

            if (NULL != dataRef || err != noErr)
            {
                err = NewMovieFromDataRef( &movie, newMovieDontAskUnresolvedDataRefs , NULL, dataRef, dataRefType );
                wxASSERT(err == noErr);
                DisposeHandle(dataRef);
            }

            if (err != noErr)
            {
                wxLogSysError(
                    wxString::Format(wxT("wxSound - Could not open file: %s\nError:%i"), m_sndname.c_str(), err )
                    );
                return false;
            }
        }
        break;
    default:
        return false;
    }//end switch(m_type)

    //Start the movie!
    StartMovie(movie);

    if (flags & wxSOUND_ASYNC)
    {
        //Start timer and play movie asyncronously
        lastSoundTimer = ((wxQTTimer*&)m_pTimer) =
            new wxQTTimer(movie, flags & wxSOUND_LOOP ? 1 : 0,
                          &lastSoundIsPlaying);
        lastSoundIsPlaying = true;
        ((wxQTTimer*)m_pTimer)->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS);
    }
    else
    {
        wxASSERT_MSG(!(flags & wxSOUND_LOOP), wxT("Can't loop and play syncronously at the same time"));

        //Play movie until it ends, then exit
        //Note that due to quicktime caching this may not always
        //work 100% correctly
        while (!IsMovieDone(movie))
            MoviesTask(movie, 1);

        DisposeMovie(movie);
    }

    return true;
}
Example #30
0
// init driver
static int init(sh_video_t *sh){
#ifndef CONFIG_QUICKTIME
    long result = 1;
#endif
    ComponentResult cres;
    ComponentDescription desc;
    Component prev=NULL;
    CodecInfo cinfo;	// for ImageCodecGetCodecInfo()
    ImageSubCodecDecompressCapabilities icap; // for ImageCodecInitialize()

    codec_initialized = 0;
#ifdef CONFIG_QUICKTIME
    EnterMovies();
#else

#ifdef WIN32_LOADER
    Setup_LDT_Keeper();
#endif

    //preload quicktime.qts to avoid the problems caused by the hardcoded path inside the dll
    qtime_qts = LoadLibraryA("QuickTime.qts");
    if(!qtime_qts){
    mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load QuickTime.qts\n" );
    return 0;
    }

    handler = LoadLibraryA("qtmlClient.dll");
    if(!handler){
    mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load qtmlClient.dll\n");
    return 0;
    }

    InitializeQTML = (OSErr (*)(long))GetProcAddress(handler, "InitializeQTML");
    EnterMovies = (OSErr (*)(void))GetProcAddress(handler, "EnterMovies");
    FindNextComponent = (Component (*)(Component,ComponentDescription*))GetProcAddress(handler, "FindNextComponent");
    CountComponents = (long (*)(ComponentDescription*))GetProcAddress(handler, "CountComponents");
    GetComponentInfo = (OSErr (*)(Component,ComponentDescription*,Handle,Handle,Handle))GetProcAddress(handler, "GetComponentInfo");
    OpenComponent = (ComponentInstance (*)(Component))GetProcAddress(handler, "OpenComponent");
    ImageCodecInitialize = (ComponentResult (*)(ComponentInstance,ImageSubCodecDecompressCapabilities *))GetProcAddress(handler, "ImageCodecInitialize");
    ImageCodecGetCodecInfo = (ComponentResult (*)(ComponentInstance,CodecInfo *))GetProcAddress(handler, "ImageCodecGetCodecInfo");
    ImageCodecBeginBand = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *,ImageSubCodecDecompressRecord *,long))GetProcAddress(handler, "ImageCodecBeginBand");
    ImageCodecPreDecompress = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *))GetProcAddress(handler, "ImageCodecPreDecompress");
    ImageCodecBandDecompress = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *))GetProcAddress(handler, "ImageCodecBandDecompress");
    GetGWorldPixMap = (PixMapHandle (*)(GWorldPtr))GetProcAddress(handler, "GetGWorldPixMap");
    QTNewGWorldFromPtr = (OSErr(*)(GWorldPtr *,OSType,const Rect *,CTabHandle,void*,GWorldFlags,void *,long))GetProcAddress(handler, "QTNewGWorldFromPtr");
    NewHandleClear = (OSErr(*)(Size))GetProcAddress(handler, "NewHandleClear");
    //     = GetProcAddress(handler, "");

    if(!InitializeQTML || !EnterMovies || !FindNextComponent || !ImageCodecBandDecompress){
	mp_msg(MSGT_DECVIDEO,MSGL_ERR,"invalid qtmlClient.dll!\n");
	return 0;
    }

    result=InitializeQTML(6+16);
//    result=InitializeQTML(0);
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"InitializeQTML returned %li\n",result);
//    result=EnterMovies();
//    printf("EnterMovies->%d\n",result);
#endif /* CONFIG_QUICKTIME */

#if 0
    memset(&desc,0,sizeof(desc));
    while((prev=FindNextComponent(prev,&desc))){
	ComponentDescription desc2;
	unsigned char* c1=&desc2.componentType;
	unsigned char* c2=&desc2.componentSubType;
	memset(&desc2,0,sizeof(desc2));
//	printf("juhee %p (%p)\n",prev,&desc);
	GetComponentInfo(prev,&desc2,NULL,NULL,NULL);
	mp_msg(MSGT_DECVIDEO,MSGL_DGB2,"DESC: %c%c%c%c/%c%c%c%c [0x%X/0x%X] 0x%X\n",
	    c1[3],c1[2],c1[1],c1[0],
	    c2[3],c2[2],c2[1],c2[0],
	    desc2.componentType,desc2.componentSubType,
	    desc2.componentFlags);
    }
#endif


    memset(&desc,0,sizeof(desc));
    desc.componentType= (((unsigned char)'i')<<24)|
			(((unsigned char)'m')<<16)|
			(((unsigned char)'d')<<8)|
			(((unsigned char)'c'));
#if 0
    desc.componentSubType=
		    (((unsigned char)'S'<<24))|
			(((unsigned char)'V')<<16)|
			(((unsigned char)'Q')<<8)|
			(((unsigned char)'3'));
#else
    desc.componentSubType = bswap_32(sh->format);
#endif
    desc.componentManufacturer=0;
    desc.componentFlags=0;
    desc.componentFlagsMask=0;

    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Count = %ld\n",CountComponents(&desc));
    prev=FindNextComponent(NULL,&desc);
    if(!prev){
	mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Cannot find requested component\n");
	return 0;
    }
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Found it! ID = %p\n",prev);

    ci=OpenComponent(prev);
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ci=%p\n",ci);

    memset(&icap,0,sizeof(icap));
    cres=ImageCodecInitialize(ci,&icap);
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageCodecInitialize->%#x  size=%d (%d)\n",cres,icap.recordSize,icap.decompressRecordSize);

    memset(&cinfo,0,sizeof(cinfo));
    cres=ImageCodecGetCodecInfo(ci,&cinfo);
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Flags: compr: 0x%X  decomp: 0x%X format: 0x%X\n",
	cinfo.compressFlags, cinfo.decompressFlags, cinfo.formatFlags);
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Codec name: %.*s\n",((unsigned char*)&cinfo.typeName)[0],
	((unsigned char*)&cinfo.typeName)+1);

    //make a yuy2 gworld
    OutBufferRect.top=0;
    OutBufferRect.left=0;
    OutBufferRect.right=sh->disp_w;
    OutBufferRect.bottom=sh->disp_h;

    //Fill the imagedescription for our SVQ3 frame
    //we can probably get this from Demuxer
#if 0
    framedescHandle=(ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription)+200);
    printf("framedescHandle=%p  *p=%p\n",framedescHandle,*framedescHandle);
{ FILE* f=fopen("/root/.wine/fake_windows/IDesc","r");
  if(!f) printf("filenot found: IDesc\n");
  fread(*framedescHandle,sizeof(ImageDescription)+200,1,f);
  fclose(f);
}
#else
    if(!sh->ImageDesc) sh->ImageDesc=(sh->bih+1); // hack for SVQ3-in-AVI
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageDescription size: %d\n",((ImageDescription*)(sh->ImageDesc))->idSize);
    framedescHandle=(ImageDescriptionHandle)NewHandleClear(((ImageDescription*)(sh->ImageDesc))->idSize);
    memcpy(*framedescHandle,sh->ImageDesc,((ImageDescription*)(sh->ImageDesc))->idSize);
    dump_ImageDescription(*framedescHandle);
#endif
//Find codecscomponent for video decompression
//    result = FindCodec ('SVQ1',anyCodec,&compressor,&decompressor );
//    printf("FindCodec SVQ1 returned:%i compressor: 0x%X decompressor: 0x%X\n",result,compressor,decompressor);

    sh->context = (void *)kYUVSPixelFormat;
#if 1
    {
	int imgfmt = sh->codec->outfmt[sh->outfmtidx];
	int qt_imgfmt;
    switch(imgfmt)
    {
	case IMGFMT_YUY2:
	    qt_imgfmt = kYUVSPixelFormat;
	    break;
	case IMGFMT_YVU9:
	    qt_imgfmt = 0x73797639; //kYVU9PixelFormat;
	    break;
	case IMGFMT_YV12:
	    qt_imgfmt = 0x79343230;
	    break;
	case IMGFMT_UYVY:
	    qt_imgfmt = kUYVY422PixelFormat;
	    break;
	case IMGFMT_YVYU:
	    qt_imgfmt = kYVYU422PixelFormat;
	    imgfmt = IMGFMT_YUY2;
	    break;
	case IMGFMT_RGB16:
	    qt_imgfmt = k16LE555PixelFormat;
	    break;
	case IMGFMT_BGR24:
	    qt_imgfmt = k24BGRPixelFormat;
	    break;
	case IMGFMT_BGR32:
	    qt_imgfmt = k32BGRAPixelFormat;
	    break;
	case IMGFMT_RGB32:
	    qt_imgfmt = k32RGBAPixelFormat;
	    break;
	default:
	    mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Unknown requested csp\n");
	    return 0;
    }
    mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"imgfmt: %s qt_imgfmt: %.4s\n", vo_format_name(imgfmt), (char *)&qt_imgfmt);
    sh->context = (void *)qt_imgfmt;
    if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,imgfmt)) return 0;
    }
#else
    if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,IMGFMT_YUY2)) return 0;
#endif

    return 1;
}