find_subfiles: select subtitle files matching -slang
[mplayer/greg.git] / libvo / vo_corevideo.m
blob23ef30d832bd0ed8290c83477660825fde2f5dd6
1 /*
2  * CoreVideo video output driver
3  * Copyright (c) 2005 Nicolas Plourde <nicolasplourde@gmail.com>
4  *
5  * This file is part of MPlayer.
6  *
7  * MPlayer is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * MPlayer is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
22 #import "vo_corevideo.h"
23 #include <sys/types.h>
24 #include <sys/ipc.h>
25 #include <sys/mman.h>
26 #include <unistd.h>
27 #include <CoreServices/CoreServices.h>
28 //special workaround for Apple bug #6267445
29 //(OSServices Power API disabled in OSServices.h for 64bit systems)
30 #ifndef __POWER__
31 #include <CoreServices/../Frameworks/OSServices.framework/Headers/Power.h>
32 #endif
34 //MPLAYER
35 #include "config.h"
36 #include "fastmemcpy.h"
37 #include "video_out.h"
38 #include "video_out_internal.h"
39 #include "aspect.h"
40 #include "mp_msg.h"
41 #include "m_option.h"
42 #include "mp_fifo.h"
43 #include "sub/sub.h"
44 #include "subopt-helper.h"
46 #include "input/input.h"
47 #include "input/mouse.h"
49 #include "osdep/keycodes.h"
50 #include "osx_common.h"
52 //Cocoa
53 NSDistantObject *mplayerosxProxy;
54 id <MPlayerOSXVOProto> mplayerosxProto;
55 MPlayerOpenGLView *mpGLView;
56 NSAutoreleasePool *autoreleasepool;
57 OSType pixelFormat;
59 //shared memory
60 BOOL shared_buffer = false;
61 #define DEFAULT_BUFFER_NAME "mplayerosx"
62 static char *buffer_name;
64 //Screen
65 int screen_id = -1;
66 NSRect screen_frame;
67 NSScreen *screen_handle;
68 NSArray *screen_array;
70 //image
71 unsigned char *image_data;
72 // For double buffering
73 static uint8_t image_page = 0;
74 static unsigned char *image_datas[2];
76 static uint32_t image_width;
77 static uint32_t image_height;
78 static uint32_t image_depth;
79 static uint32_t image_bytes;
80 static uint32_t image_format;
82 //vo
83 static int isFullscreen;
84 static int isOntop;
85 static int isRootwin;
87 static float winAlpha = 1;
88 static int int_pause = 0;
90 static BOOL isLeopardOrLater;
92 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
93 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
95 static vo_info_t info =
97         "Mac OS X Core Video",
98         "corevideo",
99         "Nicolas Plourde <nicolas.plourde@gmail.com>",
100         ""
103 LIBVO_EXTERN(corevideo)
105 static void draw_alpha(int x0, int y0, int w, int h, unsigned char *src, unsigned char *srca, int stride)
107         switch (image_format)
108         {
109                 case IMGFMT_RGB24:
110                         vo_draw_alpha_rgb24(w,h,src,srca,stride,image_data+3*(y0*image_width+x0),3*image_width);
111                         break;
112                 case IMGFMT_ARGB:
113                 case IMGFMT_BGRA:
114                         vo_draw_alpha_rgb32(w,h,src,srca,stride,image_data+4*(y0*image_width+x0),4*image_width);
115                         break;
116                 case IMGFMT_YUY2:
117                         vo_draw_alpha_yuy2(w,h,src,srca,stride,image_data + (x0 + y0 * image_width) * 2,image_width*2);
118                         break;
119         }
122 static void update_screen_info(void)
124         if (screen_id == -1 && xinerama_screen > -1)
125                 screen_id = xinerama_screen;
127         screen_array = [NSScreen screens];
128         if(screen_id >= (int)[screen_array count])
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_id = -1;
132         }
133         if (screen_id < 0 && [mpGLView window])
134                 screen_handle = [[mpGLView window] screen];
135         else
136                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
138         screen_frame = [screen_handle frame];
139         vo_screenwidth = screen_frame.size.width;
140         vo_screenheight = screen_frame.size.height;
141         xinerama_x = xinerama_y = 0;
142         aspect_save_screenres(vo_screenwidth, vo_screenheight);
145 static void free_file_specific(void)
147         if(shared_buffer)
148         {
149                 [mplayerosxProto stop];
150                 mplayerosxProto = nil;
151                 [mplayerosxProxy release];
152                 mplayerosxProxy = nil;
154                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
155                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
157                 if (shm_unlink(buffer_name) == -1)
158                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
159     } else {
160         free(image_datas[0]);
161         if (vo_doublebuffering)
162             free(image_datas[1]);
163         image_datas[0] = NULL;
164         image_datas[1] = NULL;
165         image_data = NULL;
166     }
169 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)
171         free_file_specific();
173         //misc mplayer setup
174         image_width = width;
175         image_height = height;
176         switch (image_format)
177         {
178                 case IMGFMT_RGB24:
179                         image_depth = 24;
180                         break;
181                 case IMGFMT_ARGB:
182                 case IMGFMT_BGRA:
183                         image_depth = 32;
184                         break;
185                 case IMGFMT_YUY2:
186                         image_depth = 16;
187                         break;
188         }
189         image_bytes = (image_depth + 7) / 8;
191         if(!shared_buffer)
192         {
193                 config_movie_aspect((float)d_width/d_height);
195                 vo_dwidth  = d_width  *= mpGLView->winSizeMult;
196                 vo_dheight = d_height *= mpGLView->winSizeMult;
198                 image_data = malloc(image_width*image_height*image_bytes);
199                 image_datas[0] = image_data;
200                 if (vo_doublebuffering)
201                         image_datas[1] = malloc(image_width*image_height*image_bytes);
202                 image_page = 0;
204                 vo_fs = flags & VOFLAG_FULLSCREEN;
206                 //config OpenGL View
207                 [mpGLView config];
208                 [mpGLView reshape];
209         }
210         else
211         {
212                 int shm_fd;
213                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
214                                 "named \"%s\"\n",buffer_name);
216                 // create shared memory
217                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
218                 if (shm_fd == -1)
219                 {
220                         mp_msg(MSGT_VO, MSGL_FATAL,
221                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
222                         return 1;
223                 }
226                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
227                 {
228                         mp_msg(MSGT_VO, MSGL_FATAL,
229                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
230                         close(shm_fd);
231                         shm_unlink(buffer_name);
232                         return 1;
233                 }
235                 image_data = mmap(NULL, image_width*image_height*image_bytes,
236                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
237                 close(shm_fd);
239                 if (image_data == MAP_FAILED)
240                 {
241                         mp_msg(MSGT_VO, MSGL_FATAL,
242                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
243                         shm_unlink(buffer_name);
244                         return 1;
245                 }
247                 //connect to mplayerosx
248                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
249                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
250                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
251                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
252                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:d_width*100/d_height];
253                 }
254                 else {
255                         [mplayerosxProxy release];
256                         mplayerosxProxy = nil;
257                         mplayerosxProto = nil;
258                 }
259         }
260         return 0;
263 static void check_events(void)
265         if (mpGLView)
266                 [mpGLView check_events];
269 static void draw_osd(void)
271         vo_draw_text(image_width, image_height, draw_alpha);
274 static void flip_page(void)
276         if(shared_buffer) {
277                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
278                 [mplayerosxProto render];
279                 [pool release];
280         } else {
281                 [mpGLView setCurrentTexture];
282                 [mpGLView render];
283                 if (vo_doublebuffering) {
284                         image_page = 1 - image_page;
285                         image_data = image_datas[image_page];
286                 }
287         }
290 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
292         return 0;
296 static int draw_frame(uint8_t *src[])
298         return 0;
301 static uint32_t draw_image(mp_image_t *mpi)
303         memcpy_pic(image_data, mpi->planes[0], image_width*image_bytes, image_height, image_width*image_bytes, mpi->stride[0]);
305         return 0;
308 static int query_format(uint32_t format)
310     const int supportflags = VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
311         image_format = format;
313     switch(format)
314         {
315                 case IMGFMT_YUY2:
316                         pixelFormat = kYUVSPixelFormat;
317                         return supportflags;
319                 case IMGFMT_RGB24:
320                         pixelFormat = k24RGBPixelFormat;
321                         return supportflags;
323                 case IMGFMT_ARGB:
324                         pixelFormat = k32ARGBPixelFormat;
325                         return supportflags;
327                 case IMGFMT_BGRA:
328                         pixelFormat = k32BGRAPixelFormat;
329                         return supportflags;
330     }
331     return 0;
334 static void uninit(void)
336     SetSystemUIMode( kUIModeNormal, 0);
337     CGDisplayShowCursor(kCGDirectMainDisplay);
339     free_file_specific();
341     if(mpGLView)
342     {
343         NSAutoreleasePool *finalPool;
344         mpGLView = nil;
345         [autoreleasepool release];
346         finalPool = [[NSAutoreleasePool alloc] init];
347         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
348         [finalPool release];
349     }
351     free(buffer_name);
352     buffer_name = NULL;
355 static const opt_t subopts[] = {
356 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
357 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
358 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
359 {NULL}
362 static int preinit(const char *arg)
365         // set defaults
366         screen_id = -1;
367         shared_buffer = false;
368         buffer_name = NULL;
370         if (subopt_parse(arg, subopts) != 0) {
371                 mp_msg(MSGT_VO, MSGL_FATAL,
372                                 "\n-vo corevideo command line help:\n"
373                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
374                                 "\nOptions:\n"
375                                 "  device_id=<0-...>\n"
376                                 "    Set screen device ID for fullscreen.\n"
377                                 "  shared_buffer\n"
378                                 "    Write output to a shared memory buffer instead of displaying it.\n"
379                                 "  buffer_name=<name>\n"
380                                 "    Name of the shared buffer created with shm_open() as well as\n"
381                                 "    the name of the NSConnection MPlayer will try to open.\n"
382                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
383                                 "\n" );
384                 return -1;
385         }
387         autoreleasepool = [[NSAutoreleasePool alloc] init];
389         if (!buffer_name)
390                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
391         else
392                 shared_buffer = true;
394         if(!shared_buffer)
395         {
396                 NSApplicationLoad();
397                 NSApp = [NSApplication sharedApplication];
398                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
400                 osx_foreground_hack();
402                 if(!mpGLView)
403                 {
404                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
405                         [mpGLView autorelease];
406                 }
407                 // Install an event handler so the Quit menu entry works
408                 // The proper way using NSApp setDelegate: and
409                 // applicationShouldTerminate: does not work,
410                 // probably NSApplication never installs its handler.
411                 [[NSAppleEventManager sharedAppleEventManager]
412                         setEventHandler:mpGLView
413                         andSelector:@selector(handleQuitEvent:withReplyEvent:)
414                         forEventClass:kCoreEventClass
415                         andEventID:kAEQuitApplication];
417                 [mpGLView display];
418                 [mpGLView preinit];
419         }
421     return 0;
424 static int control(uint32_t request, void *data)
426         switch (request)
427         {
428                 case VOCTRL_DRAW_IMAGE: return draw_image(data);
429                 case VOCTRL_PAUSE: return int_pause = 1;
430                 case VOCTRL_RESUME: return int_pause = 0;
431                 case VOCTRL_QUERY_FORMAT: return query_format(*(uint32_t*)data);
432                 case VOCTRL_ONTOP: vo_ontop = !vo_ontop; if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
433                 case VOCTRL_ROOTWIN: vo_rootwin = !vo_rootwin; [mpGLView rootwin]; return VO_TRUE;
434                 case VOCTRL_FULLSCREEN: vo_fs = !vo_fs; if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
435                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
436                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
437                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
438         }
439         return VO_NOTIMPL;
442 //////////////////////////////////////////////////////////////////////////
443 // NSOpenGLView Subclass
444 //////////////////////////////////////////////////////////////////////////
445 @implementation MPlayerOpenGLView
446 - (void) preinit
448         NSOpenGLContext *glContext;
449         GLint swapInterval = 1;
450         CVReturn error;
452         //init menu
453         [self initMenu];
455         //create window
456         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
457                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
458                                                                 backing:NSBackingStoreBuffered defer:NO];
460         [window autorelease];
461         [window setDelegate:mpGLView];
462         [window setContentView:mpGLView];
463         [window setInitialFirstResponder:mpGLView];
464         [window setAcceptsMouseMovedEvents:YES];
465         [window setTitle:@"MPlayer - The Movie Player"];
467         isFullscreen = 0;
468         winSizeMult = 1;
470         //create OpenGL Context
471         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
473         [self setOpenGLContext:glContext];
474         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
475         [glContext setView:self];
476         [glContext makeCurrentContext];
477         [glContext release];
479         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
480         if(error != kCVReturnSuccess)
481                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
484 - (void) releaseVideoSpecific
486         CVPixelBufferRelease(frameBuffers[0]);
487         frameBuffers[0] = NULL;
488         CVPixelBufferRelease(frameBuffers[1]);
489         frameBuffers[1] = NULL;
490         CVOpenGLTextureRelease(texture);
491         texture = NULL;
494 - (void) dealloc
496         [self releaseVideoSpecific];
497         CVOpenGLTextureCacheRelease(textureCache);
498         textureCache = NULL;
499         [self setOpenGLContext:nil];
500         [super dealloc];
503 - (void) config
505         NSRect visibleFrame;
506         CVReturn error = kCVReturnSuccess;
508         //config window
509         [window setContentSize:NSMakeSize(vo_dwidth, vo_dheight)];
511         // Use visibleFrame to position the window taking the menu bar and dock into account.
512         // Also flip vo_dy since the screen origin is in the bottom left on OSX.
513         update_screen_info();
514         visibleFrame = [screen_handle visibleFrame];
515         [window setFrameTopLeftPoint:NSMakePoint(
516                 visibleFrame.origin.x + vo_dx,
517                 visibleFrame.origin.y + visibleFrame.size.height - vo_dy)];
519         [self releaseVideoSpecific];
520         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
521         if(error != kCVReturnSuccess)
522                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
523         if (vo_doublebuffering) {
524                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
525                 if(error != kCVReturnSuccess)
526                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
527         }
529         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
530         if(error != kCVReturnSuccess)
531                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
533         //show window
534         [window makeKeyAndOrderFront:mpGLView];
536         if(vo_rootwin)
537                 [mpGLView rootwin];
539         if(vo_fs)
540                 [mpGLView fullscreen: NO];
542         if(vo_ontop)
543                 [mpGLView ontop];
547         Init Menu
549 - (void)initMenu
551         NSMenu *menu, *aspectMenu;
552         NSMenuItem *menuItem;
554         menu = [[NSMenu new] autorelease];
555         menuItem = [[NSMenuItem new] autorelease];
556         [menu addItem: menuItem];
557         [NSApp setMainMenu: menu];
559 //Create Movie Menu
560         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
561         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
562         kHalfScreenCmd = menuItem;
563         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
564         kNormalScreenCmd = menuItem;
565         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
566         kDoubleScreenCmd = menuItem;
567         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
568         kFullScreenCmd = menuItem;
569         menuItem = [NSMenuItem separatorItem]; [menu addItem:menuItem];
571         aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
572         menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
573         if(vo_keepaspect) [menuItem setState:NSOnState];
574         kKeepAspectCmd = menuItem;
575         menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
576         if(vo_panscan) [menuItem setState:NSOnState];
577         kPanScanCmd = menuItem;
578         menuItem = [NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
579         menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
580         kAspectOrgCmd = menuItem;
581         menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
582         kAspectFullCmd = menuItem;
583         menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
584         kAspectWideCmd = menuItem;
585         menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
586         [menuItem setSubmenu:aspectMenu];
587         [menu addItem:menuItem];
588         [aspectMenu release];
590         //Add to menubar
591         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
592         [menuItem setSubmenu:menu];
593         [[NSApp mainMenu] addItem:menuItem];
595 //Create Window Menu
596         menu = [[NSMenu alloc] initWithTitle:@"Window"];
598         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
599         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
601         //Add to menubar
602         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
603         [menuItem setSubmenu:menu];
604         [[NSApp mainMenu] addItem:menuItem];
605         [NSApp setWindowsMenu:menu];
607         [menu release];
608         [menuItem release];
611 - (void)set_winSizeMult:(float)mult
613     NSRect frame;
614     int d_width, d_height;
615     aspect(&d_width, &d_height, A_NOZOOM);
617     if (isFullscreen) {
618         vo_fs = !vo_fs;
619         [self fullscreen:NO];
620     }
622     winSizeMult = mult;
623     frame.size.width  = d_width  * mult;
624     frame.size.height = d_height * mult;
625     [window setContentSize: frame.size];
626     [self reshape];
630         Menu Action
631  */
632 - (void)menuAction:(id)sender
634         if(sender == kHalfScreenCmd)
635                 [self set_winSizeMult: 0.5];
636         if(sender == kNormalScreenCmd)
637                 [self set_winSizeMult: 1];
638         if(sender == kDoubleScreenCmd)
639                 [self set_winSizeMult: 2];
640         if(sender == kFullScreenCmd)
641         {
642                 vo_fs = !vo_fs;
643                 [self fullscreen:NO];
644         }
646         if(sender == kKeepAspectCmd)
647         {
648                 vo_keepaspect = !vo_keepaspect;
649                 if(vo_keepaspect)
650                         [kKeepAspectCmd setState:NSOnState];
651                 else
652                         [kKeepAspectCmd setState:NSOffState];
654                 [self reshape];
655         }
657         if(sender == kPanScanCmd)
658         {
659                 vo_panscan = !vo_panscan;
660                 if(vo_panscan)
661                         [kPanScanCmd setState:NSOnState];
662                 else
663                         [kPanScanCmd setState:NSOffState];
665                 [self panscan];
666         }
668         if(sender == kAspectOrgCmd)
669                 change_movie_aspect(-1);
671         if(sender == kAspectFullCmd)
672                 change_movie_aspect(4.0f/3.0f);
674         if(sender == kAspectWideCmd)
675                 change_movie_aspect(16.0f/9.0f);
679         Setup OpenGL
681 - (void)prepareOpenGL
683         glEnable(GL_BLEND);
684         glDisable(GL_DEPTH_TEST);
685         glDepthMask(GL_FALSE);
686         glDisable(GL_CULL_FACE);
687         [self reshape];
691         reshape OpenGL viewport
693 - (void)reshape
695         int d_width, d_height;
697         NSRect frame = [self frame];
698         vo_dwidth  = frame.size.width;
699         vo_dheight = frame.size.height;
701         glViewport(0, 0, frame.size.width, frame.size.height);
702         glMatrixMode(GL_PROJECTION);
703         glLoadIdentity();
704         glOrtho(0, frame.size.width, frame.size.height, 0, -1.0, 1.0);
705         glMatrixMode(GL_MODELVIEW);
706         glLoadIdentity();
708         //set texture frame
709         if(vo_keepaspect)
710         {
711                 aspect(&d_width, &d_height, A_WINZOOM);
713                 textureFrame = NSMakeRect((vo_dwidth - d_width) / 2, (vo_dheight - d_height) / 2, d_width, d_height);
714         }
715         else
716         {
717                 textureFrame = frame;
718         }
722         Render frame
724 - (void) render
726         glClear(GL_COLOR_BUFFER_BIT);
728         glEnable(CVOpenGLTextureGetTarget(texture));
729         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
731         glColor3f(1,1,1);
732         glBegin(GL_QUADS);
733         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
734         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
735         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
736         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
737         glEnd();
738         glDisable(CVOpenGLTextureGetTarget(texture));
740         //render resize box
741         if(!isFullscreen)
742         {
743                 NSRect frame = [self frame];
745                 glBegin(GL_LINES);
746                 glColor4f(0.2, 0.2, 0.2, 0.5);
747                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
748                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
749                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
751                 glColor4f(0.4, 0.4, 0.4, 0.5);
752                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
753                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
754                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
756                 glColor4f(0.6, 0.6, 0.6, 0.5);
757                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
758                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
759                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
760                 glEnd();
761         }
763         glFlush();
767         Create OpenGL texture from current frame & set texco
769 - (void) setCurrentTexture
771         CVReturn error = kCVReturnSuccess;
773         CVOpenGLTextureRelease(texture);
774         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
775         if(error != kCVReturnSuccess)
776                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
778     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
782         redraw win rect
784 - (void) drawRect: (NSRect *) bounds
786         [self render];
790         Toggle Fullscreen
792 - (void) fullscreen: (BOOL) animate
794         static NSRect old_frame;
795         static NSRect old_view_frame;
797         panscan_calc();
799         //go fullscreen
800         if(vo_fs)
801         {
802                 if(!isRootwin)
803                 {
804                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
805                         CGDisplayHideCursor(kCGDirectMainDisplay);
806                         mouseHide = YES;
807                 }
809                 old_frame = [window frame];     //save main window size & position
810                 update_screen_info();
812                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
813                 old_view_frame = [self bounds];
815                 //fix origin for multi screen setup
816                 screen_frame.origin.x = 0;
817                 screen_frame.origin.y = 0;
818                 [self setFrame:screen_frame];
819                 [self setNeedsDisplay:YES];
820                 [window setHasShadow:NO];
821                 isFullscreen = 1;
822         }
823         else
824         {
825                 SetSystemUIMode( kUIModeNormal, 0);
827                 isFullscreen = 0;
828                 CGDisplayShowCursor(kCGDirectMainDisplay);
829                 mouseHide = NO;
831                 //revert window to previous setting
832                 [self setFrame:old_view_frame];
833                 [self setNeedsDisplay:YES];
834                 [window setHasShadow:YES];
835                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
836         }
840         Toggle ontop
842 - (void) ontop
844         if(vo_ontop)
845         {
846                 [window setLevel:NSScreenSaverWindowLevel];
847                 isOntop = YES;
848         }
849         else
850         {
851                 [window setLevel:NSNormalWindowLevel];
852                 isOntop = NO;
853         }
857         Toggle panscan
859 - (void) panscan
861         panscan_calc();
865         Toggle rootwin
866  */
867 - (void) rootwin
869         if(vo_rootwin)
870         {
871                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
872                 [window orderBack:self];
873                 isRootwin = YES;
874         }
875         else
876         {
877                 [window setLevel:NSNormalWindowLevel];
878                 isRootwin = NO;
879         }
883         Check event for new event
885 - (void) check_events
887         NSEvent *event;
888         int curTime = TickCount()/60;
890         //automatically hide mouse cursor (and future on-screen control?)
891         if(isFullscreen && !mouseHide && !isRootwin)
892         {
893                 if(curTime - lastMouseHide >= 5 || lastMouseHide == 0)
894                 {
895                         CGDisplayHideCursor(kCGDirectMainDisplay);
896                         mouseHide = TRUE;
897                         lastMouseHide = curTime;
898                 }
899         }
901         //update activity every 30 seconds to prevent
902         //screensaver from starting up.
903         if(curTime - lastScreensaverUpdate >= 30 || lastScreensaverUpdate == 0)
904         {
905                 UpdateSystemActivity(UsrActivity);
906                 lastScreensaverUpdate = curTime;
907         }
909         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
910         if (event == nil)
911                 return;
912         [NSApp sendEvent:event];
913         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
914         // on Leopard, we have trouble to get the play window automatically focused
915         // when the app is actived. The Following code fix this problem.
916 #ifndef CONFIG_SDL
917         if (isLeopardOrLater && [event type] == NSAppKitDefined
918                         && [event subtype] == NSApplicationActivatedEventType) {
919                 [window makeMainWindow];
920                 [window makeKeyAndOrderFront:mpGLView];
921         }
922 #endif
926         From NSView, respond to key equivalents.
928 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
930         switch([theEvent keyCode])
931         {
932                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
933                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
934         }
935         return NO;
939         Process key event
941 - (void) keyDown: (NSEvent *) theEvent
943         int key = convert_key([theEvent keyCode], *[[theEvent characters] UTF8String]);
944         if (key != -1) {
945                 if([theEvent modifierFlags] & NSShiftKeyMask)
946                         key |= KEY_MODIFIER_SHIFT;
947                 if([theEvent modifierFlags] & NSControlKeyMask)
948                         key |= KEY_MODIFIER_CTRL;
949                 if(([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
950                         key |= KEY_MODIFIER_ALT;
951                 if([theEvent modifierFlags] & NSCommandKeyMask)
952                         key |= KEY_MODIFIER_META;
953                 mplayer_put_key(key);
954         }
958         Process mouse button event
960 - (void) mouseMoved: (NSEvent *) theEvent
962         if(isFullscreen && !isRootwin)
963         {
964                 CGDisplayShowCursor(kCGDirectMainDisplay);
965                 mouseHide = NO;
966         }
967         if (enable_mouse_movements && !isRootwin) {
968                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
969                 if ([self mouse:p inRect:textureFrame]) {
970                        vo_mouse_movement(global_vo, vo_fs ? p.x : p.x - textureFrame.origin.x,
971                                           vo_fs ? [self frame].size.height - p.y : NSMaxY(textureFrame) - p.y);
972                 }
973         }
976 - (void) mouseDown: (NSEvent *) theEvent
978         [self mouseEvent: theEvent];
981 - (void) mouseUp: (NSEvent *) theEvent
983         [self mouseEvent: theEvent];
986 - (void) rightMouseDown: (NSEvent *) theEvent
988         [self mouseEvent: theEvent];
991 - (void) rightMouseUp: (NSEvent *) theEvent
993         [self mouseEvent: theEvent];
996 - (void) otherMouseDown: (NSEvent *) theEvent
998         [self mouseEvent: theEvent];
1001 - (void) otherMouseUp: (NSEvent *) theEvent
1003         [self mouseEvent: theEvent];
1006 - (void) scrollWheel: (NSEvent *) theEvent
1008         if([theEvent deltaY] > 0)
1009                 mplayer_put_key(MOUSE_BTN3);
1010         else
1011                 mplayer_put_key(MOUSE_BTN4);
1014 - (void) mouseEvent: (NSEvent *) theEvent
1016         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1017         {
1018                 int buttonNumber = [theEvent buttonNumber];
1019                 // Fix to mplayer defined button order: left, middle, right
1020                 if (buttonNumber == 1)
1021                         buttonNumber = 2;
1022                 else if (buttonNumber == 2)
1023                         buttonNumber = 1;
1024                 switch([theEvent type])
1025                 {
1026                         case NSLeftMouseDown:
1027                         case NSRightMouseDown:
1028                         case NSOtherMouseDown:
1029                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1030                                 break;
1031                         case NSLeftMouseUp:
1032                         case NSRightMouseUp:
1033                         case NSOtherMouseUp:
1034                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1035                                 break;
1036                 }
1037         }
1041         NSResponder
1043 - (BOOL) acceptsFirstResponder
1045         return YES;
1048 - (BOOL) becomeFirstResponder
1050         return YES;
1053 - (BOOL) resignFirstResponder
1055         return YES;
1058 - (BOOL)windowShouldClose:(id)sender
1060         mplayer_put_key(KEY_CLOSE_WIN);
1061         // We have to wait for MPlayer to handle this,
1062         // otherwise we are in trouble if the
1063         // KEY_CLOSE_WIN handler is disabled
1064         return NO;
1067 - (void)handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
1069         mplayer_put_key(KEY_CLOSE_WIN);
1071 @end