Пример #1
0
// left here for compatability
ImageHandle EncodeTheRect(PixMapHandle thePixMap,Rect *theRect,short clearCol,short shadowCol)
{
	EncodeRec		theEncode=emptyEncodeRec;
	BCRec			theRec;
	
	LockPixels(thePixMap);
	theEncode.theRec=&theRec;

	theRec.world=0L;
	theRec.pixMap=thePixMap;
	theRec.baseAddr=(unsigned char *)GetPixBaseAddr(thePixMap);
	theRec.rowBytes=(**thePixMap).rowBytes&0x3FFF;

	theEncode.theImage=0L;
	theEncode.theRect=theRect;
	theEncode.clearCol=clearCol;
	theEncode.shadowCol=shadowCol;
	theEncode.shrinkHandle=true;
	theEncode.shrinkRect=true;

	EckerEncodeTheRect(&theEncode);
	
	UnlockPixels(thePixMap);
	
	return theEncode.theImage;
}
Пример #2
0
void createOffscreen(int pictItem)
{
	PicHandle	pict;
	Rect		rect;
	CGrafPtr	currentPort;
	GDHandle	currentDevice;
	
	if (gGWorld != nil)
		DisposeGWorld( gGWorld );
	
	pict = (PicHandle)GetResource( 'PICT', pictItem + 127 );
	
	rect = (**pict).picFrame;
	
	GetGWorld( &currentPort, &currentDevice );
	NewGWorld( &gGWorld, 32, &rect, nil, nil, 0 );
		
	LockPixels( GetPortPixMap(gGWorld));
	SetGWorld( gGWorld, nil );

	DrawPicture( pict, &rect );
	
	SetGWorld( currentPort, currentDevice );
	
	ReleaseResource( (Handle)pict );
}
Пример #3
0
void wxMemoryDC::SelectObject( const wxBitmap& bitmap )
{
    if ( m_selected.Ok() )
    {
        UnlockPixels( GetGWorldPixMap(MAC_WXHBITMAP(m_selected.GetHBITMAP())) );
    }
    m_selected = bitmap;
    if (m_selected.Ok())
    {
        if ( m_selected.GetHBITMAP() )
        {
            m_macPort = (GrafPtr) m_selected.GetHBITMAP() ;
            LockPixels( GetGWorldPixMap(  (CGrafPtr)  m_macPort ) ) ;
            wxMask * mask = bitmap.GetMask() ;
            if ( mask )
            {
                m_macMask = mask->GetMaskBitmap() ;
            }
            SetRectRgn( (RgnHandle) m_macBoundaryClipRgn , 0 , 0 , m_selected.GetWidth() , m_selected.GetHeight() ) ;
            CopyRgn( (RgnHandle) m_macBoundaryClipRgn ,(RgnHandle)  m_macCurrentClipRgn ) ;
            m_ok = TRUE ;
        }
        else
        {
            m_ok = FALSE;
        }
    }
    else
    {
        m_ok = FALSE;
    }
}
void ofVideoPlayer::createImgMemAndGWorld(){
	Rect movieRect;
	movieRect.top 			= 0;
	movieRect.left 			= 0;
	movieRect.bottom 		= height;
	movieRect.right 		= width;
	offscreenGWorldPixels 	= new unsigned char[4 * width * height + 32];
	pixels					= new unsigned char[width*height*3];

	#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
		QTNewGWorldFromPtr (&(offscreenGWorld), k32ARGBPixelFormat, &(movieRect), NULL, NULL, 0, (offscreenGWorldPixels), 4 * width);		
	#else
		QTNewGWorldFromPtr (&(offscreenGWorld), k24RGBPixelFormat, &(movieRect), NULL, NULL, 0, (pixels), 3 * width);
	#endif

	LockPixels(GetGWorldPixMap(offscreenGWorld));
	SetGWorld (offscreenGWorld, NULL);
	SetMovieGWorld (moviePtr, offscreenGWorld, nil);
	//------------------------------------ texture stuff:
	if (bUseTexture){
		// create the texture, set the pixels to black and
		// upload them to the texture (so at least we see nothing black the callback)
		tex.allocate(width,height,GL_RGB);
		memset(pixels, 0, width*height*3);
		tex.loadData(pixels, width, height, GL_RGB);
		allocated = true;
	}
}
void ofQuickTimePlayer::createImgMemAndGWorld() {
    Rect movieRect;
    movieRect.top 			= 0;
    movieRect.left 			= 0;
    movieRect.bottom 		= height;
    movieRect.right 		= width;
    offscreenGWorldPixels = new unsigned char[4 * width * height + 32];
    pixels.allocate(width,height,OF_IMAGE_COLOR);

#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
    QTNewGWorldFromPtr (&(offscreenGWorld), k32ARGBPixelFormat, &(movieRect), NULL, NULL, 0, (offscreenGWorldPixels), 4 * width);
#else
    QTNewGWorldFromPtr (&(offscreenGWorld), k24RGBPixelFormat, &(movieRect), NULL, NULL, 0, (pixels.getPixels()), 3 * width);
#endif

    LockPixels(GetGWorldPixMap(offscreenGWorld));

    // from : https://github.com/openframeworks/openFrameworks/issues/244
    // SetGWorld do not seems to be necessary for offscreen rendering of the movie
    // only SetMovieGWorld should be called
    // if both are called, the app will crash after a few ofVideoPlayer object have been deleted

#ifndef TARGET_WIN32
    SetGWorld (offscreenGWorld, NULL);
#endif
    SetMovieGWorld (moviePtr, offscreenGWorld, nil);

}
Пример #6
0
void EraseRectAndAlpha(GWorldPtr gWorld, Rect *pRect)
{
	PixMapHandle	pixMap = GetGWorldPixMap(gWorld);
	long			rows;
	Ptr				rowBaseAddr;


    LockPixels(pixMap);
	rows = pRect->bottom - pRect->top;
    
    rowBaseAddr = GetPixBaseAddr(pixMap) + (GetPixRowBytes(pixMap) & 0x3fff) * pRect->top + pRect->left * GetPixDepth(pixMap) / 8;
	do
	{
		long	cols;
		UInt32	*baseAddr;
		
		cols = pRect->right - pRect->left;
		baseAddr = (UInt32*)rowBaseAddr;
		rowBaseAddr += (**pixMap).rowBytes & 0x3fff;
		do
		{
			*baseAddr++ = 0;
		} while (--cols);
	} while (--rows);

    UnlockPixels(pixMap);

} // EraseRectAndAlpha
Пример #7
0
// Create the offscreen GWorld (using Image  as target memory)
void QuicktimeLiveImageStream::createGWorld()
{
    Rect         destinationBounds;
    OSStatus     err;
    GDHandle     origDevice;
    CGrafPtr     origPort;
    destinationBounds.left   = 0;
    destinationBounds.top    = 0;
    destinationBounds.right  = m_videoRectWidth;
    destinationBounds.bottom = m_videoRectHeight;
    err = QTNewGWorldFromPtr(&m_gw, k32ARGBPixelFormat, &destinationBounds,
                             NULL, NULL, 0, (Ptr)data(), 4*m_videoRectWidth);
    if (err !=0 )
    {
        OSG_DEBUG << "Could not create gWorld" << std::endl;
    }
    else
    {
        // Query
        GetGWorld (&origPort, &origDevice);
        SetGWorld (m_gw, NULL); // set current graphics port to offscreen
        m_pixmap = GetGWorldPixMap(m_gw);
        if (m_pixmap)
         {
             if (!LockPixels (m_pixmap)) // lock offscreen pixel map
             {
                 OSG_FATAL << "Could not lock PixMap" << std::endl;
             }
         }
        // Set back
        SetGWorld(origPort, origDevice);
    }
}
void ofxAlphaVideoPlayer::createImgMemAndGWorld(){
	Rect movieRect;
	movieRect.top 			= 0;
	movieRect.left 			= 0;
	movieRect.bottom 		= height;
	movieRect.right 		= width;
	offscreenGWorldPixels 	= new unsigned char[4 * width * height + 32];
	pixels					= new unsigned char[width*height*4]; // 4 =>rgba

	#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
		//cout << "with Big Endian"<<endl;
		QTNewGWorldFromPtr (&(offscreenGWorld), k32ARGBPixelFormat, &(movieRect), NULL, NULL, 0, (offscreenGWorldPixels), 4 * width);		
	#else
		//cout << "no Big Endian"<<endl;
		QTNewGWorldFromPtr (&(offscreenGWorld), k32RGBAPixelFormat, &(movieRect), NULL, NULL, 0, (pixels), 4 * width);
	#endif
	/** POSSIBLE PIXEL FORMATS 
	k32BGRAPixelFormat            = 'BGRA', // 32 bit bgra    (Matrox)
	k32ABGRPixelFormat            = 'ABGR', // 32 bit abgr   
	k32RGBAPixelFormat            = 'RGBA', // 32 bit rgba   	
	 ***********/
	LockPixels(GetGWorldPixMap(offscreenGWorld));
	SetGWorld (offscreenGWorld, NULL);
	SetMovieGWorld (moviePtr, offscreenGWorld, nil);
	//------------------------------------ texture stuff:
	if (bUseTexture){
		// create the texture, set the pixels to black and
		// upload them to the texture (so at least we see nothing black the callback)
		tex.allocate(width,height,GL_RGBA);
		memset(pixels, 0, width*height*4);
		tex.loadData(pixels, width, height, GL_RGBA);
		allocated = true;
	}
}
void ofQuickTimePlayer::createImgMemAndGWorld(){
	Rect movieRect;
	movieRect.top 			= 0;
	movieRect.left 			= 0;
	movieRect.bottom 		= height;
	movieRect.right 		= width;
    if (pixelFormat == OF_PIXELS_RGBA) {
        pixels.allocate(width, height, OF_IMAGE_COLOR_ALPHA);
    } 
    else {
        pixels.allocate(width, height, OF_IMAGE_COLOR);
    }

	#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
		offscreenGWorldPixels = new unsigned char[4 * width * height + 32];
		QTNewGWorldFromPtr (&(offscreenGWorld), k32ARGBPixelFormat, &(movieRect), NULL, NULL, 0, (offscreenGWorldPixels), 4 * width);		
	#else
        if (pixelFormat == OF_PIXELS_RGBA) {
            QTNewGWorldFromPtr (&(offscreenGWorld), k32RGBAPixelFormat, &(movieRect), NULL, NULL, 0, (pixels.getPixels()), 4 * width);
        }
        else {
            QTNewGWorldFromPtr (&(offscreenGWorld), k24RGBPixelFormat, &(movieRect), NULL, NULL, 0, (pixels.getPixels()), 3 * width);
        }
	#endif

	LockPixels(GetGWorldPixMap(offscreenGWorld));
	SetGWorld (offscreenGWorld, NULL);
	SetMovieGWorld (moviePtr, offscreenGWorld, nil);

}
Пример #10
0
Pixmap
Tk_GetPixmap(
    Display *display,	/* Display for new pixmap (can be null). */
    Drawable d,		/* Drawable where pixmap will be used (ignored). */
    int width,		/* Dimensions of pixmap. */
    int height,
    int depth)		/* Bits per pixel for pixmap. */
{
    QDErr err;
    GWorldPtr gWorld;
    Rect bounds;
    MacDrawable *macPix;
    PixMapHandle pixels;
    
    if (display != NULL) {
	display->request++;
    }
    macPix = (MacDrawable *) ckalloc(sizeof(MacDrawable));
    macPix->winPtr = NULL;
    macPix->xOff = 0;
    macPix->yOff = 0;
    macPix->clipRgn = NULL;
    macPix->aboveClipRgn = NULL;
    macPix->referenceCount = 0;
    macPix->toplevel = NULL;
    macPix->flags = 0;

    bounds.top = bounds.left = 0;
    bounds.right = (short) width;
    bounds.bottom = (short) height;
    if (depth != 1) {
	depth = 0;
    }

    /*
     * Allocate memory for the off screen pixmap.  If we fail
     * try again from system memory.  Eventually, we may have
     * to panic.
     */
    err = NewGWorld(&gWorld, depth, &bounds, NULL, NULL, 0);
    if (err != noErr) {
	err = NewGWorld(&gWorld, depth, &bounds, NULL, NULL, useTempMem);
    }
    if (err != noErr) {
        panic("Out of memory: NewGWorld failed in Tk_GetPixmap");
    }

    /*
     * Lock down the pixels so they don't move out from under us.
     */
    pixels = GetGWorldPixMap(gWorld);
    LockPixels(pixels);
    macPix->portPtr = gWorld;

    return (Pixmap) macPix;
}
Пример #11
0
void wxMemoryDC::DoSelect( const wxBitmap& bitmap )
{
    if ( m_selected.Ok() )
    {
#if wxMAC_USE_CORE_GRAPHICS
        m_selected.EndRawAccess() ;
        delete m_graphicContext ;
        m_graphicContext = NULL ;
#else
// TODO: UnlockPixels( GetGWorldPixMap(MAC_WXHBITMAP(m_selected.GetHBITMAP())) );
#endif
    }

    m_selected = bitmap;
    if (m_selected.Ok())
    { 
#if wxMAC_USE_CORE_GRAPHICS
        if ( m_selected.GetDepth() != 1 )
            m_selected.UseAlpha() ;
        m_selected.BeginRawAccess() ;
		m_width = bitmap.GetWidth();
		m_height = bitmap.GetHeight();
        CGColorSpaceRef genericColorSpace  = wxMacGetGenericRGBColorSpace();
        CGContextRef bmCtx = (CGContextRef) m_selected.GetHBITMAP();

        if ( bmCtx )
        {
            CGContextSetFillColorSpace( bmCtx, genericColorSpace );
            CGContextSetStrokeColorSpace( bmCtx, genericColorSpace );
			SetGraphicsContext( wxGraphicsContext::CreateFromNative( bmCtx ) );
        }
        m_ok = (m_graphicContext != NULL) ;

#else
        m_macPort = m_selected.GetHBITMAP( &m_macMask ) ;
        m_ok = (m_macPort != NULL) ;
        if (m_ok)
        {
            LockPixels( GetGWorldPixMap( (CGrafPtr) m_macPort ) ) ;
            SetRectRgn( (RgnHandle) m_macBoundaryClipRgn , 0 , 0 , m_selected.GetWidth() , m_selected.GetHeight() ) ;
            CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
        }
#endif
    }
    else
    {
        m_ok = false;
    }
}
Пример #12
0
// A handy routine which will return the colour of a pixel in a pixmap
// It's not effiecient enough to be called a lot as it works out some values every time even
// though they don't change.
short GPixelColour(PixMapHandle thePixMap,short x,short y)
{
	Ptr		pixBase;
	short	rowBytes,colour;

	LockPixels(thePixMap);
	
	pixBase=GetPixBaseAddr(thePixMap);
	rowBytes=(**thePixMap).rowBytes & 0x3fff;
	
	colour=(unsigned char)*(pixBase + y * rowBytes + x);
	
	UnlockPixels(thePixMap);
	
	return colour;
}
Пример #13
0
void drawGraphic( CGContextRef context, float x, float y )
{
    static GWorldPtr imageGW = NULL;
    static CGImageRef imageRef = NULL;
    static CGDataProviderRef dataProviderRef = NULL;

    Rect bounds;
    static size_t width;
    static size_t height;
    size_t bitsPerComponent;
    size_t bitsPerPixel;
    size_t bytesPerRow;
    PixMapHandle pmh;    
    
    //	Load the image if we haven't already
    if ( NULL == imageGW )
    {
        //	Load and create the GWorld
        imageGW = OpenImage();
        
        if ( imageGW != NULL )
        {
            
            GetPortBounds( imageGW, &bounds );
            width = bounds.right - bounds.left;
            height = bounds.bottom - bounds.top;
            
            pmh = GetPortPixMap( imageGW );
            bitsPerComponent = (**pmh).cmpSize;
            bitsPerPixel = (**pmh).pixelSize;
            bytesPerRow = GetPixRowBytes( pmh );
            
            LockPixels( pmh );
            
            dataProviderRef = CGDataProviderCreateWithData( NULL, GetPixBaseAddr( pmh ), height * bytesPerRow, releaseData );
            
            
            //	Create the imageRef for that GWorld
            imageRef = CGImageCreate( width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedFirst/*kCGImageAlphaNone*/, dataProviderRef, NULL, 0, kCGRenderingIntentDefault );
        }
    }
    
    
    //	Draw the image at 0,0
    CGContextDrawImage( context, CGRectMake( x - 20, y, 40, 40 * height / width ), imageRef );
    
}
Пример #14
0
void mac_setfont(GWorldPtr world, Str255 fontname)
{
	GDHandle	oldGD;
	GWorldPtr	oldGW;
	
	GetGWorld(&oldGW, &oldGD);
	LockPixels(world->portPixMap);
	{
		short		fontID;
		SetGWorld( world, 0);
		GetFNum(fontname, &fontID);
		TextFont(fontID);
		TextSize(14);
		TextFace(extend/*|bold*/);
	}
	SetGWorld(oldGW, oldGD);
	UnlockPixels(world->portPixMap);
}
Пример #15
0
void dev_draw_text_gmode(PixMapHandle pixmap, int x, int y, const char* s, int len,
		int pmask, int mode, int fgcolor, int bgcolor, int ton_mode)
{			//pixmap must be already locked
	GDHandle	oldGD;
	GWorldPtr	oldGW;
	int		color, trans, width;
	Rect		rect= {0,0,16,32},
			destrect;
	
	GetGWorld(&oldGW, &oldGD);
	LockPixels(charbufWorld->portPixMap);
	SetGWorld(charbufWorld,0);
		trans=0;
		if( fgcolor==trans ) trans++;
		if( bgcolor==trans ) trans++;
		if( fgcolor==trans ) trans++;
		
		color= ( (mode&2)? bgcolor:trans );
		dev_box(charbufWorld->portPixMap, rect, color, 0xFF);
		
		color= ( (mode&1)? fgcolor:trans );
		charbufWorld->fgColor= color;
		TextMode(srcOr);
		MoveTo(0,13);
		DrawText(s,0,len);
		if( ton_mode==2 ){
			expand_horizontality(charbufWorld->portPixMap, len*8, 16);
		}
		
		width= len*8;
		if( ton_mode==2 ) width*=2;
		
		rect.right=width;
		destrect.left=x; destrect.top=y;
		destrect.right=x+width; destrect.bottom=destrect.top+16;
		
		MyCopyBits(charbufWorld->portPixMap, pixmap,
			rect, destrect, 0x11/*trans*/, trans, pmask,
			0, 0, NULL);
		
		
	SetGWorld(oldGW, oldGD);
	UnlockPixels(charbufWorld->portPixMap);
}
Пример #16
0
PRIVATE GWorldPtr
gworld_from_pict (PicHandle ph)
{
  GWorldPtr retval;

  retval = NULL;
  if (ph)
    {
      CGrafPtr save_port;
      GDHandle save_device;
      Rect r;
      OSErr err;

      GetGWorld (&save_port, &save_device);
      save_port = MR (save_port);
      save_device = MR (save_device);
      r = HxX (ph, picFrame);
      err = NewGWorld (&retval, 32, &r, NULL, NULL, keepLocal);
      if (retval)
	{
	  PixMapHandle pm;

	  retval = MR (retval);
	  SetGWorld (retval, NULL);
	  pm = GetGWorldPixMap (retval);
	  LockPixels (pm);
	  DrawPicture (ph, &r);
#if 0
#warning THIS INTERFERES WITH PICT PASTING
	  {
	    char *p;

	    EraseRect (&r);
	    p = GetPixBaseAddr (pm);
	    memset (p, 0x00, 4 * RECT_HEIGHT(&r) * RECT_WIDTH (&r));
	    memset (p, 0xFF, 4 * RECT_HEIGHT(&r) * RECT_WIDTH (&r) / 2);
	  }
#endif
	  UnlockPixels (pm);
	}
      SetGWorld (save_port, save_device);
    }
  return retval;
}
Пример #17
0
void _HYPlatformGraphicPane::_StartDraw	 (void)
{	
	_HYGraphicPane * parent = (_HYGraphicPane*)this;
	GetGWorld (&savedPort,&savedDevice);
	::GetForeColor (&saveFG);
	::GetBackColor (&saveBG);
	SetGWorld (thePane,nil);
	LockPixels (GetGWorldPixMap(thePane));
	RGBColor c  = {256*parent->bColor.R,256*parent->bColor.G,256*parent->bColor.B};
	if (parent->bColor.R+parent->bColor.B+(long)parent->bColor.G==765)
		c = (RGBColor){0xffff,0xffff,0xffff};
	RGBBackColor (&c);
	c = (RGBColor){256*parent->color.R,256*parent->color.G,256*parent->color.B};
	RGBForeColor (&c);
	//if (parent->depth>1)
		TextMode 	 (srcOr);
	//else
		//TextMode 	 (srcCopy);
}
Пример #18
0
PRIVATE SDL_Surface *
surface_from_gworld (GWorldPtr gp)
{
  SDL_Surface *retval;

  if (!gp)
    retval = NULL;
  else
    {
      int pixels_per_line;
      int n_lines;
      PixMapHandle pm;
      enum { A = 0x00000000,
	     R = 0x0000FF00,
	     G = 0x00FF0000,
	     B = 0xFF000000 };
      mac_pixel32 *ip;
      sdl_pixel24 *op;
      Rect r;

      pm = GetGWorldPixMap (gp);
      LockPixels (pm);

      r = PIXMAP_BOUNDS (pm);
      n_lines = RECT_HEIGHT (&r);
      pixels_per_line = RECT_WIDTH (&r);
      retval = SDL_AllocSurface (SDL_SWSURFACE, pixels_per_line, n_lines, 32,
				 R, G, B, A);
      SDL_LockSurface (retval);
      op = SDL_Surface_pixels (retval);
      ip = (typeof (ip)) GetPixBaseAddr (pm);
      memcpy (op, ip, n_lines * pixels_per_line * sizeof *ip);
#if 0
#warning THIS IS BROKEN
      memset (op, 0x00, 4 * n_lines * pixels_per_line);
      memset (op, 0xFF, 4 * n_lines * pixels_per_line / 2);
#endif
      SDL_UnlockSurface (retval);
      UnlockPixels (pm);
    }

  return retval;
}
Пример #19
0
void _HYPlatformGraphicPane::_CopyToClipboard	(void)
{
	_HYGraphicPane* parent = (_HYGraphicPane*)this;
	#ifdef TARGET_API_MAC_CARBON
		ClearCurrentScrap();
	#else
		ZeroScrap();
	#endif
	Rect  bRect;
	
	bRect.left 			= bRect.top = 0;
	bRect.right 		= parent->w;
	bRect.bottom 		= parent->h;

	PicHandle	 pic 	= OpenPicture (&bRect);
	
	GrafPtr      topPort;
	GetPort		 (&topPort);
	
	LockPixels (GetGWorldPixMap(thePane));
	#ifdef OPAQUE_TOOLBOX_STRUCTS 
		CopyBits (GetPortBitMapForCopyBits(thePane),GetPortBitMapForCopyBits(topPort),
				&bRect,&bRect,srcCopy,(RgnHandle)nil);
	#else
		CopyBits ((BitMap*)*GetGWorldPixMap(thePane),
				  (BitMap*)&(topPort->portBits),&bRect,&bRect,
	    		   srcCopy,(RgnHandle)nil);
	#endif
	UnlockPixels (GetGWorldPixMap(thePane));
    			   
	ClosePicture ();
	HLock	((Handle)pic);		
						
	#ifdef TARGET_API_MAC_CARBON
		ScrapRef		 theScrapRef;
		GetCurrentScrap(&theScrapRef);
		PutScrapFlavor(theScrapRef, 'PICT', kScrapFlavorMaskNone,GetHandleSize((Handle)pic),*pic);
	#else
		PutScrap (GetHandleSize((Handle)pic),'PICT',*pic);
	#endif
	KillPicture (pic);	
}		
Пример #20
0
	bool LockGraphics(MCRegionRef p_area, MCGContextRef& r_context)
	{
		MCGRaster t_raster;
		if (LockPixels(p_area, t_raster))
		{
			if (MCGContextCreateWithRaster(t_raster, m_locked_context))
			{
				// Set origin
				MCGContextTranslateCTM(m_locked_context, -m_locked_area.x, -m_locked_area.y);
				// Set clipping rect
				MCGContextClipToRect(m_locked_context, MCRectangleToMCGRectangle(m_locked_area));
				
				r_context = m_locked_context;
				
				return true;
			}

			UnlockPixels();
		}

		return false;
	}
