/* Copyright (c) 2004-2006, Marcus Müller . Copyright (c) 2006, Michael Maier . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Mulle kybernetiK nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "OpenGLView.h" #import #import #import #import #import #include "common.h" #include "LiveVideo.h" // The renderer output callback function. // The display link invokes this callback whenever it wants you to output a frame. static CVReturn MyOutputCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *inNow, const CVTimeStamp *inOutputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext) { return [(OpenGLView *)displayLinkContext outputForTime:inOutputTime]; } @implementation OpenGLView - (id)initWithFrame:(NSRect)_rect { self= [super initWithFrame:_rect]; if (self) { // don't forget the lock instance! self->lock= [[NSRecursiveLock alloc] init]; } return self; } /** * initialize OpenGL */ - (void)initOpenGL { NSNotificationCenter *nc; // set up OpenGL NSOpenGLPixelFormatAttribute attributes[] = { NSOpenGLPFAColorSize, 24, NSOpenGLPFAAlphaSize, 8, NSOpenGLPFADepthSize, 32, 0 }; self->pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:(NSOpenGLPixelFormatAttribute*) attributes]; self->context = [[NSOpenGLContext alloc] initWithFormat:self->pixelFormat shareContext:nil]; if ([self useOpenGLForDrawing]) [self->context setView:self]; // set up CoreImage context /* Create CGColorSpaceRef */ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); /* Create CIContext */ NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:(id)colorSpace, kCIContextOutputColorSpace, (id)colorSpace, kCIContextWorkingColorSpace, nil]; self->ciContext = [[CIContext contextWithCGLContext:(CGLContextObj)[self->context CGLContextObj] pixelFormat:(CGLPixelFormatObj) [self->pixelFormat CGLPixelFormatObj] options:options] retain]; CGColorSpaceRelease(colorSpace); // register for changing the view's size nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(update:) name:NSViewGlobalFrameDidChangeNotification object:self]; // update OpenGL [self update:nil]; // initialize the display link [self initDisplayLink]; // start the live video [self startVideo:self]; } /** * Initialization for display link */ - (void)initDisplayLink { // Create display link CVDisplayLinkCreateWithActiveCGDisplays(&self->displayLink); CVDisplayLinkSetCurrentCGDisplay(self->displayLink, kCGDirectMainDisplay); CVDisplayLinkSetOutputCallback(self->displayLink, &MyOutputCallback, self); CVDisplayLinkStart(self->displayLink); // Create visual context QTOpenGLTextureContextCreate(NULL, (CGLContextObj)[self->context CGLContextObj], (CGLPixelFormatObj)[self->pixelFormat CGLPixelFormatObj], nil, &self->textureContext); self->currentFrame = nil; self->liveVideo = nil; } - (void)setShouldFlipImage:(BOOL)_yn { self->flipImage = _yn; } - (BOOL)shouldFlipImage { return self->flipImage; } /** * This method is called if the view's size is changed. */ -(void)update:(NSNotification*)_notif { [self->context makeCurrentContext]; [self->context update]; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); GLdouble width= [self bounds].size.width; GLdouble height= [self bounds].size.height; glViewport( 0, 0, width, height ); } /** * Cleanup */ - (void)dealloc { // remove display link CVDisplayLinkStop(self->displayLink); CVDisplayLinkRelease(self->displayLink); // remove live video [self disposeVideo]; [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove texture CVOpenGLTextureRelease(self->currentFrame); // remove CoreImage context [self->ciContext release]; // remove openGL [self->context release]; [self->pixelFormat release]; QTVisualContextRelease(self->textureContext); // remove lock [self->lock release]; [super dealloc]; } /** * Dispose the LiveVideo object. */ - (void)disposeVideo { if (self->liveVideo) [self->liveVideo release]; self->liveVideo = nil; } /** * How to render? Return YES for OpenGL. */ - (BOOL)useOpenGLForDrawing { return YES; } #pragma mark display link call back /** * Called by the display link thread */ - (CVReturn)outputForTime:(const CVTimeStamp*)timeStamp { NSAutoreleasePool *pool; pool = [[NSAutoreleasePool alloc] init]; // Check for new textures if (self->textureContext != nil && QTVisualContextIsNewImageAvailable(self->textureContext, timeStamp)) { CVOpenGLTextureRef newTexture; if (QTVisualContextCopyImageForTime(self->textureContext, NULL, timeStamp, &newTexture) == noErr) { CVOpenGLTextureRelease(self->currentFrame); self->currentFrame = newTexture; // if we use OpenGL then we have to draw in this thread if ([self useOpenGLForDrawing]) { [self drawRect:[self frame]]; } else { // otherwise mark it dirty [self setNeedsDisplay:YES]; } } } [pool release]; return kCVReturnSuccess; } /** * Returns the CoreImage context. */ - (CIContext*)ciContext { return self->ciContext; } /** * This method draws the content. It is called threadsafe from the * drawRect method. All initializations are done. */ - (void)openGLdrawRect:(NSRect)rect { // set context to current [self->context makeCurrentContext]; // clear color for OpenGL glClearColor(0, 0, 0, 0); // only color buuter glClear( GL_COLOR_BUFFER_BIT ); if (self->currentFrame) { // now we can draw the OpenGL texture // first we get some texture data for OpenGL GLenum target= CVOpenGLTextureGetTarget( self->currentFrame ); GLint name= CVOpenGLTextureGetName( self->currentFrame ); // get the coordinates of the texture for drawing GLfloat topLeft[2], topRight[2], bottomRight[2], bottomLeft[2]; CVOpenGLTextureGetCleanTexCoords( self->currentFrame, bottomLeft, bottomRight, topRight, topLeft); glPushMatrix(); // flip horizontally if asked so if (self->flipImage) glScaled(-1, 1, 1); // Draw texture! glEnable( target ); glBindTexture( target, name ); glBegin(GL_QUADS); glTexCoord2fv(bottomLeft); glVertex2i(-1, -1); glTexCoord2fv(topLeft); glVertex2i(-1, 1); glTexCoord2fv(topRight); glVertex2i( 1, 1); glTexCoord2fv(bottomRight); glVertex2i( 1, -1); glEnd(); glDisable(target); glPopMatrix(); } glFlush(); } /** * Called after rendering to cleanup */ - (void)flush { [self->context flushBuffer]; QTVisualContextTask(self->textureContext); } #pragma mark overwritten - (void)drawRect:(NSRect)rect { if (self->lock) { [self->lock lock]; if (!self->context) [self initOpenGL]; [self openGLdrawRect:rect]; [self flush]; [self->lock unlock]; } else { NSLog(@"Warning: no lock initiated!"); } } #pragma mark IBAction /** * Start the LiveVideo */ - (IBAction)startVideo:(id)sender { if (self->liveVideo == nil) self->liveVideo = [[LiveVideo alloc] initWithVisualContext:self->textureContext]; } /** * Stops the LiveVideo, the method calls disposeVideo. */ - (IBAction)stopVideo:(id)sender { [self disposeVideo]; } @end /* OpenGLView */