Fix crash with partial fribidi conversion.
[mplayer/greg.git] / libvo / vo_corevideo.m
blobe4b5e85545e8f0f06084cab2c54d45f8d31f3672
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;
86 extern int enable_mouse_movements;
88 static float winAlpha = 1;
89 static int int_pause = 0;
91 static BOOL isLeopardOrLater;
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_RGB32:
108                         vo_draw_alpha_rgb32(w,h,src,srca,stride,image_data+4*(y0*image_width+x0),4*image_width);
109                         break;
110                 case IMGFMT_YUY2:
111                         vo_draw_alpha_yuy2(w,h,src,srca,stride,image_data + (x0 + y0 * image_width) * 2,image_width*2);
112                         break;
113         }
116 static void update_screen_info(void)
118         screen_array = [NSScreen screens];
119         if(screen_id < (int)[screen_array count])
120         {
121                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
122         }
123         else
124         {
125                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
126                 screen_handle = [screen_array objectAtIndex:0];
127                 screen_id = -1;
128         }
130         screen_frame = ![mpGLView window] || screen_id >= 0 ? [screen_handle frame] : [[[mpGLView window] screen] frame];
131         vo_screenwidth = screen_frame.size.width;
132         vo_screenheight = screen_frame.size.height;
133         xinerama_x = xinerama_y = 0;
134         aspect_save_screenres(vo_screenwidth, vo_screenheight);
137 static void free_file_specific(void)
139         if(shared_buffer)
140         {
141                 [mplayerosxProto stop];
142                 mplayerosxProto = nil;
143                 [mplayerosxProxy release];
144                 mplayerosxProxy = nil;
146                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
147                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
149                 if (shm_unlink(buffer_name) == -1)
150                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
151     } else {
152         free(image_datas[0]);
153         if (vo_doublebuffering)
154             free(image_datas[1]);
155         image_datas[0] = NULL;
156         image_datas[1] = NULL;
157         image_data = NULL;
158     }
161 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)
163         free_file_specific();
165         //misc mplayer setup
166         image_width = width;
167         image_height = height;
168         switch (image_format)
169         {
170                 case IMGFMT_BGR32:
171                 case IMGFMT_RGB32:
172                         image_depth = 32;
173                         break;
174                 case IMGFMT_YUY2:
175                         image_depth = 16;
176                         break;
177         }
178         image_bytes = (image_depth + 7) / 8;
180         if(!shared_buffer)
181         {
182                 config_movie_aspect((float)d_width/d_height);
184                 vo_dwidth  = d_width  *= mpGLView->winSizeMult;
185                 vo_dheight = d_height *= mpGLView->winSizeMult;
187                 image_data = malloc(image_width*image_height*image_bytes);
188                 image_datas[0] = image_data;
189                 if (vo_doublebuffering)
190                         image_datas[1] = malloc(image_width*image_height*image_bytes);
191                 image_page = 0;
193                 vo_fs = flags & VOFLAG_FULLSCREEN;
195                 //config OpenGL View
196                 [mpGLView config];
197                 [mpGLView reshape];
198         }
199         else
200         {
201                 int shm_fd;
202                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
203                                 "named \"%s\"\n",buffer_name);
205                 // create shared memory
206                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
207                 if (shm_fd == -1)
208                 {
209                         mp_msg(MSGT_VO, MSGL_FATAL,
210                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
211                         return 1;
212                 }
215                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
216                 {
217                         mp_msg(MSGT_VO, MSGL_FATAL,
218                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
219                         close(shm_fd);
220                         shm_unlink(buffer_name);
221                         return 1;
222                 }
224                 image_data = mmap(NULL, image_width*image_height*image_bytes,
225                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
226                 close(shm_fd);
228                 if (image_data == MAP_FAILED)
229                 {
230                         mp_msg(MSGT_VO, MSGL_FATAL,
231                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
232                         shm_unlink(buffer_name);
233                         return 1;
234                 }
236                 //connect to mplayerosx
237                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
238                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
239                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
240                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
241                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:d_width*100/d_height];
242                 }
243                 else {
244                         [mplayerosxProxy release];
245                         mplayerosxProxy = nil;
246                         mplayerosxProto = nil;
247                 }
248         }
249         return 0;
252 static void check_events(void)
254         if (mpGLView)
255                 [mpGLView check_events];
258 static void draw_osd(void)
260         vo_draw_text(image_width, image_height, draw_alpha);
263 static void flip_page(void)
265         if(shared_buffer) {
266                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
267                 [mplayerosxProto render];
268                 [pool release];
269         } else {
270                 [mpGLView setCurrentTexture];
271                 [mpGLView render];
272                 if (vo_doublebuffering) {
273                         image_page = 1 - image_page;
274                         image_data = image_datas[image_page];
275                 }
276         }
279 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
281         return 0;
285 static int draw_frame(uint8_t *src[])
287         switch (image_format)
288         {
289                 case IMGFMT_BGR32:
290                 case IMGFMT_RGB32:
291                         fast_memcpy(image_data, src[0], image_width*image_height*image_bytes);
292                         break;
294                 case IMGFMT_YUY2:
295                         memcpy_pic(image_data, src[0], image_width * 2, image_height, image_width * 2, image_width * 2);
296                         break;
297         }
299         return 0;
302 static int query_format(uint32_t format)
304         image_format = format;
306     switch(format)
307         {
308                 case IMGFMT_YUY2:
309                         pixelFormat = kYUVSPixelFormat;
310                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
312                 case IMGFMT_RGB32:
313                 case IMGFMT_BGR32:
314                         pixelFormat = k32ARGBPixelFormat;
315                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
316     }
317     return 0;
320 static void uninit(void)
322     SetSystemUIMode( kUIModeNormal, 0);
323     CGDisplayShowCursor(kCGDirectMainDisplay);
325     free_file_specific();
327     if(mpGLView)
328     {
329         NSAutoreleasePool *finalPool;
330         mpGLView = nil;
331         [autoreleasepool release];
332         finalPool = [[NSAutoreleasePool alloc] init];
333         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
334         [finalPool release];
335     }
337     if (buffer_name) free(buffer_name);
338     buffer_name = NULL;
341 static const opt_t subopts[] = {
342 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
343 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
344 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
345 {NULL}
348 static int preinit(const char *arg)
351         // set defaults
352         screen_id = -1;
353         shared_buffer = false;
354         buffer_name = NULL;
356         if (subopt_parse(arg, subopts) != 0) {
357                 mp_msg(MSGT_VO, MSGL_FATAL,
358                                 "\n-vo corevideo command line help:\n"
359                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
360                                 "\nOptions:\n"
361                                 "  device_id=<0-...>\n"
362                                 "    Set screen device ID for fullscreen.\n"
363                                 "  shared_buffer\n"
364                                 "    Write output to a shared memory buffer instead of displaying it.\n"
365                                 "  buffer_name=<name>\n"
366                                 "    Name of the shared buffer created with shm_open() as well as\n"
367                                 "    the name of the NSConnection MPlayer will try to open.\n"
368                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
369                                 "\n" );
370                 return -1;
371         }
373         autoreleasepool = [[NSAutoreleasePool alloc] init];
375         if (!buffer_name)
376                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
377         else
378                 shared_buffer = true;
380         if(!shared_buffer)
381         {
382                 NSApplicationLoad();
383                 NSApp = [NSApplication sharedApplication];
384                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
386                 #if !defined (CONFIG_MACOSX_FINDER) || !defined (CONFIG_SDL)
387                 //this chunk of code is heavily based off SDL_macosx.m from SDL
388                 ProcessSerialNumber myProc, frProc;
389                 Boolean sameProc;
391                 if (GetFrontProcess(&frProc) == noErr)
392                 {
393                         if (GetCurrentProcess(&myProc) == noErr)
394                         {
395                                 if (SameProcess(&frProc, &myProc, &sameProc) == noErr && !sameProc)
396                                 {
397                                         TransformProcessType(&myProc, kProcessTransformToForegroundApplication);
398                                 }
399                                 SetFrontProcess(&myProc);
400                         }
401                 }
402                 #endif
404                 if(!mpGLView)
405                 {
406                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
407                         [mpGLView autorelease];
408                 }
410                 [mpGLView display];
411                 [mpGLView preinit];
412         }
414     return 0;
417 static int control(uint32_t request, void *data, ...)
419         switch (request)
420         {
421                 case VOCTRL_PAUSE: return int_pause = 1;
422                 case VOCTRL_RESUME: return int_pause = 0;
423                 case VOCTRL_QUERY_FORMAT: return query_format(*((uint32_t*)data));
424                 case VOCTRL_ONTOP: vo_ontop = (!(vo_ontop)); if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
425                 case VOCTRL_ROOTWIN: vo_rootwin = (!(vo_rootwin)); [mpGLView rootwin]; return VO_TRUE;
426                 case VOCTRL_FULLSCREEN: vo_fs = (!(vo_fs)); if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
427                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
428                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
429                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
430         }
431         return VO_NOTIMPL;
434 //////////////////////////////////////////////////////////////////////////
435 // NSOpenGLView Subclass
436 //////////////////////////////////////////////////////////////////////////
437 @implementation MPlayerOpenGLView
438 - (void) preinit
440         NSOpenGLContext *glContext;
441         GLint swapInterval = 1;
442         CVReturn error;
444         //init menu
445         [self initMenu];
447         //create window
448         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
449                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
450                                                                 backing:NSBackingStoreBuffered defer:NO];
452         [window autorelease];
453         [window setDelegate:mpGLView];
454         [window setContentView:mpGLView];
455         [window setInitialFirstResponder:mpGLView];
456         [window setAcceptsMouseMovedEvents:YES];
457     [window setTitle:@"MPlayer - The Movie Player"];
459         isFullscreen = 0;
460         winSizeMult = 1;
462         //create OpenGL Context
463         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
465         [self setOpenGLContext:glContext];
466         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
467         [glContext setView:self];
468         [glContext makeCurrentContext];
469         [glContext release];
471         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
472         if(error != kCVReturnSuccess)
473                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
476 - (void) releaseVideoSpecific
478         CVPixelBufferRelease(frameBuffers[0]);
479         frameBuffers[0] = NULL;
480         CVPixelBufferRelease(frameBuffers[1]);
481         frameBuffers[1] = NULL;
482         CVOpenGLTextureRelease(texture);
483         texture = NULL;
486 - (void) dealloc
488         [self releaseVideoSpecific];
489         CVOpenGLTextureCacheRelease(textureCache);
490         textureCache = NULL;
491         [self setOpenGLContext:nil];
492         [super dealloc];
495 - (void) config
497         uint32_t d_width;
498         uint32_t d_height;
500         NSRect frame;
501         CVReturn error = kCVReturnSuccess;
503         //config window
504         d_width = vo_dwidth; d_height = vo_dheight;
505         frame = NSMakeRect(0, 0, d_width, d_height);
506         [window setContentSize: frame.size];
508         [self releaseVideoSpecific];
509         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
510         if(error != kCVReturnSuccess)
511                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
512         if (vo_doublebuffering) {
513                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
514                 if(error != kCVReturnSuccess)
515                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
516         }
518         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
519         if(error != kCVReturnSuccess)
520                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
522         //show window
523         [window center];
524         [window makeKeyAndOrderFront:mpGLView];
526         if(vo_rootwin)
527                 [mpGLView rootwin];
529         if(vo_fs)
530                 [mpGLView fullscreen: NO];
532         if(vo_ontop)
533                 [mpGLView ontop];
537         Init Menu
539 - (void)initMenu
541         NSMenu *menu, *aspectMenu;
542         NSMenuItem *menuItem;
544         [NSApp setMainMenu:[[NSMenu alloc] init]];
546 //Create Movie Menu
547         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
548         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
549         kHalfScreenCmd = menuItem;
550         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
551         kNormalScreenCmd = menuItem;
552         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
553         kDoubleScreenCmd = menuItem;
554         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
555         kFullScreenCmd = menuItem;
556         menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [menu addItem:menuItem];
558                 aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
559                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
560                 if(vo_keepaspect) [menuItem setState:NSOnState];
561                 kKeepAspectCmd = menuItem;
562                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
563                 if(vo_panscan) [menuItem setState:NSOnState];
564                 kPanScanCmd = menuItem;
565                 menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
566                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
567                 kAspectOrgCmd = menuItem;
568                 menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
569                 kAspectFullCmd = menuItem;
570                 menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
571                 kAspectWideCmd = menuItem;
572                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
573                 [menuItem setSubmenu:aspectMenu];
574                 [menu addItem:menuItem];
575                 [aspectMenu release];
577         //Add to menubar
578         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
579         [menuItem setSubmenu:menu];
580         [[NSApp mainMenu] addItem:menuItem];
582 //Create Window Menu
583         menu = [[NSMenu alloc] initWithTitle:@"Window"];
585         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
586         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
588         //Add to menubar
589         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
590         [menuItem setSubmenu:menu];
591         [[NSApp mainMenu] addItem:menuItem];
592         [NSApp setWindowsMenu:menu];
594         [menu release];
595         [menuItem release];
598 - (void)set_winSizeMult:(float)mult
600     NSRect frame;
601     int d_width, d_height;
602     aspect(&d_width, &d_height, A_NOZOOM);
604     if (isFullscreen) {
605         vo_fs = !vo_fs;
606         [self fullscreen:NO];
607     }
609     winSizeMult = mult;
610     frame.size.width  = d_width  * mult;
611     frame.size.height = d_height * mult;
612     [window setContentSize: frame.size];
613     [self reshape];
617         Menu Action
618  */
619 - (void)menuAction:(id)sender
621         if(sender == kQuitCmd)
622         {
623                 mplayer_put_key(KEY_ESC);
624         }
626         if(sender == kHalfScreenCmd)
627                 [self set_winSizeMult: 0.5];
628         if(sender == kNormalScreenCmd)
629                 [self set_winSizeMult: 1];
630         if(sender == kDoubleScreenCmd)
631                 [self set_winSizeMult: 2];
632         if(sender == kFullScreenCmd)
633         {
634                 vo_fs = (!(vo_fs));
635                 [self fullscreen:NO];
636         }
638         if(sender == kKeepAspectCmd)
639         {
640                 vo_keepaspect = (!(vo_keepaspect));
641                 if(vo_keepaspect)
642                         [kKeepAspectCmd setState:NSOnState];
643                 else
644                         [kKeepAspectCmd setState:NSOffState];
646                 [self reshape];
647         }
649         if(sender == kPanScanCmd)
650         {
651                 vo_panscan = (!(vo_panscan));
652                 if(vo_panscan)
653                         [kPanScanCmd setState:NSOnState];
654                 else
655                         [kPanScanCmd setState:NSOffState];
657                 [self panscan];
658         }
660         if(sender == kAspectOrgCmd)
661                 change_movie_aspect(-1);
663         if(sender == kAspectFullCmd)
664                 change_movie_aspect(4.0f/3.0f);
666         if(sender == kAspectWideCmd)
667                 change_movie_aspect(16.0f/9.0f);
671         Setup OpenGL
673 - (void)prepareOpenGL
675         glEnable(GL_BLEND);
676         glDisable(GL_DEPTH_TEST);
677         glDepthMask(GL_FALSE);
678         glDisable(GL_CULL_FACE);
679         [self reshape];
683         reshape OpenGL viewport
685 - (void)reshape
687         uint32_t d_width;
688         uint32_t d_height;
690         NSRect frame = [self frame];
691         vo_dwidth  = frame.size.width;
692         vo_dheight = frame.size.height;
694         glViewport(0, 0, frame.size.width, frame.size.height);
695         glMatrixMode(GL_PROJECTION);
696         glLoadIdentity();
697         glOrtho(0, frame.size.width, frame.size.height, 0, -1.0, 1.0);
698         glMatrixMode(GL_MODELVIEW);
699         glLoadIdentity();
701         //set texture frame
702         if(vo_keepaspect)
703         {
704                 aspect( (int *)&d_width, (int *)&d_height, A_WINZOOM);
706                 textureFrame = NSMakeRect((vo_dwidth - d_width) / 2, (vo_dheight - d_height) / 2, d_width, d_height);
707         }
708         else
709         {
710                 textureFrame = frame;
711         }
715         Render frame
717 - (void) render
719         int curTime;
721         glClear(GL_COLOR_BUFFER_BIT);
723         glEnable(CVOpenGLTextureGetTarget(texture));
724         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
726         glColor3f(1,1,1);
727         glBegin(GL_QUADS);
728         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
729         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
730         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
731         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
732         glEnd();
733         glDisable(CVOpenGLTextureGetTarget(texture));
735         //render resize box
736         if(!isFullscreen)
737         {
738                 NSRect frame = [self frame];
740                 glBegin(GL_LINES);
741                 glColor4f(0.2, 0.2, 0.2, 0.5);
742                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
743                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
744                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
746                 glColor4f(0.4, 0.4, 0.4, 0.5);
747                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
748                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
749                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
751                 glColor4f(0.6, 0.6, 0.6, 0.5);
752                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
753                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
754                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
755                 glEnd();
756         }
758         glFlush();
760         curTime  = TickCount()/60;
762         //automatically hide mouse cursor (and future on-screen control?)
763         if(isFullscreen && !mouseHide && !isRootwin)
764         {
765                 if( ((curTime - lastMouseHide) >= 5) || (lastMouseHide == 0) )
766                 {
767                         CGDisplayHideCursor(kCGDirectMainDisplay);
768                         mouseHide = TRUE;
769                         lastMouseHide = curTime;
770                 }
771         }
773         //update activity every 30 seconds to prevent
774         //screensaver from starting up.
775         if( ((curTime - lastScreensaverUpdate) >= 30) || (lastScreensaverUpdate == 0) )
776         {
777                 UpdateSystemActivity(UsrActivity);
778                 lastScreensaverUpdate = curTime;
779         }
783         Create OpenGL texture from current frame & set texco
785 - (void) setCurrentTexture
787         CVReturn error = kCVReturnSuccess;
789         CVOpenGLTextureRelease(texture);
790         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
791         if(error != kCVReturnSuccess)
792                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
794     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
798         redraw win rect
800 - (void) drawRect: (NSRect *) bounds
802         [self render];
806         Toggle Fullscreen
808 - (void) fullscreen: (BOOL) animate
810         static NSRect old_frame;
811         static NSRect old_view_frame;
813         panscan_calc();
815         //go fullscreen
816         if(vo_fs)
817         {
818                 if(!isRootwin)
819                 {
820                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
821                         CGDisplayHideCursor(kCGDirectMainDisplay);
822                         mouseHide = YES;
823                 }
825                 old_frame = [window frame];     //save main window size & position
826                 update_screen_info();
828                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
829                 old_view_frame = [self bounds];
831                 //fix origin for multi screen setup
832                 screen_frame.origin.x = 0;
833                 screen_frame.origin.y = 0;
834                 [self setFrame:screen_frame];
835                 [self setNeedsDisplay:YES];
836                 [window setHasShadow:NO];
837                 isFullscreen = 1;
838         }
839         else
840         {
841                 SetSystemUIMode( kUIModeNormal, 0);
843                 isFullscreen = 0;
844                 CGDisplayShowCursor(kCGDirectMainDisplay);
845                 mouseHide = NO;
847                 //revert window to previous setting
848                 [self setFrame:old_view_frame];
849                 [self setNeedsDisplay:YES];
850                 [window setHasShadow:YES];
851                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
852         }
856         Toggle ontop
858 - (void) ontop
860         if(vo_ontop)
861         {
862                 [window setLevel:NSScreenSaverWindowLevel];
863                 isOntop = YES;
864         }
865         else
866         {
867                 [window setLevel:NSNormalWindowLevel];
868                 isOntop = NO;
869         }
873         Toggle panscan
875 - (void) panscan
877         panscan_calc();
881         Toggle rootwin
882  */
883 - (void) rootwin
885         if(vo_rootwin)
886         {
887                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
888                 [window orderBack:self];
889                 isRootwin = YES;
890         }
891         else
892         {
893                 [window setLevel:NSNormalWindowLevel];
894                 isRootwin = NO;
895         }
899         Check event for new event
901 - (void) check_events
903         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001] 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         mplayer_put_key(key);
943         Process mouse button event
945 - (void) mouseMoved: (NSEvent *) theEvent
947         if(isFullscreen && !isRootwin)
948         {
949                 CGDisplayShowCursor(kCGDirectMainDisplay);
950                 mouseHide = NO;
951         }
952         if (enable_mouse_movements && !isRootwin) {
953                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
954                 if ([self mouse:p inRect:textureFrame]) {
955                         char cmdstr[40];
956                         snprintf(cmdstr, sizeof(cmdstr), "set_mouse_pos %i %i",
957                                  (int)(vo_fs ? p.x : (p.x - textureFrame.origin.x)),
958                                  (int)(vo_fs ? [self frame].size.height - p.y: (NSMaxY(textureFrame) - p.y)));
959                         mp_input_queue_cmd(mp_input_parse_cmd(cmdstr));
960                 }
961         }
964 - (void) mouseDown: (NSEvent *) theEvent
966         [self mouseEvent: theEvent];
969 - (void) mouseUp: (NSEvent *) theEvent
971         [self mouseEvent: theEvent];
974 - (void) rightMouseDown: (NSEvent *) theEvent
976         [self mouseEvent: theEvent];
979 - (void) rightMouseUp: (NSEvent *) theEvent
981         [self mouseEvent: theEvent];
984 - (void) otherMouseDown: (NSEvent *) theEvent
986         [self mouseEvent: theEvent];
989 - (void) otherMouseUp: (NSEvent *) theEvent
991         [self mouseEvent: theEvent];
994 - (void) scrollWheel: (NSEvent *) theEvent
996         if([theEvent deltaY] > 0)
997                 mplayer_put_key(MOUSE_BTN3);
998         else
999                 mplayer_put_key(MOUSE_BTN4);
1002 - (void) mouseEvent: (NSEvent *) theEvent
1004         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1005         {
1006                 int buttonNumber = [theEvent buttonNumber];
1007                 // Fix to mplayer defined button order: left, middle, right
1008                 if (buttonNumber == 1)
1009                         buttonNumber = 2;
1010                 else if (buttonNumber == 2)
1011                         buttonNumber = 1;
1012                 switch([theEvent type])
1013                 {
1014                         case NSLeftMouseDown:
1015                         case NSRightMouseDown:
1016                         case NSOtherMouseDown:
1017                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1018                                 break;
1019                         case NSLeftMouseUp:
1020                         case NSRightMouseUp:
1021                         case NSOtherMouseUp:
1022                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1023                                 break;
1024                 }
1025         }
1029         NSResponder
1031 - (BOOL) acceptsFirstResponder
1033         return YES;
1036 - (BOOL) becomeFirstResponder
1038         return YES;
1041 - (BOOL) resignFirstResponder
1043         return YES;
1046 - (void)windowWillClose:(NSNotification *)aNotification
1048     mpGLView = NULL;
1049         mplayer_put_key(KEY_ESC);
1051 @end