Пример #21
0
static void QT_StartAddVideoSamplesToMedia (const Rect *trackFrame, int rectx, int recty, ReportList *reports)
{
	SCTemporalSettings gTemporalSettings;
	OSErr err = noErr;

	qtexport->ibuf = IMB_allocImBuf (rectx, recty, 32, IB_rect);
	qtexport->ibuf2 = IMB_allocImBuf (rectx, recty, 32, IB_rect);

	err = NewGWorldFromPtr( &qtexport->theGWorld,
							k32ARGBPixelFormat,
							trackFrame,
							NULL, NULL, 0,
							(Ptr)qtexport->ibuf->rect,
							rectx * 4 );
	CheckError (err, "NewGWorldFromPtr error", reports);

	qtexport->thePixMap = GetGWorldPixMap(qtexport->theGWorld);
	LockPixels(qtexport->thePixMap);

	SCDefaultPixMapSettings (qtdata->theComponent, qtexport->thePixMap, true);

	// workaround for crash with H.264, which requires an upgrade to
	// the new callback based api for proper encoding, but that's not
	// really compatible with rendering out frames sequentially
	gTemporalSettings = qtdata->gTemporalSettings;
	if(qtdata->gSpatialSettings.codecType == kH264CodecType) {
		if(gTemporalSettings.temporalQuality != codecMinQuality) {
			BKE_reportf(reports, RPT_WARNING, "Only minimum quality compression supported for QuickTime H.264.\n");
			gTemporalSettings.temporalQuality = codecMinQuality;
		}
	}

	SCSetInfo(qtdata->theComponent, scTemporalSettingsType,	&gTemporalSettings);
	SCSetInfo(qtdata->theComponent, scSpatialSettingsType,	&qtdata->gSpatialSettings);
	SCSetInfo(qtdata->theComponent, scDataRateSettingsType,	&qtdata->aDataRateSetting);

	err = SCCompressSequenceBegin(qtdata->theComponent, qtexport->thePixMap, NULL, &qtexport->anImageDescription); 
	CheckError (err, "SCCompressSequenceBegin error", reports );
}
Пример #22
0
short FindGWUnusedCol(GWorldPtr theWorld)
{
	Ptr				pixBase;
	short			rowBytes,colour,colCount[255],xCount,yCount;
	short			width,height;
	PixMapHandle	thePixMap=GetGWorldPixMap(theWorld);

	LockPixels(thePixMap);
	
	pixBase=GetPixBaseAddr(thePixMap);
	rowBytes=(**thePixMap).rowBytes & 0x3fff;
	width=(theWorld->portRect.right)-(theWorld->portRect.left);
	height=(theWorld->portRect.bottom)-(theWorld->portRect.top);
		
	// clear all the counts
	for(xCount=0; xCount<=255; xCount++)
		colCount[xCount]=0;
	
	for (yCount=0; yCount<height; yCount++)
	{
		for(xCount=0; xCount<width; xCount++)
		{
			colour=(unsigned char)*(pixBase + yCount * rowBytes + xCount);
			colCount[colour]++;
		}
	}
	
	UnlockPixels(thePixMap);

	// scan through for a 0 use col
	for(xCount=0; xCount<=255; xCount++)
	{
		if (colCount[xCount]==0)
			return xCount;
	}

	return -1; // not found
}
Пример #23
0
RgnHandle getWindowStructureRegion(WindowRef window, RgnHandle structureRegion)
{
    /*------------------------------------------------------
        Define the structural region of our window.
    --------------------------------------------------------*/
    static RgnHandle pictureRgn=NULL;
    static Rect pictureRect;
    Rect windowRect;
    
    SetEmptyRgn(structureRegion);
    
    if(!pictureRgn){//haven't Cached our region yet
        PicHandle myPicture=GetPicture(kMaskPictureID);
        GrafPtr	origPort;
        GDHandle origDev;
        GWorldPtr pictMask;
        PixMapHandle maskBitMap;
        GetGWorld(&origPort,&origDev);
        pictureRgn=NewRgn();
        pictureRect=(*myPicture)->picFrame;
        NewGWorld(&pictMask,1,&pictureRect,NULL,NULL,0);
        maskBitMap=GetPortPixMap(pictMask);
        LockPixels(maskBitMap);
        SetGWorld(pictMask,NULL);
        EraseRect(&pictureRect);
        DrawPicture(myPicture,&pictureRect);
        BitMapToRegion(pictureRgn,(BitMap*)*maskBitMap);//use the mask to create a region
        InsetRgn(pictureRgn,1,1);
        SetGWorld(origPort,origDev);
        UnlockPixels(maskBitMap);
        DisposeGWorld(pictMask);
        ReleaseResource((Handle)myPicture);
    }
    getCurrentPortBounds(&windowRect);//how big is the window
    CopyRgn(pictureRgn,structureRegion);//make a copy of our cached region
    MapRgn(structureRegion,&pictureRect,&windowRect);//scale it to our actual window size
    return structureRegion;
}
Пример #24
0
void CreateSpriteStuff (Rect *windowBounds, CGrafPtr windowPtr)
{
	OSErr err;
	Rect bounds;

	// calculate the size of the destination
	bounds = *windowBounds;
	OffsetRect (&bounds, -bounds.left, -bounds.top);
	gBounceBox = bounds;
	InsetRect (&gBounceBox, 16, 16);

	// create a sprite layer graphics world with a bit depth of 32
	NewGWorld (&gSpritePlane, 32, &bounds, nil, nil, useTempMem);
	if (gSpritePlane == nil)
	{
		NewGWorld (&gSpritePlane, 32, &bounds, nil, nil, 0);
	}
	
	if (gSpritePlane)
	{
		LockPixels (GetPortPixMap(gSpritePlane));
		
		gBackgroundColor.red = 0x1234;
		gBackgroundColor.green = 0x0001;
		gBackgroundColor.blue = 0x0044;
		

		// create a sprite world
		err = NewSpriteWorld (&gSpriteWorld,		/* on return, a new sprite world */
								windowPtr,			/* destination */
								gSpritePlane,		/* sprite layer graphics world */
								&gBackgroundColor,	/* background color */
								nil);				/* graphics world to be used as the background. */
		
		// create sprites
		CreateSprites();
	}
}
void ofQtVideoSaver::setup( int width , int height, string movieName){

	w = width;
	h = height;
    
   
    fileName = (ofToDataPath(movieName));
    //pszFlatFilename = flatFileName;
    
    initializeQuicktime();
    	/*  Load the FSSpec structure to describe the receiving file.  For a 
    description of this and related calls see 
    http://developer.apple.com/quicktime/icefloe/dispatch004.html.
    ================================================================  */


	#ifdef TARGET_WIN32
		//FILE * pFile = NULL;
		//pFile = fopen (fileName.c_str(),"w");
		//fclose (pFile);
		char fileNameStr[255];
		sprintf(fileNameStr, "%s", fileName.c_str());
		osErr = NativePathNameToFSSpec (fileNameStr, &fsSpec, 0);
		
	#endif
	#ifdef TARGET_OSX
	
		/// kill a file and make a new one if needed:		
		FILE * pFile;
		pFile = fopen (fileName.c_str(),"w");
		fclose (pFile);
	
		Boolean isdir;
		osErr = FSPathMakeRef((const UInt8*)fileName.c_str(), &fsref, &isdir);
		osErr = FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fsSpec, NULL);
	#endif

    if (osErr && (osErr != fnfErr))    /* File-not-found error is ok         */
      { 
      printf ("getting FSS spec failed %d\n", osErr); 
      goto bail; 
     }
	 

	/*  Step 1:  Create a new, empty movie file and a movie that references that 
    file (CreateMovieFile).  
    ======================================================================== */
            
    osErr = CreateMovieFile 
      (
      &fsSpec,                         /* FSSpec specifier                   */
      FOUR_CHAR_CODE('TVOD'),          /* file creator type, TVOD = QT player*/
      smCurrentScript,                 /* movie script system to use         */
      createMovieFileDeleteCurFile     /* movie file creation flags          */
        | createMovieFileDontCreateResFile,
      &sResRefNum,                     /* returned file ref num to data fork */
      &movie                           /* returned handle to open empty movie*/
                                       /*   that references the created file */
      );
    if (osErr) 
      { 
      printf ("CreateMovieFile failed %d\n", osErr); 
      goto bail; 
      }


	/*  Step 2:  Add a new track to that movie (NewMovieTrack).
    =======================================================  */

    track = NewMovieTrack 
      (
      movie,                           /* the movie to add track to          */
      ((long) w << 16),              /* width of track in pixels (Fixed)   */
      FixRatio (h, 1),               /* height of track in pixels (Fixed)  */ 
      kNoVolume                        /* default volume level               */
      );
    osErr = GetMoviesError ();
    if (osErr) 
      { 
      printf ("NewMovieTrack failed %d\n", osErr); 
      goto bail; 
      }
    

	/*  Step 3:  Add a new media to that track (NewTrackMedia).
    =======================================================  */
    
    media = NewTrackMedia 
      (
      track,                           /* the track to add the media to      */
      VideoMediaType,                  /* media type, e.g. SoundMediaType    */
      600,                             /* num media time units that elapse/sec*/
      NULL,                            /* ptr to file that holds media sampls*/
      0                                /* type of ptr to media samples       */
      );
    osErr = GetMoviesError ();
    if (osErr) 
      { 
      printf ("NewTrackMedia failed %d\n", osErr); 
      goto bail; 
      }

	/*  Step 4:  Add media samples to the media. 
    ========================================  */
    
    BeginMediaEdits (media);           /* Inform the Movie Toolbox that we   */
                                       /*   want to change the media samples */
                                       /*   referenced by a track's media.   */
                                       /*   This opens the media container   */
                                       /*   and makes it ready to receive    */
                                       /*   and/or remove sample data.       */
    
    
    

    // Step 5: setup graphics port for qt movie and compression type ---
    
    /*  Create a new offscreen graphics world that will hold the movie's
    drawing surface.  draw_image() copies the image of IceFlow to this
    surface with varying amounts of transparency.
    =================================================================  */
    
    MacSetRect (&rect, 0, 0, w, h);

    osErr = NewGWorld 
      (
      &pMovieGWorld,                   /* receives the new GWorld.           */
      24,                              /* pixel depth in bits/pixel          */
      &rect,                           /* desired size of the GWorld.        */
      NULL, 
      NULL, 
      (GWorldFlags) 0
      );
    if (osErr != noErr) 
      { 
      printf ("NewGWorld 1 failed %d\n", osErr); 
      goto bail; 
      }


