Fix vf_tcdump's compilation
[mplayer/kovensky.git] / libvo / vo_corevideo.m
blob9cd34470723a10d13226bba354288f4d9e688a22
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         if (screen_id == -1 && xinerama_screen > -1)
119                 screen_id = xinerama_screen;
121         screen_array = [NSScreen screens];
122         if(screen_id < (int)[screen_array count])
123         {
124                 screen_handle = [screen_array objectAtIndex:(screen_id < 0 ? 0 : screen_id)];
125         }
126         else
127         {
128                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] Device ID %d does not exist, falling back to main device\n", screen_id);
129                 screen_handle = [screen_array objectAtIndex:0];
130                 screen_id = -1;
131         }
133         screen_frame = ![mpGLView window] || screen_id >= 0 ? [screen_handle frame] : [[[mpGLView window] screen] frame];
134         vo_screenwidth = screen_frame.size.width;
135         vo_screenheight = screen_frame.size.height;
136         xinerama_x = xinerama_y = 0;
137         aspect_save_screenres(vo_screenwidth, vo_screenheight);
140 static void free_file_specific(void)
142         if(shared_buffer)
143         {
144                 [mplayerosxProto stop];
145                 mplayerosxProto = nil;
146                 [mplayerosxProxy release];
147                 mplayerosxProxy = nil;
149                 if (munmap(image_data, image_width*image_height*image_bytes) == -1)
150                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: munmap failed. Error: %s\n", strerror(errno));
152                 if (shm_unlink(buffer_name) == -1)
153                         mp_msg(MSGT_VO, MSGL_FATAL, "[vo_corevideo] uninit: shm_unlink failed. Error: %s\n", strerror(errno));
154     } else {
155         free(image_datas[0]);
156         if (vo_doublebuffering)
157             free(image_datas[1]);
158         image_datas[0] = NULL;
159         image_datas[1] = NULL;
160         image_data = NULL;
161     }
164 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)
166         free_file_specific();
168         //misc mplayer setup
169         image_width = width;
170         image_height = height;
171         switch (image_format)
172         {
173                 case IMGFMT_BGR32:
174                 case IMGFMT_RGB32:
175                         image_depth = 32;
176                         break;
177                 case IMGFMT_YUY2:
178                         image_depth = 16;
179                         break;
180         }
181         image_bytes = (image_depth + 7) / 8;
183         if(!shared_buffer)
184         {
185                 config_movie_aspect((float)d_width/d_height);
187                 vo_dwidth  = d_width  *= mpGLView->winSizeMult;
188                 vo_dheight = d_height *= mpGLView->winSizeMult;
190                 image_data = malloc(image_width*image_height*image_bytes);
191                 image_datas[0] = image_data;
192                 if (vo_doublebuffering)
193                         image_datas[1] = malloc(image_width*image_height*image_bytes);
194                 image_page = 0;
196                 vo_fs = flags & VOFLAG_FULLSCREEN;
198                 //config OpenGL View
199                 [mpGLView config];
200                 [mpGLView reshape];
201         }
202         else
203         {
204                 int shm_fd;
205                 mp_msg(MSGT_VO, MSGL_INFO, "[vo_corevideo] writing output to a shared buffer "
206                                 "named \"%s\"\n",buffer_name);
208                 // create shared memory
209                 shm_fd = shm_open(buffer_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
210                 if (shm_fd == -1)
211                 {
212                         mp_msg(MSGT_VO, MSGL_FATAL,
213                                    "[vo_corevideo] failed to open shared memory. Error: %s\n", strerror(errno));
214                         return 1;
215                 }
218                 if (ftruncate(shm_fd, image_width*image_height*image_bytes) == -1)
219                 {
220                         mp_msg(MSGT_VO, MSGL_FATAL,
221                                    "[vo_corevideo] failed to size shared memory, possibly already in use. Error: %s\n", strerror(errno));
222                         close(shm_fd);
223                         shm_unlink(buffer_name);
224                         return 1;
225                 }
227                 image_data = mmap(NULL, image_width*image_height*image_bytes,
228                                         PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
229                 close(shm_fd);
231                 if (image_data == MAP_FAILED)
232                 {
233                         mp_msg(MSGT_VO, MSGL_FATAL,
234                                    "[vo_corevideo] failed to map shared memory. Error: %s\n", strerror(errno));
235                         shm_unlink(buffer_name);
236                         return 1;
237                 }
239                 //connect to mplayerosx
240                 mplayerosxProxy=[NSConnection rootProxyForConnectionWithRegisteredName:[NSString stringWithCString:buffer_name] host:nil];
241                 if ([mplayerosxProxy conformsToProtocol:@protocol(MPlayerOSXVOProto)]) {
242                         [mplayerosxProxy setProtocolForProxy:@protocol(MPlayerOSXVOProto)];
243                         mplayerosxProto = (id <MPlayerOSXVOProto>)mplayerosxProxy;
244                         [mplayerosxProto startWithWidth: image_width withHeight: image_height withBytes: image_bytes withAspect:d_width*100/d_height];
245                 }
246                 else {
247                         [mplayerosxProxy release];
248                         mplayerosxProxy = nil;
249                         mplayerosxProto = nil;
250                 }
251         }
252         return 0;
255 static void check_events(void)
257         if (mpGLView)
258                 [mpGLView check_events];
261 static void draw_osd(void)
263         vo_draw_text(image_width, image_height, draw_alpha);
266 static void flip_page(void)
268         if(shared_buffer) {
269                 NSAutoreleasePool *pool = [NSAutoreleasePool new];
270                 [mplayerosxProto render];
271                 [pool release];
272         } else {
273                 [mpGLView setCurrentTexture];
274                 [mpGLView render];
275                 if (vo_doublebuffering) {
276                         image_page = 1 - image_page;
277                         image_data = image_datas[image_page];
278                 }
279         }
282 static int draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
284         return 0;
288 static int draw_frame(uint8_t *src[])
290         switch (image_format)
291         {
292                 case IMGFMT_BGR32:
293                 case IMGFMT_RGB32:
294                         fast_memcpy(image_data, src[0], image_width*image_height*image_bytes);
295                         break;
297                 case IMGFMT_YUY2:
298                         memcpy_pic(image_data, src[0], image_width * 2, image_height, image_width * 2, image_width * 2);
299                         break;
300         }
302         return 0;
305 static int query_format(uint32_t format)
307         image_format = format;
309     switch(format)
310         {
311                 case IMGFMT_YUY2:
312                         pixelFormat = kYUVSPixelFormat;
313                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
315                 case IMGFMT_RGB32:
316                 case IMGFMT_BGR32:
317                         pixelFormat = k32ARGBPixelFormat;
318                         return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
319     }
320     return 0;
323 static void uninit(void)
325     SetSystemUIMode( kUIModeNormal, 0);
326     CGDisplayShowCursor(kCGDirectMainDisplay);
328     free_file_specific();
330     if(mpGLView)
331     {
332         NSAutoreleasePool *finalPool;
333         mpGLView = nil;
334         [autoreleasepool release];
335         finalPool = [[NSAutoreleasePool alloc] init];
336         [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
337         [finalPool release];
338     }
340     if (buffer_name) free(buffer_name);
341     buffer_name = NULL;
344 static const opt_t subopts[] = {
345 {"device_id",     OPT_ARG_INT,  &screen_id,     NULL},
346 {"shared_buffer", OPT_ARG_BOOL, &shared_buffer, NULL},
347 {"buffer_name",   OPT_ARG_MSTRZ,&buffer_name,   NULL},
348 {NULL}
351 static int preinit(const char *arg)
354         // set defaults
355         screen_id = -1;
356         shared_buffer = false;
357         buffer_name = NULL;
359         if (subopt_parse(arg, subopts) != 0) {
360                 mp_msg(MSGT_VO, MSGL_FATAL,
361                                 "\n-vo corevideo command line help:\n"
362                                 "Example: mplayer -vo corevideo:device_id=1:shared_buffer:buffer_name=mybuff\n"
363                                 "\nOptions:\n"
364                                 "  device_id=<0-...>\n"
365                                 "    Set screen device ID for fullscreen.\n"
366                                 "  shared_buffer\n"
367                                 "    Write output to a shared memory buffer instead of displaying it.\n"
368                                 "  buffer_name=<name>\n"
369                                 "    Name of the shared buffer created with shm_open() as well as\n"
370                                 "    the name of the NSConnection MPlayer will try to open.\n"
371                                 "    Setting buffer_name implicitly enables shared_buffer.\n"
372                                 "\n" );
373                 return -1;
374         }
376         autoreleasepool = [[NSAutoreleasePool alloc] init];
378         if (!buffer_name)
379                 buffer_name = strdup(DEFAULT_BUFFER_NAME);
380         else
381                 shared_buffer = true;
383         if(!shared_buffer)
384         {
385                 NSApplicationLoad();
386                 NSApp = [NSApplication sharedApplication];
387                 isLeopardOrLater = floor(NSAppKitVersionNumber) > 824;
389                 #if !defined (CONFIG_MACOSX_FINDER) || !defined (CONFIG_SDL)
390                 //this chunk of code is heavily based off SDL_macosx.m from SDL
391                 ProcessSerialNumber myProc, frProc;
392                 Boolean sameProc;
394                 if (GetFrontProcess(&frProc) == noErr)
395                 {
396                         if (GetCurrentProcess(&myProc) == noErr)
397                         {
398                                 if (SameProcess(&frProc, &myProc, &sameProc) == noErr && !sameProc)
399                                 {
400                                         TransformProcessType(&myProc, kProcessTransformToForegroundApplication);
401                                 }
402                                 SetFrontProcess(&myProc);
403                         }
404                 }
405                 #endif
407                 if(!mpGLView)
408                 {
409                         mpGLView = [[MPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) pixelFormat:[MPlayerOpenGLView defaultPixelFormat]];
410                         [mpGLView autorelease];
411                 }
413                 [mpGLView display];
414                 [mpGLView preinit];
415         }
417     return 0;
420 static int control(uint32_t request, void *data)
422         switch (request)
423         {
424                 case VOCTRL_PAUSE: return int_pause = 1;
425                 case VOCTRL_RESUME: return int_pause = 0;
426                 case VOCTRL_QUERY_FORMAT: return query_format(*((uint32_t*)data));
427                 case VOCTRL_ONTOP: vo_ontop = (!(vo_ontop)); if(!shared_buffer){ [mpGLView ontop]; } else { [mplayerosxProto ontop]; } return VO_TRUE;
428                 case VOCTRL_ROOTWIN: vo_rootwin = (!(vo_rootwin)); [mpGLView rootwin]; return VO_TRUE;
429                 case VOCTRL_FULLSCREEN: vo_fs = (!(vo_fs)); if(!shared_buffer){ [mpGLView fullscreen: NO]; } else { [mplayerosxProto toggleFullscreen]; } return VO_TRUE;
430                 case VOCTRL_GET_PANSCAN: return VO_TRUE;
431                 case VOCTRL_SET_PANSCAN: [mpGLView panscan]; return VO_TRUE;
432                 case VOCTRL_UPDATE_SCREENINFO: update_screen_info(); return VO_TRUE;
433         }
434         return VO_NOTIMPL;
437 //////////////////////////////////////////////////////////////////////////
438 // NSOpenGLView Subclass
439 //////////////////////////////////////////////////////////////////////////
440 @implementation MPlayerOpenGLView
441 - (void) preinit
443         NSOpenGLContext *glContext;
444         GLint swapInterval = 1;
445         CVReturn error;
447         //init menu
448         [self initMenu];
450         //create window
451         window = [[NSWindow alloc]      initWithContentRect:NSMakeRect(0, 0, 100, 100)
452                                                                 styleMask:NSTitledWindowMask|NSTexturedBackgroundWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask
453                                                                 backing:NSBackingStoreBuffered defer:NO];
455         [window autorelease];
456         [window setDelegate:mpGLView];
457         [window setContentView:mpGLView];
458         [window setInitialFirstResponder:mpGLView];
459         [window setAcceptsMouseMovedEvents:YES];
460     [window setTitle:@"MPlayer - The Movie Player"];
462         isFullscreen = 0;
463         winSizeMult = 1;
465         //create OpenGL Context
466         glContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
468         [self setOpenGLContext:glContext];
469         [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
470         [glContext setView:self];
471         [glContext makeCurrentContext];
472         [glContext release];
474         error = CVOpenGLTextureCacheCreate(NULL, 0, [glContext CGLContextObj], [[self pixelFormat] CGLPixelFormatObj], 0, &textureCache);
475         if(error != kCVReturnSuccess)
476                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture Cache(%d)\n", error);
479 - (void) releaseVideoSpecific
481         CVPixelBufferRelease(frameBuffers[0]);
482         frameBuffers[0] = NULL;
483         CVPixelBufferRelease(frameBuffers[1]);
484         frameBuffers[1] = NULL;
485         CVOpenGLTextureRelease(texture);
486         texture = NULL;
489 - (void) dealloc
491         [self releaseVideoSpecific];
492         CVOpenGLTextureCacheRelease(textureCache);
493         textureCache = NULL;
494         [self setOpenGLContext:nil];
495         [super dealloc];
498 - (void) config
500         NSRect visibleFrame;
501         CVReturn error = kCVReturnSuccess;
503         //config window
504         [window setContentSize:NSMakeSize(vo_dwidth, vo_dheight)];
506         // Use visibleFrame to position the window taking the menu bar and dock into account.
507         // Also flip vo_dy since the screen origin is in the bottom left on OSX.
508         if (screen_id < 0)
509                 visibleFrame = [[[mpGLView window] screen] visibleFrame];
510         else
511                 visibleFrame = [[[NSScreen screens] objectAtIndex:screen_id] visibleFrame];
512         [window setFrameTopLeftPoint:NSMakePoint(
513                 visibleFrame.origin.x + vo_dx,
514                 visibleFrame.origin.y + visibleFrame.size.height - vo_dy)];
516         [self releaseVideoSpecific];
517         error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[0], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[0]);
518         if(error != kCVReturnSuccess)
519                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Buffer(%d)\n", error);
520         if (vo_doublebuffering) {
521                 error = CVPixelBufferCreateWithBytes(NULL, image_width, image_height, pixelFormat, image_datas[1], image_width*image_bytes, NULL, NULL, NULL, &frameBuffers[1]);
522                 if(error != kCVReturnSuccess)
523                         mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create Pixel Double Buffer(%d)\n", error);
524         }
526         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
527         if(error != kCVReturnSuccess)
528                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
530         //show window
531         [window makeKeyAndOrderFront:mpGLView];
533         if(vo_rootwin)
534                 [mpGLView rootwin];
536         if(vo_fs)
537                 [mpGLView fullscreen: NO];
539         if(vo_ontop)
540                 [mpGLView ontop];
544         Init Menu
546 - (void)initMenu
548         NSMenu *menu, *aspectMenu;
549         NSMenuItem *menuItem;
551         [NSApp setMainMenu:[[NSMenu alloc] init]];
553 //Create Movie Menu
554         menu = [[NSMenu alloc] initWithTitle:@"Movie"];
555         menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(menuAction:) keyEquivalent:@"0"]; [menu addItem:menuItem];
556         kHalfScreenCmd = menuItem;
557         menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(menuAction:) keyEquivalent:@"1"]; [menu addItem:menuItem];
558         kNormalScreenCmd = menuItem;
559         menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(menuAction:) keyEquivalent:@"2"]; [menu addItem:menuItem];
560         kDoubleScreenCmd = menuItem;
561         menuItem = [[NSMenuItem alloc] initWithTitle:@"Full Size" action:@selector(menuAction:) keyEquivalent:@"f"]; [menu addItem:menuItem];
562         kFullScreenCmd = menuItem;
563         menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [menu addItem:menuItem];
565                 aspectMenu = [[NSMenu alloc] initWithTitle:@"Aspect Ratio"];
566                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Keep" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
567                 if(vo_keepaspect) [menuItem setState:NSOnState];
568                 kKeepAspectCmd = menuItem;
569                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Pan-Scan" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
570                 if(vo_panscan) [menuItem setState:NSOnState];
571                 kPanScanCmd = menuItem;
572                 menuItem = (NSMenuItem *)[NSMenuItem separatorItem]; [aspectMenu addItem:menuItem];
573                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Original" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
574                 kAspectOrgCmd = menuItem;
575                 menuItem = [[NSMenuItem alloc] initWithTitle:@"4:3" action:@selector(menuAction:) keyEquivalent:@""]; [aspectMenu addItem:menuItem];
576                 kAspectFullCmd = menuItem;
577                 menuItem = [[NSMenuItem alloc] initWithTitle:@"16:9" action:@selector(menuAction:) keyEquivalent:@""];  [aspectMenu addItem:menuItem];
578                 kAspectWideCmd = menuItem;
579                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Aspect Ratio" action:nil keyEquivalent:@""];
580                 [menuItem setSubmenu:aspectMenu];
581                 [menu addItem:menuItem];
582                 [aspectMenu release];
584         //Add to menubar
585         menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
586         [menuItem setSubmenu:menu];
587         [[NSApp mainMenu] addItem:menuItem];
589 //Create Window Menu
590         menu = [[NSMenu alloc] initWithTitle:@"Window"];
592         menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [menu addItem:menuItem];
593         menuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; [menu addItem:menuItem];
595         //Add to menubar
596         menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
597         [menuItem setSubmenu:menu];
598         [[NSApp mainMenu] addItem:menuItem];
599         [NSApp setWindowsMenu:menu];
601         [menu release];
602         [menuItem release];
605 - (void)set_winSizeMult:(float)mult
607     NSRect frame;
608     int d_width, d_height;
609     aspect(&d_width, &d_height, A_NOZOOM);
611     if (isFullscreen) {
612         vo_fs = !vo_fs;
613         [self fullscreen:NO];
614     }
616     winSizeMult = mult;
617     frame.size.width  = d_width  * mult;
618     frame.size.height = d_height * mult;
619     [window setContentSize: frame.size];
620     [self reshape];
624         Menu Action
625  */
626 - (void)menuAction:(id)sender
628         if(sender == kQuitCmd)
629         {
630                 mplayer_put_key(KEY_ESC);
631         }
633         if(sender == kHalfScreenCmd)
634                 [self set_winSizeMult: 0.5];
635         if(sender == kNormalScreenCmd)
636                 [self set_winSizeMult: 1];
637         if(sender == kDoubleScreenCmd)
638                 [self set_winSizeMult: 2];
639         if(sender == kFullScreenCmd)
640         {
641                 vo_fs = (!(vo_fs));
642                 [self fullscreen:NO];
643         }
645         if(sender == kKeepAspectCmd)
646         {
647                 vo_keepaspect = (!(vo_keepaspect));
648                 if(vo_keepaspect)
649                         [kKeepAspectCmd setState:NSOnState];
650                 else
651                         [kKeepAspectCmd setState:NSOffState];
653                 [self reshape];
654         }
656         if(sender == kPanScanCmd)
657         {
658                 vo_panscan = (!(vo_panscan));
659                 if(vo_panscan)
660                         [kPanScanCmd setState:NSOnState];
661                 else
662                         [kPanScanCmd setState:NSOffState];
664                 [self panscan];
665         }
667         if(sender == kAspectOrgCmd)
668                 change_movie_aspect(-1);
670         if(sender == kAspectFullCmd)
671                 change_movie_aspect(4.0f/3.0f);
673         if(sender == kAspectWideCmd)
674                 change_movie_aspect(16.0f/9.0f);
678         Setup OpenGL
680 - (void)prepareOpenGL
682         glEnable(GL_BLEND);
683         glDisable(GL_DEPTH_TEST);
684         glDepthMask(GL_FALSE);
685         glDisable(GL_CULL_FACE);
686         [self reshape];
690         reshape OpenGL viewport
692 - (void)reshape
694         uint32_t d_width;
695         uint32_t 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( (int *)&d_width, (int *)&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         int curTime;
728         glClear(GL_COLOR_BUFFER_BIT);
730         glEnable(CVOpenGLTextureGetTarget(texture));
731         glBindTexture(CVOpenGLTextureGetTarget(texture), CVOpenGLTextureGetName(texture));
733         glColor3f(1,1,1);
734         glBegin(GL_QUADS);
735         glTexCoord2f(upperLeft[0], upperLeft[1]); glVertex2i(   textureFrame.origin.x-(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
736         glTexCoord2f(lowerLeft[0], lowerLeft[1]); glVertex2i(textureFrame.origin.x-(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
737         glTexCoord2f(lowerRight[0], lowerRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), NSMaxY(textureFrame)+(vo_panscan_y >> 1));
738         glTexCoord2f(upperRight[0], upperRight[1]); glVertex2i(NSMaxX(textureFrame)+(vo_panscan_x >> 1), textureFrame.origin.y-(vo_panscan_y >> 1));
739         glEnd();
740         glDisable(CVOpenGLTextureGetTarget(texture));
742         //render resize box
743         if(!isFullscreen)
744         {
745                 NSRect frame = [self frame];
747                 glBegin(GL_LINES);
748                 glColor4f(0.2, 0.2, 0.2, 0.5);
749                 glVertex2i(frame.size.width-1, frame.size.height-1); glVertex2i(frame.size.width-1, frame.size.height-1);
750                 glVertex2i(frame.size.width-1, frame.size.height-5); glVertex2i(frame.size.width-5, frame.size.height-1);
751                 glVertex2i(frame.size.width-1, frame.size.height-9); glVertex2i(frame.size.width-9, frame.size.height-1);
753                 glColor4f(0.4, 0.4, 0.4, 0.5);
754                 glVertex2i(frame.size.width-1, frame.size.height-2); glVertex2i(frame.size.width-2, frame.size.height-1);
755                 glVertex2i(frame.size.width-1, frame.size.height-6); glVertex2i(frame.size.width-6, frame.size.height-1);
756                 glVertex2i(frame.size.width-1, frame.size.height-10); glVertex2i(frame.size.width-10, frame.size.height-1);
758                 glColor4f(0.6, 0.6, 0.6, 0.5);
759                 glVertex2i(frame.size.width-1, frame.size.height-3); glVertex2i(frame.size.width-3, frame.size.height-1);
760                 glVertex2i(frame.size.width-1, frame.size.height-7); glVertex2i(frame.size.width-7, frame.size.height-1);
761                 glVertex2i(frame.size.width-1, frame.size.height-11); glVertex2i(frame.size.width-11, frame.size.height-1);
762                 glEnd();
763         }
765         glFlush();
767         curTime  = TickCount()/60;
769         //automatically hide mouse cursor (and future on-screen control?)
770         if(isFullscreen && !mouseHide && !isRootwin)
771         {
772                 if( ((curTime - lastMouseHide) >= 5) || (lastMouseHide == 0) )
773                 {
774                         CGDisplayHideCursor(kCGDirectMainDisplay);
775                         mouseHide = TRUE;
776                         lastMouseHide = curTime;
777                 }
778         }
780         //update activity every 30 seconds to prevent
781         //screensaver from starting up.
782         if( ((curTime - lastScreensaverUpdate) >= 30) || (lastScreensaverUpdate == 0) )
783         {
784                 UpdateSystemActivity(UsrActivity);
785                 lastScreensaverUpdate = curTime;
786         }
790         Create OpenGL texture from current frame & set texco
792 - (void) setCurrentTexture
794         CVReturn error = kCVReturnSuccess;
796         CVOpenGLTextureRelease(texture);
797         error = CVOpenGLTextureCacheCreateTextureFromImage(NULL, textureCache, frameBuffers[image_page], 0, &texture);
798         if(error != kCVReturnSuccess)
799                 mp_msg(MSGT_VO, MSGL_ERR,"[vo_corevideo] Failed to create OpenGL texture(%d)\n", error);
801     CVOpenGLTextureGetCleanTexCoords(texture, lowerLeft, lowerRight, upperRight, upperLeft);
805         redraw win rect
807 - (void) drawRect: (NSRect *) bounds
809         [self render];
813         Toggle Fullscreen
815 - (void) fullscreen: (BOOL) animate
817         static NSRect old_frame;
818         static NSRect old_view_frame;
820         panscan_calc();
822         //go fullscreen
823         if(vo_fs)
824         {
825                 if(!isRootwin)
826                 {
827                         SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
828                         CGDisplayHideCursor(kCGDirectMainDisplay);
829                         mouseHide = YES;
830                 }
832                 old_frame = [window frame];     //save main window size & position
833                 update_screen_info();
835                 [window setFrame:screen_frame display:YES animate:animate]; //zoom-in window with nice useless sfx
836                 old_view_frame = [self bounds];
838                 //fix origin for multi screen setup
839                 screen_frame.origin.x = 0;
840                 screen_frame.origin.y = 0;
841                 [self setFrame:screen_frame];
842                 [self setNeedsDisplay:YES];
843                 [window setHasShadow:NO];
844                 isFullscreen = 1;
845         }
846         else
847         {
848                 SetSystemUIMode( kUIModeNormal, 0);
850                 isFullscreen = 0;
851                 CGDisplayShowCursor(kCGDirectMainDisplay);
852                 mouseHide = NO;
854                 //revert window to previous setting
855                 [self setFrame:old_view_frame];
856                 [self setNeedsDisplay:YES];
857                 [window setHasShadow:YES];
858                 [window setFrame:old_frame display:YES animate:animate];//zoom-out window with nice useless sfx
859         }
863         Toggle ontop
865 - (void) ontop
867         if(vo_ontop)
868         {
869                 [window setLevel:NSScreenSaverWindowLevel];
870                 isOntop = YES;
871         }
872         else
873         {
874                 [window setLevel:NSNormalWindowLevel];
875                 isOntop = NO;
876         }
880         Toggle panscan
882 - (void) panscan
884         panscan_calc();
888         Toggle rootwin
889  */
890 - (void) rootwin
892         if(vo_rootwin)
893         {
894                 [window setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
895                 [window orderBack:self];
896                 isRootwin = YES;
897         }
898         else
899         {
900                 [window setLevel:NSNormalWindowLevel];
901                 isRootwin = NO;
902         }
906         Check event for new event
908 - (void) check_events
910         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001] inMode:NSEventTrackingRunLoopMode dequeue:YES];
911         if (event == nil)
912                 return;
913         [NSApp sendEvent:event];
914         // Without SDL's bootstrap code (include SDL.h in mplayer.c),
915         // on Leopard, we have trouble to get the play window automatically focused
916         // when the app is actived. The Following code fix this problem.
917 #ifndef CONFIG_SDL
918         if (isLeopardOrLater && [event type] == NSAppKitDefined
919                         && [event subtype] == NSApplicationActivatedEventType) {
920                 [window makeMainWindow];
921                 [window makeKeyAndOrderFront:mpGLView];
922         }
923 #endif
927         From NSView, respond to key equivalents.
929 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
931         switch([theEvent keyCode])
932     {
933                 case 0x21: [window setAlphaValue: winAlpha-=0.05]; return YES;
934                 case 0x1e: [window setAlphaValue: winAlpha+=0.05]; return YES;
935     }
936         return NO;
940         Process key event
942 - (void) keyDown: (NSEvent *) theEvent
944         int key = convert_key([theEvent keyCode], *[[theEvent characters] UTF8String]);
945         if (key != -1)
946         mplayer_put_key(key);
950         Process mouse button event
952 - (void) mouseMoved: (NSEvent *) theEvent
954         if(isFullscreen && !isRootwin)
955         {
956                 CGDisplayShowCursor(kCGDirectMainDisplay);
957                 mouseHide = NO;
958         }
959         if (enable_mouse_movements && !isRootwin) {
960                 NSPoint p =[self convertPoint:[theEvent locationInWindow] fromView:nil];
961                 if ([self mouse:p inRect:textureFrame]) {
962                         char cmdstr[40];
963                         snprintf(cmdstr, sizeof(cmdstr), "set_mouse_pos %i %i",
964                                  (int)(vo_fs ? p.x : (p.x - textureFrame.origin.x)),
965                                  (int)(vo_fs ? [self frame].size.height - p.y: (NSMaxY(textureFrame) - p.y)));
966                         mp_input_queue_cmd(global_vo->input_ctx, mp_input_parse_cmd(cmdstr));
967                 }
968         }
971 - (void) mouseDown: (NSEvent *) theEvent
973         [self mouseEvent: theEvent];
976 - (void) mouseUp: (NSEvent *) theEvent
978         [self mouseEvent: theEvent];
981 - (void) rightMouseDown: (NSEvent *) theEvent
983         [self mouseEvent: theEvent];
986 - (void) rightMouseUp: (NSEvent *) theEvent
988         [self mouseEvent: theEvent];
991 - (void) otherMouseDown: (NSEvent *) theEvent
993         [self mouseEvent: theEvent];
996 - (void) otherMouseUp: (NSEvent *) theEvent
998         [self mouseEvent: theEvent];
1001 - (void) scrollWheel: (NSEvent *) theEvent
1003         if([theEvent deltaY] > 0)
1004                 mplayer_put_key(MOUSE_BTN3);
1005         else
1006                 mplayer_put_key(MOUSE_BTN4);
1009 - (void) mouseEvent: (NSEvent *) theEvent
1011         if ( [theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9 )
1012         {
1013                 int buttonNumber = [theEvent buttonNumber];
1014                 // Fix to mplayer defined button order: left, middle, right
1015                 if (buttonNumber == 1)
1016                         buttonNumber = 2;
1017                 else if (buttonNumber == 2)
1018                         buttonNumber = 1;
1019                 switch([theEvent type])
1020                 {
1021                         case NSLeftMouseDown:
1022                         case NSRightMouseDown:
1023                         case NSOtherMouseDown:
1024                                 mplayer_put_key((MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
1025                                 break;
1026                         case NSLeftMouseUp:
1027                         case NSRightMouseUp:
1028                         case NSOtherMouseUp:
1029                                 mplayer_put_key(MOUSE_BTN0 + buttonNumber);
1030                                 break;
1031                 }
1032         }
1036         NSResponder
1038 - (BOOL) acceptsFirstResponder
1040         return YES;
1043 - (BOOL) becomeFirstResponder
1045         return YES;
1048 - (BOOL) resignFirstResponder
1050         return YES;
1053 - (void)windowWillClose:(NSNotification *)aNotification
1055     mpGLView = NULL;
1056         mplayer_put_key(KEY_ESC);
1058 @end