]> git.sesse.net Git - vlc/blob - modules/gui/macosx/vout.m
* ALL: new main --video-on-top config option (in use by the x11/xvideo/osx/directx...
[vlc] / modules / gui / macosx / vout.m
1 /*****************************************************************************
2  * vout.m: MacOS X video output plugin
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id: vout.m,v 1.66 2003/12/08 19:50:22 gbazin Exp $
6  *
7  * Authors: Colin Delacroix <colin@zoy.org>
8  *          Florian G. Pflug <fgp@phlo.org>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *          Derk-Jan Hartman <thedj@users.sourceforge.net>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  * 
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <stdlib.h>                                                /* free() */
32 #include <string.h>                                            /* strerror() */
33
34 #include <QuickTime/QuickTime.h>
35
36 #include <vlc_keys.h>
37
38 #include "intf.h"
39 #include "vout.h"
40
41 #define QT_MAX_DIRECTBUFFERS 10
42 #define VL_MAX_DISPLAYS 16
43
44 struct picture_sys_t
45 {
46     void *p_info;
47     unsigned int i_size;
48
49     /* When using I420 output */
50     PlanarPixmapInfoYUV420 pixmap_i420;
51 };
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56
57 static int  vout_Init      ( vout_thread_t * );
58 static void vout_End       ( vout_thread_t * );
59 static int  vout_Manage    ( vout_thread_t * );
60 static void vout_Display   ( vout_thread_t *, picture_t * );
61
62 static int  CoSendRequest      ( vout_thread_t *, SEL );
63 static int  CoCreateWindow     ( vout_thread_t * );
64 static int  CoDestroyWindow    ( vout_thread_t * );
65 static int  CoToggleFullscreen ( vout_thread_t * );
66
67 static void VLCHideMouse       ( vout_thread_t *, BOOL );
68
69 static void QTScaleMatrix      ( vout_thread_t * );
70 static int  QTCreateSequence   ( vout_thread_t * );
71 static void QTDestroySequence  ( vout_thread_t * );
72 static int  QTNewPicture       ( vout_thread_t *, picture_t * );
73 static void QTFreePicture      ( vout_thread_t *, picture_t * );
74
75 /*****************************************************************************
76  * OpenVideo: allocates MacOS X video thread output method
77  *****************************************************************************
78  * This function allocates and initializes a MacOS X vout method.
79  *****************************************************************************/
80 int E_(OpenVideo) ( vlc_object_t *p_this )
81 {   
82     vout_thread_t * p_vout = (vout_thread_t *)p_this;
83     OSErr err;
84     int i_timeout;
85
86     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
87     if( p_vout->p_sys == NULL )
88     {
89         msg_Err( p_vout, "out of memory" );
90         return( 1 );
91     }
92
93     memset( p_vout->p_sys, 0, sizeof( vout_sys_t ) );
94
95     /* Wait for a MacOS X interface to appear. Timeout is 2 seconds. */
96     for( i_timeout = 20 ; i_timeout-- ; )
97     {
98         if( NSApp == NULL )
99         {
100             msleep( INTF_IDLE_SLEEP );
101         }
102     }
103
104     if( NSApp == NULL )
105     {
106         /* no MacOS X intf, unable to communicate with MT */
107         msg_Err( p_vout, "no MacOS X interface present" );
108         free( p_vout->p_sys );
109         return( 1 );
110     }
111
112     if( [NSApp respondsToSelector: @selector(getIntf)] )
113     {
114         intf_thread_t * p_intf;
115
116         for( i_timeout = 10 ; i_timeout-- ; )
117         {
118             if( ( p_intf = [NSApp getIntf] ) == NULL )
119             {
120                 msleep( INTF_IDLE_SLEEP );
121             }
122         }
123
124         if( p_intf == NULL )
125         {
126             msg_Err( p_vout, "MacOS X intf has getIntf, but is NULL" );
127             free( p_vout->p_sys );
128             return( 1 );
129         }
130     }
131
132     p_vout->p_sys->h_img_descr = 
133         (ImageDescriptionHandle)NewHandleClear( sizeof(ImageDescription) );
134     p_vout->p_sys->p_matrix = (MatrixRecordPtr)malloc( sizeof(MatrixRecord) );
135     p_vout->p_sys->p_fullscreen_state = NULL;
136
137     p_vout->p_sys->b_mouse_moved = VLC_TRUE;
138     p_vout->p_sys->i_time_mouse_last_moved = mdate();
139
140     /* set window size */
141     p_vout->p_sys->s_rect.size.width = p_vout->i_window_width;
142     p_vout->p_sys->s_rect.size.height = p_vout->i_window_height;
143
144     if( ( err = EnterMovies() ) != noErr )
145     {
146         msg_Err( p_vout, "EnterMovies failed: %d", err );
147         free( p_vout->p_sys->p_matrix );
148         DisposeHandle( (Handle)p_vout->p_sys->h_img_descr );
149         free( p_vout->p_sys );
150         return( 1 );
151     } 
152
153     /* Damn QT isn't thread safe. so keep a lock in the p_vlc object */
154     vlc_mutex_lock( &p_vout->p_vlc->quicktime_lock );
155
156     err = FindCodec( kYUV420CodecType, bestSpeedCodec,
157                         nil, &p_vout->p_sys->img_dc );
158     
159     vlc_mutex_unlock( &p_vout->p_vlc->quicktime_lock );
160     if( err == noErr && p_vout->p_sys->img_dc != 0 )
161     {
162         p_vout->output.i_chroma = VLC_FOURCC('I','4','2','0');
163         p_vout->p_sys->i_codec = kYUV420CodecType;
164     }
165     else
166     {
167         msg_Err( p_vout, "failed to find an appropriate codec" );
168     }
169
170     if( p_vout->p_sys->img_dc == 0 )
171     {
172         free( p_vout->p_sys->p_matrix );
173         DisposeHandle( (Handle)p_vout->p_sys->h_img_descr );
174         free( p_vout->p_sys );
175         return VLC_EGENERIC;        
176     }
177
178     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
179     NSArray * o_screens = [NSScreen screens];
180     if( [o_screens count] > 0 && var_Type( p_vout, "video-device" ) == 0 )
181     {
182         int i = 1;
183         vlc_value_t val, text;
184         NSScreen * o_screen;
185
186         int i_option = config_GetInt( p_vout, "macosx-vdev" );
187
188         var_Create( p_vout, "video-device", VLC_VAR_INTEGER |
189                                             VLC_VAR_HASCHOICE ); 
190         text.psz_string = _("Video device");
191         var_Change( p_vout, "video-device", VLC_VAR_SETTEXT, &text, NULL );
192         
193         NSEnumerator * o_enumerator = [o_screens objectEnumerator];
194
195         while( (o_screen = [o_enumerator nextObject]) != NULL )
196         {
197             char psz_temp[255];
198             NSRect s_rect = [o_screen frame];
199
200             snprintf( psz_temp, sizeof(psz_temp)/sizeof(psz_temp[0])-1, 
201                       "%s %d (%dx%d)", _("Screen"), i,
202                       (int)s_rect.size.width, (int)s_rect.size.height ); 
203
204             text.psz_string = psz_temp;
205             val.i_int = i;
206             var_Change( p_vout, "video-device",
207                         VLC_VAR_ADDCHOICE, &val, &text );
208
209             if( ( i - 1 ) == i_option )
210             {
211                 var_Set( p_vout, "video-device", val );
212             }
213             i++;
214         }
215
216         var_AddCallback( p_vout, "video-device", vout_VarCallback,
217                          NULL );
218
219         val.b_bool = VLC_TRUE;
220         var_Set( p_vout, "intf-change", val );
221     }
222     [o_pool release];
223
224     if( CoCreateWindow( p_vout ) )
225     {
226         msg_Err( p_vout, "unable to create window" );
227         free( p_vout->p_sys->p_matrix );
228         DisposeHandle( (Handle)p_vout->p_sys->h_img_descr );
229         free( p_vout->p_sys ); 
230         return( 1 );
231     }
232
233     p_vout->pf_init = vout_Init;
234     p_vout->pf_end = vout_End;
235     p_vout->pf_manage = vout_Manage;
236     p_vout->pf_render = NULL;
237     p_vout->pf_display = vout_Display;
238
239     return( 0 );
240 }
241
242 /*****************************************************************************
243  * vout_Init: initialize video thread output method
244  *****************************************************************************/
245 static int vout_Init( vout_thread_t *p_vout )
246 {
247     int i_index;
248     picture_t *p_pic;
249
250     I_OUTPUTPICTURES = 0;
251
252     /* Initialize the output structure; we already found a codec,
253      * and the corresponding chroma we will be using. Since we can
254      * arbitrary scale, stick to the coordinates and aspect. */
255     p_vout->output.i_width  = p_vout->render.i_width;
256     p_vout->output.i_height = p_vout->render.i_height;
257     p_vout->output.i_aspect = p_vout->render.i_aspect;
258
259     SetPort( p_vout->p_sys->p_qdport );
260     QTScaleMatrix( p_vout );
261
262     if( QTCreateSequence( p_vout ) )
263     {
264         msg_Err( p_vout, "unable to create sequence" );
265         return( 1 );
266     }
267
268     /* Try to initialize up to QT_MAX_DIRECTBUFFERS direct buffers */
269     while( I_OUTPUTPICTURES < QT_MAX_DIRECTBUFFERS )
270     {
271         p_pic = NULL;
272
273         /* Find an empty picture slot */
274         for( i_index = 0; i_index < VOUT_MAX_PICTURES; i_index++ )
275         {
276             if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
277             {
278                 p_pic = p_vout->p_picture + i_index;
279                 break;
280             }
281         }
282
283         /* Allocate the picture */
284         if( p_pic == NULL || QTNewPicture( p_vout, p_pic ) )
285         {
286             break;
287         }
288
289         p_pic->i_status = DESTROYED_PICTURE;
290         p_pic->i_type   = DIRECT_PICTURE;
291
292         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
293
294         I_OUTPUTPICTURES++;
295     }
296
297     return( 0 );
298 }
299
300 /*****************************************************************************
301  * vout_End: terminate video thread output method
302  *****************************************************************************/
303 static void vout_End( vout_thread_t *p_vout )
304 {
305     int i_index;
306
307     QTDestroySequence( p_vout );
308
309     /* Free the direct buffers we allocated */
310     for( i_index = I_OUTPUTPICTURES; i_index; )
311     {
312         i_index--;
313         QTFreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
314     }
315 }
316
317 /*****************************************************************************
318  * CloseVideo: destroy video thread output method
319  *****************************************************************************/
320 void E_(CloseVideo) ( vlc_object_t *p_this )
321 {       
322     vout_thread_t * p_vout = (vout_thread_t *)p_this;     
323
324     if( CoDestroyWindow( p_vout ) )
325     {
326         msg_Err( p_vout, "unable to destroy window" );
327     }
328
329     if ( p_vout->p_sys->p_fullscreen_state != NULL )
330         EndFullScreen ( p_vout->p_sys->p_fullscreen_state, NULL );
331
332     ExitMovies();
333
334     free( p_vout->p_sys->p_matrix );
335     DisposeHandle( (Handle)p_vout->p_sys->h_img_descr );
336
337     free( p_vout->p_sys );
338 }
339
340 /*****************************************************************************
341  * vout_Manage: handle events
342  *****************************************************************************
343  * This function should be called regularly by video output thread. It manages
344  * console events. It returns a non null value on error.
345  *****************************************************************************/
346 static int vout_Manage( vout_thread_t *p_vout )
347 {
348     if( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
349     {
350         if( CoToggleFullscreen( p_vout ) )  
351         {
352             return( 1 );
353         }
354
355         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
356     }
357
358     if( p_vout->i_changes & VOUT_SIZE_CHANGE ) 
359     {
360         QTScaleMatrix( p_vout );
361         SetDSequenceMatrix( p_vout->p_sys->i_seq, 
362                             p_vout->p_sys->p_matrix );
363  
364         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
365     }
366
367     /* hide/show mouse cursor 
368      * this code looks unnecessarily complicated, but is necessary like this.
369      * it has to deal with multiple monitors and therefore checks a lot */
370     if( !p_vout->p_sys->b_mouse_moved && p_vout->b_fullscreen )
371     {
372         if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 3000000 )
373         {
374             VLCHideMouse( p_vout, YES );
375         }
376     }
377     else if ( p_vout->p_sys->b_mouse_moved && p_vout->b_fullscreen )
378     {
379         VLCHideMouse( p_vout, NO );
380     }
381     
382     /* disable screen saver */
383     UpdateSystemActivity( UsrActivity );
384     
385     return( 0 );
386 }
387
388 /*****************************************************************************
389  * vout_Display: displays previously rendered output
390  *****************************************************************************
391  * This function sends the currently rendered image to the display.
392  *****************************************************************************/
393 static void vout_Display( vout_thread_t *p_vout, picture_t *p_pic )
394 {
395     OSErr err;
396     CodecFlags flags;
397
398     if( ( err = DecompressSequenceFrameS( 
399                     p_vout->p_sys->i_seq,
400                     p_pic->p_sys->p_info,
401                     p_pic->p_sys->i_size,                    
402                     codecFlagUseImageBuffer, &flags, nil ) != noErr ) )
403     {
404         msg_Warn( p_vout, "DecompressSequenceFrameS failed: %d", err );
405     }
406     else
407     {
408         QDFlushPortBuffer( p_vout->p_sys->p_qdport, nil );
409     }
410 }
411
412 /*****************************************************************************
413  * CoSendRequest: send request to interface thread
414  *****************************************************************************
415  * Returns 0 on success, 1 otherwise
416  *****************************************************************************/
417 static int CoSendRequest( vout_thread_t *p_vout, SEL sel )
418 {
419     int i_ret = 0;
420
421     VLCVout * o_vlv = [[VLCVout alloc] init];
422
423     if( ( i_ret = ExecuteOnMainThread( o_vlv, sel, (void *)p_vout ) ) )
424     {
425         msg_Err( p_vout, "SendRequest: no way to communicate with mt" );
426     }
427
428     [o_vlv release];
429
430     return( i_ret );
431 }
432
433 /*****************************************************************************
434  * CoCreateWindow: create new window 
435  *****************************************************************************
436  * Returns 0 on success, 1 otherwise
437  *****************************************************************************/
438 static int CoCreateWindow( vout_thread_t *p_vout )
439 {
440     if( CoSendRequest( p_vout, @selector(createWindow:) ) )
441     {
442         msg_Err( p_vout, "CoSendRequest (createWindow) failed" );
443         return( 1 );
444     }
445
446     return( 0 );
447 }
448
449 /*****************************************************************************
450  * CoDestroyWindow: destroy window 
451  *****************************************************************************
452  * Returns 0 on success, 1 otherwise
453  *****************************************************************************/
454 static int CoDestroyWindow( vout_thread_t *p_vout )
455 {
456
457     VLCHideMouse( p_vout, NO );
458
459     if( CoSendRequest( p_vout, @selector(destroyWindow:) ) )
460     {
461         msg_Err( p_vout, "CoSendRequest (destroyWindow) failed" );
462         return( 1 );
463     }
464
465     return( 0 );
466 }
467
468 /*****************************************************************************
469  * CoToggleFullscreen: toggle fullscreen 
470  *****************************************************************************
471  * Returns 0 on success, 1 otherwise
472  *****************************************************************************/
473 static int CoToggleFullscreen( vout_thread_t *p_vout )
474 {
475     QTDestroySequence( p_vout );
476
477     if( CoDestroyWindow( p_vout ) )
478     {
479         msg_Err( p_vout, "unable to destroy window" );
480         return( 1 );
481     }
482     
483     p_vout->b_fullscreen = !p_vout->b_fullscreen;
484
485     config_PutInt( p_vout, "fullscreen", p_vout->b_fullscreen );
486
487     if( CoCreateWindow( p_vout ) )
488     {
489         msg_Err( p_vout, "unable to create window" );
490         return( 1 );
491     }
492
493     SetPort( p_vout->p_sys->p_qdport );
494     QTScaleMatrix( p_vout );
495
496     if( QTCreateSequence( p_vout ) )
497     {
498         msg_Err( p_vout, "unable to create sequence" );
499         return( 1 ); 
500     } 
501
502     return( 0 );
503 }
504
505 /*****************************************************************************
506  * VLCHideMouse: if b_hide then hide the cursor
507  *****************************************************************************/
508 static void VLCHideMouse ( vout_thread_t *p_vout, BOOL b_hide )
509 {
510     BOOL b_inside;
511     NSRect s_rect;
512     NSPoint ml;
513     NSWindow *o_window = p_vout->p_sys->o_window;
514     NSView *o_contents = [o_window contentView];
515     
516     s_rect = [o_contents bounds];
517     ml = [o_window convertScreenToBase:[NSEvent mouseLocation]];
518     ml = [o_contents convertPoint:ml fromView:nil];
519     b_inside = [o_contents mouse: ml inRect: s_rect];
520     
521     if ( b_hide && b_inside )
522     {
523         /* only hide if mouse over VLCView */
524         [NSCursor setHiddenUntilMouseMoves: YES];
525     }
526     else if ( !b_hide )
527     {
528         [NSCursor setHiddenUntilMouseMoves: NO];
529     }
530     p_vout->p_sys->b_mouse_moved = NO;
531     p_vout->p_sys->i_time_mouse_last_moved = mdate();
532     return;
533 }
534
535 /*****************************************************************************
536  * QTScaleMatrix: scale matrix 
537  *****************************************************************************/
538 static void QTScaleMatrix( vout_thread_t *p_vout )
539 {
540     Rect s_rect;
541     unsigned int i_width, i_height;
542     Fixed factor_x, factor_y;
543     unsigned int i_offset_x = 0;
544     unsigned int i_offset_y = 0;
545
546     GetPortBounds( p_vout->p_sys->p_qdport, &s_rect );
547
548     i_width = s_rect.right - s_rect.left;
549     i_height = s_rect.bottom - s_rect.top;
550
551     if( i_height * p_vout->output.i_aspect < i_width * VOUT_ASPECT_FACTOR )
552     {
553         int i_adj_width = i_height * p_vout->output.i_aspect /
554                           VOUT_ASPECT_FACTOR;
555
556         factor_x = FixDiv( Long2Fix( i_adj_width ),
557                            Long2Fix( p_vout->output.i_width ) );
558         factor_y = FixDiv( Long2Fix( i_height ),
559                            Long2Fix( p_vout->output.i_height ) );
560
561         i_offset_x = (i_width - i_adj_width) / 2;
562     }
563     else
564     {
565         int i_adj_height = i_width * VOUT_ASPECT_FACTOR /
566                            p_vout->output.i_aspect;
567
568         factor_x = FixDiv( Long2Fix( i_width ),
569                            Long2Fix( p_vout->output.i_width ) );
570         factor_y = FixDiv( Long2Fix( i_adj_height ),
571                            Long2Fix( p_vout->output.i_height ) );
572
573         i_offset_y = (i_height - i_adj_height) / 2;
574     }
575     
576     SetIdentityMatrix( p_vout->p_sys->p_matrix );
577
578     ScaleMatrix( p_vout->p_sys->p_matrix,
579                  factor_x, factor_y,
580                  Long2Fix(0), Long2Fix(0) );            
581
582     TranslateMatrix( p_vout->p_sys->p_matrix, 
583                      Long2Fix(i_offset_x), 
584                      Long2Fix(i_offset_y) );
585
586 }
587
588 /*****************************************************************************
589  * QTCreateSequence: create a new sequence 
590  *****************************************************************************
591  * Returns 0 on success, 1 otherwise
592  *****************************************************************************/
593 static int QTCreateSequence( vout_thread_t *p_vout )
594 {
595     OSErr err;
596     ImageDescriptionPtr p_descr;
597
598     HLock( (Handle)p_vout->p_sys->h_img_descr );
599     p_descr = *p_vout->p_sys->h_img_descr;
600
601     p_descr->idSize = sizeof(ImageDescription);
602     p_descr->cType = p_vout->p_sys->i_codec;
603     p_descr->version = 1;
604     p_descr->revisionLevel = 0;
605     p_descr->vendor = 'appl';
606     p_descr->width = p_vout->output.i_width;
607     p_descr->height = p_vout->output.i_height;
608     p_descr->hRes = Long2Fix(72);
609     p_descr->vRes = Long2Fix(72);
610     p_descr->spatialQuality = codecLosslessQuality;
611     p_descr->frameCount = 1;
612     p_descr->clutID = -1;
613     p_descr->dataSize = 0;
614     p_descr->depth = 24;
615
616     HUnlock( (Handle)p_vout->p_sys->h_img_descr );
617
618     if( ( err = DecompressSequenceBeginS( 
619                               &p_vout->p_sys->i_seq,
620                               p_vout->p_sys->h_img_descr,
621                               NULL, 0,
622                               p_vout->p_sys->p_qdport,
623                               NULL, NULL,
624                               p_vout->p_sys->p_matrix,
625                               0, NULL,
626                               codecFlagUseImageBuffer,
627                               codecLosslessQuality,
628                               p_vout->p_sys->img_dc ) ) )
629     {
630         msg_Err( p_vout, "DecompressSequenceBeginS failed: %d", err );
631         return( 1 );
632     }
633
634     return( 0 );
635 }
636
637 /*****************************************************************************
638  * QTDestroySequence: destroy sequence 
639  *****************************************************************************/
640 static void QTDestroySequence( vout_thread_t *p_vout )
641 {
642     CDSequenceEnd( p_vout->p_sys->i_seq );
643 }
644
645 /*****************************************************************************
646  * QTNewPicture: allocate a picture
647  *****************************************************************************
648  * Returns 0 on success, 1 otherwise
649  *****************************************************************************/
650 static int QTNewPicture( vout_thread_t *p_vout, picture_t *p_pic )
651 {
652     int i_width  = p_vout->output.i_width;
653     int i_height = p_vout->output.i_height;
654
655     /* We know the chroma, allocate a buffer which will be used
656      * directly by the decoder */
657     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
658
659     if( p_pic->p_sys == NULL )
660     {
661         return( -1 );
662     }
663
664     switch( p_vout->output.i_chroma )
665     {
666         case VLC_FOURCC('I','4','2','0'):
667
668             p_pic->p_sys->p_info = (void *)&p_pic->p_sys->pixmap_i420;
669             p_pic->p_sys->i_size = sizeof(PlanarPixmapInfoYUV420);
670
671             /* Allocate the memory buffer */
672             p_pic->p_data = vlc_memalign( &p_pic->p_data_orig,
673                                           16, i_width * i_height * 3 / 2 );
674
675             /* Y buffer */
676             p_pic->Y_PIXELS = p_pic->p_data; 
677             p_pic->p[Y_PLANE].i_lines = i_height;
678             p_pic->p[Y_PLANE].i_pitch = i_width;
679             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
680             p_pic->p[Y_PLANE].i_visible_pitch = i_width;
681
682             /* U buffer */
683             p_pic->U_PIXELS = p_pic->Y_PIXELS + i_height * i_width;
684             p_pic->p[U_PLANE].i_lines = i_height / 2;
685             p_pic->p[U_PLANE].i_pitch = i_width / 2;
686             p_pic->p[U_PLANE].i_pixel_pitch = 1;
687             p_pic->p[U_PLANE].i_visible_pitch = i_width / 2;
688
689             /* V buffer */
690             p_pic->V_PIXELS = p_pic->U_PIXELS + i_height * i_width / 4;
691             p_pic->p[V_PLANE].i_lines = i_height / 2;
692             p_pic->p[V_PLANE].i_pitch = i_width / 2;
693             p_pic->p[V_PLANE].i_pixel_pitch = 1;
694             p_pic->p[V_PLANE].i_visible_pitch = i_width / 2;
695
696             /* We allocated 3 planes */
697             p_pic->i_planes = 3;
698
699 #define P p_pic->p_sys->pixmap_i420
700             P.componentInfoY.offset = (void *)p_pic->Y_PIXELS
701                                        - p_pic->p_sys->p_info;
702             P.componentInfoCb.offset = (void *)p_pic->U_PIXELS
703                                         - p_pic->p_sys->p_info;
704             P.componentInfoCr.offset = (void *)p_pic->V_PIXELS
705                                         - p_pic->p_sys->p_info;
706
707             P.componentInfoY.rowBytes = i_width;
708             P.componentInfoCb.rowBytes = i_width / 2;
709             P.componentInfoCr.rowBytes = i_width / 2;
710 #undef P
711
712             break;
713
714     default:
715         /* Unknown chroma, tell the guy to get lost */
716         free( p_pic->p_sys );
717         msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
718                  p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
719         p_pic->i_planes = 0;
720         return( -1 );
721     }
722
723     return( 0 );
724 }
725
726 /*****************************************************************************
727  * QTFreePicture: destroy a picture allocated with QTNewPicture
728  *****************************************************************************/
729 static void QTFreePicture( vout_thread_t *p_vout, picture_t *p_pic )
730 {
731     switch( p_vout->output.i_chroma )
732     {
733         case VLC_FOURCC('I','4','2','0'):
734             free( p_pic->p_data_orig );
735             break;
736     }
737
738     free( p_pic->p_sys );
739 }
740
741 /*****************************************************************************
742  * VLCWindow implementation
743  *****************************************************************************/
744 @implementation VLCWindow
745
746 - (void)setVout:(vout_thread_t *)_p_vout
747 {
748     p_vout = _p_vout;
749 }
750
751 - (vout_thread_t *)getVout
752 {
753     return( p_vout );
754 }
755
756 - (void)scaleWindowWithFactor: (float)factor
757 {
758     NSSize newsize;
759     int i_corrected_height, i_corrected_width;
760     NSPoint topleftbase;
761     NSPoint topleftscreen;
762     
763     if ( !p_vout->b_fullscreen )
764     {
765         topleftbase.x = 0;
766         topleftbase.y = [self frame].size.height;
767         topleftscreen = [self convertBaseToScreen: topleftbase];
768         
769         if( p_vout->output.i_height * p_vout->output.i_aspect > 
770                         p_vout->output.i_width * VOUT_ASPECT_FACTOR )
771         {
772             i_corrected_width = p_vout->output.i_height * p_vout->output.i_aspect /
773                                             VOUT_ASPECT_FACTOR;
774             newsize.width = (int) ( i_corrected_width * factor );
775             newsize.height = (int) ( p_vout->render.i_height * factor );
776         }
777         else
778         {
779             i_corrected_height = p_vout->output.i_width * VOUT_ASPECT_FACTOR /
780                                             p_vout->output.i_aspect;
781             newsize.width = (int) ( p_vout->render.i_width * factor );
782             newsize.height = (int) ( i_corrected_height * factor );
783         }
784     
785         [self setContentSize: newsize];
786         
787         [self setFrameTopLeftPoint: topleftscreen];
788         p_vout->i_changes |= VOUT_SIZE_CHANGE;
789     }
790 }
791
792 - (void)toggleFloatOnTop
793 {
794     if( config_GetInt( p_vout, "video-on-top" ) )
795     {
796         config_PutInt( p_vout, "video-on-top", 0 );
797         [p_vout->p_sys->o_window setLevel: NSNormalWindowLevel];
798     }
799     else
800     {
801         config_PutInt( p_vout, "video-on-top", 1 );
802         [p_vout->p_sys->o_window setLevel: NSStatusWindowLevel];
803     }
804 }
805
806 - (void)toggleFullscreen
807 {
808     p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
809 }
810
811 - (BOOL)isFullscreen
812 {
813     return( p_vout->b_fullscreen );
814 }
815
816 - (BOOL)canBecomeKeyWindow
817 {
818     return( YES );
819 }
820
821 - (void)keyDown:(NSEvent *)o_event
822 {
823     unichar key = 0;
824     vlc_value_t val;
825     unsigned int i_pressed_modifiers = 0;
826     val.i_int = 0;
827     
828     i_pressed_modifiers = [o_event modifierFlags];
829
830     if( i_pressed_modifiers & NSShiftKeyMask )
831         val.i_int |= KEY_MODIFIER_SHIFT;
832     if( i_pressed_modifiers & NSControlKeyMask )
833         val.i_int |= KEY_MODIFIER_CTRL;
834     if( i_pressed_modifiers & NSAlternateKeyMask )
835         val.i_int |= KEY_MODIFIER_ALT;
836     if( i_pressed_modifiers & NSCommandKeyMask )
837         val.i_int |= KEY_MODIFIER_COMMAND;
838
839     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
840
841     if( key )
842     {
843         /* Escape should always get you out of fullscreen */
844         if( key == (unichar) 0x1b )
845         {
846              if( [self isFullscreen] )
847              {
848                  [self toggleFullscreen];
849              }
850         }
851         else if ( key == ' ' )
852         {
853              playlist_t *p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
854                                                      FIND_ANYWHERE );
855              if ( p_playlist != NULL )
856              {
857                  playlist_Pause( p_playlist );
858                  vlc_object_release( p_playlist);
859              }
860         }
861         else
862         {
863             val.i_int |= CocoaKeyToVLC( key );
864             var_Set( p_vout->p_vlc, "key-pressed", val );
865         }
866     }
867     else
868     {
869         [super keyDown: o_event];
870     }
871 }
872
873 - (void)updateTitle
874 {
875     NSMutableString * o_title;
876     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
877                                                        FIND_ANYWHERE );
878     
879     if( p_playlist == NULL )
880     {
881         return;
882     }
883
884     vlc_mutex_lock( &p_playlist->object_lock );
885     o_title = [NSMutableString stringWithUTF8String: 
886         p_playlist->pp_items[p_playlist->i_index]->psz_uri]; 
887     vlc_mutex_unlock( &p_playlist->object_lock );
888
889     vlc_object_release( p_playlist );
890
891     if( o_title != nil )
892     {
893         NSRange prefix_range = [o_title rangeOfString: @"file:"];
894         if( prefix_range.location != NSNotFound )
895         {
896             [o_title deleteCharactersInRange: prefix_range];
897         }
898
899         [self setTitleWithRepresentedFilename: o_title];
900     }
901     else
902     {
903         [self setTitle:
904             [NSString stringWithCString: VOUT_TITLE " (QuickTime)"]];
905     }
906 }
907
908 /* This is actually the same as VLCControls::stop. */
909 - (BOOL)windowShouldClose:(id)sender
910 {
911     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
912                                                        FIND_ANYWHERE );
913     if( p_playlist == NULL )      
914     {
915         return NO;
916     }
917
918     playlist_Stop( p_playlist );
919     vlc_object_release( p_playlist );
920
921     /* The window will be closed by the intf later. */
922     return NO;
923 }
924
925 @end
926
927 /*****************************************************************************
928  * VLCView implementation
929  *****************************************************************************/
930 @implementation VLCView
931
932 - (void)drawRect:(NSRect)rect
933 {
934     vout_thread_t * p_vout;
935     id o_window = [self window];
936     p_vout = (vout_thread_t *)[o_window getVout];
937     
938     [[NSColor blackColor] set];
939     NSRectFill( rect );
940     [super drawRect: rect];
941
942     p_vout->i_changes |= VOUT_SIZE_CHANGE;
943 }
944
945 - (BOOL)acceptsFirstResponder
946 {
947     return( YES );
948 }
949
950 - (BOOL)becomeFirstResponder
951 {
952     vout_thread_t * p_vout;
953     id o_window = [self window];
954     p_vout = (vout_thread_t *)[o_window getVout];
955     
956     [o_window setAcceptsMouseMovedEvents: YES];
957     return( YES );
958 }
959
960 - (BOOL)resignFirstResponder
961 {
962     vout_thread_t * p_vout;
963     id o_window = [self window];
964     p_vout = (vout_thread_t *)[o_window getVout];
965     
966     [o_window setAcceptsMouseMovedEvents: NO];
967     VLCHideMouse( p_vout, NO );
968     return( YES );
969 }
970
971 - (void)mouseDown:(NSEvent *)o_event
972 {
973     vout_thread_t * p_vout;
974     id o_window = [self window];
975     p_vout = (vout_thread_t *)[o_window getVout];
976     vlc_value_t val;
977
978     switch( [o_event type] )
979     {        
980         case NSLeftMouseDown:
981         {
982             var_Get( p_vout, "mouse-button-down", &val );
983             val.i_int |= 1;
984             var_Set( p_vout, "mouse-button-down", val );
985         }
986         break;
987         
988         default:
989             [super mouseDown: o_event];
990         break;
991     }
992 }
993
994 - (void)otherMouseDown:(NSEvent *)o_event
995 {
996     /* This is not the the wheel button. you need to poll the
997      * mouseWheel event for that. other is a third, forth or fifth button */
998     vout_thread_t * p_vout;
999     id o_window = [self window];
1000     p_vout = (vout_thread_t *)[o_window getVout];
1001     vlc_value_t val;
1002
1003     switch( [o_event type] )
1004     {
1005         case NSOtherMouseDown:
1006         {
1007             var_Get( p_vout, "mouse-button-down", &val );
1008             val.i_int |= 2;
1009             var_Set( p_vout, "mouse-button-down", val );
1010         }
1011         break;
1012         
1013         default:
1014             [super mouseDown: o_event];
1015         break;
1016     }
1017 }
1018
1019 - (void)rightMouseDown:(NSEvent *)o_event
1020 {
1021     vout_thread_t * p_vout;
1022     id o_window = [self window];
1023     p_vout = (vout_thread_t *)[o_window getVout];
1024     vlc_value_t val;
1025
1026     switch( [o_event type] )
1027     {
1028         case NSRightMouseDown:
1029         {
1030             var_Get( p_vout, "mouse-button-down", &val );
1031             val.i_int |= 4;
1032             var_Set( p_vout, "mouse-button-down", val );
1033         }
1034         break;
1035         
1036         default:
1037             [super mouseDown: o_event];
1038         break;
1039     }
1040 }
1041
1042 - (void)mouseUp:(NSEvent *)o_event
1043 {
1044     vout_thread_t * p_vout;
1045     id o_window = [self window];
1046     p_vout = (vout_thread_t *)[o_window getVout];
1047     vlc_value_t val;
1048
1049     switch( [o_event type] )
1050     {
1051         case NSLeftMouseUp:
1052         {
1053             vlc_value_t b_val;
1054             b_val.b_bool = VLC_TRUE;
1055             var_Set( p_vout, "mouse-clicked", b_val );
1056             
1057             var_Get( p_vout, "mouse-button-down", &val );
1058             val.i_int &= ~1;
1059             var_Set( p_vout, "mouse-button-down", val );
1060         }
1061         break;
1062                 
1063         default:
1064             [super mouseUp: o_event];
1065         break;
1066     }
1067 }
1068
1069 - (void)otherMouseUp:(NSEvent *)o_event
1070 {
1071     vout_thread_t * p_vout;
1072     id o_window = [self window];
1073     p_vout = (vout_thread_t *)[o_window getVout];
1074     vlc_value_t val;
1075
1076     switch( [o_event type] )
1077     {
1078         case NSOtherMouseUp:
1079         {
1080             var_Get( p_vout, "mouse-button-down", &val );
1081             val.i_int &= ~2;
1082             var_Set( p_vout, "mouse-button-down", val );
1083         }
1084         break;
1085                 
1086         default:
1087             [super mouseUp: o_event];
1088         break;
1089     }
1090 }
1091
1092 - (void)rightMouseUp:(NSEvent *)o_event
1093 {
1094     vout_thread_t * p_vout;
1095     id o_window = [self window];
1096     p_vout = (vout_thread_t *)[o_window getVout];
1097     vlc_value_t val;
1098
1099     switch( [o_event type] )
1100     {
1101         case NSRightMouseUp:
1102         {
1103             var_Get( p_vout, "mouse-button-down", &val );
1104             val.i_int &= ~4;
1105             var_Set( p_vout, "mouse-button-down", val );
1106         }
1107         break;
1108         
1109         default:
1110             [super mouseUp: o_event];
1111         break;
1112     }
1113 }
1114
1115 - (void)mouseDragged:(NSEvent *)o_event
1116 {
1117     [self mouseMoved:o_event];
1118 }
1119
1120 - (void)otherMouseDragged:(NSEvent *)o_event
1121 {
1122     [self mouseMoved:o_event];
1123 }
1124
1125 - (void)rightMouseDragged:(NSEvent *)o_event
1126 {
1127     [self mouseMoved:o_event];
1128 }
1129
1130 - (void)mouseMoved:(NSEvent *)o_event
1131 {
1132     NSPoint ml;
1133     NSRect s_rect;
1134     BOOL b_inside;
1135
1136     vout_thread_t * p_vout;
1137     id o_window = [self window];
1138     p_vout = (vout_thread_t *)[o_window getVout];
1139
1140     s_rect = [self bounds];
1141     ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
1142     b_inside = [self mouse: ml inRect: s_rect];
1143
1144     if( b_inside )
1145     {
1146         vlc_value_t val;
1147         int i_width, i_height, i_x, i_y;
1148         
1149         vout_PlacePicture( p_vout, (unsigned int)s_rect.size.width,
1150                                    (unsigned int)s_rect.size.height,
1151                                    &i_x, &i_y, &i_width, &i_height );
1152
1153         val.i_int = ( ((int)ml.x) - i_x ) * 
1154                     p_vout->render.i_width / i_width;
1155         var_Set( p_vout, "mouse-x", val );
1156
1157         val.i_int = ( ((int)ml.y) - i_y ) * 
1158                     p_vout->render.i_height / i_height;
1159         var_Set( p_vout, "mouse-y", val );
1160             
1161         val.b_bool = VLC_TRUE;
1162         var_Set( p_vout, "mouse-moved", val );
1163         p_vout->p_sys->i_time_mouse_last_moved = mdate();
1164         p_vout->p_sys->b_mouse_moved = YES;
1165     }
1166
1167     [super mouseMoved: o_event];
1168 }
1169
1170 @end
1171
1172 /*****************************************************************************
1173  * VLCVout implementation
1174  *****************************************************************************/
1175 @implementation VLCVout
1176
1177 - (void)createWindow:(NSValue *)o_value
1178 {
1179     vlc_value_t val;
1180     VLCView * o_view;
1181     NSScreen * o_screen;
1182     vout_thread_t * p_vout;
1183     vlc_bool_t b_main_screen;
1184     
1185     p_vout = (vout_thread_t *)[o_value pointerValue];
1186
1187     p_vout->p_sys->o_window = [VLCWindow alloc];
1188     [p_vout->p_sys->o_window setVout: p_vout];
1189     [p_vout->p_sys->o_window setReleasedWhenClosed: YES];
1190
1191     if( var_Get( p_vout, "video-device", &val ) < 0 )
1192     {
1193         o_screen = [NSScreen mainScreen];
1194         b_main_screen = 1;
1195     }
1196     else
1197     {
1198         NSArray *o_screens = [NSScreen screens];
1199         unsigned int i_index = val.i_int;
1200         
1201         if( [o_screens count] < i_index )
1202         {
1203             o_screen = [NSScreen mainScreen];
1204             b_main_screen = 1;
1205         }
1206         else
1207         {
1208             i_index--;
1209             o_screen = [o_screens objectAtIndex: i_index];
1210             config_PutInt( p_vout, "macosx-vdev", i_index );
1211             b_main_screen = (i_index == 0);
1212         }
1213     } 
1214
1215     if( p_vout->b_fullscreen )
1216     {
1217         NSRect screen_rect = [o_screen frame];
1218         screen_rect.origin.x = screen_rect.origin.y = 0;
1219
1220         if ( b_main_screen && p_vout->p_sys->p_fullscreen_state == NULL )
1221             BeginFullScreen( &p_vout->p_sys->p_fullscreen_state, NULL, 0, 0,
1222                              NULL, NULL, fullScreenAllowEvents );
1223
1224         [p_vout->p_sys->o_window 
1225             initWithContentRect: screen_rect
1226             styleMask: NSBorderlessWindowMask
1227             backing: NSBackingStoreBuffered
1228             defer: NO screen: o_screen];
1229
1230         //[p_vout->p_sys->o_window setLevel: NSPopUpMenuWindowLevel - 1];
1231         p_vout->p_sys->b_mouse_moved = YES;
1232         p_vout->p_sys->i_time_mouse_last_moved = mdate();
1233     }
1234     else
1235     {
1236         unsigned int i_stylemask = NSTitledWindowMask |
1237                                    NSMiniaturizableWindowMask |
1238                                    NSClosableWindowMask |
1239                                    NSResizableWindowMask;
1240         
1241         if ( p_vout->p_sys->p_fullscreen_state != NULL )
1242             EndFullScreen ( p_vout->p_sys->p_fullscreen_state, NULL );
1243         p_vout->p_sys->p_fullscreen_state = NULL;
1244
1245         [p_vout->p_sys->o_window 
1246             initWithContentRect: p_vout->p_sys->s_rect
1247             styleMask: i_stylemask
1248             backing: NSBackingStoreBuffered
1249             defer: NO screen: o_screen];
1250
1251         [p_vout->p_sys->o_window setAlphaValue: config_GetFloat( p_vout, "macosx-opaqueness" )];
1252         
1253         if( config_GetInt( p_vout, "video-on-top" ) )
1254         {
1255             [p_vout->p_sys->o_window setLevel: NSStatusWindowLevel];
1256         }
1257         
1258         if( !p_vout->p_sys->b_pos_saved )   
1259         {
1260             [p_vout->p_sys->o_window center];
1261         }
1262     }
1263
1264     o_view = [[VLCView alloc] init];
1265     /* FIXME: [o_view setMenu:] */
1266     [p_vout->p_sys->o_window setContentView: o_view];
1267     [o_view autorelease];
1268
1269     [o_view lockFocus];
1270     p_vout->p_sys->p_qdport = [o_view qdPort];
1271
1272     [o_view unlockFocus];
1273     
1274     [p_vout->p_sys->o_window updateTitle];
1275     [p_vout->p_sys->o_window makeKeyAndOrderFront: nil];
1276 }
1277
1278 - (void)destroyWindow:(NSValue *)o_value
1279 {
1280     vout_thread_t * p_vout;
1281
1282     p_vout = (vout_thread_t *)[o_value pointerValue];
1283
1284     if( !p_vout->b_fullscreen )
1285     {
1286         NSRect s_rect;
1287
1288         s_rect = [[p_vout->p_sys->o_window contentView] frame];
1289         p_vout->p_sys->s_rect.size = s_rect.size;
1290
1291         s_rect = [p_vout->p_sys->o_window frame];
1292         p_vout->p_sys->s_rect.origin = s_rect.origin;
1293
1294         p_vout->p_sys->b_pos_saved = YES;
1295     }
1296     
1297     p_vout->p_sys->p_qdport = nil;
1298     [p_vout->p_sys->o_window close];
1299     p_vout->p_sys->o_window = nil;
1300 }
1301
1302 @end