/*  Retrieve the pixel map associated with that graphics world and lock 
    the pixel map in memory.  GetMaxCompressionSize() and CompressImage()
    only operate on pixel maps, not graphics worlds.
    =====================================================================  */
    
    pixMapHandle = GetGWorldPixMap (pMovieGWorld);
    if (pixMapHandle == NULL) 
      { 
      printf ("GetGWorldPixMap failed\n"); 
      goto bail; 
      }
    LockPixels (pixMapHandle);


/*  Get the maximum number of bytes required to hold an image having the 
    specified characteristics compressed using the specified compressor.
    ====================================================================  */

     
    osErr = GetMaxCompressionSize 
      (
      pixMapHandle,							/* the pixel map to compress from.    */
      &rect,								/* the image rectangle.               */
      0,									/* let ICM choose image bit depth.    */
      codecHighQuality,						/* compression quality specifier.     */
      kRawCodecType,						/* desired compression type           */   // < set to RAW in case we set to a new compression type...
      (CompressorComponent) anyCodec,		/* codec specifier.                   */
      &lMaxCompressionSize					/* receives max bytes needed for cmp. */
      );
    if (osErr != noErr) 
      { 
      printf ("GetMaxCompressionSize failed %d\n", osErr); 
      goto bail; 
      }


/*  Allocate a buffer to hold the compressed image data by creating a new
    handle.
    =====================================================================  */
    hCompressedData = NewHandle (lMaxCompressionSize);
    if (hCompressedData == NULL) 
      { 
      printf ("NewHandle(%ld) failed\n", lMaxCompressionSize); 
      goto bail; 
      }

