20% faster hqdn3d on x86_64
[mplayer/glamo.git] / libvo / vo_corevideo.m
blob73d5bf961a8902f6a3f094f575215da979e96199
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"
51 //Cocoa
52 NSDistantObject *mplayerosxProxy;
53 id <MPlayerOSXVOProto> mplayerosxProto;
54 MPlayerOpenGLView *mpGLView;
55 NSAutoreleasePool *autoreleasepool;
56 OSType pixelFormat;
58 //shared memory
59 int shm_fd;
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 float monitor_aspect;
87 extern float movie_aspect;
88 static float old_movie_aspect;
89 extern int enable_mouse_movements;
91 static float winAlpha = 1;
92 static int int_pause = 0;
94 static BOOL isLeopardOrLater;
96 static vo_info_t info =
98         "Mac OS X Core Video",
99         "corevideo",
100         "Nicolas Plourde <nicolas.plourde@gmail.com>",
101         ""
104 LIBVO_EXTERN(corevideo)
106 static void draw_alpha(int x0, int y0, int w, int h, unsigned char *src, unsigned char *srca, int stride)
108         switch (image_format)
109         {
110                 case IMGFMT_RGB32:
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 int config(uint32_t width, uint32_t height, uint32_t d_width, uint32_t d_height, uint32_t flags, char *title, uint32_t format)
122         //init screen
123         screen_array = [NSScreen screens];
124         if(screen_id < (int)[screen_array count])
125         {
126                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
127         }
128         else
129         {
130                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
131                 screen_handle = [screen_array objectAtIndex:0];
132                 screen_id = -1;
133         }
134         screen_frame = [screen_handle frame];
135         vo_screenwidth = screen_frame.size.width;
136         vo_screenheight = screen_frame.size.height;
138         //misc mplayer setup
139         image_width = width;
140         image_height = height;
141         switch (image_format)
142         {
143                 case IMGFMT_BGR32:
144                 case IMGFMT_RGB32:
145                         image_depth = 32;
146                         break;
147                 case IMGFMT_YUY2:
148                         image_depth = 16;
149                         break;
150         }
151         image_bytes = (image_depth + 7) / 8;
153         if(!shared_buffer)
154         {
155                 image_data = malloc(image_width*image_height*image_bytes);
156                 image_datas[0] = image_data;
157                 if (vo_doublebuffering)
158                         image_datas[1] = malloc(image_width*image_height*image_bytes);
159                 image_page = 0;
161                 monitor_aspect = (float)screen_frame.size.width/(float)screen_frame.size.height;
163                 //set aspect
164                 panscan_init();
165                 aspect_save_orig(width,height);
166                 aspect_save_prescale(d_width,d_height);
167                 aspect_save_screenres(screen_frame.size.width, screen_frame.size.height);
168                 aspect((int *)&d_width,(int *)&d_height,A_NOZOOM);
170                 movie_aspect = (float)d_width/(float)d_height;
171                 old_movie_aspect = movie_aspect;
173                 vo_fs = flags & VOFLAG_FULLSCREEN;
175                 //config OpenGL View
176                 [mpGLView config];
177                 [mpGLView reshape];
178         }
179         else
180         {
181                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
182                                 "named \"%s\"\n",buffer_name);
184                 movie_aspect = (float)d_width/(float)d_height;
186                 // create shared memory
187                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
188                 if (shm_fd == -1)
189                 {
190                         mp_msg(MSGT_VO, MSGL_FATAL,
191                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
192                         return 1;
193                 }
196                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
197                 {
198                         mp_msg(MSGT_VO, MSGL_FATAL,
199                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
200                         shm_unlink(buffer_name);
201                         return 1;
202                 }
204                 image_data = mmap(NULL, image_width*image_height*image_bytes,
205                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
207                 if (image_data == MAP_FAILED)
208                 {
209                         mp_msg(MSGT_VO, MSGL_FATAL,
210                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
211                         shm_unlink(buffer_name);
212                         return 1;
213                 }
215                 //connect to mplayerosx
216                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
217                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
218                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
219                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
220                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:(int)(movie_aspect*100)];
221                 }
222                 else {
223                         [mplayerosxProxy release];
224                         mplayerosxProxy = nil;
225                         mplayerosxProto = nil;
226                 }
227         }
228         return 0;
231 static void check_events(void)
233         if (mpGLView)
234                 [mpGLView check_events];
237 static void draw_osd(void)
239         vo_draw_text(image_width, image_height, draw_alpha);
242 static void flip_page(void)
244         if(shared_buffer) {
245                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
246                 [mplayerosxProto render];
247                 [pool release];
248         } else {
249                 [mpGLView setCurrentTexture];
250                 [mpGLView render];
251                 if (vo_doublebuffering) {
252                         image_page = 1 - image_page;
253                         image_data = image_datas[image_page];
254                 }
255         }
258 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
260         return 0;
264 static int draw_frame(uint8_t *src[])
266         switch (image_format)
267         {
268                 case IMGFMT_BGR32:
269                 case IMGFMT_RGB32:
270                         fast_memcpy(image_data, src[0], image_width*image_height*image_bytes);
271                         break;
273                 case IMGFMT_YUY2:
274                         memcpy_pic(image_data, src[0], image_width * 2, image_height, image_width * 2, image_width * 2);
275                         break;
276         }
278         return 0;
281 static int query_format(uint32_t format)
283         image_format = format;
285     switch(format)
286         {
287                 case IMGFMT_YUY2:
288                         pixelFormat = kYUVSPixelFormat;
289                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
291                 case IMGFMT_RGB32:
292                 case IMGFMT_BGR32:
293                         pixelFormat = k32ARGBPixelFormat;
294                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
295     }
296     return 0;
299 static void uninit(void)
301         if(shared_buffer)
302         {
303                 [mplayerosxProto stop];
304                 mplayerosxProto = nil;
305                 [mplayerosxProxy release];
306                 mplayerosxProxy = nil;
308                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
309                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
311                 if (shm_unlink(buffer_name) == -1)
312                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
314         }
316     SetSystemUIMode( kUIModeNormal, 0);
317     CGDisplayShowCursor(kCGDirectMainDisplay);
319     if(mpGLView)
320     {
321         NSAutoreleasePool *finalPool;
322         mpGLView = nil;
323         [autoreleasepool release];
324         finalPool = [[NSAutoreleasePool alloc] init];
325         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
326         [finalPool release];
327     }
328     if (!shared_buffer)
329     {
330         free(image_datas[0]);
331         if (vo_doublebuffering)
332             free(image_datas[1]);
333         image_datas[0] = NULL;
334         image_datas[1] = NULL;
335         image_data = NULL;
336     }
338     if (buffer_name) free(buffer_name);
339     buffer_name = NULL;
342 static opt_t subopts[] = {
343 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
344 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
345 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
346 {NULL}
349 static int preinit(const char *arg)
352         // set defaults
353         screen_id = -1;
354         shared_buffer = false;
355         buffer_name = NULL;
357         if (subopt_parse(arg, subopts) != 0) {
358                 mp_msg(MSGT_VO, MSGL_FATAL,
359                                 "\n-vo corevideo command line help:\n"
360                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
361                                 "\nOptions:\n"
362                                 "  device_id=<0-...>\n"
363                                 "    Set screen device ID for fullscreen.\n"
364                                 "  shared_buffer\n"
365                                 "    Write output to a shared memory buffer instead of displaying it.\n"
366                                 "  buffer_name=<name>\n"
367                                 "    Name of the shared buffer created with shm_open() as well as\n"
368                                 "    the name of the NSConnection MPlayer will try to open.\n"
369                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
370                                 "\n" );
371                 return -1;
372         }
374         autoreleasepool = [[NSAutoreleasePool alloc] init];
376         if (!buffer_name)
377                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
378         else
379                 shared_buffer = true;
381         if(!shared_buffer)
382         {
383                 NSApplicationLoad();
384                 NSApp = [NSApplication sharedApplication];
385                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
387                 #if !defined (CONFIG_MACOSX_FINDER) || !defined (CONFIG_SDL)
388                 //this chunk of code is heavily based off SDL_macosx.m from SDL
389                 ProcessSerialNumber myProc, frProc;
390                 Boolean sameProc;
392                 if (GetFrontProcess(&frProc) == noErr)
393                 {
394                         if (GetCurrentProcess(&myProc) == noErr)
395                         {
396                                 if (SameProcess(&frProc, &myProc, &sameProc) == noErr && !sameProc)
397                                 {
398                                         TransformProcessType(&myProc, kProcessTransformToForegroundApplication);
399                                 }
400                                 SetFrontProcess(&myProc);
401                         }
402                 }
403                 #endif
405                 if(!mpGLView)
406                 {
407                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
408                         [mpGLView autorelease];
409                 }
411                 [mpGLView display];
412                 [mpGLView preinit];
413         }
415     return 0;
418 static int control(uint32_t request, void *data, ...)
420         switch (request)
421         {
422                 case VOCTRL_PAUSE: return int_pause = 1;
423                 case VOCTRL_RESUME: return int_pause = 0;
424                 case VOCTRL_QUERY_FORMAT: return query_format(*((uint32_t*)data));
425                 case VOCTRL_ONTOP: vo_ontop = (!(vo_ontop)); if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
426                 case VOCTRL_ROOTWIN: vo_rootwin = (!(vo_rootwin)); [mpGLView rootwin]; return VO_TRUE;
427                 case VOCTRL_FULLSCREEN: vo_fs = (!(vo_fs)); if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
428                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
429                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
430         }
431         return VO_NOTIMPL;
434 //////////////////////////////////////////////////////////////////////////
435 // NSOpenGLView Subclass
436 //////////////////////////////////////////////////////////////////////////
437 @implementation MPlayerOpenGLView
438 - (void) preinit
440         //init menu
441         [self initMenu];
443         //create window
444         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
445                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
446                                                                 backing:NSBackingStoreBuffered defer:NO];
448         [window autorelease];
449         [window setDelegate:mpGLView];
450         [window setContentView:mpGLView];
451         [window setInitialFirstResponder:mpGLView];
452         [window setAcceptsMouseMovedEvents:YES];
453     [window setTitle:@"MPlayer - The Movie Player"];
455         isFullscreen = 0;
456         winSizeMult = 1;
459 - (void) config
461         uint32_t d_width;
462         uint32_t d_height;
464         GLint swapInterval = 1;
466         NSRect frame;
467         CVReturn error = kCVReturnSuccess;
469         //config window
470         aspect((int *)&d_width, (int *)&d_height,A_NOZOOM);
471         frame = NSMakeRect(0, 0, d_width, d_height);
472         [window setContentSize: frame.size];
474         //create OpenGL Context
475         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
477         [self setOpenGLContext:glContext];
478         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
479         [glContext setView:self];
480         [glContext makeCurrentContext];
482         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
483         if(error != kCVReturnSuccess)
484                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
485         if (vo_doublebuffering) {
486                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
487                 if(error != kCVReturnSuccess)
488                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
489         }
491         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
492         if(error != kCVReturnSuccess)
493                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
495         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
496         if(error != kCVReturnSuccess)
497                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
499         //show window
500         [window center];
501         [window makeKeyAndOrderFront:mpGLView];
503         if(vo_rootwin)
504                 [mpGLView rootwin];
506         if(vo_fs)
507                 [mpGLView fullscreen: NO];
509         if(vo_ontop)
510                 [mpGLView ontop];
514         Init Menu
516 - (void)initMenu
518         NSMenu *menu, *aspectMenu;
519         NSMenuItem *menuItem;
521         [NSApp setMainMenu:[[NSMenu alloc] init]];
523 //Create Movie Menu
524         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
525         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
526         kHalfScreenCmd = menuItem;
527         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
528         kNormalScreenCmd = menuItem;
529         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
530         kDoubleScreenCmd = menuItem;
531         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
532         kFullScreenCmd = menuItem;
533         menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [menu addItem:menuItem];
535                 aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
536                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
537                 if(vo_keepaspect) [menuItem setState:NSOnState];
538                 kKeepAspectCmd = menuItem;
539                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
540                 if(vo_panscan) [menuItem setState:NSOnState];
541                 kPanScanCmd = menuItem;
542                 menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
543                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
544                 kAspectOrgCmd = menuItem;
545                 menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
546                 kAspectFullCmd = menuItem;
547                 menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
548                 kAspectWideCmd = menuItem;
549                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
550                 [menuItem setSubmenu:aspectMenu];
551                 [menu addItem:menuItem];
552                 [aspectMenu release];
554         //Add to menubar
555         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
556         [menuItem setSubmenu:menu];
557         [[NSApp mainMenu] addItem:menuItem];
559 //Create Window Menu
560         menu = [[NSMenu alloc] initWithTitle:@"Window"];
562         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
563         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
565         //Add to menubar
566         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
567         [menuItem setSubmenu:menu];
568         [[NSApp mainMenu] addItem:menuItem];
569         [NSApp setWindowsMenu:menu];
571         [menu release];
572         [menuItem release];
576         Menu Action
577  */
578 - (void)menuAction:(id)sender
580         uint32_t d_width;
581         uint32_t d_height;
582         NSRect frame;
584         aspect((int *)&d_width, (int *)&d_height,A_NOZOOM);
586         if(sender == kQuitCmd)
587         {
588                 mplayer_put_key(KEY_ESC);
589         }
591         if(sender == kHalfScreenCmd)
592         {
593                 if(isFullscreen) {
594                         vo_fs = (!(vo_fs)); [self fullscreen:NO];
595                 }
597                 winSizeMult = 0.5;
598                 frame.size.width = (d_width*winSizeMult);
599                 frame.size.height = ((d_width/movie_aspect)*winSizeMult);
600                 [window setContentSize: frame.size];
601                 [self reshape];
602         }
603         if(sender == kNormalScreenCmd)
604         {
605                 if(isFullscreen) {
606                         vo_fs = (!(vo_fs)); [self fullscreen:NO];
607                 }
609                 winSizeMult = 1;
610                 frame.size.width = d_width;
611                 frame.size.height = d_width/movie_aspect;
612                 [window setContentSize: frame.size];
613                 [self reshape];
614         }
615         if(sender == kDoubleScreenCmd)
616         {
617                 if(isFullscreen) {
618                         vo_fs = (!(vo_fs)); [self fullscreen:NO];
619                 }
621                 winSizeMult = 2;
622                 frame.size.width = d_width*winSizeMult;
623                 frame.size.height = (d_width/movie_aspect)*winSizeMult;
624                 [window setContentSize: frame.size];
625                 [self reshape];
626         }
627         if(sender == kFullScreenCmd)
628         {
629                 vo_fs = (!(vo_fs));
630                 [self fullscreen:NO];
631         }
633         if(sender == kKeepAspectCmd)
634         {
635                 vo_keepaspect = (!(vo_keepaspect));
636                 if(vo_keepaspect)
637                         [kKeepAspectCmd setState:NSOnState];
638                 else
639                         [kKeepAspectCmd setState:NSOffState];
641                 [self reshape];
642         }
644         if(sender == kPanScanCmd)
645         {
646                 vo_panscan = (!(vo_panscan));
647                 if(vo_panscan)
648                         [kPanScanCmd setState:NSOnState];
649                 else
650                         [kPanScanCmd setState:NSOffState];
652                 [self panscan];
653         }
655         if(sender == kAspectOrgCmd)
656         {
657                 movie_aspect = old_movie_aspect;
659                 if(isFullscreen)
660                 {
661                         [self reshape];
662                 }
663                 else
664                 {
665                         frame.size.width = d_width*winSizeMult;
666                         frame.size.height = (d_width/movie_aspect)*winSizeMult;
667                         [window setContentSize: frame.size];
668                         [self reshape];
669                 }
670         }
672         if(sender == kAspectFullCmd)
673         {
674                 movie_aspect = 4.0f/3.0f;
676                 if(isFullscreen)
677                 {
678                         [self reshape];
679                 }
680                 else
681                 {
682                         frame.size.width = d_width*winSizeMult;
683                         frame.size.height = (d_width/movie_aspect)*winSizeMult;
684                         [window setContentSize: frame.size];
685                         [self reshape];
686                 }
687         }
689         if(sender == kAspectWideCmd)
690         {
691                 movie_aspect = 16.0f/9.0f;
693                 if(isFullscreen)
694                 {
695                         [self reshape];
696                 }
697                 else
698                 {
699                         frame.size.width = d_width*winSizeMult;
700                         frame.size.height = (d_width/movie_aspect)*winSizeMult;
701                         [window setContentSize: frame.size];
702                         [self reshape];
703                 }
704         }
708         Setup OpenGL
710 - (void)prepareOpenGL
712         glEnable(GL_BLEND);
713         glDisable(GL_DEPTH_TEST);
714         glDepthMask(GL_FALSE);
715         glDisable(GL_CULL_FACE);
716         [self reshape];
720         reshape OpenGL viewport
722 - (void)reshape
724         uint32_t d_width;
725         uint32_t d_height;
726         float aspectX;
727         float aspectY;
728         int padding = 0;
730         NSRect frame = [self frame];
732         glViewport(0, 0, frame.size.width, frame.size.height);
733         glMatrixMode(GL_PROJECTION);
734         glLoadIdentity();
735         glOrtho(0, frame.size.width, frame.size.height, 0, -1.0, 1.0);
736         glMatrixMode(GL_MODELVIEW);
737         glLoadIdentity();
739         //set texture frame
740         if(vo_keepaspect)
741         {
742                 aspect( (int *)&d_width, (int *)&d_height, A_NOZOOM);
743                 d_height = ((float)d_width/movie_aspect);
745                 aspectX = (float)((float)frame.size.width/(float)d_width);
746                 aspectY = (float)((float)(frame.size.height)/(float)d_height);
748                 if((d_height*aspectX)>(frame.size.height))
749                 {
750                         padding = (frame.size.width - d_width*aspectY)/2;
751                         textureFrame = NSMakeRect(padding, 0, d_width*aspectY, d_height*aspectY);
752                 }
753                 else
754                 {
755                         padding = ((frame.size.height) - d_height*aspectX)/2;
756                         textureFrame = NSMakeRect(0, padding, d_width*aspectX, d_height*aspectX);
757                 }
758         }
759         else
760         {
761                 textureFrame = frame;
762         }
763         vo_dwidth = textureFrame.size.width;
764         vo_dheight = textureFrame.size.height;
768         Render frame
770 - (void) render
772         int curTime;
774         glClear(GL_COLOR_BUFFER_BIT);
776         glEnable(CVOpenGLTextureGetTarget(texture));
777         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
779         glColor3f(1,1,1);
780         glBegin(GL_QUADS);
781         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
782         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
783         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
784         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
785         glEnd();
786         glDisable(CVOpenGLTextureGetTarget(texture));
788         //render resize box
789         if(!isFullscreen)
790         {
791                 NSRect frame = [self frame];
793                 glBegin(GL_LINES);
794                 glColor4f(0.2, 0.2, 0.2, 0.5);
795                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
796                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
797                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
799                 glColor4f(0.4, 0.4, 0.4, 0.5);
800                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
801                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
802                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
804                 glColor4f(0.6, 0.6, 0.6, 0.5);
805                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
806                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
807                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
808                 glEnd();
809         }
811         glFlush();
813         curTime  = TickCount()/60;
815         //automatically hide mouse cursor (and future on-screen control?)
816         if(isFullscreen && !mouseHide && !isRootwin)
817         {
818                 if( ((curTime - lastMouseHide) >= 5) || (lastMouseHide == 0) )
819                 {
820                         CGDisplayHideCursor(kCGDirectMainDisplay);
821                         mouseHide = TRUE;
822                         lastMouseHide = curTime;
823                 }
824         }
826         //update activity every 30 seconds to prevent
827         //screensaver from starting up.
828         if( ((curTime - lastScreensaverUpdate) >= 30) || (lastScreensaverUpdate == 0) )
829         {
830                 UpdateSystemActivity(UsrActivity);
831                 lastScreensaverUpdate = curTime;
832         }
836         Create OpenGL texture from current frame & set texco
838 - (void) setCurrentTexture
840         CVReturn error = kCVReturnSuccess;
842         CVOpenGLTextureRelease(texture);
843         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
844         if(error != kCVReturnSuccess)
845                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
847     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
851         redraw win rect
853 - (void) drawRect: (NSRect *) bounds
855         [self render];
859         Toggle Fullscreen
861 - (void) fullscreen: (BOOL) animate
863         static NSRect old_frame;
864         static NSRect old_view_frame;
866         panscan_calc();
868         //go fullscreen
869         if(vo_fs)
870         {
871                 if(!isRootwin)
872                 {
873                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
874                         CGDisplayHideCursor(kCGDirectMainDisplay);
875                         mouseHide = YES;
876                 }
878                 old_frame = [window frame];     //save main window size & position
879                 if(screen_id >= 0)
880                         screen_frame = [screen_handle frame];
881                 else {
882                         screen_frame = [[window screen] frame];
883                         vo_screenwidth = screen_frame.size.width;
884                         vo_screenheight = screen_frame.size.height;
885                 }
887                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
888                 old_view_frame = [self bounds];
890                 //fix origin for multi screen setup
891                 screen_frame.origin.x = 0;
892                 screen_frame.origin.y = 0;
893                 [self setFrame:screen_frame];
894                 [self setNeedsDisplay:YES];
895                 [window setHasShadow:NO];
896                 isFullscreen = 1;
897         }
898         else
899         {
900                 SetSystemUIMode( kUIModeNormal, 0);
902                 isFullscreen = 0;
903                 CGDisplayShowCursor(kCGDirectMainDisplay);
904                 mouseHide = NO;
906                 //revert window to previous setting
907                 [self setFrame:old_view_frame];
908                 [self setNeedsDisplay:YES];
909                 [window setHasShadow:YES];
910                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
911         }
915         Toggle ontop
917 - (void) ontop
919         if(vo_ontop)
920         {
921                 [window setLevel:NSScreenSaverWindowLevel];
922                 isOntop = YES;
923         }
924         else
925         {
926                 [window setLevel:NSNormalWindowLevel];
927                 isOntop = NO;
928         }
932         Toggle panscan
934 - (void) panscan
936         panscan_calc();
940         Toggle rootwin
941  */
942 - (void) rootwin
944         if(vo_rootwin)
945         {
946                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
947                 [window orderBack:self];
948                 isRootwin = YES;
949         }
950         else
951         {
952                 [window setLevel:NSNormalWindowLevel];
953                 isRootwin = NO;
954         }
958         Check event for new event
960 - (void) check_events
962         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001] inMode:NSEventTrackingRunLoopMode dequeue:YES];
963         if (event == nil)
964                 return;
965         [NSApp sendEvent:event];
966         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
967         // on Leopard, we have trouble to get the play window automatically focused
968         // when the app is actived. The Following code fix this problem.
969 #ifndef CONFIG_SDL
970         if (isLeopardOrLater && [event type] == NSAppKitDefined
971                         && [event subtype] == NSApplicationActivatedEventType) {
972                 [window makeMainWindow];
973                 [window makeKeyAndOrderFront:mpGLView];
974         }
975 #endif
979         From NSView, respond to key equivalents.
981 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
983         switch([theEvent keyCode])
984     {
985                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
986                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
987     }
988         return NO;
992         Process key event
994 - (void) keyDown: (NSEvent *) theEvent
996         unsigned int key;
998         switch([theEvent keyCode])
999     {
1000                 case 0x34:
1001                 case 0x24: key = KEY_ENTER; break;
1002                 case 0x35: key = KEY_ESC; break;
1003                 case 0x33: key = KEY_BACKSPACE; break;
1004                 case 0x3A: key = KEY_BACKSPACE; break;
1005                 case 0x3B: key = KEY_BACKSPACE; break;
1006                 case 0x38: key = KEY_BACKSPACE; break;
1007                 case 0x7A: key = KEY_F+1; break;
1008                 case 0x78: key = KEY_F+2; break;
1009                 case 0x63: key = KEY_F+3; break;
1010                 case 0x76: key = KEY_F+4; break;
1011                 case 0x60: key = KEY_F+5; break;
1012                 case 0x61: key = KEY_F+6; break;
1013                 case 0x62: key = KEY_F+7; break;
1014                 case 0x64: key = KEY_F+8; break;
1015                 case 0x65: key = KEY_F+9; break;
1016                 case 0x6D: key = KEY_F+10; break;
1017                 case 0x67: key = KEY_F+11; break;
1018                 case 0x6F: key = KEY_F+12; break;
1019                 case 0x72: key = KEY_INSERT; break;
1020                 case 0x75: key = KEY_DELETE; break;
1021                 case 0x73: key = KEY_HOME; break;
1022                 case 0x77: key = KEY_END; break;
1023                 case 0x45: key = '+'; break;
1024                 case 0x4E: key = '-'; break;
1025                 case 0x30: key = KEY_TAB; break;
1026                 case 0x74: key = KEY_PAGE_UP; break;
1027                 case 0x79: key = KEY_PAGE_DOWN; break;
1028                 case 0x7B: key = KEY_LEFT; break;
1029                 case 0x7C: key = KEY_RIGHT; break;
1030                 case 0x7D: key = KEY_DOWN; break;
1031                 case 0x7E: key = KEY_UP; break;
1032                 case 0x43: key = '*'; break;
1033                 case 0x4B: key = '/'; break;
1034                 case 0x4C: key = KEY_KPENTER; break;
1035                 case 0x41: key = KEY_KPDEC; break;
1036                 case 0x52: key = KEY_KP0; break;
1037                 case 0x53: key = KEY_KP1; break;
1038                 case 0x54: key = KEY_KP2; break;
1039                 case 0x55: key = KEY_KP3; break;
1040                 case 0x56: key = KEY_KP4; break;
1041                 case 0x57: key = KEY_KP5; break;
1042                 case 0x58: key = KEY_KP6; break;
1043                 case 0x59: key = KEY_KP7; break;
1044                 case 0x5B: key = KEY_KP8; break;
1045                 case 0x5C: key = KEY_KP9; break;
1046                 default: key = *[[theEvent characters] UTF8String]; break;
1047     }
1048         mplayer_put_key(key);
1052         Process mouse button event
1054 - (void) mouseMoved: (NSEvent *) theEvent
1056         if(isFullscreen && !isRootwin)
1057         {
1058                 CGDisplayShowCursor(kCGDirectMainDisplay);
1059                 mouseHide = NO;
1060         }
1061         if (enable_mouse_movements && !isRootwin) {
1062                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
1063                 if ([self mouse:p inRect:textureFrame]) {
1064                         char cmdstr[40];
1065                         snprintf(cmdstr, sizeof(cmdstr), "set_mouse_pos %i %i",
1066                                  (int)(vo_fs ? p.x : (p.x - textureFrame.origin.x)),
1067                                  (int)(vo_fs ? [self frame].size.height - p.y: (NSMaxY(textureFrame) - p.y)));
1068                         mp_input_queue_cmd(mp_input_parse_cmd(cmdstr));
1069                 }
1070         }
1073 - (void) mouseDown: (NSEvent *) theEvent
1075         [self mouseEvent: theEvent];
1078 - (void) mouseUp: (NSEvent *) theEvent
1080         [self mouseEvent: theEvent];
1083 - (void) rightMouseDown: (NSEvent *) theEvent
1085         [self mouseEvent: theEvent];
1088 - (void) rightMouseUp: (NSEvent *) theEvent
1090         [self mouseEvent: theEvent];
1093 - (void) otherMouseDown: (NSEvent *) theEvent
1095         [self mouseEvent: theEvent];
1098 - (void) otherMouseUp: (NSEvent *) theEvent
1100         [self mouseEvent: theEvent];
1103 - (void) scrollWheel: (NSEvent *) theEvent
1105         if([theEvent deltaY] > 0)
1106                 mplayer_put_key(MOUSE_BTN3);
1107         else
1108                 mplayer_put_key(MOUSE_BTN4);
1111 - (void) mouseEvent: (NSEvent *) theEvent
1113         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1114         {
1115                 int buttonNumber = [theEvent buttonNumber];
1116                 // Fix to mplayer defined button order: left, middle, right
1117                 if (buttonNumber == 1)
1118                         buttonNumber = 2;
1119                 else if (buttonNumber == 2)
1120                         buttonNumber = 1;
1121                 switch([theEvent type])
1122                 {
1123                         case NSLeftMouseDown:
1124                         case NSRightMouseDown:
1125                         case NSOtherMouseDown:
1126                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1127                                 break;
1128                         case NSLeftMouseUp:
1129                         case NSRightMouseUp:
1130                         case NSOtherMouseUp:
1131                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1132                                 break;
1133                 }
1134         }
1138         NSResponder
1140 - (BOOL) acceptsFirstResponder
1142         return YES;
1145 - (BOOL) becomeFirstResponder
1147         return YES;
1150 - (BOOL) resignFirstResponder
1152         return YES;
1155 - (void)windowWillClose:(NSNotification *)aNotification
1157     mpGLView = NULL;
1158         mplayer_put_key(KEY_ESC);
1160 @end