Directly mark jpeg_buf_src() as void instead of using some indirection marcro.
[mplayer.git] / libvo / vo_corevideo.m
blob568fd7b802e2dc9e2dba16c6bfdb1c79b7047d1c
1 /*
2  * CoreVideo video output driver
3  * Copyright (c) 2005 Nicolas Plourde <nicolasplourde@gmail.com>
4  *
5  * This file is part of MPlayer.
6  *
7  * MPlayer is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * MPlayer is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
22 #import "vo_corevideo.h"
23 #include <sys/types.h>
24 #include <sys/ipc.h>
25 #include <sys/mman.h>
26 #include <unistd.h>
27 #include <CoreServices/CoreServices.h>
28 //special workaround for Apple bug #6267445
29 //(OSServices Power API disabled in OSServices.h for 64bit systems)
30 #ifndef __POWER__
31 #include <CoreServices/../Frameworks/OSServices.framework/Headers/Power.h>
32 #endif
34 //MPLAYER
35 #include "config.h"
36 #include "fastmemcpy.h"
37 #include "video_out.h"
38 #include "video_out_internal.h"
39 #include "aspect.h"
40 #include "mp_msg.h"
41 #include "m_option.h"
42 #include "mp_fifo.h"
43 #include "libvo/sub.h"
44 #include "subopt-helper.h"
46 #include "input/input.h"
47 #include "input/mouse.h"
49 #include "osdep/keycodes.h"
50 #include "osx_common.h"
52 //Cocoa
53 NSDistantObject *mplayerosxProxy;
54 id <MPlayerOSXVOProto> mplayerosxProto;
55 MPlayerOpenGLView *mpGLView;
56 NSAutoreleasePool *autoreleasepool;
57 OSType pixelFormat;
59 //shared memory
60 BOOL shared_buffer = false;
61 #define DEFAULT_BUFFER_NAME "mplayerosx"
62 static char *buffer_name;
64 //Screen
65 int screen_id = -1;
66 NSRect screen_frame;
67 NSScreen *screen_handle;
68 NSArray *screen_array;
70 //image
71 unsigned char *image_data;
72 // For double buffering
73 static uint8_t image_page = 0;
74 static unsigned char *image_datas[2];
76 static uint32_t image_width;
77 static uint32_t image_height;
78 static uint32_t image_depth;
79 static uint32_t image_bytes;
80 static uint32_t image_format;
82 //vo
83 static int isFullscreen;
84 static int isOntop;
85 static int isRootwin;
87 static float winAlpha = 1;
88 static int int_pause = 0;
90 static BOOL isLeopardOrLater;
92 static vo_info_t info =
94         "Mac OS X Core Video",
95         "corevideo",
96         "Nicolas Plourde <nicolas.plourde@gmail.com>",
97         ""
100 LIBVO_EXTERN(corevideo)
102 static void draw_alpha(int x0, int y0, int w, int h, unsigned char *src, unsigned char *srca, int stride)
104         switch (image_format)
105         {
106                 case IMGFMT_RGB24:
107                         vo_draw_alpha_rgb24(w,h,src,srca,stride,image_data+3*(y0*image_width+x0),3*image_width);
108                         break;
109                 case IMGFMT_ARGB:
110                 case IMGFMT_BGRA:
111                         vo_draw_alpha_rgb32(w,h,src,srca,stride,image_data+4*(y0*image_width+x0),4*image_width);
112                         break;
113                 case IMGFMT_YUY2:
114                         vo_draw_alpha_yuy2(w,h,src,srca,stride,image_data + (x0 + y0 * image_width) * 2,image_width*2);
115                         break;
116         }
119 static void update_screen_info(void)
121         if (screen_id == -1 && xinerama_screen > -1)
122                 screen_id = xinerama_screen;
124         screen_array = [NSScreen screens];
125         if(screen_id < (int)[screen_array count])
126         {
127                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
128         }
129         else
130         {
131                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
132                 screen_handle = [screen_array objectAtIndex:0];
133                 screen_id = -1;
134         }
136         screen_frame = ![mpGLView window] || screen_id >= 0 ? [screen_handle frame] : [[[mpGLView window] screen] frame];
137         vo_screenwidth = screen_frame.size.width;
138         vo_screenheight = screen_frame.size.height;
139         xinerama_x = xinerama_y = 0;
140         aspect_save_screenres(vo_screenwidth, vo_screenheight);
143 static void free_file_specific(void)
145         if(shared_buffer)
146         {
147                 [mplayerosxProto stop];
148                 mplayerosxProto = nil;
149                 [mplayerosxProxy release];
150                 mplayerosxProxy = nil;
152                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
153                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
155                 if (shm_unlink(buffer_name) == -1)
156                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
157     } else {
158         free(image_datas[0]);
159         if (vo_doublebuffering)
160             free(image_datas[1]);
161         image_datas[0] = NULL;
162         image_datas[1] = NULL;
163         image_data = NULL;
164     }
167 static int config(uint32_t width, uint32_t height, uint32_t d_width, uint32_t d_height, uint32_t flags, char *title, uint32_t format)
169         free_file_specific();
171         //misc mplayer setup
172         image_width = width;
173         image_height = height;
174         switch (image_format)
175         {
176                 case IMGFMT_RGB24:
177                         image_depth = 24;
178                         break;
179                 case IMGFMT_ARGB:
180                 case IMGFMT_BGRA:
181                         image_depth = 32;
182                         break;
183                 case IMGFMT_YUY2:
184                         image_depth = 16;
185                         break;
186         }
187         image_bytes = (image_depth + 7) / 8;
189         if(!shared_buffer)
190         {
191                 config_movie_aspect((float)d_width/d_height);
193                 vo_dwidth  = d_width  *= mpGLView->winSizeMult;
194                 vo_dheight = d_height *= mpGLView->winSizeMult;
196                 image_data = malloc(image_width*image_height*image_bytes);
197                 image_datas[0] = image_data;
198                 if (vo_doublebuffering)
199                         image_datas[1] = malloc(image_width*image_height*image_bytes);
200                 image_page = 0;
202                 vo_fs = flags & VOFLAG_FULLSCREEN;
204                 //config OpenGL View
205                 [mpGLView config];
206                 [mpGLView reshape];
207         }
208         else
209         {
210                 int shm_fd;
211                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
212                                 "named \"%s\"\n",buffer_name);
214                 // create shared memory
215                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
216                 if (shm_fd == -1)
217                 {
218                         mp_msg(MSGT_VO, MSGL_FATAL,
219                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
220                         return 1;
221                 }
224                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
225                 {
226                         mp_msg(MSGT_VO, MSGL_FATAL,
227                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
228                         close(shm_fd);
229                         shm_unlink(buffer_name);
230                         return 1;
231                 }
233                 image_data = mmap(NULL, image_width*image_height*image_bytes,
234                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
235                 close(shm_fd);
237                 if (image_data == MAP_FAILED)
238                 {
239                         mp_msg(MSGT_VO, MSGL_FATAL,
240                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
241                         shm_unlink(buffer_name);
242                         return 1;
243                 }
245                 //connect to mplayerosx
246                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
247                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
248                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
249                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
250                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:d_width*100/d_height];
251                 }
252                 else {
253                         [mplayerosxProxy release];
254                         mplayerosxProxy = nil;
255                         mplayerosxProto = nil;
256                 }
257         }
258         return 0;
261 static void check_events(void)
263         if (mpGLView)
264                 [mpGLView check_events];
267 static void draw_osd(void)
269         vo_draw_text(image_width, image_height, draw_alpha);
272 static void flip_page(void)
274         if(shared_buffer) {
275                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
276                 [mplayerosxProto render];
277                 [pool release];
278         } else {
279                 [mpGLView setCurrentTexture];
280                 [mpGLView render];
281                 if (vo_doublebuffering) {
282                         image_page = 1 - image_page;
283                         image_data = image_datas[image_page];
284                 }
285         }
288 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
290         return 0;
294 static int draw_frame(uint8_t *src[])
296         return 0;
299 static uint32_t draw_image(mp_image_t *mpi)
301         memcpy_pic(image_data, mpi->planes[0], image_width*image_bytes, image_height, image_width*image_bytes, mpi->stride[0]);
303         return 0;
306 static int query_format(uint32_t format)
308     const int supportflags = VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
309         image_format = format;
311     switch(format)
312         {
313                 case IMGFMT_YUY2:
314                         pixelFormat = kYUVSPixelFormat;
315                         return supportflags;
317                 case IMGFMT_RGB24:
318                         pixelFormat = k24RGBPixelFormat;
319                         return supportflags;
321                 case IMGFMT_ARGB:
322                         pixelFormat = k32ARGBPixelFormat;
323                         return supportflags;
325                 case IMGFMT_BGRA:
326                         pixelFormat = k32BGRAPixelFormat;
327                         return supportflags;
328     }
329     return 0;
332 static void uninit(void)
334     SetSystemUIMode( kUIModeNormal, 0);
335     CGDisplayShowCursor(kCGDirectMainDisplay);
337     free_file_specific();
339     if(mpGLView)
340     {
341         NSAutoreleasePool *finalPool;
342         mpGLView = nil;
343         [autoreleasepool release];
344         finalPool = [[NSAutoreleasePool alloc] init];
345         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
346         [finalPool release];
347     }
349     if (buffer_name) free(buffer_name);
350     buffer_name = NULL;
353 static const opt_t subopts[] = {
354 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
355 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
356 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
357 {NULL}
360 static int preinit(const char *arg)
363         // set defaults
364         screen_id = -1;
365         shared_buffer = false;
366         buffer_name = NULL;
368         if (subopt_parse(arg, subopts) != 0) {
369                 mp_msg(MSGT_VO, MSGL_FATAL,
370                                 "\n-vo corevideo command line help:\n"
371                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
372                                 "\nOptions:\n"
373                                 "  device_id=<0-...>\n"
374                                 "    Set screen device ID for fullscreen.\n"
375                                 "  shared_buffer\n"
376                                 "    Write output to a shared memory buffer instead of displaying it.\n"
377                                 "  buffer_name=<name>\n"
378                                 "    Name of the shared buffer created with shm_open() as well as\n"
379                                 "    the name of the NSConnection MPlayer will try to open.\n"
380                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
381                                 "\n" );
382                 return -1;
383         }
385         autoreleasepool = [[NSAutoreleasePool alloc] init];
387         if (!buffer_name)
388                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
389         else
390                 shared_buffer = true;
392         if(!shared_buffer)
393         {
394                 NSApplicationLoad();
395                 NSApp = [NSApplication sharedApplication];
396                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
398                 osx_foreground_hack();
400                 if(!mpGLView)
401                 {
402                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
403                         [mpGLView autorelease];
404                 }
406                 [mpGLView display];
407                 [mpGLView preinit];
408         }
410     return 0;
413 static int control(uint32_t request, void *data, ...)
415         switch (request)
416         {
417                 case VOCTRL_DRAW_IMAGE: return draw_image(data);
418                 case VOCTRL_PAUSE: return int_pause = 1;
419                 case VOCTRL_RESUME: return int_pause = 0;
420                 case VOCTRL_QUERY_FORMAT: return query_format(*((uint32_t*)data));
421                 case VOCTRL_ONTOP: vo_ontop = (!(vo_ontop)); if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
422                 case VOCTRL_ROOTWIN: vo_rootwin = (!(vo_rootwin)); [mpGLView rootwin]; return VO_TRUE;
423                 case VOCTRL_FULLSCREEN: vo_fs = (!(vo_fs)); if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
424                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
425                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
426                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
427         }
428         return VO_NOTIMPL;
431 //////////////////////////////////////////////////////////////////////////
432 // NSOpenGLView Subclass
433 //////////////////////////////////////////////////////////////////////////
434 @implementation MPlayerOpenGLView
435 - (void) preinit
437         NSOpenGLContext *glContext;
438         GLint swapInterval = 1;
439         CVReturn error;
441         //init menu
442         [self initMenu];
444         //create window
445         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
446                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
447                                                                 backing:NSBackingStoreBuffered defer:NO];
449         [window autorelease];
450         [window setDelegate:mpGLView];
451         [window setContentView:mpGLView];
452         [window setInitialFirstResponder:mpGLView];
453         [window setAcceptsMouseMovedEvents:YES];
454     [window setTitle:@"MPlayer - The Movie Player"];
456         isFullscreen = 0;
457         winSizeMult = 1;
459         //create OpenGL Context
460         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
462         [self setOpenGLContext:glContext];
463         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
464         [glContext setView:self];
465         [glContext makeCurrentContext];
466         [glContext release];
468         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
469         if(error != kCVReturnSuccess)
470                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
473 - (void) releaseVideoSpecific
475         CVPixelBufferRelease(frameBuffers[0]);
476         frameBuffers[0] = NULL;
477         CVPixelBufferRelease(frameBuffers[1]);
478         frameBuffers[1] = NULL;
479         CVOpenGLTextureRelease(texture);
480         texture = NULL;
483 - (void) dealloc
485         [self releaseVideoSpecific];
486         CVOpenGLTextureCacheRelease(textureCache);
487         textureCache = NULL;
488         [self setOpenGLContext:nil];
489         [super dealloc];
492 - (void) config
494         NSRect visibleFrame;
495         CVReturn error = kCVReturnSuccess;
497         //config window
498         [window setContentSize:NSMakeSize(vo_dwidth, vo_dheight)];
500         // Use visibleFrame to position the window taking the menu bar and dock into account.
501         // Also flip vo_dy since the screen origin is in the bottom left on OSX.
502         if (screen_id < 0)
503                 visibleFrame = [[[mpGLView window] screen] visibleFrame];
504         else
505                 visibleFrame = [[[NSScreen screens] objectAtIndex:screen_id] visibleFrame];
506         [window setFrameTopLeftPoint:NSMakePoint(
507                 visibleFrame.origin.x + vo_dx,
508                 visibleFrame.origin.y + visibleFrame.size.height - vo_dy)];
510         [self releaseVideoSpecific];
511         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
512         if(error != kCVReturnSuccess)
513                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
514         if (vo_doublebuffering) {
515                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
516                 if(error != kCVReturnSuccess)
517                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
518         }
520         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
521         if(error != kCVReturnSuccess)
522                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
524         //show window
525         [window makeKeyAndOrderFront:mpGLView];
527         if(vo_rootwin)
528                 [mpGLView rootwin];
530         if(vo_fs)
531                 [mpGLView fullscreen: NO];
533         if(vo_ontop)
534                 [mpGLView ontop];
538         Init Menu
540 - (void)initMenu
542         NSMenu *menu, *aspectMenu;
543         NSMenuItem *menuItem;
545         [NSApp setMainMenu:[[NSMenu alloc] init]];
547 //Create Movie Menu
548         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
549         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
550         kHalfScreenCmd = menuItem;
551         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
552         kNormalScreenCmd = menuItem;
553         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
554         kDoubleScreenCmd = menuItem;
555         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
556         kFullScreenCmd = menuItem;
557         menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [menu addItem:menuItem];
559                 aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
560                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
561                 if(vo_keepaspect) [menuItem setState:NSOnState];
562                 kKeepAspectCmd = menuItem;
563                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
564                 if(vo_panscan) [menuItem setState:NSOnState];
565                 kPanScanCmd = menuItem;
566                 menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
567                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
568                 kAspectOrgCmd = menuItem;
569                 menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
570                 kAspectFullCmd = menuItem;
571                 menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
572                 kAspectWideCmd = menuItem;
573                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
574                 [menuItem setSubmenu:aspectMenu];
575                 [menu addItem:menuItem];
576                 [aspectMenu release];
578         //Add to menubar
579         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
580         [menuItem setSubmenu:menu];
581         [[NSApp mainMenu] addItem:menuItem];
583 //Create Window Menu
584         menu = [[NSMenu alloc] initWithTitle:@"Window"];
586         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
587         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
589         //Add to menubar
590         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
591         [menuItem setSubmenu:menu];
592         [[NSApp mainMenu] addItem:menuItem];
593         [NSApp setWindowsMenu:menu];
595         [menu release];
596         [menuItem release];
599 - (void)set_winSizeMult:(float)mult
601     NSRect frame;
602     int d_width, d_height;
603     aspect(&d_width, &d_height, A_NOZOOM);
605     if (isFullscreen) {
606         vo_fs = !vo_fs;
607         [self fullscreen:NO];
608     }
610     winSizeMult = mult;
611     frame.size.width  = d_width  * mult;
612     frame.size.height = d_height * mult;
613     [window setContentSize: frame.size];
614     [self reshape];
618         Menu Action
619  */
620 - (void)menuAction:(id)sender
622         if(sender == kQuitCmd)
623         {
624                 mplayer_put_key(KEY_ESC);
625         }
627         if(sender == kHalfScreenCmd)
628                 [self set_winSizeMult: 0.5];
629         if(sender == kNormalScreenCmd)
630                 [self set_winSizeMult: 1];
631         if(sender == kDoubleScreenCmd)
632                 [self set_winSizeMult: 2];
633         if(sender == kFullScreenCmd)
634         {
635                 vo_fs = (!(vo_fs));
636                 [self fullscreen:NO];
637         }
639         if(sender == kKeepAspectCmd)
640         {
641                 vo_keepaspect = (!(vo_keepaspect));
642                 if(vo_keepaspect)
643                         [kKeepAspectCmd setState:NSOnState];
644                 else
645                         [kKeepAspectCmd setState:NSOffState];
647                 [self reshape];
648         }
650         if(sender == kPanScanCmd)
651         {
652                 vo_panscan = (!(vo_panscan));
653                 if(vo_panscan)
654                         [kPanScanCmd setState:NSOnState];
655                 else
656                         [kPanScanCmd setState:NSOffState];
658                 [self panscan];
659         }
661         if(sender == kAspectOrgCmd)
662                 change_movie_aspect(-1);
664         if(sender == kAspectFullCmd)
665                 change_movie_aspect(4.0f/3.0f);
667         if(sender == kAspectWideCmd)
668                 change_movie_aspect(16.0f/9.0f);
672         Setup OpenGL
674 - (void)prepareOpenGL
676         glEnable(GL_BLEND);
677         glDisable(GL_DEPTH_TEST);
678         glDepthMask(GL_FALSE);
679         glDisable(GL_CULL_FACE);
680         [self reshape];
684         reshape OpenGL viewport
686 - (void)reshape
688         uint32_t d_width;
689         uint32_t d_height;
691         NSRect frame = [self frame];
692         vo_dwidth  = frame.size.width;
693         vo_dheight = frame.size.height;
695         glViewport(0, 0, frame.size.width, frame.size.height);
696         glMatrixMode(GL_PROJECTION);
697         glLoadIdentity();
698         glOrtho(0, frame.size.width, frame.size.height, 0, -1.0, 1.0);
699         glMatrixMode(GL_MODELVIEW);
700         glLoadIdentity();
702         //set texture frame
703         if(vo_keepaspect)
704         {
705                 aspect( (int *)&d_width, (int *)&d_height, A_WINZOOM);
707                 textureFrame = NSMakeRect((vo_dwidth - d_width) / 2, (vo_dheight - d_height) / 2, d_width, d_height);
708         }
709         else
710         {
711                 textureFrame = frame;
712         }
716         Render frame
718 - (void) render
720         int curTime;
722         glClear(GL_COLOR_BUFFER_BIT);
724         glEnable(CVOpenGLTextureGetTarget(texture));
725         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
727         glColor3f(1,1,1);
728         glBegin(GL_QUADS);
729         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
730         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
731         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
732         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
733         glEnd();
734         glDisable(CVOpenGLTextureGetTarget(texture));
736         //render resize box
737         if(!isFullscreen)
738         {
739                 NSRect frame = [self frame];
741                 glBegin(GL_LINES);
742                 glColor4f(0.2, 0.2, 0.2, 0.5);
743                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
744                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
745                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
747                 glColor4f(0.4, 0.4, 0.4, 0.5);
748                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
749                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
750                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
752                 glColor4f(0.6, 0.6, 0.6, 0.5);
753                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
754                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
755                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
756                 glEnd();
757         }
759         glFlush();
761         curTime  = TickCount()/60;
763         //automatically hide mouse cursor (and future on-screen control?)
764         if(isFullscreen && !mouseHide && !isRootwin)
765         {
766                 if( ((curTime - lastMouseHide) >= 5) || (lastMouseHide == 0) )
767                 {
768                         CGDisplayHideCursor(kCGDirectMainDisplay);
769                         mouseHide = TRUE;
770                         lastMouseHide = curTime;
771                 }
772         }
774         //update activity every 30 seconds to prevent
775         //screensaver from starting up.
776         if( ((curTime - lastScreensaverUpdate) >= 30) || (lastScreensaverUpdate == 0) )
777         {
778                 UpdateSystemActivity(UsrActivity);
779                 lastScreensaverUpdate = curTime;
780         }
784         Create OpenGL texture from current frame & set texco
786 - (void) setCurrentTexture
788         CVReturn error = kCVReturnSuccess;
790         CVOpenGLTextureRelease(texture);
791         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
792         if(error != kCVReturnSuccess)
793                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
795     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
799         redraw win rect
801 - (void) drawRect: (NSRect *) bounds
803         [self render];
807         Toggle Fullscreen
809 - (void) fullscreen: (BOOL) animate
811         static NSRect old_frame;
812         static NSRect old_view_frame;
814         panscan_calc();
816         //go fullscreen
817         if(vo_fs)
818         {
819                 if(!isRootwin)
820                 {
821                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
822                         CGDisplayHideCursor(kCGDirectMainDisplay);
823                         mouseHide = YES;
824                 }
826                 old_frame = [window frame];     //save main window size & position
827                 update_screen_info();
829                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
830                 old_view_frame = [self bounds];
832                 //fix origin for multi screen setup
833                 screen_frame.origin.x = 0;
834                 screen_frame.origin.y = 0;
835                 [self setFrame:screen_frame];
836                 [self setNeedsDisplay:YES];
837                 [window setHasShadow:NO];
838                 isFullscreen = 1;
839         }
840         else
841         {
842                 SetSystemUIMode( kUIModeNormal, 0);
844                 isFullscreen = 0;
845                 CGDisplayShowCursor(kCGDirectMainDisplay);
846                 mouseHide = NO;
848                 //revert window to previous setting
849                 [self setFrame:old_view_frame];
850                 [self setNeedsDisplay:YES];
851                 [window setHasShadow:YES];
852                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
853         }
857         Toggle ontop
859 - (void) ontop
861         if(vo_ontop)
862         {
863                 [window setLevel:NSScreenSaverWindowLevel];
864                 isOntop = YES;
865         }
866         else
867         {
868                 [window setLevel:NSNormalWindowLevel];
869                 isOntop = NO;
870         }
874         Toggle panscan
876 - (void) panscan
878         panscan_calc();
882         Toggle rootwin
883  */
884 - (void) rootwin
886         if(vo_rootwin)
887         {
888                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
889                 [window orderBack:self];
890                 isRootwin = YES;
891         }
892         else
893         {
894                 [window setLevel:NSNormalWindowLevel];
895                 isRootwin = NO;
896         }
900         Check event for new event
902 - (void) check_events
904         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001] inMode:NSEventTrackingRunLoopMode dequeue:YES];
905         if (event == nil)
906                 return;
907         [NSApp sendEvent:event];
908         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
909         // on Leopard, we have trouble to get the play window automatically focused
910         // when the app is actived. The Following code fix this problem.
911 #ifndef CONFIG_SDL
912         if (isLeopardOrLater && [event type] == NSAppKitDefined
913                         && [event subtype] == NSApplicationActivatedEventType) {
914                 [window makeMainWindow];
915                 [window makeKeyAndOrderFront:mpGLView];
916         }
917 #endif
921         From NSView, respond to key equivalents.
923 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
925         switch([theEvent keyCode])
926     {
927                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
928                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
929     }
930         return NO;
934         Process key event
936 - (void) keyDown: (NSEvent *) theEvent
938         int key = convert_key([theEvent keyCode], *[[theEvent characters] UTF8String]);
939         if (key != -1)
940         mplayer_put_key(key);
944         Process mouse button event
946 - (void) mouseMoved: (NSEvent *) theEvent
948         if(isFullscreen && !isRootwin)
949         {
950                 CGDisplayShowCursor(kCGDirectMainDisplay);
951                 mouseHide = NO;
952         }
953         if (enable_mouse_movements && !isRootwin) {
954                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
955                 if ([self mouse:p inRect:textureFrame]) {
956                         vo_mouse_movement(vo_fs ? p.x : p.x - textureFrame.origin.x,
957                                           vo_fs ? [self frame].size.height - p.y : NSMaxY(textureFrame) - p.y);
958                 }
959         }
962 - (void) mouseDown: (NSEvent *) theEvent
964         [self mouseEvent: theEvent];
967 - (void) mouseUp: (NSEvent *) theEvent
969         [self mouseEvent: theEvent];
972 - (void) rightMouseDown: (NSEvent *) theEvent
974         [self mouseEvent: theEvent];
977 - (void) rightMouseUp: (NSEvent *) theEvent
979         [self mouseEvent: theEvent];
982 - (void) otherMouseDown: (NSEvent *) theEvent
984         [self mouseEvent: theEvent];
987 - (void) otherMouseUp: (NSEvent *) theEvent
989         [self mouseEvent: theEvent];
992 - (void) scrollWheel: (NSEvent *) theEvent
994         if([theEvent deltaY] > 0)
995                 mplayer_put_key(MOUSE_BTN3);
996         else
997                 mplayer_put_key(MOUSE_BTN4);
1000 - (void) mouseEvent: (NSEvent *) theEvent
1002         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1003         {
1004                 int buttonNumber = [theEvent buttonNumber];
1005                 // Fix to mplayer defined button order: left, middle, right
1006                 if (buttonNumber == 1)
1007                         buttonNumber = 2;
1008                 else if (buttonNumber == 2)
1009                         buttonNumber = 1;
1010                 switch([theEvent type])
1011                 {
1012                         case NSLeftMouseDown:
1013                         case NSRightMouseDown:
1014                         case NSOtherMouseDown:
1015                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1016                                 break;
1017                         case NSLeftMouseUp:
1018                         case NSRightMouseUp:
1019                         case NSOtherMouseUp:
1020                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1021                                 break;
1022                 }
1023         }
1027         NSResponder
1029 - (BOOL) acceptsFirstResponder
1031         return YES;
1034 - (BOOL) becomeFirstResponder
1036         return YES;
1039 - (BOOL) resignFirstResponder
1041         return YES;
1044 - (void)windowWillClose:(NSNotification *)aNotification
1046     mpGLView = NULL;
1047         mplayer_put_key(KEY_ESC);
1049 @end