/*  Lock the handle and then dereference it to obtain a pointer to the data 
    buffer because CompressImage() wants us to pass it a pointer, not a 
    handle. 
    =======================================================================  */

    HLockHi (hCompressedData);
    pCompressedData = *hCompressedData;

/*  Create an image description object in memory of minimum size to pass 
    to CompressImage().  CompressImage() will resize the memory as 
    necessary so create it small here.
    ====================================================================  */
    
    hImageDescription = (ImageDescriptionHandle) NewHandle (4);
    if (hImageDescription == NULL) 
      { 
      printf ("NewHandle(4) failed\n"); 
      goto bail; 
      }
	
	
	
	bSetupForRecordingMovie = true;
    return;
    
    
    
    
  bail:    
	printf("got to bail somehows \n");
    if (sResRefNum != 0) CloseMovieFile (sResRefNum);
    if (movie     != NULL) DisposeMovie (movie);

    //ExitMovies ();                     /* Finalize Quicktime                 */
    
    return;
}
Пример #26
0
osg::Image* QuicktimeImportExport::doImport(unsigned char* data, unsigned int sizeData, const std::string& fileTypeHint)
{
    GWorldPtr gworld = 0;
    OSType pixelFormat;
    int rowStride;
    GraphicsImportComponent gicomp = 0;
    Rect rectImage;
    GDHandle origDevice = 0;
    CGrafPtr origPort = 0;
    ImageDescriptionHandle desc = 0;
    int depth = 32;
    unsigned int xsize, ysize;
    unsigned char* imageData = 0;
    
    // Data Handle for file data ( & load data from file )
    Handle dataRef = getPtrDataRef(data, sizeData, fileTypeHint);
    
    try {
        OSErr err = noErr;
        
        // GraphicsImporter - Get Importer for our filetype
        GetGraphicsImporterForDataRef(dataRef, 'ptr ', &gicomp);

        // GWorld - Get Texture Info
        err = GraphicsImportGetNaturalBounds(gicomp, &rectImage);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportGetNaturalBounds failed");
            
        }
        xsize = (unsigned int)(rectImage.right - rectImage.left);
        ysize = (unsigned int)(rectImage.bottom - rectImage.top);

        // ImageDescription - Get Image Description
        err = GraphicsImportGetImageDescription(gicomp, &desc);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportGetImageDescription failed");
        }

        // ImageDescription - Get Bit Depth
        HLock(reinterpret_cast<char **>(desc));
        

        // GWorld - Pixel Format stuff
        pixelFormat = k32ARGBPixelFormat; // Make sure its forced...NOTE: i'm pretty sure this cannot be RGBA!

        // GWorld - Row stride
        rowStride = xsize * 4; // (width * depth_bpp / 8)

        // GWorld - Allocate output buffer
        imageData = new unsigned char[rowStride * ysize];

        // GWorld - Actually Create IT!
        QTNewGWorldFromPtr(&gworld, pixelFormat, &rectImage, 0, 0, 0, imageData, rowStride);
        if (!gworld) {
            throw QTImportExportException(-1, "QTNewGWorldFromPtr failed");
        }

        // Save old Graphics Device and Graphics Port to reset to later
        GetGWorld (&origPort, &origDevice);

        // GraphicsImporter - Set Destination GWorld (our buffer)
        err = GraphicsImportSetGWorld(gicomp, gworld, 0);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportSetGWorld failed");
        }

        // GraphicsImporter - Set Quality Level
        err = GraphicsImportSetQuality(gicomp, codecLosslessQuality);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportSetQuality failed");
        }

        // Lock pixels so that we can draw to our memory texture
        if (!GetGWorldPixMap(gworld) || !LockPixels(GetGWorldPixMap(gworld))) {
            throw QTImportExportException(0, "GetGWorldPixMap failed");
        }
        
           
        //*** Draw GWorld into our Memory Texture!
        GraphicsImportDraw(gicomp);
 
        // Clean up
        UnlockPixels(GetGWorldPixMap(gworld));
        SetGWorld(origPort, origDevice); // set graphics port to offscreen (we don't need it now)
        DisposeGWorld(gworld);
        CloseComponent(gicomp);
        DisposeHandle(reinterpret_cast<char **>(desc));
        DisposeHandle(dataRef);
    } 
    catch (QTImportExportException& e) 
    {
        setError(e.what());
        
        if (gworld) {
            UnlockPixels(GetGWorldPixMap(gworld));
            SetGWorld(origPort, origDevice); // set graphics port to offscreen (we don't need it now)
            DisposeGWorld(gworld);
        }
        if (gicomp)
            CloseComponent(gicomp);
        if (desc) 
            DisposeHandle(reinterpret_cast<char **>(desc));
        
        if (imageData) 
            delete[] imageData;
        if (dataRef)
            DisposeHandle(dataRef);
            
        return NULL;
    }
    

    
    unsigned int bytesPerPixel = depth / 8;
    unsigned int glpixelFormat;
    switch(bytesPerPixel) {
        case 3 :
            glpixelFormat = GL_RGB;
            break;
        case 4 :
            glpixelFormat = GL_RGBA;
            break;
        default :
            delete[] imageData;
            setError("unknown pixelformat");
            return NULL;
            break;
    }
    
    unsigned char* swizzled = pepareBufferForOSG(imageData, bytesPerPixel, xsize, ysize);
    
    delete[] imageData;
 
    osg::Image* image = new osg::Image();
    image->setFileName(fileTypeHint.c_str());
    image->setImage(xsize,ysize,1,
        bytesPerPixel,
        glpixelFormat,
        GL_UNSIGNED_BYTE,
        swizzled,
        osg::Image::USE_NEW_DELETE );
    
 
    return image;
}
Пример #27
0
TechkonDialog::TechkonDialog(ProfileDoc *dc,RawData *pD):InputDialog(dc,pD,1)
{
	short		iType;
	Handle		iHandle;
	Handle		sHandle;
	Rect 		iRect, r,pRect,tRect;	
	UserItemUPP  box3D;
	
	QDErr		error;
	GDHandle	oldGD;
	GWorldPtr	oldGW;
	RGBColor	c,oldbackcolor,oldforecolor;
	WindowPtr	oldP;
	OSErr			err;
	int32 		i,wi,hi;
	double w,h;
	short		gtsl_ids[] = GTSL_IDS;
	Str255		theString;
	PixMapHandle	bigPixMap;
	McoStatus  	state;
	
	for (i=0; i<NumInputIDS; i++) ids[i] = gtsl_ids[i];

	WinType = TechkonWindow;
	WinNum = 0;

	setDialog(Input_Dialog);
	frame_button(ids[Ok_Box]);	

	

	
	// Added by James, 3D the box
	threeD_box(ids[ThreeDBox]);
	
	HideDItem(dp,ids[Redo]);
	
	GetDItem ( dp,ids[Message], &iType, (Handle*)&iHandle, &iRect );
	GetIndString(theString,Message_List_ID,6);
	SetIText(iHandle,theString);
	
	Scramble = FALSE;	
	
	if (Scramble)
		{
		voice_set = 1;
		}	
	else
		{
		Disable(dp,ids[VoiceSet]);
		voice_set = 2;
		}

	// initialize comminications with the device
	state = doc->openInputDevice(0,0,0);
	if (state != MCO_SUCCESS) McoErrorAlert(state);
	
	// initialize the big gworld 
	GetDItem (dp, ids[Strip_Rect], &iType, (Handle*)&iHandle, &iRect);
	tRect = iRect;
	OffsetRect(&tRect,-iRect.left,-iRect.top);
	error = NewGWorld( &BigGW, 32, &tRect, 0, 0, 0 );
	if (error != 0) 
		{
		delete this;
		return;
		} 
	GetGWorld(&oldGW,&oldGD);
	SetGWorld(BigGW,nil);	
	
	
//	GetBackColor(&oldbackcolor);
	GetForeColor(&oldforecolor);
	c.red = 65535;
	c.green = 65535;
	c.blue = 65535;
	RGBBackColor(&c);
	c.red = 0;
	c.green = 0;
	c.blue = 0;
	RGBForeColor(&c);		
	bigPixMap = GetGWorldPixMap ( BigGW );
	if (LockPixels ( bigPixMap ))	EraseRect( &tRect );
	
	SetGWorld(oldGW,oldGD);	
//	RGBBackColor(&oldbackcolor);
	RGBForeColor(&oldforecolor);	

//	SetPort(oldP);
		
	GetDItem (dp, ids[Patch_Rect], &iType, (Handle*)&iHandle, &pRect);
	num_display_patch = (iRect.bottom-iRect.top)/(pRect.bottom-pRect.top);
	top_patch = 0;
						
//init the static members
	//current_patch = total_patches-1;
	//current_patch = 0;
	current_patch = 0;
	current_strip = 0;
	current_sheet = 0;
 		
 	_done = 0;
 	_waiting = 0;
	
	
	SetSheetStripText();
	
	current_top = current_patch - 2*num_display_patch/3;
	current_bottom = current_top + num_display_patch - 1;
	if (current_top < 0) 
		{
		current_top = 0;
		current_bottom = current_top + num_display_patch - 1;
		}
	if (current_bottom >= total_patches-1)
		{
		current_bottom = total_patches - 1;
		current_top = current_bottom - num_display_patch + 1;
		}
	
	current_disp = 2*num_display_patch/3;
	
	init();	
	getpatchRGB();
	
	
	Disable(dp,ids[Redo]);

	
	GetDItem (dp, ids[Slider], &iType, (Handle*)&iHandle, &pRect);
	SetCtlMin((ControlHandle)iHandle,0);
	SetCtlMax((ControlHandle)iHandle,total_patches-1);
	
	GetDItem(dp, ids[VoiceSet], &iType, (Handle*)&iHandle, &pRect);
	SetCtlValue((ControlHandle)iHandle,1);
	//voice_set = 1;
	checkFinished();
	DrawWindow();
}	
Пример #28
0
//--------------------------------------------------------------------
bool ofVideoGrabber::initGrabber(int w, int h, bool setUseTexture){

	bUseTexture = setUseTexture;

	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_QUICKTIME
	//---------------------------------

		//---------------------------------- 1 - open the sequence grabber
		if( !qtInitSeqGrabber() ){
			ofLog(OF_LOG_ERROR, "error: unable to initialize the seq grabber");
			return false;
		}

		//---------------------------------- 2 - set the dimensions
		width 		= w;
		height 		= h;

		MacSetRect(&videoRect, 0, 0, width, height);

		//---------------------------------- 3 - buffer allocation
		// Create a buffer big enough to hold the video data,
		// make sure the pointer is 32-byte aligned.
		// also the rgb image that people will grab

		offscreenGWorldPixels 	= (unsigned char*)malloc(4 * width * height + 32);
		pixels					= new unsigned char[width*height*3];
		QTNewGWorldFromPtr (&videogworld, k32ARGBPixelFormat, &videoRect, NULL, NULL, 0, offscreenGWorldPixels, 4 * width);
		LockPixels(GetGWorldPixMap(videogworld));
		SetGWorld (videogworld, NULL);
		SGSetGWorld(gSeqGrabber, videogworld, nil);


		//---------------------------------- 4 - device selection
		bool didWeChooseADevice = bChooseDevice;
		bool deviceIsSelected	=  false;

		//if we have a device selected then try first to setup
		//that device
		if(didWeChooseADevice){
			deviceIsSelected = qtSelectDevice(deviceID, true);
			if(!deviceIsSelected && bVerbose) ofLog(OF_LOG_WARNING, "unable to open device[%i] - will attempt other devices", deviceID);
		}

		//if we couldn't select our required device
		//or we aren't specifiying a device to setup
		//then lets try to setup ANY device!
		if(deviceIsSelected == false){
			//lets list available devices
			listDevices();

			setDeviceID(0);
			deviceIsSelected = qtSelectDevice(deviceID, false);
		}

		//if we still haven't been able to setup a device
		//we should error and stop!
		if( deviceIsSelected == false){
			goto bail;
		}

		//---------------------------------- 5 - final initialization steps
		OSStatus err;

	 	err = SGSetChannelUsage(gVideoChannel,seqGrabPreview);
		if ( err != noErr ) goto bail;

		err = SGSetChannelBounds(gVideoChannel, &videoRect);
		if ( err != noErr ) goto bail;

		err = SGPrepare(gSeqGrabber,  true, false); //theo swapped so preview is true and capture is false
		if ( err != noErr ) goto bail;

		err = SGStartPreview(gSeqGrabber);
		if ( err != noErr ) goto bail;

		bGrabberInited = true;
		loadSettings();

		ofLog(OF_LOG_NOTICE,"end setup ofVideoGrabber");
		ofLog(OF_LOG_NOTICE,"-------------------------------------\n");


		//---------------------------------- 6 - setup texture if needed

		if (bUseTexture){
			// create the texture, set the pixels to black and
			// upload them to the texture (so at least we see nothing black the callback)
			tex.allocate(width,height,GL_RGB);
			memset(pixels, 0, width*height*3);
			tex.loadData(pixels, width, height, GL_RGB);
		}

		// we are done
		return true;


		//--------------------- (bail) something's wrong -----
		bail:

			ofLog(OF_LOG_ERROR, "***** ofVideoGrabber error *****");
			ofLog(OF_LOG_ERROR, "-------------------------------------\n");

			//if we don't close this - it messes up the next device!
			if(bSgInited) qtCloseSeqGrabber();

			bGrabberInited = false;
			return false;

	//---------------------------------
	#endif
	//---------------------------------


	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_DIRECTSHOW
	//---------------------------------

		if (bChooseDevice){
			device = deviceID;
			ofLog(OF_LOG_NOTICE, "choosing %i", deviceID);
		} else {
			device = 0;
		}

		width = w;
		height = h;
		bGrabberInited = false;

		bool bOk = VI.setupDevice(device, width, height);

		int ourRequestedWidth = width;
		int ourRequestedHeight = height;

		if (bOk == true){
			bGrabberInited = true;
			width 	= VI.getWidth(device);
			height 	= VI.getHeight(device);

			if (width == ourRequestedWidth && height == ourRequestedHeight){
				bDoWeNeedToResize = false;
			} else {
				bDoWeNeedToResize = true;
				width = ourRequestedWidth;
				height = ourRequestedHeight;
			}


			pixels	= new unsigned char[width * height * 3];

			if (bUseTexture){
				// create the texture, set the pixels to black and
				// upload them to the texture (so at least we see nothing black the callback)
				tex.allocate(width,height,GL_RGB);
				memset(pixels, 0, width*height*3);
				tex.loadData(pixels, width, height, GL_RGB);
			}

			return true;
		} else {
			ofLog(OF_LOG_ERROR, "error allocating a video device");
			ofLog(OF_LOG_ERROR, "please check your camera with AMCAP or other software");
			bGrabberInited = false;
			return false;
		}

	//---------------------------------
	#endif
	//---------------------------------



	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_UNICAP
	//--------------------------------
		if( !bGrabberInited ){
			if ( !bChooseDevice ){
				deviceID = 0;
			}

			width 	= w;
			height 	= h;
			pixels	= new unsigned char[width * height * 3];

			if (bUseTexture){
				// create the texture, set the pixels to black and
				// upload them to the texture (so at least we see nothing black the callback)
				tex.allocate(width,height,GL_RGB);
				memset(pixels, 0, width*height*3);
				tex.loadData(pixels, width, height, GL_RGB);
			}

			bGrabberInited = ucGrabber.open_device (deviceID);
			if( bGrabberInited ){
			ofLog(OF_LOG_NOTICE, "choosing device %i: %s", deviceID,ucGrabber.device_identifier());
				ucGrabber.set_format(w,h);
				ucGrabber.start_capture();
			}

		}
			return bGrabberInited;
	//---------------------------------
	#endif
	//---------------------------------

	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_GSTREAMER
	//--------------------------------
		if(gstUtils.initGrabber(w,h)){
			if ( !bChooseDevice ){
				deviceID = 0;
			}

			width 	= w;
			height 	= h;
			if (bUseTexture){
				// create the texture, set the pixels to black and
				// upload them to the texture (so at least we see nothing black the callback)
				tex.allocate(width,height,GL_RGB);
				tex.loadData(gstUtils.getPixels(), width, height, GL_RGB);
			}
			bGrabberInited = true;
			ofLog(OF_LOG_VERBOSE, "ofVideoGrabber: initied");
		}else{
			bGrabberInited = false;
			ofLog(OF_LOG_ERROR, "ofVideoGrabber: couldn't init");
		}
		return bGrabberInited;


	//---------------------------------
	#endif
	//---------------------------------

	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_V4L
	//--------------------------------
		if (bChooseDevice){
			device = deviceID;
		} else {
			device = 0;
		}
		sprintf(dev_name, "/dev/video%i", device);
		ofLog(OF_LOG_NOTICE, "choosing device %s",dev_name);

		bool bOk = initV4L(w, h, dev_name);

		if (bOk == true){
			bV4LGrabberInited = true;
			width 	= getV4L_Width();
			height 	= getV4L_Height();
			pixels	= new unsigned char[width * height * 3];

			if (bUseTexture){
				// create the texture, set the pixels to black and
				// upload them to the texture (so at least we see nothing black the callback)
				tex.allocate(width,height,GL_RGB);
				//memset(pixels, 0, width*height*3);
				//tex.loadData(pixels, width, height, GL_RGB);
			}

			ofLog(OF_LOG_NOTICE, "success allocating a video device ");
			return true;
		} else {
			ofLog(OF_LOG_ERROR, "error allocating a video device");
			ofLog(OF_LOG_ERROR, "please check your camera and verify that your driver is correctly installed.");
			return false;
		}	//---------------------------------


	//---------------------------------
	#endif
	//---------------------------------



}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::initGrabber(int w, int h){

	//---------------------------------
	#ifdef OF_VIDEO_CAPTURE_QUICKTIME
	//---------------------------------

		//---------------------------------- 1 - open the sequence grabber
		if( !qtInitSeqGrabber() ){
			ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to initialize the seq grabber";
			return false;
		}

		//---------------------------------- 2 - set the dimensions
		//width 		= w;
		//height 		= h;

		MacSetRect(&videoRect, 0, 0, w, h);

		//---------------------------------- 3 - buffer allocation
		// Create a buffer big enough to hold the video data,
		// make sure the pointer is 32-byte aligned.
		// also the rgb image that people will grab

		offscreenGWorldPixels 	= (unsigned char*)malloc(4 * w * h + 32);
		pixels.allocate(w, h, OF_IMAGE_COLOR);
		
		#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
			QTNewGWorldFromPtr (&(videogworld), k32ARGBPixelFormat, &(videoRect), NULL, NULL, 0, (offscreenGWorldPixels), 4 * w);		
		#else
			QTNewGWorldFromPtr (&(videogworld), k24RGBPixelFormat, &(videoRect), NULL, NULL, 0, (pixels.getPixels()), 3 * w);
		#endif		
		
		LockPixels(GetGWorldPixMap(videogworld));
		SetGWorld (videogworld, NULL);
		SGSetGWorld(gSeqGrabber, videogworld, nil);

		
		//---------------------------------- 4 - device selection
		bool didWeChooseADevice = bChooseDevice;
		bool deviceIsSelected	=  false;

		//if we have a device selected then try first to setup
		//that device
		if(didWeChooseADevice){
			deviceIsSelected = qtSelectDevice(deviceID, true);
			if(!deviceIsSelected && bVerbose)
				ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to open device[" << deviceID << "], will attempt other devices";
		}

		//if we couldn't select our required device
		//or we aren't specifiying a device to setup
		//then lets try to setup ANY device!
		if(deviceIsSelected == false){
			//lets list available devices
			listDevices();

			setDeviceID(0);
			deviceIsSelected = qtSelectDevice(deviceID, false);
		}

		//if we still haven't been able to setup a device
		//we should error and stop!
		if( deviceIsSelected == false){
			goto bail;
		}

		//---------------------------------- 5 - final initialization steps
		OSStatus err;

	 	err = SGSetChannelUsage(gVideoChannel,seqGrabPreview);
		if ( err != noErr ) goto bail;

	
		//----------------- callback method for notifying new frame
		err = SGSetChannelRefCon(gVideoChannel, (long)&bHavePixelsChanged );
		if(!err) {

			VideoBottles vb; 
			/* get the current bottlenecks */ 
			vb.procCount = 9; 
			err = SGGetVideoBottlenecks(gVideoChannel, &vb); 
			if (!err) { 			
				myGrabCompleteProc = NewSGGrabCompleteBottleUPP(frameIsGrabbedProc);
				vb.grabCompleteProc = myGrabCompleteProc;
			
				/* add our GrabFrameComplete function */ 
				err = SGSetVideoBottlenecks(gVideoChannel, &vb); 	
			}
		
		}
				
		err = SGSetChannelBounds(gVideoChannel, &videoRect);
		if ( err != noErr ) goto bail;

		err = SGPrepare(gSeqGrabber,  true, false); //theo swapped so preview is true and capture is false
		if ( err != noErr ) goto bail;

		err = SGStartPreview(gSeqGrabber);
		if ( err != noErr ) goto bail;

		bGrabberInited = true;
		loadSettings();
		
		if( attemptFramerate >= 0 ){
			err = SGSetFrameRate(gVideoChannel, IntToFixed(attemptFramerate) );
			if ( err != noErr ){
				ofLogError("ofQuickTimeGrabber") << "initGrabber: couldn't setting framerate to " << attemptFramerate << ": OSStatus " << err;
			}		
		}
		
		ofLogNotice("ofQuickTimeGrabber") << "           inited grabbed            ";
		ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";

		// we are done
		return true;


		//--------------------- (bail) something's wrong -----
		bail:

			ofLogError("ofQuickTimeGrabber") << "***** ofQuickTimeGrabber error *****";
			ofLogError("ofQuickTimeGrabber") << "------------------------------------";

			//if we don't close this - it messes up the next device!
			if(bSgInited) qtCloseSeqGrabber();

			bGrabberInited = false;
			return false;
			
	//---------------------------------
	#else
	//---------------------------------
		return false;
	//---------------------------------
	#endif
	//---------------------------------

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

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

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

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

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

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

		if (energyPlotWindow) {
			if (KillEPlot) {
				delete energyPlotWindow;
				energyPlotWindow = NULL;
			} else {
				energyPlotWindow->SetSize(savedEPlotWidth, savedEPlotHeight);
				energyPlotWindow->FrameChanged();
				energyPlotWindow->Show(true);
			}
		}
	}
	ExitMovies();	//Close out quicktime as we are done with it for now
	FinishOperation();
}