vo_corevideo: support modifier keys in keyboard input
[mplayer.git] / libvo / vo_corevideo.m
blob1effb449f3551b37049abbe8d3e1a184e8b0fdd4
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 "sub/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                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
128                 screen_id = -1;
129         }
130         if (screen_id < 0 && [mpGLView window])
131                 screen_handle = [[mpGLView window] screen];
132         else
133                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
135         screen_frame = [screen_handle frame];
136         vo_screenwidth = screen_frame.size.width;
137         vo_screenheight = screen_frame.size.height;
138         xinerama_x = xinerama_y = 0;
139         aspect_save_screenres(vo_screenwidth, vo_screenheight);
142 static void free_file_specific(void)
144         if(shared_buffer)
145         {
146                 [mplayerosxProto stop];
147                 mplayerosxProto = nil;
148                 [mplayerosxProxy release];
149                 mplayerosxProxy = nil;
151                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
152                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
154                 if (shm_unlink(buffer_name) == -1)
155                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
156     } else {
157         free(image_datas[0]);
158         if (vo_doublebuffering)
159             free(image_datas[1]);
160         image_datas[0] = NULL;
161         image_datas[1] = NULL;
162         image_data = NULL;
163     }
166 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)
168         free_file_specific();
170         //misc mplayer setup
171         image_width = width;
172         image_height = height;
173         switch (image_format)
174         {
175                 case IMGFMT_RGB24:
176                         image_depth = 24;
177                         break;
178                 case IMGFMT_ARGB:
179                 case IMGFMT_BGRA:
180                         image_depth = 32;
181                         break;
182                 case IMGFMT_YUY2:
183                         image_depth = 16;
184                         break;
185         }
186         image_bytes = (image_depth + 7) / 8;
188         if(!shared_buffer)
189         {
190                 config_movie_aspect((float)d_width/d_height);
192                 vo_dwidth  = d_width  *= mpGLView->winSizeMult;
193                 vo_dheight = d_height *= mpGLView->winSizeMult;
195                 image_data = malloc(image_width*image_height*image_bytes);
196                 image_datas[0] = image_data;
197                 if (vo_doublebuffering)
198                         image_datas[1] = malloc(image_width*image_height*image_bytes);
199                 image_page = 0;
201                 vo_fs = flags & VOFLAG_FULLSCREEN;
203                 //config OpenGL View
204                 [mpGLView config];
205                 [mpGLView reshape];
206         }
207         else
208         {
209                 int shm_fd;
210                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
211                                 "named \"%s\"\n",buffer_name);
213                 // create shared memory
214                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
215                 if (shm_fd == -1)
216                 {
217                         mp_msg(MSGT_VO, MSGL_FATAL,
218                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
219                         return 1;
220                 }
223                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
224                 {
225                         mp_msg(MSGT_VO, MSGL_FATAL,
226                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
227                         close(shm_fd);
228                         shm_unlink(buffer_name);
229                         return 1;
230                 }
232                 image_data = mmap(NULL, image_width*image_height*image_bytes,
233                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
234                 close(shm_fd);
236                 if (image_data == MAP_FAILED)
237                 {
238                         mp_msg(MSGT_VO, MSGL_FATAL,
239                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
240                         shm_unlink(buffer_name);
241                         return 1;
242                 }
244                 //connect to mplayerosx
245                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
246                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
247                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
248                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
249                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:d_width*100/d_height];
250                 }
251                 else {
252                         [mplayerosxProxy release];
253                         mplayerosxProxy = nil;
254                         mplayerosxProto = nil;
255                 }
256         }
257         return 0;
260 static void check_events(void)
262         if (mpGLView)
263                 [mpGLView check_events];
266 static void draw_osd(void)
268         vo_draw_text(image_width, image_height, draw_alpha);
271 static void flip_page(void)
273         if(shared_buffer) {
274                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
275                 [mplayerosxProto render];
276                 [pool release];
277         } else {
278                 [mpGLView setCurrentTexture];
279                 [mpGLView render];
280                 if (vo_doublebuffering) {
281                         image_page = 1 - image_page;
282                         image_data = image_datas[image_page];
283                 }
284         }
287 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
289         return 0;
293 static int draw_frame(uint8_t *src[])
295         return 0;
298 static uint32_t draw_image(mp_image_t *mpi)
300         memcpy_pic(image_data, mpi->planes[0], image_width*image_bytes, image_height, image_width*image_bytes, mpi->stride[0]);
302         return 0;
305 static int query_format(uint32_t format)
307     const int supportflags = VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
308         image_format = format;
310     switch(format)
311         {
312                 case IMGFMT_YUY2:
313                         pixelFormat = kYUVSPixelFormat;
314                         return supportflags;
316                 case IMGFMT_RGB24:
317                         pixelFormat = k24RGBPixelFormat;
318                         return supportflags;
320                 case IMGFMT_ARGB:
321                         pixelFormat = k32ARGBPixelFormat;
322                         return supportflags;
324                 case IMGFMT_BGRA:
325                         pixelFormat = k32BGRAPixelFormat;
326                         return supportflags;
327     }
328     return 0;
331 static void uninit(void)
333     SetSystemUIMode( kUIModeNormal, 0);
334     CGDisplayShowCursor(kCGDirectMainDisplay);
336     free_file_specific();
338     if(mpGLView)
339     {
340         NSAutoreleasePool *finalPool;
341         mpGLView = nil;
342         [autoreleasepool release];
343         finalPool = [[NSAutoreleasePool alloc] init];
344         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
345         [finalPool release];
346     }
348     free(buffer_name);
349     buffer_name = NULL;
352 static const opt_t subopts[] = {
353 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
354 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
355 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
356 {NULL}
359 static int preinit(const char *arg)
362         // set defaults
363         screen_id = -1;
364         shared_buffer = false;
365         buffer_name = NULL;
367         if (subopt_parse(arg, subopts) != 0) {
368                 mp_msg(MSGT_VO, MSGL_FATAL,
369                                 "\n-vo corevideo command line help:\n"
370                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
371                                 "\nOptions:\n"
372                                 "  device_id=<0-...>\n"
373                                 "    Set screen device ID for fullscreen.\n"
374                                 "  shared_buffer\n"
375                                 "    Write output to a shared memory buffer instead of displaying it.\n"
376                                 "  buffer_name=<name>\n"
377                                 "    Name of the shared buffer created with shm_open() as well as\n"
378                                 "    the name of the NSConnection MPlayer will try to open.\n"
379                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
380                                 "\n" );
381                 return -1;
382         }
384         autoreleasepool = [[NSAutoreleasePool alloc] init];
386         if (!buffer_name)
387                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
388         else
389                 shared_buffer = true;
391         if(!shared_buffer)
392         {
393                 NSApplicationLoad();
394                 NSApp = [NSApplication sharedApplication];
395                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
397                 osx_foreground_hack();
399                 if(!mpGLView)
400                 {
401                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
402                         [mpGLView autorelease];
403                 }
404                 // Install an event handler so the Quit menu entry works
405                 // The proper way using NSApp setDelegate: and
406                 // applicationShouldTerminate: does not work,
407                 // probably NSApplication never installs its handler.
408                 [[NSAppleEventManager sharedAppleEventManager]
409                         setEventHandler:mpGLView
410                         andSelector:@selector(handleQuitEvent:withReplyEvent:)
411                         forEventClass:kCoreEventClass
412                         andEventID:kAEQuitApplication];
414                 [mpGLView display];
415                 [mpGLView preinit];
416         }
418     return 0;
421 static int control(uint32_t request, void *data)
423         switch (request)
424         {
425                 case VOCTRL_DRAW_IMAGE: return draw_image(data);
426                 case VOCTRL_PAUSE: return int_pause = 1;
427                 case VOCTRL_RESUME: return int_pause = 0;
428                 case VOCTRL_QUERY_FORMAT: return query_format(*(uint32_t*)data);
429                 case VOCTRL_ONTOP: vo_ontop = !vo_ontop; if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
430                 case VOCTRL_ROOTWIN: vo_rootwin = !vo_rootwin; [mpGLView rootwin]; return VO_TRUE;
431                 case VOCTRL_FULLSCREEN: vo_fs = !vo_fs; if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
432                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
433                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
434                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
435         }
436         return VO_NOTIMPL;
439 //////////////////////////////////////////////////////////////////////////
440 // NSOpenGLView Subclass
441 //////////////////////////////////////////////////////////////////////////
442 @implementation MPlayerOpenGLView
443 - (void) preinit
445         NSOpenGLContext *glContext;
446         GLint swapInterval = 1;
447         CVReturn error;
449         //init menu
450         [self initMenu];
452         //create window
453         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
454                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
455                                                                 backing:NSBackingStoreBuffered defer:NO];
457         [window autorelease];
458         [window setDelegate:mpGLView];
459         [window setContentView:mpGLView];
460         [window setInitialFirstResponder:mpGLView];
461         [window setAcceptsMouseMovedEvents:YES];
462         [window setTitle:@"MPlayer - The Movie Player"];
464         isFullscreen = 0;
465         winSizeMult = 1;
467         //create OpenGL Context
468         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
470         [self setOpenGLContext:glContext];
471         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
472         [glContext setView:self];
473         [glContext makeCurrentContext];
474         [glContext release];
476         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
477         if(error != kCVReturnSuccess)
478                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
481 - (void) releaseVideoSpecific
483         CVPixelBufferRelease(frameBuffers[0]);
484         frameBuffers[0] = NULL;
485         CVPixelBufferRelease(frameBuffers[1]);
486         frameBuffers[1] = NULL;
487         CVOpenGLTextureRelease(texture);
488         texture = NULL;
491 - (void) dealloc
493         [self releaseVideoSpecific];
494         CVOpenGLTextureCacheRelease(textureCache);
495         textureCache = NULL;
496         [self setOpenGLContext:nil];
497         [super dealloc];
500 - (void) config
502         NSRect visibleFrame;
503         CVReturn error = kCVReturnSuccess;
505         //config window
506         [window setContentSize:NSMakeSize(vo_dwidth, vo_dheight)];
508         // Use visibleFrame to position the window taking the menu bar and dock into account.
509         // Also flip vo_dy since the screen origin is in the bottom left on OSX.
510         update_screen_info();
511         visibleFrame = [screen_handle visibleFrame];
512         [window setFrameTopLeftPoint:NSMakePoint(
513                 visibleFrame.origin.x + vo_dx,
514                 visibleFrame.origin.y + visibleFrame.size.height - vo_dy)];
516         [self releaseVideoSpecific];
517         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
518         if(error != kCVReturnSuccess)
519                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
520         if (vo_doublebuffering) {
521                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
522                 if(error != kCVReturnSuccess)
523                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
524         }
526         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
527         if(error != kCVReturnSuccess)
528                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
530         //show window
531         [window makeKeyAndOrderFront:mpGLView];
533         if(vo_rootwin)
534                 [mpGLView rootwin];
536         if(vo_fs)
537                 [mpGLView fullscreen: NO];
539         if(vo_ontop)
540                 [mpGLView ontop];
544         Init Menu
546 - (void)initMenu
548         NSMenu *menu, *aspectMenu;
549         NSMenuItem *menuItem;
551         [NSApp setMainMenu:[[NSMenu alloc] init]];
553 //Create Movie Menu
554         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
555         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
556         kHalfScreenCmd = menuItem;
557         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
558         kNormalScreenCmd = menuItem;
559         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
560         kDoubleScreenCmd = menuItem;
561         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
562         kFullScreenCmd = menuItem;
563         menuItem = [NSMenuItem separatorItem]; [menu addItem:menuItem];
565         aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
566         menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
567         if(vo_keepaspect) [menuItem setState:NSOnState];
568         kKeepAspectCmd = menuItem;
569         menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
570         if(vo_panscan) [menuItem setState:NSOnState];
571         kPanScanCmd = menuItem;
572         menuItem = [NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
573         menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
574         kAspectOrgCmd = menuItem;
575         menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
576         kAspectFullCmd = menuItem;
577         menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
578         kAspectWideCmd = menuItem;
579         menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
580         [menuItem setSubmenu:aspectMenu];
581         [menu addItem:menuItem];
582         [aspectMenu release];
584         //Add to menubar
585         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
586         [menuItem setSubmenu:menu];
587         [[NSApp mainMenu] addItem:menuItem];
589 //Create Window Menu
590         menu = [[NSMenu alloc] initWithTitle:@"Window"];
592         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
593         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
595         //Add to menubar
596         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
597         [menuItem setSubmenu:menu];
598         [[NSApp mainMenu] addItem:menuItem];
599         [NSApp setWindowsMenu:menu];
601         [menu release];
602         [menuItem release];
605 - (void)set_winSizeMult:(float)mult
607     NSRect frame;
608     int d_width, d_height;
609     aspect(&d_width, &d_height, A_NOZOOM);
611     if (isFullscreen) {
612         vo_fs = !vo_fs;
613         [self fullscreen:NO];
614     }
616     winSizeMult = mult;
617     frame.size.width  = d_width  * mult;
618     frame.size.height = d_height * mult;
619     [window setContentSize: frame.size];
620     [self reshape];
624         Menu Action
625  */
626 - (void)menuAction:(id)sender
628         if(sender == kHalfScreenCmd)
629                 [self set_winSizeMult: 0.5];
630         if(sender == kNormalScreenCmd)
631                 [self set_winSizeMult: 1];
632         if(sender == kDoubleScreenCmd)
633                 [self set_winSizeMult: 2];
634         if(sender == kFullScreenCmd)
635         {
636                 vo_fs = !vo_fs;
637                 [self fullscreen:NO];
638         }
640         if(sender == kKeepAspectCmd)
641         {
642                 vo_keepaspect = !vo_keepaspect;
643                 if(vo_keepaspect)
644                         [kKeepAspectCmd setState:NSOnState];
645                 else
646                         [kKeepAspectCmd setState:NSOffState];
648                 [self reshape];
649         }
651         if(sender == kPanScanCmd)
652         {
653                 vo_panscan = !vo_panscan;
654                 if(vo_panscan)
655                         [kPanScanCmd setState:NSOnState];
656                 else
657                         [kPanScanCmd setState:NSOffState];
659                 [self panscan];
660         }
662         if(sender == kAspectOrgCmd)
663                 change_movie_aspect(-1);
665         if(sender == kAspectFullCmd)
666                 change_movie_aspect(4.0f/3.0f);
668         if(sender == kAspectWideCmd)
669                 change_movie_aspect(16.0f/9.0f);
673         Setup OpenGL
675 - (void)prepareOpenGL
677         glEnable(GL_BLEND);
678         glDisable(GL_DEPTH_TEST);
679         glDepthMask(GL_FALSE);
680         glDisable(GL_CULL_FACE);
681         [self reshape];
685         reshape OpenGL viewport
687 - (void)reshape
689         int d_width, 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(&d_width, &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         glClear(GL_COLOR_BUFFER_BIT);
722         glEnable(CVOpenGLTextureGetTarget(texture));
723         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
725         glColor3f(1,1,1);
726         glBegin(GL_QUADS);
727         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
728         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
729         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
730         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
731         glEnd();
732         glDisable(CVOpenGLTextureGetTarget(texture));
734         //render resize box
735         if(!isFullscreen)
736         {
737                 NSRect frame = [self frame];
739                 glBegin(GL_LINES);
740                 glColor4f(0.2, 0.2, 0.2, 0.5);
741                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
742                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
743                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
745                 glColor4f(0.4, 0.4, 0.4, 0.5);
746                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
747                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
748                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
750                 glColor4f(0.6, 0.6, 0.6, 0.5);
751                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
752                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
753                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
754                 glEnd();
755         }
757         glFlush();
761         Create OpenGL texture from current frame & set texco
763 - (void) setCurrentTexture
765         CVReturn error = kCVReturnSuccess;
767         CVOpenGLTextureRelease(texture);
768         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
769         if(error != kCVReturnSuccess)
770                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
772     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
776         redraw win rect
778 - (void) drawRect: (NSRect *) bounds
780         [self render];
784         Toggle Fullscreen
786 - (void) fullscreen: (BOOL) animate
788         static NSRect old_frame;
789         static NSRect old_view_frame;
791         panscan_calc();
793         //go fullscreen
794         if(vo_fs)
795         {
796                 if(!isRootwin)
797                 {
798                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
799                         CGDisplayHideCursor(kCGDirectMainDisplay);
800                         mouseHide = YES;
801                 }
803                 old_frame = [window frame];     //save main window size & position
804                 update_screen_info();
806                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
807                 old_view_frame = [self bounds];
809                 //fix origin for multi screen setup
810                 screen_frame.origin.x = 0;
811                 screen_frame.origin.y = 0;
812                 [self setFrame:screen_frame];
813                 [self setNeedsDisplay:YES];
814                 [window setHasShadow:NO];
815                 isFullscreen = 1;
816         }
817         else
818         {
819                 SetSystemUIMode( kUIModeNormal, 0);
821                 isFullscreen = 0;
822                 CGDisplayShowCursor(kCGDirectMainDisplay);
823                 mouseHide = NO;
825                 //revert window to previous setting
826                 [self setFrame:old_view_frame];
827                 [self setNeedsDisplay:YES];
828                 [window setHasShadow:YES];
829                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
830         }
834         Toggle ontop
836 - (void) ontop
838         if(vo_ontop)
839         {
840                 [window setLevel:NSScreenSaverWindowLevel];
841                 isOntop = YES;
842         }
843         else
844         {
845                 [window setLevel:NSNormalWindowLevel];
846                 isOntop = NO;
847         }
851         Toggle panscan
853 - (void) panscan
855         panscan_calc();
859         Toggle rootwin
860  */
861 - (void) rootwin
863         if(vo_rootwin)
864         {
865                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
866                 [window orderBack:self];
867                 isRootwin = YES;
868         }
869         else
870         {
871                 [window setLevel:NSNormalWindowLevel];
872                 isRootwin = NO;
873         }
877         Check event for new event
879 - (void) check_events
881         NSEvent *event;
882         int curTime = TickCount()/60;
884         //automatically hide mouse cursor (and future on-screen control?)
885         if(isFullscreen && !mouseHide && !isRootwin)
886         {
887                 if(curTime - lastMouseHide >= 5 || lastMouseHide == 0)
888                 {
889                         CGDisplayHideCursor(kCGDirectMainDisplay);
890                         mouseHide = TRUE;
891                         lastMouseHide = curTime;
892                 }
893         }
895         //update activity every 30 seconds to prevent
896         //screensaver from starting up.
897         if(curTime - lastScreensaverUpdate >= 30 || lastScreensaverUpdate == 0)
898         {
899                 UpdateSystemActivity(UsrActivity);
900                 lastScreensaverUpdate = curTime;
901         }
903         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
904         if (event == nil)
905                 return;
906         [NSApp sendEvent:event];
907         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
908         // on Leopard, we have trouble to get the play window automatically focused
909         // when the app is actived. The Following code fix this problem.
910 #ifndef CONFIG_SDL
911         if (isLeopardOrLater && [event type] == NSAppKitDefined
912                         && [event subtype] == NSApplicationActivatedEventType) {
913                 [window makeMainWindow];
914                 [window makeKeyAndOrderFront:mpGLView];
915         }
916 #endif
920         From NSView, respond to key equivalents.
922 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
924         switch([theEvent keyCode])
925         {
926                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
927                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
928         }
929         return NO;
933         Process key event
935 - (void) keyDown: (NSEvent *) theEvent
937         int key = convert_key([theEvent keyCode], *[[theEvent characters] UTF8String]);
938         if (key != -1) {
939                 if([theEvent modifierFlags] & NSShiftKeyMask)
940                         key |= KEY_MODIFIER_SHIFT;
941                 if([theEvent modifierFlags] & NSControlKeyMask)
942                         key |= KEY_MODIFIER_CTRL;
943                 if([theEvent modifierFlags] & NSAlternateKeyMask)
944                         key |= KEY_MODIFIER_ALT;
945                 if([theEvent modifierFlags] & NSCommandKeyMask)
946                         key |= KEY_MODIFIER_META;
947                 mplayer_put_key(key);
948         }
952         Process mouse button event
954 - (void) mouseMoved: (NSEvent *) theEvent
956         if(isFullscreen && !isRootwin)
957         {
958                 CGDisplayShowCursor(kCGDirectMainDisplay);
959                 mouseHide = NO;
960         }
961         if (enable_mouse_movements && !isRootwin) {
962                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
963                 if ([self mouse:p inRect:textureFrame]) {
964                        vo_mouse_movement(global_vo, vo_fs ? p.x : p.x - textureFrame.origin.x,
965                                           vo_fs ? [self frame].size.height - p.y : NSMaxY(textureFrame) - p.y);
966                 }
967         }
970 - (void) mouseDown: (NSEvent *) theEvent
972         [self mouseEvent: theEvent];
975 - (void) mouseUp: (NSEvent *) theEvent
977         [self mouseEvent: theEvent];
980 - (void) rightMouseDown: (NSEvent *) theEvent
982         [self mouseEvent: theEvent];
985 - (void) rightMouseUp: (NSEvent *) theEvent
987         [self mouseEvent: theEvent];
990 - (void) otherMouseDown: (NSEvent *) theEvent
992         [self mouseEvent: theEvent];
995 - (void) otherMouseUp: (NSEvent *) theEvent
997         [self mouseEvent: theEvent];
1000 - (void) scrollWheel: (NSEvent *) theEvent
1002         if([theEvent deltaY] > 0)
1003                 mplayer_put_key(MOUSE_BTN3);
1004         else
1005                 mplayer_put_key(MOUSE_BTN4);
1008 - (void) mouseEvent: (NSEvent *) theEvent
1010         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1011         {
1012                 int buttonNumber = [theEvent buttonNumber];
1013                 // Fix to mplayer defined button order: left, middle, right
1014                 if (buttonNumber == 1)
1015                         buttonNumber = 2;
1016                 else if (buttonNumber == 2)
1017                         buttonNumber = 1;
1018                 switch([theEvent type])
1019                 {
1020                         case NSLeftMouseDown:
1021                         case NSRightMouseDown:
1022                         case NSOtherMouseDown:
1023                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1024                                 break;
1025                         case NSLeftMouseUp:
1026                         case NSRightMouseUp:
1027                         case NSOtherMouseUp:
1028                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1029                                 break;
1030                 }
1031         }
1035         NSResponder
1037 - (BOOL) acceptsFirstResponder
1039         return YES;
1042 - (BOOL) becomeFirstResponder
1044         return YES;
1047 - (BOOL) resignFirstResponder
1049         return YES;
1052 - (BOOL)windowShouldClose:(id)sender
1054         mplayer_put_key(KEY_CLOSE_WIN);
1055         // We have to wait for MPlayer to handle this,
1056         // otherwise we are in trouble if the
1057         // KEY_CLOSE_WIN handler is disabled
1058         return NO;
1061 - (void)handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
1063         mplayer_put_key(KEY_CLOSE_WIN);
1065 @end