playtree: make some char * function arguments const
[mplayer.git] / libvo / vo_corevideo.m
blob3b83051eb7b4fe6d0a876e5dd8e0778a08993574
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/keycodes.h"
48 #include "osx_common.h"
50 //Cocoa
51 NSDistantObject *mplayerosxProxy;
52 id <MPlayerOSXVOProto> mplayerosxProto;
53 MPlayerOpenGLView *mpGLView;
54 NSAutoreleasePool *autoreleasepool;
55 OSType pixelFormat;
57 //shared memory
58 BOOL shared_buffer = false;
59 #define DEFAULT_BUFFER_NAME "mplayerosx"
60 static char *buffer_name;
62 //Screen
63 int screen_id = -1;
64 NSRect screen_frame;
65 NSScreen *screen_handle;
66 NSArray *screen_array;
68 //image
69 unsigned char *image_data;
70 // For double buffering
71 static uint8_t image_page = 0;
72 static unsigned char *image_datas[2];
74 static uint32_t image_width;
75 static uint32_t image_height;
76 static uint32_t image_depth;
77 static uint32_t image_bytes;
78 static uint32_t image_format;
80 //vo
81 static int isFullscreen;
82 static int isOntop;
83 static int isRootwin;
85 static float winAlpha = 1;
86 static int int_pause = 0;
88 static BOOL isLeopardOrLater;
90 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
91 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
93 static vo_info_t info =
95         "Mac OS X Core Video",
96         "corevideo",
97         "Nicolas Plourde <nicolas.plourde@gmail.com>",
98         ""
101 LIBVO_EXTERN(corevideo)
103 static void draw_alpha(int x0, int y0, int w, int h, unsigned char *src, unsigned char *srca, int stride)
105         switch (image_format)
106         {
107                 case IMGFMT_RGB24:
108                         vo_draw_alpha_rgb24(w,h,src,srca,stride,image_data+3*(y0*image_width+x0),3*image_width);
109                         break;
110                 case IMGFMT_ARGB:
111                 case IMGFMT_BGRA:
112                         vo_draw_alpha_rgb32(w,h,src,srca,stride,image_data+4*(y0*image_width+x0),4*image_width);
113                         break;
114                 case IMGFMT_YUY2:
115                         vo_draw_alpha_yuy2(w,h,src,srca,stride,image_data + (x0 + y0 * image_width) * 2,image_width*2);
116                         break;
117         }
120 static void update_screen_info(void)
122         if (screen_id == -1 && xinerama_screen > -1)
123                 screen_id = xinerama_screen;
125         screen_array = [NSScreen screens];
126         if(screen_id >= (int)[screen_array count])
127         {
128                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
129                 screen_id = -1;
130         }
131         if (screen_id < 0 && [mpGLView window])
132                 screen_handle = [[mpGLView window] screen];
133         else
134                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
136         screen_frame = [screen_handle 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     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                 }
405                 // Install an event handler so the Quit menu entry works
406                 // The proper way using NSApp setDelegate: and
407                 // applicationShouldTerminate: does not work,
408                 // probably NSApplication never installs its handler.
409                 [[NSAppleEventManager sharedAppleEventManager]
410                         setEventHandler:mpGLView
411                         andSelector:@selector(handleQuitEvent:withReplyEvent:)
412                         forEventClass:kCoreEventClass
413                         andEventID:kAEQuitApplication];
415                 [mpGLView display];
416                 [mpGLView preinit];
417         }
419     return 0;
422 static int control(uint32_t request, void *data)
424         switch (request)
425         {
426                 case VOCTRL_DRAW_IMAGE: return draw_image(data);
427                 case VOCTRL_PAUSE: return int_pause = 1;
428                 case VOCTRL_RESUME: return int_pause = 0;
429                 case VOCTRL_QUERY_FORMAT: return query_format(*(uint32_t*)data);
430                 case VOCTRL_ONTOP: vo_ontop = !vo_ontop; if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
431                 case VOCTRL_ROOTWIN: vo_rootwin = !vo_rootwin; [mpGLView rootwin]; return VO_TRUE;
432                 case VOCTRL_FULLSCREEN: vo_fs = !vo_fs; if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
433                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
434                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
435                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
436         }
437         return VO_NOTIMPL;
440 //////////////////////////////////////////////////////////////////////////
441 // NSOpenGLView Subclass
442 //////////////////////////////////////////////////////////////////////////
443 @implementation MPlayerOpenGLView
444 - (void) preinit
446         NSOpenGLContext *glContext;
447         GLint swapInterval = 1;
448         CVReturn error;
450         //init menu
451         [self initMenu];
453         //create window
454         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
455                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
456                                                                 backing:NSBackingStoreBuffered defer:NO];
458         [window autorelease];
459         [window setDelegate:mpGLView];
460         [window setContentView:mpGLView];
461         [window setInitialFirstResponder:mpGLView];
462         [window setAcceptsMouseMovedEvents:YES];
463         [window setTitle:@"MPlayer - The Movie Player"];
465         isFullscreen = 0;
466         winSizeMult = 1;
468         //create OpenGL Context
469         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
471         [self setOpenGLContext:glContext];
472         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
473         [glContext setView:self];
474         [glContext makeCurrentContext];
475         [glContext release];
477         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
478         if(error != kCVReturnSuccess)
479                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
482 - (void) releaseVideoSpecific
484         CVPixelBufferRelease(frameBuffers[0]);
485         frameBuffers[0] = NULL;
486         CVPixelBufferRelease(frameBuffers[1]);
487         frameBuffers[1] = NULL;
488         CVOpenGLTextureRelease(texture);
489         texture = NULL;
492 - (void) dealloc
494         [self releaseVideoSpecific];
495         CVOpenGLTextureCacheRelease(textureCache);
496         textureCache = NULL;
497         [self setOpenGLContext:nil];
498         [super dealloc];
501 - (void) config
503         NSRect visibleFrame;
504         CVReturn error = kCVReturnSuccess;
506         //config window
507         [window setContentSize:NSMakeSize(vo_dwidth, vo_dheight)];
509         // Use visibleFrame to position the window taking the menu bar and dock into account.
510         // Also flip vo_dy since the screen origin is in the bottom left on OSX.
511         update_screen_info();
512         visibleFrame = [screen_handle visibleFrame];
513         [window setFrameTopLeftPoint:NSMakePoint(
514                 visibleFrame.origin.x + vo_dx,
515                 visibleFrame.origin.y + visibleFrame.size.height - vo_dy)];
517         [self releaseVideoSpecific];
518         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
519         if(error != kCVReturnSuccess)
520                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
521         if (vo_doublebuffering) {
522                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
523                 if(error != kCVReturnSuccess)
524                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
525         }
527         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
528         if(error != kCVReturnSuccess)
529                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
531         //show window
532         [window makeKeyAndOrderFront:mpGLView];
534         if(vo_rootwin)
535                 [mpGLView rootwin];
537         if(vo_fs)
538                 [mpGLView fullscreen: NO];
540         if(vo_ontop)
541                 [mpGLView ontop];
545         Init Menu
547 - (void)initMenu
549         NSMenu *menu, *aspectMenu;
550         NSMenuItem *menuItem;
552         menu = [[NSMenu new] autorelease];
553         menuItem = [[NSMenuItem new] autorelease];
554         [menu addItem: menuItem];
555         [NSApp setMainMenu: menu];
557 //Create Movie Menu
558         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
559         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
560         kHalfScreenCmd = menuItem;
561         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
562         kNormalScreenCmd = menuItem;
563         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
564         kDoubleScreenCmd = menuItem;
565         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
566         kFullScreenCmd = menuItem;
567         menuItem = [NSMenuItem separatorItem]; [menu addItem:menuItem];
569         aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
570         menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
571         if(vo_keepaspect) [menuItem setState:NSOnState];
572         kKeepAspectCmd = menuItem;
573         menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
574         if(vo_panscan) [menuItem setState:NSOnState];
575         kPanScanCmd = menuItem;
576         menuItem = [NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
577         menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
578         kAspectOrgCmd = menuItem;
579         menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
580         kAspectFullCmd = menuItem;
581         menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
582         kAspectWideCmd = menuItem;
583         menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
584         [menuItem setSubmenu:aspectMenu];
585         [menu addItem:menuItem];
586         [aspectMenu release];
588         //Add to menubar
589         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
590         [menuItem setSubmenu:menu];
591         [[NSApp mainMenu] addItem:menuItem];
593 //Create Window Menu
594         menu = [[NSMenu alloc] initWithTitle:@"Window"];
596         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
597         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
599         //Add to menubar
600         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
601         [menuItem setSubmenu:menu];
602         [[NSApp mainMenu] addItem:menuItem];
603         [NSApp setWindowsMenu:menu];
605         [menu release];
606         [menuItem release];
609 - (void)set_winSizeMult:(float)mult
611     NSRect frame;
612     int d_width, d_height;
613     aspect(&d_width, &d_height, A_NOZOOM);
615     if (isFullscreen) {
616         vo_fs = !vo_fs;
617         [self fullscreen:NO];
618     }
620     winSizeMult = mult;
621     frame.size.width  = d_width  * mult;
622     frame.size.height = d_height * mult;
623     [window setContentSize: frame.size];
624     [self reshape];
628         Menu Action
629  */
630 - (void)menuAction:(id)sender
632         if(sender == kHalfScreenCmd)
633                 [self set_winSizeMult: 0.5];
634         if(sender == kNormalScreenCmd)
635                 [self set_winSizeMult: 1];
636         if(sender == kDoubleScreenCmd)
637                 [self set_winSizeMult: 2];
638         if(sender == kFullScreenCmd)
639         {
640                 vo_fs = !vo_fs;
641                 [self fullscreen:NO];
642         }
644         if(sender == kKeepAspectCmd)
645         {
646                 vo_keepaspect = !vo_keepaspect;
647                 if(vo_keepaspect)
648                         [kKeepAspectCmd setState:NSOnState];
649                 else
650                         [kKeepAspectCmd setState:NSOffState];
652                 [self reshape];
653         }
655         if(sender == kPanScanCmd)
656         {
657                 vo_panscan = !vo_panscan;
658                 if(vo_panscan)
659                         [kPanScanCmd setState:NSOnState];
660                 else
661                         [kPanScanCmd setState:NSOffState];
663                 [self panscan];
664         }
666         if(sender == kAspectOrgCmd)
667                 change_movie_aspect(-1);
669         if(sender == kAspectFullCmd)
670                 change_movie_aspect(4.0f/3.0f);
672         if(sender == kAspectWideCmd)
673                 change_movie_aspect(16.0f/9.0f);
677         Setup OpenGL
679 - (void)prepareOpenGL
681         glEnable(GL_BLEND);
682         glDisable(GL_DEPTH_TEST);
683         glDepthMask(GL_FALSE);
684         glDisable(GL_CULL_FACE);
685         [self reshape];
689         reshape OpenGL viewport
691 - (void)reshape
693         int d_width, d_height;
695         NSRect frame = [self frame];
696         vo_dwidth  = frame.size.width;
697         vo_dheight = frame.size.height;
699         glViewport(0, 0, frame.size.width, frame.size.height);
700         glMatrixMode(GL_PROJECTION);
701         glLoadIdentity();
702         glOrtho(0, frame.size.width, frame.size.height, 0, -1.0, 1.0);
703         glMatrixMode(GL_MODELVIEW);
704         glLoadIdentity();
706         //set texture frame
707         if(vo_keepaspect)
708         {
709                 aspect(&d_width, &d_height, A_WINZOOM);
711                 textureFrame = NSMakeRect((vo_dwidth - d_width) / 2, (vo_dheight - d_height) / 2, d_width, d_height);
712         }
713         else
714         {
715                 textureFrame = frame;
716         }
720         Render frame
722 - (void) render
724         glClear(GL_COLOR_BUFFER_BIT);
726         glEnable(CVOpenGLTextureGetTarget(texture));
727         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
729         glColor3f(1,1,1);
730         glBegin(GL_QUADS);
731         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
732         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
733         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
734         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
735         glEnd();
736         glDisable(CVOpenGLTextureGetTarget(texture));
738         //render resize box
739         if(!isFullscreen)
740         {
741                 NSRect frame = [self frame];
743                 glBegin(GL_LINES);
744                 glColor4f(0.2, 0.2, 0.2, 0.5);
745                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
746                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
747                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
749                 glColor4f(0.4, 0.4, 0.4, 0.5);
750                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
751                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
752                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
754                 glColor4f(0.6, 0.6, 0.6, 0.5);
755                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
756                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
757                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
758                 glEnd();
759         }
761         glFlush();
765         Create OpenGL texture from current frame & set texco
767 - (void) setCurrentTexture
769         CVReturn error = kCVReturnSuccess;
771         CVOpenGLTextureRelease(texture);
772         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
773         if(error != kCVReturnSuccess)
774                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
776     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
780         redraw win rect
782 - (void) drawRect: (NSRect *) bounds
784         [self render];
788         Toggle Fullscreen
790 - (void) fullscreen: (BOOL) animate
792         static NSRect old_frame;
793         static NSRect old_view_frame;
795         panscan_calc();
797         //go fullscreen
798         if(vo_fs)
799         {
800                 if(!isRootwin)
801                 {
802                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
803                         CGDisplayHideCursor(kCGDirectMainDisplay);
804                         mouseHide = YES;
805                 }
807                 old_frame = [window frame];     //save main window size & position
808                 update_screen_info();
810                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
811                 old_view_frame = [self bounds];
813                 //fix origin for multi screen setup
814                 screen_frame.origin.x = 0;
815                 screen_frame.origin.y = 0;
816                 [self setFrame:screen_frame];
817                 [self setNeedsDisplay:YES];
818                 [window setHasShadow:NO];
819                 isFullscreen = 1;
820         }
821         else
822         {
823                 SetSystemUIMode( kUIModeNormal, 0);
825                 isFullscreen = 0;
826                 CGDisplayShowCursor(kCGDirectMainDisplay);
827                 mouseHide = NO;
829                 //revert window to previous setting
830                 [self setFrame:old_view_frame];
831                 [self setNeedsDisplay:YES];
832                 [window setHasShadow:YES];
833                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
834         }
838         Toggle ontop
840 - (void) ontop
842         if(vo_ontop)
843         {
844                 [window setLevel:NSScreenSaverWindowLevel];
845                 isOntop = YES;
846         }
847         else
848         {
849                 [window setLevel:NSNormalWindowLevel];
850                 isOntop = NO;
851         }
855         Toggle panscan
857 - (void) panscan
859         panscan_calc();
863         Toggle rootwin
864  */
865 - (void) rootwin
867         if(vo_rootwin)
868         {
869                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
870                 [window orderBack:self];
871                 isRootwin = YES;
872         }
873         else
874         {
875                 [window setLevel:NSNormalWindowLevel];
876                 isRootwin = NO;
877         }
881         Check event for new event
883 - (void) check_events
885         NSEvent *event;
886         int curTime = TickCount()/60;
888         //automatically hide mouse cursor (and future on-screen control?)
889         if(isFullscreen && !mouseHide && !isRootwin)
890         {
891                 if(curTime - lastMouseHide >= 5 || lastMouseHide == 0)
892                 {
893                         CGDisplayHideCursor(kCGDirectMainDisplay);
894                         mouseHide = TRUE;
895                         lastMouseHide = curTime;
896                 }
897         }
899         //update activity every 30 seconds to prevent
900         //screensaver from starting up.
901         if(curTime - lastScreensaverUpdate >= 30 || lastScreensaverUpdate == 0)
902         {
903                 UpdateSystemActivity(UsrActivity);
904                 lastScreensaverUpdate = curTime;
905         }
907         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
908         if (event == nil)
909                 return;
910         [NSApp sendEvent:event];
911         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
912         // on Leopard, we have trouble to get the play window automatically focused
913         // when the app is actived. The Following code fix this problem.
914 #ifndef CONFIG_SDL
915         if (isLeopardOrLater && [event type] == NSAppKitDefined
916                         && [event subtype] == NSApplicationActivatedEventType) {
917                 [window makeMainWindow];
918                 [window makeKeyAndOrderFront:mpGLView];
919         }
920 #endif
924         From NSView, respond to key equivalents.
926 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
928         switch([theEvent keyCode])
929         {
930                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
931                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
932         }
933         return NO;
937         Process key event
939 - (void) keyDown: (NSEvent *) theEvent
941         int key = convert_key([theEvent keyCode], *[[theEvent characters] UTF8String]);
942         if (key != -1) {
943                 if([theEvent modifierFlags] & NSShiftKeyMask)
944                         key |= KEY_MODIFIER_SHIFT;
945                 if([theEvent modifierFlags] & NSControlKeyMask)
946                         key |= KEY_MODIFIER_CTRL;
947                 if(([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
948                         key |= KEY_MODIFIER_ALT;
949                 if([theEvent modifierFlags] & NSCommandKeyMask)
950                         key |= KEY_MODIFIER_META;
951                 mplayer_put_key(key);
952         }
956         Process mouse button event
958 - (void) mouseMoved: (NSEvent *) theEvent
960         if(isFullscreen && !isRootwin)
961         {
962                 CGDisplayShowCursor(kCGDirectMainDisplay);
963                 mouseHide = NO;
964         }
965         if (enable_mouse_movements && !isRootwin) {
966                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
967                 if ([self mouse:p inRect:textureFrame]) {
968                        vo_mouse_movement(global_vo, vo_fs ? p.x : p.x - textureFrame.origin.x,
969                                           vo_fs ? [self frame].size.height - p.y : NSMaxY(textureFrame) - p.y);
970                 }
971         }
974 - (void) mouseDown: (NSEvent *) theEvent
976         [self mouseEvent: theEvent];
979 - (void) mouseUp: (NSEvent *) theEvent
981         [self mouseEvent: theEvent];
984 - (void) rightMouseDown: (NSEvent *) theEvent
986         [self mouseEvent: theEvent];
989 - (void) rightMouseUp: (NSEvent *) theEvent
991         [self mouseEvent: theEvent];
994 - (void) otherMouseDown: (NSEvent *) theEvent
996         [self mouseEvent: theEvent];
999 - (void) otherMouseUp: (NSEvent *) theEvent
1001         [self mouseEvent: theEvent];
1004 - (void) scrollWheel: (NSEvent *) theEvent
1006         if([theEvent deltaY] > 0)
1007                 mplayer_put_key(MOUSE_BTN3);
1008         else
1009                 mplayer_put_key(MOUSE_BTN4);
1012 - (void) mouseEvent: (NSEvent *) theEvent
1014         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1015         {
1016                 int buttonNumber = [theEvent buttonNumber];
1017                 // Fix to mplayer defined button order: left, middle, right
1018                 if (buttonNumber == 1)
1019                         buttonNumber = 2;
1020                 else if (buttonNumber == 2)
1021                         buttonNumber = 1;
1022                 switch([theEvent type])
1023                 {
1024                         case NSLeftMouseDown:
1025                         case NSRightMouseDown:
1026                         case NSOtherMouseDown:
1027                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1028                                 break;
1029                         case NSLeftMouseUp:
1030                         case NSRightMouseUp:
1031                         case NSOtherMouseUp:
1032                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1033                                 break;
1034                 }
1035         }
1039         NSResponder
1041 - (BOOL) acceptsFirstResponder
1043         return YES;
1046 - (BOOL) becomeFirstResponder
1048         return YES;
1051 - (BOOL) resignFirstResponder
1053         return YES;
1056 - (BOOL)windowShouldClose:(id)sender
1058         mplayer_put_key(KEY_CLOSE_WIN);
1059         // We have to wait for MPlayer to handle this,
1060         // otherwise we are in trouble if the
1061         // KEY_CLOSE_WIN handler is disabled
1062         return NO;
1065 - (void)handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
1067         mplayer_put_key(KEY_CLOSE_WIN);
1069 @end